def changeBackgroundAnimation(animationSpeed=40): global bgColor newBgColor = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) newBgSurf = pygame.Surface((WINDOWWIDTH, WINDOWHEIGHT)) newBgSurf = newBgSurf.convert_alpha() r, g, b = newBgColor for alpha in range(0, 255, animationSpeed): # animation loop checkForQuit() DISPLAYSURF.fill(bgColor) newBgSurf.fill((r, g, b, alpha)) DISPLAYSURF.blit(newBgSurf, (0, 0)) drawButtons() # redraw the buttons on top of the tint pygame.display.update() FPSCLOCK.tick(FPS) bgColor = newBgColor
The background color change animation happens whenever the player finishes entering the entire pattern correctly. On each iteration through the loop which starts on line 8  the entire display Surface has to be redrawn (blended with a less and less transparent new background color, until the background is completely covered by the new color). The steps done on each iteration of the loop are:
- Line 10  fills in the entire display Surface (stored in
DISPLAYSURF) with the old background color (which is stored in
- Line 12  fills in a different Surface object (stored in
newBgSurf) with the new background color’s RGB values (and the alpha transparency value changes on each iteration since that is what the for loop on line 8  does).
- Line 13  then draws the
newBgSurfSurface to the display Surface in
DISPLAYSURF. The reason we didn’t just paint our semitransparent new background color on
DISPLAYSURFto begin with is because the
fill()method will just replace the color on the Surface, whereas the
blit()method will blend the colors.
- Now that we have the background the way we want it, we’ll draw the buttons over it with a call to
drawButtons()on line 15 .
- Line 17  and 18  then just draws the display Surface to the screen and adds a pause.
The reason there is a
global statement at the beginning of the
changeBackgroundAnimation() function is for the
bgColor variable is because this function modifies the content of the variable with an assignment statement on line 19 . Any function can read the value of a global variable without specifying the
If that function assigns a value to a global variable without a
global statement, then Python considers that variable to be a local variable that just happens to have the same name as a global variable. The
main() function uses the
bgColor variable but doesn’t need a global statement for it because it only reads the contents of the
main() function never assigns
bgColor a new value. This concept is explained in more detail at http://invpy.com/global.