How to move and flip the gaming character with Pygame

This tutorial will add the flip mechanism to the GameSprite module to flip the game character along the y axis as well as includes the script to move the game character along the x axis in our main game module.

In order to flip the gaming character we need to use the below method

pygame.transform.flip(sub_surface, self.flip, False)

where sub_surface is the surface return by the

self.sprite.subsurface(self.sprite.get_clip())

method which we have mentioned in our previous tutorial. Besides the sub_surface, the pygame.transform.flip method also takes in two other parameters, the first one is the xboolean uses to flip the surface along the y axis and the second one is the yboolean uses to flip the surface along the x axis, we will only use the xboolean in this example so the yboolean value is always set to False. By setting the xboolean to True or False we can flip the surface along the y axis which will make the game character facing left or right.

There is only one minor change to your original GameSprite module which is to add in another boolean parameter to it so you can use that boolean parameter to control the flipping x-direction.

import pygame

class GameSprite(object):
    
    def __init__(self, image, rect, flip):
        self.image = image
        self.rect = rect
        self.flip = flip
        self.sprite = pygame.image.load(image).convert_alpha()
        
    def getImage(self): # this method will return a subsurface which represents a portion of the spritesheet
        self.sprite.set_clip(self.rect) # clip a portion of the sprite with the rectangle object
        sub_surface = self.sprite.subsurface(self.sprite.get_clip())
        return pygame.transform.flip(sub_surface, self.flip, False)

In order to move our game character we need to get all the keys a user has pressed with this statement.

pressed_keys = pygame.key.get_pressed() # get all the keys from key-press events 

Then we will see whether the left arrow key is within the pressed_keys list or not.

if pressed_keys[K_LEFT]: 
        flip = True # if the user pressed the left arrow key then makes the object facing left
        v = Vector2D(-1., 0.) # move the object one unit to the left

Or else whether the right arrow key is within the pressed_keys list or not.

elif pressed_keys[K_RIGHT]:
        flip = False # if the user pressed the right arrow key then makes the object facing right
        v = Vector2D(1., 0.) # move the object one unit to the right

The rest of the script in our main game module is the same as the 1) animate the stand still sprite and the 2) moving the game sprite tutorial.

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit
from vector2d import Vector2D
from game_sorite import GameSprite

robot_sprite_sheet = 'left.png'

pygame.init()

screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Pygame Demo")

w, h = 64, 64 # width and height of the sprite
sprite_counter = 0 # initialize the sprite_counter
game_frame = 0 # initialize the game_frame counter
flip = False

clock = pygame.time.Clock() # initialize the clock object
player_pos = Vector2D(320, 240) # initial position of the sprite
player_speed = 70. # speed per second

while True:
   
    for event in pygame.event.get():
        
        if event.type == QUIT:
            exit()
            
    v = Vector2D(0., 0.) # reset the speed to zero on each pass
    
    pressed_keys = pygame.key.get_pressed() # get all the keys from key-press events 
        
    if pressed_keys[K_LEFT]: 
        flip = True # if the user pressed the left arrow key then makes the object facing left
        v = Vector2D(-1., 0.) # move the object one unit to the left
        
    elif pressed_keys[K_RIGHT]:
        flip = False # if the user pressed the right arrow key then makes the object facing right
        v = Vector2D(1., 0.) # move the object one unit to the right
            
    screen.fill((205, 200, 115))
    
    rect = Rect((sprite_counter * 64, 0), (64, 64)) # the rectangle object used to clip the sprite area 
    game_sprite = GameSprite(robot_sprite_sheet, rect, flip)
    game_sprite_surface = game_sprite.getImage() # get the sprite surface
    
    player_draw_pos = Vector2D(player_pos.x-w/2, player_pos.y-h/2)
    screen.blit(game_sprite_surface, player_draw_pos)
    
    #increase the sprite counter after x numbers of frame
    if(game_frame % 30 == 0):
        sprite_counter += 1
        
        if(sprite_counter > 5):
            sprite_counter = 0
            
    game_frame += 1
    
    time_passed = clock.tick()
    time_passed_seconds = time_passed / 1000.0
            
    player_pos+= v * player_speed * time_passed_seconds   
    
    pygame.display.flip()

Now run the above module and press the left or right arrow key to see how the game character flip and move around.

How to create a stand still sprite animation with Pygame

In order to create a stand still sprite animation with Pygame we need to

  1. Create a GameSprite object which will take in the spritesheet and processes it then return a surface of the sprite which can then be used in the screen.blit method.
  2. Create a rectangle object which will be used to clip the area of the spritesheet.
  3. Create a mechanism which will change the sprite image as well as only change to the new sprite image after x numbers of frame so the sprite will not change that fast on the screen!

Before we start make sure you have created your own spritesheet with each sprite consists of 64px width and 64px height. Below is the spritesheet I have used in this tutorial, I am only using six out of the seven sprite from below spritesheet because the last sprite which is the jumping sprite is not required in this tutorial.

Animated Pygame Spritesheet
Pygame Spritesheet

Below is the GameSprite module which will be used in our next pygame module.

import pygame

