Skip to main content
Engineering LibreTexts

4.30: Animating the Board Reset

  • Page ID
    14525
  • def resetAnimation(board, allMoves):
        # make all of the moves in allMoves in reverse.
        revAllMoves = allMoves[:] # gets a copy of the list
        revAllMoves.reverse()
    
        for move in revAllMoves:
            if move == UP:
                oppositeMove = DOWN
            elif move == DOWN:
                oppositeMove = UP
            elif move == RIGHT:
                oppositeMove = LEFT
            elif move == LEFT:
                oppositeMove = RIGHT
            slideAnimation(board, oppositeMove, '', animationSpeed=int(TILESIZE / 2))
            makeMove(board, oppositeMove)
    
    
    if __name__ == '__main__':
        main()
    

    When the player clicks on "Reset" or "Solve", the Slide Puzzle game program needs to undo all of the moves that were made to the board. The list of directional values for the slides will be passed as the argument for the allMoves parameter.

    Line 3 [315] uses list slicing to create a duplicate of the allMoves list. Remember that if you don’t specify a number before the :, then Python assumes the slice should start from the very beginning of the list. And if you don’t specify a number after the :, then Python assumes the slice should keep going to the very end of the list. So allMoves[:] creates a list slice of the entire allMoves list. This makes a copy of the actual list to store in revAllMoves, rather than just a copy of the list reference. (See http://invpy.com/references for details.)

    To undo all the moves in allMoves, we need to perform the opposite move of the moves in allMoves, and in reverse order. There is a list method called reverse() which will reverse the order of the items in a list. We call this on the revAllMoves list on line 4 [316].

    The for loop on line 6 [318] iterates over the list of directional values. Remember, we want the opposite move, so the if and elif statements from line 7 [319] to 14 [326] set the correct directional value in the oppositeMove variable. Then we call slideAnimation() to perform the animation, and makeMove() to update the board data structure.

    Just like in the Memory Puzzle game, after all the def statements have been executed to create all the functions, we call the main() function to begin the meat of the program.

    That’s all there is to the Slide Puzzle program! But let’s talk about some general programming concepts that came up in this game.