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.

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.

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.

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.

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.

Moving the sprite with Vector in Pygame

In this chapter we are going to use our newly created Vector2D class to move the game sprite within a pygame screen. What we are doing here is to add up a vector with another vector which will then create a new vector that will be use as the sprite’s new position. If the user presses any of these keys on the keyboard : left arrow, right arrow, up arrow or the down arrow key then a new unit vector will be created and by multiplying that unit vector with the speed and time we will get a new vector which can then be added up to the old one and becomes the new position of the sprite object.

#!/usr/bin/env python

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

pygame.init()

boat = 'boat.png'

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

player = pygame.image.load(boat).convert_alpha()

clock = pygame.time.Clock()
player_pos = Vector2D(350, 350)
player_speed = 300.
v = Vector2D(0., 0.)

while True:
   
    for event in pygame.event.get():
        
        if event.type == QUIT:
            exit()
            
    pressed_keys = pygame.key.get_pressed()
        
    if pressed_keys[K_UP]:
        v = Vector2D(0., -1.) 
    elif pressed_keys[K_DOWN]:
        v = Vector2D(0., 1.) 
    elif pressed_keys[K_LEFT]:
        v = Vector2D(-1., 0.) 
    elif pressed_keys[K_RIGHT]:
        v = Vector2D(1., 0.)
            
    screen.fill((255, 255, 255))
    
    player_draw_pos = Vector2D(player_pos.x, player_pos.y)
    screen.blit(player, player_draw_pos)
    
    time_passed = clock.tick()
    time_passed_seconds = time_passed / 1000.0
            
    player_pos+= v * player_speed * time_passed_seconds   
    pygame.display.update()

With that we are almost done with the vector part of the pygame tutorial and ready for the next chapter in pygame so make sure you visit this blog everyday to learn the complete pygame tutorial!

How to detect boundary in Pygame

When we design a game first thing we need to do is to make sure our game character stays within the game boundary. In order to make sure our game character will move within the game boundary we will create a set of rule such as if the top-left corner of that game character moves pass the x or the y boundary of the screen then we will need to reset the coordinate for the top-left corner of that game character accordingly. Below script will create a bouncing ball which will change color randomly and moves within the boundary of the screen.

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

from random import *

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)

clock = pygame.time.Clock()

x, y = 10., 10.
speed_x, speed_y = 100., 90.

circle_radius = 7
circle_pos = (int(x), int(y))


while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    random_color = (randint(100,255), randint(30,255), randint(155,255))
    screen.fill((255, 255, 255))
    
    pygame.draw.circle(screen, random_color, circle_pos, circle_radius)
    
    time_has_passed = clock.tick(30) #return the time delta after each frame
    time_has_passed_in_second = time_has_passed / 1000.0
    
    x += speed_x * time_has_passed_in_second
    y += speed_y * time_has_passed_in_second
    
    # If the ball goes off the edge of the screen,
    # reset it's position and then move it in the opposite direction
    if x > 640 - (circle_radius * 2):
        speed_x = -speed_x
        x = 640 - (circle_radius * 2)
    elif x < 0:
        speed_x = -speed_x
        x = 0.
    if y > 480 - (circle_radius * 2):
        speed_y = -speed_y
        y = 480 - (circle_radius * 2)
    elif y < 0:
        speed_y = -speed_y
        y = 0
        
    circle_pos = (int(x), int(y))
            
    pygame.display.update()

The script above also shows us that we can actually use the pygame.draw module to draw out our gaming character instead of loading graphic into the computer memory.

If you run the above script then you will see the below outcome!

Pygame tutorial 2 – Moving the object with keyboard

Before we start, make sure you have read the first tutorial of creating game in python with pygame, if you not then just go ahead and read the first part of this pygame tutorial series.

In this tutorial I am going to show you how to move the game object within the pygame’s display screen with your keyboard.

In order to move our object within pygame we will need to find out whether the user has pressed a certain key or not from the value of the event’s key property and also we will only move our character if the user is continue pressing that key.

Below is the entire python script to move a boat in the right or the left direction on the display screen. The display portion of the script is almost the same as the previous one but with an additional loop to retrieve the value of the event’s key property (in this example the left or the right arrow key on your keyboard) as well as to detect whether you are continue pressing that key or have already released it, if you have released the key then the direction will again set to zero which means no movement will be made by that object at the moment or else the object will move to either left or the right by 0.05 unit (if you pressed the left arrow key then the boat will move left or else it will move right if right arrow key is pressed).

#!/usr/bin/env python

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

background_image = 'terain7.png'
boat = 'boat.png'

pygame.init()
SCREEN_SIZE = (500, 500)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
pygame.display.set_caption("Pygame Demo")
background = pygame.image.load(background_image).convert()
player = pygame.image.load(boat).convert_alpha()

x, y = 150, 353
MOVE_RIGHT = 1
MOVE_LEFT = 2
direction = 0

