Creating rock on the screen with Pygame

Starting from this chapter I will no longer posting script on the article but just to let you know what is the progress I have made in this game. This is an open source game so at the end of this project I will upload the game as well as all the source code online for you to download, so don’t worry about it!

Basically what I have accomplished today is to create a RockSprite module and then use this module to create as many as 30 rocks on the screen which will move toward the ships. The player can now use the ship to intercept the rock as mentioned earlier in my previous article.

from game_sprite import GameSprite
from pygame.locals import *
from vector2d import Vector2D

class RockSprite(GameSprite):
    
    # Constructor. Pass in the image file
    # and it's width and height and the position on the spritesheet
    def __init__(self, image, width, height, pos, world):
        # Call the parent class constructor
        GameSprite.__init__(self, image, width, height, pos)
        
        self.world = world
        self.rock_health = 100
        
    def updatePosition(self): 
        self.pos += Vector2D(0.0, 0.1)
        #if the rock get passed the boundary then remove it
        if(self.pos.y > 560):
            self.world.removeRockEntity(self)
        else:
            #else create the new rectangle object of that rock
            self.rect = Rect(self.pos.x - self.width/2, self.pos.y - self.height/2, self.width, self.height) #self.rect will be called by the rock group

After the first ship has intercepted the rock the second ship will intercept it again to destroy it, the next thing I will need to do is to create a state engine for this game, see you tomorrow!

Create the spaceship in Rock Sweeper

In this chapter we are going to create two spaceships, one in front and one at the back. The first thing we need to do here is to create a spritesheet as shown below.

spritesheet
spritesheet

The spritesheet above consists of a spaceship with the width and height of 32px at spritesheet’s coordinate (0,0) as well as a rock (16px x 16px) at coordinate (32,0) and background image at the spritesheet’s coordinate of (0, 32). Import the above spritesheet into the project folder.

The next thing we need to do is to import the previous Vector2D module into our game project folder so we can use it later.

Then we will import the previous GameSprite module into our project as well then change a few lines of script.

import pygame
from pygame.locals import *
from vector2d import Vector2D

class GameSprite(pygame.sprite.Sprite):

    # Constructor. Pass in the image file
    # and it's width and height and position on the spritesheet
    def __init__(self, image, width, height, pos):
        # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self)
        
        #register the width and height of the sprite
        self.width = width
        self.height = height
        #use the radius to detect overlap
        self.radius = self.width/4

        # Create the spritesheet surface from the image file
        self.sprite = pygame.image.load(image).convert_alpha()
        
        #the rectangle object uses in clipping
        self.clip_rect = Rect((pos.x, pos.y), (self.width, self.height))
        
        self.sprite.set_clip(self.clip_rect) # clip a portion of the spritesheet with the rectangle object
        self.image = self.sprite.subsurface(self.sprite.get_clip()) #create sprite surface
        
        self.pos = Vector2D(0,0) #initialize the original position of the sprite 
        
        #initialize the id of sprite
        self.entity_id = 0
        
    def updatePosition(self, pos): 
        pass

Next we will create a subclass for the ship based on the GameSprite module above.

from game_sprite import GameSprite
from pygame.locals import *

class ShipSprite(GameSprite):
    
    # Constructor. Pass in the image file
    # and it's width and height and the position on the spritesheet
    def __init__(self, image, width, height, pos):
        # Call the parent class constructor
        GameSprite.__init__(self, image, width, height, pos)
        
    def updatePosition(self, pos): 
        
        #make sure the ship stays within the boundry of the screen
        if(pos.x - self.width/2 < 0):
            pos.x = self.width/2
        elif(pos.x + self.width/2 >= 550):
            pos.x = 550 - self.width/2
        
        self.rect = Rect(pos.x - self.width/2, pos.y - self.height/2, self.width, self.height) #self.rect will be called by group

Next add a few lines of script into the World module which we have created previously.

from pygame.locals import *
from pygame.sprite import Group

