Skip to main content
Engineering LibreTexts

6.18: Animating the Background Change

  • Page ID
    14548
  • 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 [198] 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 [200] fills in the entire display Surface (stored in DISPLAYSURF) with the old background color (which is stored in bgColor).
    • Line 12 [202] 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 [198] does).
    • Line 13 [203] then draws the newBgSurf Surface to the display Surface in DISPLAYSURF. The reason we didn’t just paint our semitransparent new background color on DISPLAYSURF to 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 [205].
    • Line 17 [207] and 18 [208] 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 [209]. Any function can read the value of a global variable without specifying the global statement.

    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 bgColor the main() function never assigns bgColor a new value. This concept is explained in more detail at http://invpy.com/global.