Skip to main content
Engineering LibreTexts

8.11: The Game Loop

  • Page ID
    14586
  •     while True: # game loop
            if fallingPiece == None:
                # No falling piece in play, so start a new piece at the top
                fallingPiece = nextPiece
                nextPiece = getNewPiece()
                lastFallTime = time.time() # reset lastFallTime
    
                if not isValidPosition(board, fallingPiece):
                    return # can't fit a new piece on the board, so game over
    
            checkForQuit()
    

    The main game loop that starts on line 1 [194] handles all of the code for the main part of the game when pieces are falling to the bottom. The fallingPiece variable is set to None after the falling piece has landed. This means that the piece in nextPiece should be copied to the fallingPiece variable, and a random new piece should be put into the nextPiece variable. A new piece can be generated from the getNewPiece() function. The lastFallTime variable is also reset to the current time so that the piece will fall in however many seconds is in fallFreq.

    The pieces that getNewPiece() are positioned a little bit above the board, usually with part of the piece already on the board. But if this is an invalid position because the board is already filled up there (in which case the isValidPosition() call on line 8 [201] will return False), then we know that the board is full and the player should lose the game. When this happens, the runGame() function returns.

    • Was this article helpful?