Pygame: Flipping horizontally
<p>I'm making a game for my program and I'm trying to flip the image horizontally when I press the left key or right key. I found out about the function </p>

<pre><code>pygame.transform.flip
</code></pre>

<p>however I am unsure as to where to insert it in my code. It would be appreciated if someone could help me. Here is my code. Also could somebody also tell me how I could prevent the image from moving out of the screen?</p>

<pre><code>import pygame
import os

img_path = os.path.join('C:\Python27', 'player.png')

class Player(object):  
    def __init__(self):
        self.image = pygame.image.load("player1.png")

        self.x = 0
        self.y = 0

    def handle_keys(self):
        """ Handles Keys """
        key = pygame.key.get_pressed()
        dist = 5
        if key[pygame.K_DOWN]: 
            self.y += dist 
        elif key[pygame.K_UP]: 
            self.y -= dist 
        if key[pygame.K_RIGHT]: 
            self.x += dist 
        elif key[pygame.K_LEFT]:
            self.x -= dist
)

    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))


pygame.init()
screen = pygame.display.set_mode((640, 400))

player = Player() 
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()      # quit the screen
            running = False

    player.handle_keys()       # movement keys

    screen.fill((255,255,255)) # fill the screen with white
    player.draw(screen)        # draw the player to the screen
    pygame.display.update()    # update the screen

    clock.tick(60)             # Limits Frames Per Second to 60 or less
</code></pre>

<p>I would do the image processing stuff when Player is instantiated like so:</p>

<pre><code>class Player(object):  
    def __init__(self):
        self.image = pygame.image.load("player1.png")
        self.image2 = pygame.transform.flip(self.image, True, False)
        self.flipped = False
        self.x = 0
        self.y = 0
</code></pre>

<p>Handle keys would changed the state of self.flipped.</p>

<pre><code>    if key[pygame.K_RIGHT]: 
        self.x += dist
        self.flipped = False
    elif key[pygame.K_LEFT]:
        self.x -= dist
        self.flipped = True
</code></pre>

<p>Then self.draw decides which image to display.</p>

<pre><code>def draw(self, surface):
    if self.flipped:
        image = self.image2
    else:
        image = self.image
    surface.blit(image, (self.x, self.y))
</code></pre>

<p>This is the approach I take with all animated game objects.</p>

python python-2.7 pygame