0

I want to decreased the alpha value of a rectangle until it gets completely transparent, It works fine in 1 while loop, but I want to do it in a while loop inside a while loop.

The code below works and is just for demonstration, therefore i didn't write things like pygame.display.update():

screen = pygame.display.set_mode((800,800))
red = 255
green = 0
blue = 0
alpha = 255 # 255 is opaque, and a value of 0 is completely transparent.

while True:
    rectangle = pygame.Surface((40,40),pygame.SRCALPHA)
    rectangle.fill((red,green,blue,alpha))
    if alpha != 0:
       alpha -= 1
    screen.blit(rectangle,(0,0)
    ....

The problem starts to happen if I to do the same but inside another while loop:

 while True:
     while True:
        rectangle = pygame.Surface((40,40),pygame.SRCALPHA)
        rectangle.fill((red,green,blue,alpha))
        if alpha != 0:
            alpha -= 1
        screen.blit(rectangle,(0,0)
     ....
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
PyyHermit
  • 1
  • 1
  • 2
  • When do you break out of the inner loop? If you don't know what the problem is, you probably shouldn't omit any code in your question. I'm guessing you never break out of the inner loop, which means flow of execution can never reach the application loop, so your GUI hangs. Also, why are you creating a new rectangle each iteration? Why do you even need (or think you need) a second while loop? – Paul M. Jan 05 '22 at 16:32
  • *I want to do it in a while loop inside a while loop.* Why would you want to do that? – qouify Jan 05 '22 at 16:34
  • 1
    No you do not want to do it in an extra loop. This causes your system to stop responding. You have a loop, use the application loop. – Rabbid76 Jan 05 '22 at 16:35
  • If you need to change the alpha channel based on the elapsed time, you can use a timer event or measure the time with [`pygame.time.get_ticks()`](https://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks). See [Spawning multiple instances of the same object concurrently in python](https://stackoverflow.com/questions/62112754/spawning-multiple-instances-of-the-same-object-concurrently-in-python/62112894#62112894) or [How can I show explosion image when collision happens?](https://stackoverflow.com/questions/64305426/how-can-i-show-explosion-image-when-collision-happens/64305746#64305746). – Rabbid76 Jan 05 '22 at 16:51

1 Answers1

0

I have figured it out.

Essentially, when you create a new while loop you are creating a new game, therefore you must call pygame.Surface.fill((color)).

If you don't call this function, the changes on alpha won't be visible on the screen.

ZygD
  • 22,092
  • 39
  • 79
  • 102
PyyHermit
  • 1
  • 1
  • 2