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

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

Create a base class and a subclass

If we want to create the same type of game entity over and over again (for example we need to create lots of enemy robot in our game) then it is better for us to create a base class first and then create the subclass from that base class. The subclass will have all the methods and properties from it’s base class plus it’s own method and property.

The base class on the other hand will derive from the python object class.

class GameEntity(object):
    
    def __init__(self, entity_id):
        self.id = entity_id
        
    def __str__(self):
        return "Entity id is %d" % (self.id)

Below subclass will derive from the base class.

from game_entity import GameEntity

class RobotEntity(GameEntity): 
     def __init__(self, entity_id):
        GameEntity.__init__(self, entity_id)
        self.strength = 50

Please take note that we need to call the __init__ method of the base class with below command.

GameEntity.__init__(self, entity_id)

If you create another module and run it with below script then we will get

from robot_entity import RobotEntity
if __name__ == "__main__":
    robot_entity = RobotEntity(1)
    print(robot_entity)
    print("Robot strength is %s" % robot_entity.strength)

the below outcome.

Entity id is 1
Robot strength is 50

Notice that the first print command above will trigger the __str__ method of the base class (GameEntity class) to return the “Entity id is 1” string which will later get printed out on the screen!