Skip to main content
Engineering LibreTexts

9.7: The pygame.transform.flip() Function

  • Page ID
  •     # load the image files
        L_SQUIR_IMG = pygame.image.load('squirrel.png')
        R_SQUIR_IMG = pygame.transform.flip(L_SQUIR_IMG, True, False)
        GRASSIMAGES = []
        for i in range(1, 5):
            GRASSIMAGES.append(pygame.image.load('grass%s.png' % i))
        while True:

    The image for the player and enemy squirrels is loaded from squirrel.png on line 2 [74]. Make sure that this PNG file is in the same folder as, otherwise you will get the error pygame.error: Couldn't open squirrel.png.

    The image in squirrel.png (which you can download from is of a squirrel facing to the left. We also need a Surface object that contains a picture of the squirrel facing to the right. Instead of creating a second PNG image file, we can call the pygame.transform.flip() function. This function has three parameters: the Surface object with the image to flip, a Boolean value to do a horizontal flip, and a Boolean value to do a vertical flip. By passing True for the second parameter and False for the third parameter, the Surface object that returns has the image of the squirrel facing to the right. The original Surface object in L_SQUIR_IMG that we passed in is unchanged.

    Here are examples of images being horizontally and vertically flipped:

    Figure 43

    After the setup in main() is complete, the game begins with runGame() being called.