Search code examples
pythonpython-3.xpygamefading

Pygame fading error when it is in a function


I am making an RPG in Pygame and I am having an error that is ruining the point of a fade. What is happening is that when I try to put the fading code in a function, so I don't have to have it dozens of times, it completely skips over the fading part and just flashes.

This is the working code

import pygame
import time

delay = time.sleep
white = 255,255,255
black = 0,0,0

pygame.display.set_caption("Liam's RPG")
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((800,600))

clock = pygame.time.Clock()
menuIntro = False

while not menuIntro:
    menuIntro = True
    logo = pygame.image.load("logo.png").convert()
    logo.set_alpha(0)
    for alpha in range(255):
        screen.fill(black)
        screen.blit(logo, (100,35))     
        logo.set_alpha(alpha)
        clock.tick(200)
        pygame.display.update()
    delay(1.5)

This is the code that causes the fade to skip and mess up

import pygame
import time

delay = time.sleep
white = 255,255,255
black = 0,0,0

pygame.display.set_caption("Liam's RPG")
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((800,600))

clock = pygame.time.Clock()
menuIntro = False

sprite = ""
fade_x = 0
fade_y = 0
clocking = clock.tick(10)

def fading(sprite,clocking,fade_x,fade_y):  
    logo = pygame.image.load(sprite + ".png").convert()
    logo.set_alpha(0)
    for alpha in range(255):
        screen.fill(black)
        screen.blit(logo, (fade_x,fade_y))     
        logo.set_alpha(alpha)
        clocking

while not menuIntro:
    menuIntro = True
    sprite = 'logo'
    fade_x = 100
    fade_y = 35
    clocking = clock.tick(200)
    fading(sprite,clocking,fade_x,fade_y)
    pygame.display.update()
    delay(1.5)

Here is the logo thing that I am trying to fade in, it needs to be in the same directory as the file


Solution

  • In correct code you have tick and update inside for alpha loop. In incorrect code you have tick and update outside this loop - and it doesn't work as you expect.