2

I've been trying to create a short code to use for a project that can fade in and from black, but for some reason only the function that fades in is working while the fade out function is being skipped more or less. By giving them parameters I confirmed that the problem is in the second function and that the transparency isn't changing at all. Here's my code-

import pygame
screen = pygame.display.set_mode((800,600))
image = pygame.image.load_extended('Map.png').convert_alpha()
image = pygame.transform.scale(image,(530,300))
image.set_alpha(0)
x = 0
y = 255
def fade_in(x):
  while True:
    screen.blit(image,(0,0))
    pygame.display.update()
    image.set_alpha(x)
    pygame.time.delay(100)
    if x < 255:
      x += 5
    else:
      pygame.time.delay(500)
      x = 0
      fade_out(y)
def fade_out(y):
  while True:
    screen.blit(image,(0,0))
    pygame.display.update()
    image.set_alpha(y)
    pygame.time.delay(100)
    if y > 0:
      y -= 5
    else:
      pygame.time.delay(500)
      y = 255
      fade_in(x)
while True:
  fade_in(x)

Does anyone have an idea of what the problem might be?

1 Answers1

2

When you draw a transparent surface on the screen, the surface is blended with the current contents of the screen. Hence you need to clear the screen before drawing the fading background with screen.fill(0).


Do not try to control the application recursively or with loops within the application loop. Do not delay the game. delay causes the game to stop responding.

Use the application loop and use pygame.time.Clock to control the frames per second and thus the game speed.

The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():

This method should be called once per frame.

That means that the loop:

clock = pygame.time.Clock()
run = True
while run:
   clock.tick(60)

Example:

import pygame

pygame.init()
screen = pygame.display.set_mode((400,300))
clock = pygame.time.Clock()

try:
    image = pygame.image.load_extended('Map.png').convert_alpha()
    image = pygame.transform.scale(image,(530,300))
except:
    image = pygame.Surface(screen.get_size())
    pygame.draw.circle(image, (255, 0, 0), screen.get_rect().center, min(*screen.get_size()) // 2 - 20)

alpha = 0
alpha_change = 1

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False          

    alpha += alpha_change
    if not 0 <= alpha <= 255:
        alpha_change *= -1
    alpha = max(0, min(alpha, 255))   

    screen.fill(0)

    alpha_image = image.copy()
    alpha_image.set_alpha(alpha)    
    screen.blit(alpha_image, (0, 0))
    
    pygame.display.flip()

pygame.quit()
exit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174