2

I'm coding a game in python 3 using pygame latest version. I have a function that is intended to slowly fade the screen until it is totally black. It should do so by blitting a low-alpha black surface many times on the screen.

But when I test it, it only blocks the game until the loop is finished. I suspect a problem with the alpha of black_surface.

I've seen some questions on forums about fade in pygame, but none of them concerned fade directly in functions.

Here is the code:

def fade_to_black(screen):
    black_surface = Surface((screen.get_width(), screen.get_height()), flags= SRCALPHA)
    color = (255, 255, 255, 1)
    black_surface.fill(color)
    alpha_key = 1
    while alpha_key <= 255:
        screen.blit(black_surface, screen.get_rect())
        display.flip()
        alpha_key = alpha_key + 1
        time.wait(1)

I have looked in documentation and forums but can't find any solution. Hope it isn't an obvious issue I would have missed... Thanks for the help!

SinLey
  • 67
  • 7

1 Answers1

1

You create a surface called black_surface, but you fill it with white. Fill it with black (eg. (0, 0, 0, 1)) and may work, but there's another problem:

When you call display.flip() inside a loop where you change the screen surface, the display may not actually update if you don't let pygame handle events (e.g. by calling pygame.event.get()), depending on your OS. Also, while your loop runs, you can't handle events manually, e.g. the QUIT event. So while your screen fades to black, you can't quit your game.

Generally, you should only have one main loop and not call blocking functions like pygame.time.sleep, but there are exceptions, of course).

Here's simple Sprite-based example:

import pygame

class Fade(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.rect = pygame.display.get_surface().get_rect()
        self.image = pygame.Surface(self.rect.size, flags=pygame.SRCALPHA)
        self.alpha = 0
        self.direction = 1

    def update(self, events):
        self.image.fill((0, 0, 0, self.alpha))
        self.alpha += self.direction
        if self.alpha > 255 or self.alpha < 0:
            self.direction *= -1
            self.alpha += self.direction

def main():
    pygame.init()
    screen = pygame.display.set_mode((500, 500))
    sprites = pygame.sprite.Group(Fade())
    clock = pygame.time.Clock()

    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return
        sprites.update(events)
        screen.fill((30, 30, 30))
        pygame.draw.rect(screen, pygame.Color('dodgerblue'), (100, 100, 100, 100))
        sprites.draw(screen)
        pygame.display.update()
        clock.tick(60)

if __name__ == '__main__':
    main()

enter image description here

sloth
  • 99,095
  • 21
  • 171
  • 219