while True:
   
    for event in pygame.event.get():
        
        if event.type == QUIT:
            exit()
            
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                direction = MOVE_LEFT
            elif event.key == K_RIGHT:
                direction = MOVE_RIGHT
                
        elif event.type == KEYUP:
            if event.key == K_LEFT:
                direction = 0
            elif event.key == K_RIGHT:
                direction = 0
                
        
    if(direction == MOVE_LEFT):
        x-=0.05
    elif(direction == MOVE_RIGHT):
        x+=0.05
    
    screen.blit(background, (0, 0))
    screen.blit(player, (x, y))
    pygame.display.update()

Run the above script in NetBeans 8.1 and you will see the below outcome.

If you are interested in pygame then don’t miss my daily pygame tutorial because starting from today I will write one to three posts per day on pygame so do visit this blog everyday and master the entire pygame tutorial within a week!

How to create a python class

In this tutorial I am going to show you how to create a class in python and then create an instance object from that class. What we want here is to create a python class which will receive the name, job, salary and a boolean parameter which indicates whether that person has changed his or her job recently or not so the default __str__ method from that class will return different string based on that boolean value. OK let get started.

This time I will use eclipse to write the python script but you can use other IDE such as NetBeans 8.1 as well if you want to, both Eclipse and NetBeans are the top IDE I use to write the python script. Before you can create a python project in Eclipse make sure you have installed the PyDev plugin through Help->Install New Software.

Install PyDev
Install PyDev

If you have not yet installed the PyDev plugin before then click on the Add button and provide a name together with this link http://pydev.org/updates to download and install the PyDev plugin.

Once you have installed the plugin in Eclipse you can now go to File->New->PyDev project and create a new python project just like how you create other project in Eclipse.

I will leave you to create the new project with Eclipse and concentrate on the main topic which is how to create a python class.

After creating a package within that project you can now create a new module calls personaldata.py and enter the below script into it.

class PersonalData(object):

        def __init__(self, name, work, earning = 0, change = False):
            self.name = name
            self.work = work
            self.earning = earning
            self.change = change
        
        def __str__(self):
            if(self.change == False):
                return "%s works as a %s and he has a monthly income of %s" % (self.name, self.work, self.earning)
            else:
                return "%s now works as a %s and he has a monthly income of %s" % (self.name, self.work, self.earning)
        
        def changeJob(self, work, income, change = False):
            self.work = work
            self.earning = income
            self.change = change

Every python class needs to have an __init__ method where self is the first parameter which will be automatically passed into the method, self is very important because the instance of that class will use this parameter to call a method or to access a variable of that object.

The rest of the parameters will be passed in at the time you create a new instance of that class. You can also set the default value for each parameter so that instance can use any of those values if any of those values has not been passed into the class at the time you create an instance of that class. The same goes to the class’s method as well.

Now let us create the main python module which will include the PersonalData’s class instance in it. Let create a new python module and name it runmyclass.py. Now you should see those two python modules under the same package.

Folder Tree
Folder Tree

Next enter below script into the runmyclass.py module…

from personaldata import PersonalData

if __name__ == '__main__':
    
    personalData = PersonalData("John", "computer programmer","1000")
    print (personalData)
    personalData.changeJob("project manager", "3000", True)
    print (personalData)

As you can see you will need to import the PersonalData class into this module before you can use it.

If you want to run any python module then you will need this line of statement,

if __name__ == ‘__main__’

make sure you do that.

Next let create an instance of the PersonalData class and enter the second, third and fourth parameter into it, you do not need to enter the fifth parameter if you don’t want to because it already has a default boolean value which is False.

Now you can call the print method and pass in that new instance, what will happen here is this instance will call it’s own __str__ method and return a string based on the boolean value you have passed in, in this example when we first create the new instance Mr. John has not changed his job yet so change = False.  We can overwrite the __str__ method and return any string that we wish to in this program.

We then call the changeJob method and pass three parameters into that method, the last one will be used as the boolean value to decide which string should we return this time.

The program above will produce the below output.

Python Class Demo
Python Class Demo

That is it for this tutorial, as you can see creating class in python is not that hard after all, right? If you are interested in learning more about class in python then continue to read this tutorial Create an inner class in python language.

How to write python program in windows command prompt

After you have installed python in your computer, you can either use NetBeans 8.1 or Eclipse or any other IDE to write the python script then run it. However, for some of you who do not have any IDE installed on your computer then you might want to consider using the windows command prompt which is also good for writing simple python program if you know how to use it.

With Python installed on your pc lets open up the command prompt, then type in python to start the python shell, then from there you can start to type in the python script then run the program.

Lets write a simple python script to sort a list as follow, you will need to press the enter key each time you have completed a line.

windows command prompt
windows command prompt

The script above will sort the data in ascending order.

As you see we can use windows command prompt to write and run the python script easily, but for the complicated program which requires us to debug and change the script rapidly then we will need to use the real IDE such as NetBeans or Eclipse.