class World(object):
    
    def __init__(self, maintile, background_coordinate, screen_size):
        
        #main spritesheet surface
        self.spritesheet = maintile
        
        #game entities dict to store all the game entities
        self.entities = {}
        
        #create a ship group
        self.ship_group = Group()
        
        #initialize the id of the first entity
        self.entity_id = 0
        
        #the rectangle object uses in clipping the background area
        self.clip_rect = Rect(background_coordinate, screen_size)
        self.spritesheet.set_clip(self.clip_rect) # clip a portion of the spritesheet with that rectangle object
        self.background = self.spritesheet.subsurface(self.spritesheet.get_clip()) #create the background surface 
       
    def render(self, surface):
         
        surface.blit(self.background, (0,0)) #blit the background to the pygame screen
        self.ship_group.draw(surface) #blit the ships to the pygame screen
        
    def addEntity(self, entity):
        self.entities[self.entity_id] = entity
        entity.entity_id = self.entity_id
        self.ship_group.add(entity)
        self.entity_id += 1
        
    def updateShipPosition(self, ship_one_pos, ship_two_pos):
        self.entities[0].updatePosition(ship_one_pos)
        self.entities[1].updatePosition(ship_two_pos)

Finally run the main module…

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit
from world import World
from vector2d import Vector2D
from ship_sprite import ShipSprite

maintile = 'maintile.png' #spritesheet file

SCREEN_SIZE = (550, 550) 
BACKGROUND_COORDINATE = (0, 32)

screen_w, screen_h = SCREEN_SIZE

pygame.init()

screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
pygame.display.set_caption("Rock Sweeper")

spritesheet = pygame.image.load(maintile).convert_alpha() #spritesheet surface object

pygame.display.set_icon(spritesheet) #use the entire spritesheet surface as the window icon

world = World(spritesheet, BACKGROUND_COORDINATE, SCREEN_SIZE) #initialize the World object

clock = pygame.time.Clock() # initialize the clock object
game_speed = 70. # game speed per second

#width and height of the ship
w, h = 32, 32

#ship sprite left top position within maintile
pos = Vector2D(0, 0)

#create the first ship and add to group
ship_one = ShipSprite(maintile, w, h, pos)
ship_one.pos = Vector2D(screen_w/2-w, screen_h-h-h-h-h) 
world.addEntity(ship_one)

#create the second ship and add to group
ship_two = ShipSprite(maintile, w, h, pos)
ship_two.pos = Vector2D(screen_w/2-w-w, screen_h-h-h-h)
world.addEntity(ship_two)

while True:
   
    for event in pygame.event.get():
        
        if event.type == QUIT:
            exit()  
    
    #reset the speed to zero for both sjips
    v = Vector2D(0.0, 0.0)
    v1 = Vector2D(0.0, 0.0)
            
    pressed_keys = pygame.key.get_pressed() # get all the keys from key-press events 
        
    if pressed_keys[K_LEFT]: 
        v = Vector2D(-1., 0.) # move the top ship one unit to the left
        v1 = Vector2D(1., 0.) # move the bottom ship one unit to the right
        
    elif pressed_keys[K_RIGHT]:
        v = Vector2D(1., 0.) # move the top ship one unit to the right
        v1 = Vector2D(-1., 0.) # move the bottom ship one unit to the left
    
    world.updateShipPosition(ship_one.pos, ship_two.pos)
    world.render(screen) #render the game background and all the game entities 
    
    time_passed = clock.tick() #delta time for each frame
    time_passed_seconds = time_passed / 1000.0
    
    #re-adjust the position for both ships
    ship_one.pos+= v * game_speed * time_passed_seconds  
    ship_two.pos+= v1 * game_speed * time_passed_seconds
    
    pygame.display.flip()

One thing to take note here is that the world object will be used to control all the game entities as well as the background from here onward.

Create the World module for Rock Sweeper

Welcome to the second chapter of the Rock Sweeper project, a game which creates with Pygame. In this article we will create a World module which will later be used to manage game entities such as spaceship and rock as well as render the background image of the game.

We will use NetBeans IDE 8.1 to create this game, first open up your NetBeans IDE if you already have one or else you can refer to my previous article on how to install the NetBeans IDE on your computer. Start a new project and call it Rock Sweeper.

pygame's project
pygame’s project

Create an empty module under the same folder as the existing module and named it World. Below is the script for the World module which includes those use to blit the background.

from pygame.locals import *

