4.18: The Game Loop
- Page ID
- 14452
while True: # main game loop mouseClicked = False DISPLAYSURF.fill(BGCOLOR) # drawing the window drawBoard(mainBoard, revealedBoxes)
The game loop is an infinite loop that starts on line 1 [66] that keeps iterating for as long as the game is in progress. Remember that the game loop handles events, updates the game state, and draws the game state to the screen.
The game state for the Memory Puzzle program is stored in the following variables:
mainBoard
revealedBoxes
firstSelection
mouseClicked
mousex
mousey
On each iteration of the game loop in the Memory Puzzle program, the mouseClicked
variable stores a Boolean value that is True
if the player has clicked the mouse during this iteration through the game loop. (This is part of keeping track of the game state.)
On line 4 [69], the surface is painted over with the background color to erase anything that was previously drawn on it. The program then calls drawBoard()
to draw the current state of the board based on the board and "revealed boxes" data structures that we pass it. (These lines of code are part of drawing and updating the screen.)
Remember that our drawing functions only draw on the in-memory display Surface object. This Surface object will not actually appear on the screen until we call pygame.display.update()
, which is done at the end of the game loop on line 121.