Skip to main content
Engineering LibreTexts

7.16: Finding the Bottom

  • Page ID
    14592
  •                 # move the current piece all the way down
                    elif event.key == K_SPACE:
                        movingDown = False
                        movingLeft = False
                        movingRight = False
                        for i in range(1, BOARDHEIGHT):
                            if not isValidPosition(board, fallingPiece, adjY=i):
                                break
                        fallingPiece['y'] += i - 1
    

    When the player presses the space key the falling piece will immediately drop down as far as it can go on the board and land. The program first needs to find out how many spaces the piece can move until it lands.

    Lines 3 [256] to 5 [258] will set all the moving variables to False (which makes the code in later parts of the programming think that the user has let up on any arrow keys that were held down). This is done because this code will move the piece to the absolute bottom and begin falling the next piece, and we don’t want to surprise the player by having those pieces immediately start moving just because they were holding down an arrow key when they hit the space key.

    To find the farthest that the piece can fall, we should first call isValidPosition() and pass the integer 1 for the adjY parameter. If isValidPosition() returns False, we know that the piece cannot fall any further and is already at the bottom. If isValidPosition() returns True, then we know that it can fall 1 space down.

    In that case, we should call isValidPosition() with adjY set to 2. If it returns True again, we will call isValidPosition() with adjY set to 3, and so on. This is what the for loop on line 6 [259] handles: calling isValidPosition() with increasing integer values to pass for adjY until the function call returns False. At that point, we know that the value in i is one space more past the bottom. This is why line 9 [262] increases fallingPiece['y'] by i - 1 instead of i.

    (Also note that the second parameter to range() on line 259’s for statement is set to BOARDHEIGHT because this is the maximum amount that the piece could fall before it must hit the bottom of the board.)