class World(object):
    
    def __init__(self, maintile, background_coordinate, screen_size):
        
        #spritesheet
        self.spritesheet = maintile
        
        #the rectangle object uses in clipping the background area
        self.clip_rect = Rect(background_coordinate, screen_size)
        self.spritesheet.set_clip(self.clip_rect) # clip a portion of the spritesheet with that rectangle object
        self.background = self.spritesheet.subsurface(self.spritesheet.get_clip()) #create the background surface 
       
    def render(self, surface):
        surface.blit(self.background, (0,0))

In the main module we will call the World module to render the background within the while loop.

#!/usr/bin/env python

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

maintile = 'maintile.png' #spritesheet file

SCREEN_SIZE = (550, 550) 
BACKGROUND_COORDINATE = (0, 32)

pygame.init()

screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
pygame.display.set_caption("Rock Sweeper")

spritesheet = pygame.image.load(maintile).convert_alpha() #spritesheet surface object

pygame.display.set_icon(spritesheet) #use the entire spritesheet surface as the window icon

world = World(spritesheet, BACKGROUND_COORDINATE, SCREEN_SIZE)

while True:
   
    for event in pygame.event.get():
        
        if event.type == QUIT:
            exit()
            
    world.render(screen) #render the background
    
    pygame.display.update()

If you run the main module above then you will see the below outcome.

blit background
blit background

The next chapter we will create game entities such as spaceship and rock so make sure you continue reading the tutorial!

The concept behind the Rock Sweeper game

Hi, this is the first chapter of create a game in pygame and in this part I am going to talk a little bit about the game I am going to create before we start coding in the next chapter!

The game concept:

Imagine two spaceships are exploring another planet and suddenly there are lot of rocks heading toward them, the only method for them to survive is to intercept and destroy those rocks.

How to destroy the rock:

The front ship will intercept the rock for the first time and the second ship will further intercept that same rock to destroy it, after a rock has been destroyed, the player will be rewarded with 1 point. The player also needs to make sure that the second ship will not intercept the rock before that rock has been intercepted by the first ship or else it will be game over!

How many levels are there:

There are 10 levels in this game and in each level the player is requires to destroy a certain number of rock before he can proceed to the next stage.

Total 10 Level
Total 10 Level

How to control the game:

Use the left and right arrow key to move the front and the back ship to the left and to the right. If the front ship is moving toward the left then the back ship will automatically move toward the right.

This is the desktop version of the game:

This game is actually derives from the browser game which I have developed recently and you can play the browser’s version of this game online through the Rock Sweeper online page!

Alright, after a simple introduction we are now ready to create the game begin on the next chapter.

Pygame ready made Vector2 module

If you are following this tutorial from the beginning you know that I have created a Vector2D module to help the game character to accomplish various tasks such as moves to a certain coordinate point on the game screen and so on but do you know that actually you do not need to create the Vector2D module if you do not want to because there is already a ready made Vector2 module in Pygame which will do most of the jobs above for us. This Vector2 module is under the pygame.math package so if we want to extend the features of this module then all we need to do is just to create a subclass based upon that Vector2 module. I will make the previous Vector2D module as the subclass of this Vector2 module when I create my next game with Pygame if I ever need to!

With the introduction of the Vector2 module above we have finally finished our pygame tutorial series for beginner and as I have promised to my reader before I will start to create a real game with Pygame where you will be able to read every step I have made in order to create this new game. So make sure that you subscribe and continue reading my blog if you want to learn how to develop your own game with Pygame. See you in the next tutorial!

The most advance sprites overlapping detection method from Pygame

When it comes to sprites overlap detection rectangle detection method is not as accurate as circle detection method and circle detection method is less accurate than the bitmasks detection method. According to the Pygame wiki page this is what the bitmasks method does and what it needs to detect the overlapping between two sprites.

Tests for collision between two sprites, by testing if their bitmasks overlap. If the sprites have a “mask” attribute, that is used as the mask, otherwise a mask is created from the sprite image. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a “rect” and an optional “mask” attribute.

You should consider creating a mask for your sprite at load time if you are going to check collisions many times. This will increase the performance, otherwise this can be an expensive function because it will create the masks each time you check for collisions.

If you want to create the mask attribute then all you need is this line of command

sprite.mask = pygame.mask.from_surface(sprite.image)

where sprite.image is the surface of the game sprite. Then you will use this command to check the overlapping between two sprites

pygame.sprite.collide_mask(left_sprite, right_sprite)

where the left_sprite and the right_sprite is the sprite object you wish to check for overlapping, the method above will return the first point on the mask where the overlapping occurs or None if there was no overlapping.