class GameSprite(object):
    
    def __init__(self, image, rect):
        self.image = image
        self.rect = rect
        self.sprite = pygame.image.load(image).convert_alpha()
        
    def getImage(self): # this method will return a subsurface which is a portion of the spritesheet
        self.sprite.set_clip(self.rect) # clip a portion of the sprite with the rectangle object
        return self.sprite.subsurface(self.sprite.get_clip())

We can use the above module in this next module to create a stand still animation sprite.

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit
from vector2d import Vector2D
from game_sorite import GameSprite

robot_sprite_sheet = 'left.png'

pygame.init()

screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Pygame Demo")

w, h = 64, 64 # width and height of the sprite
sprite_counter = 0 # initialize the sprite_counter
game_frame = 0 # initialize the game_frame counter

player_pos = Vector2D(320, 240) # initialize the position of the sprite

while True:
   
    for event in pygame.event.get():
        
        if event.type == QUIT:
            exit()
            
    
    screen.fill((205, 200, 115))
    
    rect = Rect((sprite_counter * 64, 0), (64, 64)) # the rectangle object uses to clip the sprite area 
    game_sprite = GameSprite(robot_sprite_sheet, rect)
    game_sprite_surface = game_sprite.getImage() # get the sprite surface
    
    player_draw_pos = Vector2D(player_pos.x-w/2, player_pos.y-h/2)
    screen.blit(game_sprite_surface, player_draw_pos)
    
    #increase the sprite counter after x numbers of frame
    if(game_frame % 30 == 0):
        sprite_counter += 1
        if(sprite_counter > 5):
            sprite_counter = 0
            
    game_frame += 1
    
    pygame.display.flip()

If you run the above script then you will get the below outcome…

Reference:

1. http://stackoverflow.com/questions/10560446/how-do-you-select-a-sprite-image-from-a-sprite-sheet-in-python

2. The Vector2D module has already been mentioned in the previous post

Playing background music with Pygame

Playing background music with Pygame is relatively simple with just a few lines of code. Before you can start playing a background music you will need to initialize the pygame.mixer interface first.

pygame.init()
pygame.mixer.pre_init(frequency, size, stereo, buffer)

As you can see from above the init method takes in a few parameters.

1) frequency is the sample rate of the audio playback and has the same meaning as the sample rate of music files.
2) size is the size, in bits, of the audio samples for the playback.
3) stereo only has two options : 1 for mono sound or 2 for stereo sound.
4) buffer is the number of samples that are buffered for playback.

Below is an example of how to initialize the mixer.

pygame.mixer.pre_init(44100, 16, 2, 5000)

In the above example we set the mixer to 16-bit, 44100Hz stereo music.

Now to play the background music all you need is these two lines.

sound1 = pygame.mixer.Sound("music.ogg")
channel1 = sound1.play(-1)

The first line takes the music file and create the sound object. The next line play the background music with an infinite number of time.

The channel object returns by the play method can then be used in other part of the code, for example we can

channel1.queue(sound1)

set up a queue by passing in a sound object which will be played after the main music has stopped.

Journey into PyGame — The beginning

For those python fans, Pygame is indeed a great python’s game engine which you all should really consider if you want to write game using the python language. Although some of you might disagree with my thought but if we remove PyGame from the list of Python’s gaming engine then the only one left for us to consider will be pyglet which is not that well documented as compared to PyGame and thus makes our game development process even harder as compared to using the PyGame engine.

In this article I am going to show you how to install and run your first pygame program with a few lines of python script, ok, without wasting any time let get started.

I have installed python 3.5.2 in my computer and thus I will need to install the PyGame version which matches my python version. In order to install PyGame which matches Python 3.x you will need to visit this PyGame download page. Although my computer’s os belongs to windows 64bit but it seems like the 64bit PyGame version is not working due to some unknown reason (either one of the module is missing or the platform is not supported), due to that I have selected the 32bit version instead because it really doesn’t matter either we are installing the 32bit or the 64bit in our 64bit os as long as the os is 64bit then we can either select the 32bit or the 64bit version, however the reverse is not true because if we install the 64bit PyGame in our 32bit pc then we will not be able to use it at all.

I have downloaded this file pygame-1.9.2b1-cp35-cp35m-win32.whl from the above website. The cp35 in the filename means python 3.5 and win32 means it is for 32bit of windows os. After I have downloaded this file I will need to install it either with pip or pip3 or pip3.5. Browse to the folder where you have downloaded the whl file in the windows command prompt then type in this command : pip3 install pygame-1.9.2b1-cp35-cp35m-win32.whl to extract and then install the PyGame module into Python’s site package folder.

Next create a new project in NetBeans 8.1 IDE and then create a new python module with any name you like and enter below script into it. If you want to know how to use PyGame in your python program then you can visit the PyGame official homepage for further detail.

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit

background_image = 'terain7.png'

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Pygame Demo")
background = pygame.image.load(background_image).convert()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    screen.blit(background, (0,0))
    pygame.display.update()

You will also need to provide a background image (terain7.png) in the same folder as your gaming module in order for the display to show that image. Now run the script and you should see the below pop up with any background image which you have included together with your gaming module.

Pygame
Pygame

Pygame engine starts slowly which is a common problem for all the python programs but once it is ready then it will operate smoothly!