def gameOverAnimation(color=WHITE, animationSpeed=50): # play all beeps at once, then flash the background origSurf = DISPLAYSURF.copy() flashSurf = pygame.Surface(DISPLAYSURF.get_size()) flashSurf = flashSurf.convert_alpha() BEEP1.play() # play all four beeps at the same time, roughly. BEEP2.play() BEEP3.play() BEEP4.play() r, g, b = color for i in range(3): # do the flash 3 times for start, end, step in ((0, 255, 1), (255, 0, -1)): # The first iteration in this loop sets the following for loop # to go from 0 to 255, the second from 255 to 0. for alpha in range(start, end, animationSpeed * step): # animation loop # alpha means transparency. 255 is opaque, 0 is invisible checkForQuit() flashSurf.fill((r, g, b, alpha)) DISPLAYSURF.blit(origSurf, (0, 0)) DISPLAYSURF.blit(flashSurf, (0, 0)) drawButtons() pygame.display.update() FPSCLOCK.tick(FPS)
Each of the iterations of the
for loop on the next line will perform a flash. To have three flashes done, we put all of that code in a
for loop that has three iterations. If you want more or fewer flashes, then change the integer that is passed to
range() on line 11 .
for loop on line 12  is exactly the same as the one line 173. The
step variables will be used on the next
for loop (on line 13 ) to control how the
alpha variable changes. Reread the "Animating the Button Flash" section if you need to refresh yourself on how these loops work.
This animation loop works the same as the previous flashing animation code in the "Animating the Background Change" section. The copy of the original Surface object stored in
origSurf is drawn on the display Surface, then
flashSurf (which has the new flashing color painted on it) is blitted on top of the display Surface. After the background color is set up, the buttons are drawn on top on line 21 . Finally the display Surface is drawn to the screen with the call to
for loop on line 15  adjusts the alpha value for the color used for each frame of animation (increasing at first, and then decreasing).