One thing you need to take note of is if you are using the spritesheet to animate the sprite object instead of a single image then you should use the circle detection method instead because you will need to create different sprite surface object as well as different mask attribute which is really against the game’s performance if you go with the bitmask method above. Otherwise use the bitmasks method will result in the most precise overlapping detection as compared to the rectangle and the circle detection method!

Detect overlapping more accurately with circle detection method

In the previous tutorial we are using the rectangle area of the sprite to detect the overlapping between two sprite objects but today we will use the circle area to detect the above mentioned event instead which is more accurate as compared to the rectangle detection method because we can simple adjust the radius of the circle accordingly to achieve the best affect!

In order to use the circle detection method we will need to include a new radius attribute in the GameSprite module which will now replace the rect attribute uses to detect the sprite overlapping event (you can still use the rect attribute if you want to but the outcome will be the same as the rectangle detection method).

Below is the only line of code we have to add in under def __init__(self, image, width, height) of GameSprite module.

#use to detect overlap
self.radius = width/4

By providing the radius attribute and then set it to 1/4 of the sprite width we now don’t even need to recalculate the Rect object after each position update of the sprite and therefore we can comment out the below lines of code under detectCollide(self, right, player_draw_pos, enemy_draw_pos)

#self.rect = Rect(player_draw_pos.x, player_draw_pos.y, self.width, self.height)
#right.rect = Rect(enemy_draw_pos.x, enemy_draw_pos.y, right.width, right.height)

Under the same method above we will now change the overlapping detection method from pygame.sprite.collide_rect(self, right) to pygame.sprite.collide_circle(self, right) and that is all we need.

Now if you run the main game module you will notice that the overlapping only occurs when the enemy get closed enough to the player as compared to the previous method where the enemy will be removed even it looks like the enemy is still some distance apart from the player.

Scale your gaming character with Pygame

Pygame offers the pygame.transform module which we can use to rotate, flip as well as scale the gaming character as we wish to and today I am going to show you how to scale down the gaming character with the pygame.transform.scale method. The pygame.transform.scale method is really simple to use, all we need is a surface, and a tuple contains both the scale width and scale height, there is another third parameter in the method which is the optional destination surface but we usually do not need it in most of the scenario so we can leave it alone at the moment. Here is how to scale a game character to a new dimension.

self.image = pygame.transform.scale(self.image, (32, 32)) #this method takes in a surface plus a tuple contains both the scale width and the scale height and it returns a new surface which will be assigned to the self.image

The method above should be included under the setImage method of the GameSprite module which we have created in the previous tutorial and we will only apply it if the enemy and the player has overlapped each other. Below video will show you how the player will be scaled to smaller size after it has overlapped with the enemy.

Group all the sprites together with Pygame

In the last tutorial we have created two sprite objects and then render it on the screen with the help of the GameSprite module, in this tutorial we will further modify the GameSprite module so it can be used by the pygame.sprite.Group module later on. With the use of the pygame.sprite.Group module we can easily remove a sprite from the screen once it has overlapped with another sprite. The first thing we need to do in our today tutorial is to modify the GameSprite module so it will contain the image and the rect attributes that will be used later on by the Group module.

import pygame
from pygame.locals import *

class GameSprite(pygame.sprite.Sprite):

    # Constructor. Pass in the image file
    # and it's width and height
    def __init__(self, image, width, height):
        # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self)

        # Create the spritesheet surface from the image file
        self.sprite = pygame.image.load(image).convert_alpha()
        
        #register the width and height of the sprite
        self.width = width
        self.height = height
        
    def setImage(self, x_sprite, y_sprite, flip, player_draw_pos): # this method will return a subsurface which represents a portion of the spritesheet
    
        #the rectangle object uses in clipping
        self.clip_rect = Rect((x_sprite, y_sprite), (self.width, self.height))
        
        self.sprite.set_clip(self.clip_rect) # clip a portion of the spritesheet with the rectangle object
        sub_surface = self.sprite.subsurface(self.sprite.get_clip()) #create sub surface
        self.image = pygame.transform.flip(sub_surface, flip, False) #self.image will be called by group
        self.rect = Rect(player_draw_pos.x, player_draw_pos.y, self.width, self.height) #self.rect will be called by group
    
    def detectCollide(self, right, player_draw_pos, enemy_draw_pos): #return a boolean value indicates whether the player has collided with enemy or not
        # create the rectangle object for both enemy and player that will be used in the collide_rect function
        self.rect = Rect(player_draw_pos.x, player_draw_pos.y, self.width, self.height)
        right.rect = Rect(enemy_draw_pos.x, enemy_draw_pos.y, right.width, right.height)
        return pygame.sprite.collide_rect(self, right)

The only method which we need to change is the getImage method, first of all we will change the name of the method to setImage because this method no longer returned the sprite surface, we have also removed the return sub surface command and include a new player_draw_pos which is the Vector2D object parameter into the method. With that new parameter we can then create the new rect attribute each time the object has moved to a new position. We have also created a new image attribute on each iteration of the pygame while loop. The Group module will need the above two attributes to blit the sprite to the screen surface.

The next thing we need to do is to modify the main module a little, this time we will remove the enemy sprite once it has overlapped with the player sprite with the remove method from the Group module.

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit
from vector2d import Vector2D
from game_sprite import GameSprite
from pygame.sprite import Group

robot_sprite_sheet = 'left.png'

pygame.init()

screen = pygame.display.set_mode((640, 480), 0, 32) #return a screen surface with desire screen size
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

#direction control for player
flip = False

#direction control for enemy
face_left = True

clock = pygame.time.Clock() # initialize the clock object
player_pos = Vector2D(30, 240) # initial position of the player sprite
enemy_pos = Vector2D(450, 240) # initial position of the enemy sprite
game_speed = 70. # speed per second

#create the player sprite 
game_sprite = GameSprite(robot_sprite_sheet, w, h)

#the enemy sprite object
game_sprite_two = GameSprite(robot_sprite_sheet, w, h)

#create new sprite group
sprite_group = Group(game_sprite)
sprite_group.add(game_sprite_two)

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 sprite 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 sprite object facing right
        v = Vector2D(1., 0.) # move the object one unit to the right
            
    screen.fill([255,255,255])
    
    player_draw_pos = Vector2D(player_pos.x-w/2, player_pos.y-h/2)#set the new player position
    game_sprite.setImage(sprite_counter * 64, 0, flip, player_draw_pos) # set the new player sprite surface
    #screen.blit(game_sprite_surface, player_draw_pos)
    
    enemy_draw_pos = Vector2D(enemy_pos.x-w/2, enemy_pos.y-h/2)#set the new enemy position
    if(sprite_group.has(game_sprite_two)):
        game_sprite_two.setImage(sprite_counter * 64, 0, face_left, enemy_draw_pos) # set the new enemy sprite surface
    #screen.blit(game_sprite_surface_two, enemy_draw_pos)
    
    #blit the sprites to the pygame screen within group
    sprite_group.draw(screen)
    
    #increase the sprite counter after x numbers of frame
    if(game_frame % 50 == 0):
        
        sprite_counter += 1
        
        if(sprite_counter > 5):
            sprite_counter = 0
            
    game_frame += 1
    
    time_passed = clock.tick() #delta time for each frame
    time_passed_seconds = time_passed / 1000.0
       
    #set the player's new position after each frame
    player_pos+= v * game_speed * time_passed_seconds   
    
    #if the enemy collides with the player, remove the enemy, else continue to move left
    if(sprite_group.has(game_sprite_two)):
        if(game_sprite.detectCollide(game_sprite_two, player_draw_pos, enemy_draw_pos)):
            sprite_group.remove(game_sprite_two)
        
        elif(face_left == True):
            enemy_pos += Vector2D(-1., 0.) * game_speed * time_passed_seconds 
    
    pygame.display.flip()

With the introduction of the Group module into our game we can now easily add or remove sprite into or from one group and blit those sprites to the screen surface with just one line of code.

Detect the overlapping between two game objects with Pygame

Pygame has a a few great interfaces that we can use to detect whether game character has overlapped each other or not and today we are going to look at one of them which is the pygame.sprite.collide_rect method. This method will take in two sprite objects that will then be used to find out the condition of the overlap. If no overlap happens then the above method will return False or else it will return True.

The script below is not perfect because it will only detect the overlapping once in the entire game and moves the enemy sprite in the opposite direction after the first overlapping occurs. This program is uses just to demonstrate to you how the above mentioned method works.

First thing we need to do before going into the main module is to modify the previous GameSprite module by making it a subclass of the pygame.sprite.Sprite class and then change it’s getImage method so we do not need to create a new GameSprite object on every loop pass just like before. Finally we will include a new detectCollide method which will return a boolean value indicates whether two sprite have overlapped each other or not.

import pygame
from pygame.locals import *

class GameSprite(pygame.sprite.Sprite):

    # Constructor. Pass in the image file
    # and it's width and height
    def __init__(self, image, width, height):
        # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self)

        # Create the spritesheet surface from the image file
        self.sprite = pygame.image.load(image).convert_alpha()
        
        #register the width and height of the sprite
        self.width = width
        self.height = height
        
    def getImage(self, x_sprite, y_sprite, flip): # this method will return a subsurface which represents a portion of the spritesheet
    
        #the rectangle object uses in clipping
        self.clip_rect = Rect((x_sprite, y_sprite), (self.width, self.height))
        
        self.sprite.set_clip(self.clip_rect) # clip a portion of the spritesheet with the rectangle object
        sub_surface = self.sprite.subsurface(self.sprite.get_clip()) #create sub surface
        return pygame.transform.flip(sub_surface, flip, False) #return a new flip surface
    
    def detectCollide(self, right, player_draw_pos, enemy_draw_pos): #return a boolean value indicates whether the player has collided with enemy or not
        # create the rectangle object for both enemy and player that will be used in the collide_rect function
        self.rect = Rect(player_draw_pos.x, player_draw_pos.y, self.width, self.height)
        right.rect = Rect(enemy_draw_pos.x, enemy_draw_pos.y, right.width, right.height)
        return pygame.sprite.collide_rect(self, right)

The next thing we need to do is to include the detectCollide method in our main game loop to detect the overlapping of two objects.

#!/usr/bin/env python

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

robot_sprite_sheet = 'left.png'

pygame.init()

screen = pygame.display.set_mode((640, 480), 0, 32) #return a screen surface with desire screen size
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

#direction control for player
flip = False

#direction control for enemy
face_left = True

clock = pygame.time.Clock() # initialize the clock object
player_pos = Vector2D(30, 240) # initial position of the player sprite
enemy_pos = Vector2D(450, 240) # initial position of the enemy sprite
game_speed = 70. # speed per second

#create the player sprite 
game_sprite = GameSprite(robot_sprite_sheet, w, h)

#the enemy sprite object
game_sprite_two = GameSprite(robot_sprite_sheet, w, h)

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 sprite 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 sprite object facing right
        v = Vector2D(1., 0.) # move the object one unit to the right
            
    screen.fill((205, 200, 215))
    
    #blit the player with new position
    player_draw_pos = Vector2D(player_pos.x-w/2, player_pos.y-h/2)
    game_sprite_surface = game_sprite.getImage(sprite_counter * 64, 0, flip) # get the new sprite surface
    screen.blit(game_sprite_surface, player_draw_pos)
    
    #blit the enemy with new position
    enemy_draw_pos = Vector2D(enemy_pos.x-w/2, enemy_pos.y-h/2)
    game_sprite_surface_two = game_sprite_two.getImage(sprite_counter * 64, 0, face_left) # get the new sprite surface
    screen.blit(game_sprite_surface_two, enemy_draw_pos)
    
    #increase the sprite counter after x numbers of frame
    if(game_frame % 50 == 0):
        
        sprite_counter += 1
        
        if(sprite_counter > 5):
            sprite_counter = 0
            
    game_frame += 1
    
    time_passed = clock.tick() #delta time for each frame
    time_passed_seconds = time_passed / 1000.0
       
    #set the player's new position after each frame
    player_pos+= v * game_speed * time_passed_seconds   
    
    #if player collides with enemy, enemy flips and changes it's direction
    if(game_sprite.detectCollide(game_sprite_two, player_draw_pos, enemy_draw_pos)):
        face_left = False
    
    if(face_left == True):
        enemy_pos += Vector2D(-1., 0.) * game_speed * time_passed_seconds 
    else:
        enemy_pos += Vector2D(1., 0.) * game_speed * time_passed_seconds
    
    pygame.display.flip()

By running the above module you will see that after a contact has occurred the enemy sprite will move in the opposite direction.


pygame.sprite.collide_rect method