Game Manager Class and the modify version of the main pygame file

Finally I have finished linking everything together and get ready for the next stage. Here is the Game Manager class which is the only class we need in the main pygame project file. This class contains everything we need to control game objects, play background music and render the game graphics on the game scene.

from Player import Player
from Background import Background
from MissileManager import MissileManager
import pygame

class GameManager(object):

    def __init__(self, scene):

        self.scene = scene
        self.player = Player(self.scene)
        self.background = Background(self.scene)
        self.missile_manager = MissileManager(self.scene, self.player)
        self.load_music()
        self.play_music()

    def load_music(self):
        pygame.mixer_music.load('Music/winternight.ogg')

    def play_music(self):
        pygame.mixer_music.play(-1) #play the music infinite time

    def set_player_x(self, _x):
        self.player.setX(_x)

    def set_player_y(self, _y):
        self.player.setY(_y)

    def set_missile_strike(self, strike):
       self. missile_manager.setStrike(True)

    def update(self):
        self.player.update()
        self.missile_manager.update()

    def draw(self):
        self.background.draw()
        self.player.draw()
        self.missile_manager.draw()
        pygame.display.flip()

No new method has been introduced in this class, what we do is just to group the unorganized code in the previous main pygame file to a single Game Manager class. The main python file now looks really neat because all we need is just a single Game Manager class to control everything. Here is the modify version of the main pygame file.

import sys, pygame
from pygame.locals import *
from GameManager import GameManager

pygame.init()

size = width, height = 660, 660
pygame.display.set_caption("Air Strike") # set the title of the window
screen = pygame.display.set_mode(size)

game_manager = GameManager(screen)

while True:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.mixer_music.stop()
            sys.exit()

        # detect key press event 
        if event.type == KEYDOWN:

            if event.key == K_LEFT:
                game_manager.set_player_x(-0.1)
            elif event.key == K_RIGHT:
                game_manager.set_player_x(0.1)

            if event.key == K_UP:
                game_manager.set_player_y(-0.1)
            elif event.key == K_DOWN:
                game_manager.set_player_y(0.1)

            if event.key == K_SPACE:
                game_manager.set_missile_strike(True)

        elif event.type == KEYUP:
            if event.key == K_LEFT:
                game_manager.set_player_x(0)
            elif event.key == K_RIGHT:
                game_manager.set_player_x(0)

            if event.key == K_UP:
                game_manager.set_player_y(0)
            elif event.key == K_DOWN:
                game_manager.set_player_y(0)

            if event.key == K_SPACE:
                game_manager.set_missile_strike(False)

    game_manager.update()
    game_manager.draw()

In the next few chapters we will create the enemy ship class as well as the explosion class and the game level class which will be used to control the level of the game.

The modify version of the Pygame Missile Manager Class

Before we go ahead and create the Game Manager class we will need to take out all the code which are related to the missile manager in the main python file as shown in the previous article and put them all under a single missile manager class. Here is the modify version of the missile manager class as compared with the previous version.. This class will take in both the scene as well as the player object to start with.

from Missile import Missile
from GameSprite import GameSprite
from pygame.locals import *

class MissileManager(object):

    def __init__(self, scene, player):
        self.scene = scene
        self.player = player
        self.missile_count = 10
        self.missile_list = []
        self.image = 'Asset/missile.png'
        self.width = 20
        self.height = 20
        self.rect = Rect(0, 0, self.width, self.height)
        self.strike = False
        self.strike_again = 0
        # initialize game sprite object
        self.sprite = GameSprite(self.image, self.rect)

    def setStrike(self, strike):

        # set the missile strike flag
        self.strike = strike
        self.strike_again += 1

    def create_missile(self, x, y):
        if(self.missile_count >= 0):
            self.missile_surface = self.sprite.getImage()
            self.missile_list.append(Missile(self.missile_surface, x, y))
            self.missile_count -= 1

    def update(self):
        if (self.strike == True and self.strike_again > 1):
            self.strike_again = 0
            x, y = self.player.get()
            self.create_missile(x + 5, y - 8)  # create more missile
        self.missile_update()
        self.check_boundary()

    def missile_update(self):

        for item in list(self.missile_list):
            if(item.on == False):
                self.missile_list.remove(item)
                self.missile_count += 1
            else:
                item.update()

    def check_boundary(self):
        for i in range(len(self.missile_list)):
            if (self.missile_list[i].y < 0):
                self.missile_list[i].on = False

    def draw(self):

        # blit the missile on  the scene
        for i in range(len(self.missile_list)):
            self.scene.blit(self.missile_list[i].missile_surface, self.missile_list[i].missile_pos)

As you can see we will use a single update method to control both the missile update and the check boundary method. We have also included a new draw method to draw the missiles on the game scene. The missile manager class does not need to return the missile list anymore to the main file so the previous method has been totally removed. Finally we have a set strike method to turn the strike flag on or off depends on whether the space key has been pressed or released.

That is it for this one, now lets us look at the Game Manager class in the next chapter.

Create a background object class in Pygame

In this article we will create the next pygame object class, which is the background object class that will render the background graphic on the game scene, just like the player class in the previous article, background class will take in a scene reference object which will be used by this background class to blit the background graphic on the game scene. It has a very simple draw method which will be called in each game loop to redraw the background game graphic. Here is the entire class.

from BgSprite import BgSprite
from pygame.locals import *
from pygame import math as mt

class Background(object):

    def __init__(self, scene):
        self.scene = scene
        self.image = 'Asset/bg.png'
        self.rect = Rect(0, 0, 660, 660)
        self.sprite = BgSprite(self.image, self.rect)
        self.surface = self.sprite.getImage()  # get the background sprite surface
        self.draw_pos = mt.Vector2(0, 0)

    def draw(self):
        self.scene.blit( self.surface, self.draw_pos) # draw a background sprite

That is it, as simple as it is! Now before we can create our Game Manager class we will need to modify the Missile Manager class we have created previously in the next chapter so it can be called directly by our new Game Manager class later on.

Create a Player object in Pygame

Hello, sorry for not posting any article yesterday because I am very busy with my offline business but today I have a whole day to write more articles and I am going to create three articles for today. First of all, do you people still remember I have mentioned that I will create one single Game Manager to manage all the game objects on the game scene in my previous article? Yes we are going to do that soon, but before we doing that we will need to first create a new class for each game objects on the game scene. In this article we will start to turn our first game object into a class by it’s own, we will create a class for the Player object.

This player object will receive the scene object from the main pygame file which it can then use to blit the player graphic on the scene, besides that it can also receive the key down event and the key up event so it can move the player object to a new location on the game scene with it’s update position method.

Below is the entire Player class, more methods will be added in the future but for now here is it.

from pygame.locals import *
from GameSprite import GameSprite
from pygame import math as mt
import pygame

class Player(object):

    def __init__(self, scene):
        self.image = 'Asset/player.png'
        self.scene = scene
        self.width = 40
        self.height = 40
        self.direction_x = 0
        self.direction_y = 0
        self.rect = Rect(0, 0, self.width, self.height)
        self.sprite = GameSprite(self.image, self.rect)
        self.sprite_surface = self.sprite.getImage()  # get the player sprite surface
        self.bwidth, self.bheight = 660, 660
        self.pos = mt.Vector2(self.bwidth / 2, self.bheight / 2)  # initialize the position of the player sprite
        self.draw_pos = mt.Vector2(self.pos.x, self.pos.y)

        pygame.display.set_icon(self.sprite_surface) # use the same player surface object as the icon for the game window

    def setX(self, _x):

        # set new x position and detect the boundary on the game scene
        self.direction_x = _x

    def setY(self, _y):

        # set new y position and detect the boundary on the game scene
        self.direction_y = _y

    def update(self):

        if(self.direction_x == -0.1):
            if(self.pos.x > 0):
                self.pos.x += self.direction_x
        elif(self.direction_x == 0.1):
            if(self.pos.x + self.width <= self.bwidth):
                self.pos.x += self.direction_x
        if(self.direction_y == -0.1):
            if (self.pos.y > 0):
                self.pos.y += self.direction_y
        elif (self.direction_y == 0.1):
            if (self.pos.y + self.height <= self.bheight):
                self.pos.y += self.direction_y

        self.draw_pos = mt.Vector2(self.pos.x, self.pos.y)

    def get(self):
        return (self.pos.x, self.pos.y)


    def draw(self):
        self.scene.blit(self.sprite_surface,  self.draw_pos)

As you can see, it also has an extra get method which will return the new x and y position of the player object to be used by the missile manager to position the new missile. That is it, we will now move on to create the background object class in the next article.

Create player missile manager and player missile class in Pygame

In this article we will create two classes that will assist the player object to launch missile, they are a player missile class which serves as the missile object and a missile manager class which will manage all the missiles that player has launched. We will tune up these classes later on when the project goes on but for now lets create these two simple classes first.

First is the missile class.

from pygame import math as mt

class Missile(object):

    def __init__(self, missile_surface, x, y):
        self.on = True
        self.missile_surface = missile_surface
        self.x = x
        self.y = y
        self.missile_pos = mt.Vector2(self.x, self.y)

    def update(self):
        self.y -= 1
        self.missile_pos = mt.Vector2(self.x, self.y)

The above class has a update method which will update the position of the missile on every game loop. Now lets create the missile manager class.

from Missile import Missile

class MissileManager(object):

    def __init__(self, game_sprite):
        self.missile_count = 10
        self.game_sprite = game_sprite
        self.missile_list = []

    def create_missile(self, x, y):
        if(self.missile_count >= 0):
            self.missile_surface = self.game_sprite.getImage()
            self.missile_list.append(Missile(self.missile_surface, x, y))
            self.missile_count -= 1

    def check_boundary(self):
        for i in range(len(self.missile_list)):
            if (self.missile_list[i].y < 0):
                self.missile_list[i].on = False

    def missile_update(self):

        for item in list(self.missile_list):
            if(item.on == False):
                self.missile_list.remove(item)
                self.missile_count += 1
            else:
                item.update()

    def get_missile_list(self):
        return self.missile_list

The missile manager class above has four methods, the create missile method will be called every time the player press the spacebar, but before the missile can be created the method will first check and make sure the total missile quantity on the game scene will not exceed a certain amount which is controls by the missile_count variable. After a missile has been created, that missile will then get pushed into a missile list. Each time a missile has been created the total of the missile_count variable will be reduced by one.

The check boundary method will check to see whether a missile has crossed the top game scene boundary or not, if it has then the missile’s on variable will be switched to False.

The missile update method will loop through each missile in the missile list, if the on variable is set to False then that missile will be removed. Each time a missile has been removed the total of the missile_count variable will be increased by one so we can create a new missile again.

The last method is uses to get the updated missile list object which will be used in the main file.

A few changes have been made in the main file, we have called the missile manager class in this main file to create a new missile and update it’s position, besides that we also create a time counter so we will slow down the missile launch process as well as a new missile rectangle object which will be needed in the GameSprite object. After we have called the scene object to blit so many objects on the game scene the code indeed looks little bit unorganized but don’t worry because we will create a new Game Manager object which we can use on the main file that will organize all those game objects.

import sys, pygame
from pygame import math as mt
from pygame.locals import *
from GameSprite import GameSprite
from BgSprite import BgSprite
from MissileManager import MissileManager

pygame.init()

# game asset url
player_sprite = 'Asset/player.png'
bg_sprite = 'Asset/bg.png'
missile_sprite = 'Asset/missile.png'

player_width = 40
player_height = 40

size = width, height = 660, 660
pygame.display.set_caption("Air Strike") # set the title of the window
screen = pygame.display.set_mode(size)

rect_background = Rect(0, 0, player_width, player_height)  # the rectangle object uses to clip the sprite area
game_sprite = GameSprite(player_sprite, rect_background)
game_sprite_surface = game_sprite.getImage()  # get the player sprite surface

pygame.display.set_icon(game_sprite_surface) # use the same player surface object as the icon for the game window

rect_background = Rect(0, 0, 660, 660)
game_bg_sprite = BgSprite(bg_sprite, rect_background)
game_bg_surface = game_bg_sprite.getImage()  # get the background sprite surface

missile_width = 20
missile_height = 20
rect_missile = Rect(0, 0, missile_width, missile_height)

pygame.mixer_music.load('Music/winternight.ogg')
pygame.mixer_music.play(-1)

player_pos = mt.Vector2(width/2, height/2) # initialize the position of the player sprite

player_draw_pos = mt.Vector2(player_pos.x , player_pos.y)
bg_draw_pos = mt.Vector2(0 , 0)

# player logic variables
speed_x = 0.1
speed_y = 0.1
MOVE_RIGHT = 1
MOVE_LEFT = 2
MOVE_UP = 3
MOVE_DOWN = 4
direction_x = 0
direction_y = 0
strike = False
strike_again = 0

#initialize MissileManager object
missile_game_sprite = GameSprite(missile_sprite, rect_missile)
missile_manager = MissileManager(missile_game_sprite)
missile_list_array = None

while True:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.mixer_music.stop()
            sys.exit()

        # detect key press event for the up, down, left and the right key
        if event.type == KEYDOWN:

            if event.key == K_LEFT:
                direction_x = MOVE_LEFT
            elif event.key == K_RIGHT:
                direction_x = MOVE_RIGHT

            if event.key == K_UP:
                direction_y = MOVE_UP
            elif event.key == K_DOWN:
                direction_y = MOVE_DOWN

            if event.key == K_SPACE:
                strike = True
                strike_again += 1

        elif event.type == KEYUP:
            if event.key == K_LEFT:
                direction_x = 0
            elif event.key == K_RIGHT:
                direction_x = 0

            if event.key == K_UP:
                direction_y = 0
            elif event.key == K_DOWN:
                direction_y = 0

            if event.key == K_SPACE:
                strike = False

    # set new position and detect the boundary of the game scene
    if (direction_x == MOVE_LEFT):
        if(player_pos.x > 0):
            player_pos.x -= speed_x
    elif (direction_x == MOVE_RIGHT):
        if(player_pos.x + player_width < width):
            player_pos.x += speed_x

    if (direction_y == MOVE_UP):
        if (player_pos.y > 0):
            player_pos.y -= speed_y
    elif (direction_y == MOVE_DOWN):
        if (player_pos.y + player_height < height):
            player_pos.y += speed_y

    if(strike == True and strike_again > 1):
        strike_again = 0
        missile_manager.create_missile(player_pos.x + 6, player_pos.y - 8) # create more missile


    player_draw_pos = mt.Vector2(player_pos.x, player_pos.y) # the new vector position of the player

    screen.blit(game_bg_surface, bg_draw_pos)
    screen.blit(game_sprite_surface, player_draw_pos)

    # blit the missile on the scene
    missile_list_array = missile_manager.get_missile_list()
    missile_manager.check_boundary()
    missile_manager.missile_update()

    for i in range(len(missile_list_array)):
        screen.blit(missile_list_array[i].missile_surface, missile_list_array[i].missile_pos)

    pygame.display.flip()

Here is the PyCharm file explorer looks like at the moment.

The new file structure
The new file structure

If you run the above main program you will see this outcome.

That is about it for this article, we will create a Game Manager in the next chapter to organize all the game objects on the scene so the code on the main file will be more organize than present.

Detect boundary and respond to key press event in Pygame project

Hello there, in today article we will look at two things in our new pygame project, 1) detect the boundary so the player object will stop at the boundary of the scene and not get passed it. 2) make the player object responds to key press event so it can go up, down, left and right whenever we have pressed the correct key on our keyboard. After this lesson we will look at another key press event in the next chapter, which is when we press the spacebar the player object will launch a missile but for now lets concentrate on the above two events. There is no other file we need to create today where we will concentrate only on the main python file. So go ahead and open up the main python file which we have created together in the previous chapter of this new pygame series tutorial, and do a few modifications on it. First we need to create a few player logic variables to use in our event detection methods.

# player logic variables
speed_x = 0.1
speed_y = 0.1
MOVE_RIGHT = 1
MOVE_LEFT = 2
MOVE_UP = 3
MOVE_DOWN = 4
direction_x = 0
direction_y = 0

Next enter below code under the event detection method to set up two very important variables that we will need in order to move the player object in the left, right, up and down position : direction_x and direction_y.

        # detect key press event for the up, down, left and the right key
        if event.type == KEYDOWN:

            if event.key == K_LEFT:
                direction_x = MOVE_LEFT
            elif event.key == K_RIGHT:
                direction_x = MOVE_RIGHT

            if event.key == K_UP:
                direction_y = MOVE_UP
            elif event.key == K_DOWN:
                direction_y = MOVE_DOWN

        elif event.type == KEYUP:
            if event.key == K_LEFT:
                direction_x = 0
            elif event.key == K_RIGHT:
                direction_x = 0

            if event.key == K_UP:
                direction_y = 0
            elif event.key == K_DOWN:
                direction_y = 0

Finally we will move the player object to the left, right, up or down direction as well as controlling the player object so it will not get passed the game scene boundaries with below code.

    # set new position and detect the boundary of the game scene
    if (direction_x == MOVE_LEFT):
        if(player_pos.x > 0):
            player_pos.x -= speed_x
    elif (direction_x == MOVE_RIGHT):
        if(player_pos.x + player_width < width):
            player_pos.x += speed_x

    if (direction_y == MOVE_UP):
        if (player_pos.y > 0):
            player_pos.y -= speed_y
    elif (direction_y == MOVE_DOWN):
        if (player_pos.y + player_height < height):
            player_pos.y += speed_y

    player_draw_pos = mt.Vector2(player_pos.x, player_pos.y) # the new vector position of the player object

If you run the above program you will get this outcome.

Here are the full source code for the main file.

import sys, pygame
from pygame import math as mt
from pygame.locals import *
from GameSprite import GameSprite
from BgSprite import BgSprite

pygame.init()

# game asset url
player_sprite = 'Asset/player.png'
bg_sprite = 'Asset/bg.png'

player_width = 40
player_height = 40

size = width, height = 660, 660
pygame.display.set_caption("Air Strike") # set the title of the window
screen = pygame.display.set_mode(size)

rect_background = Rect(0, 0, player_width, player_height)  # the rectangle object uses to clip the sprite area
game_sprite = GameSprite(player_sprite, rect_background)
game_sprite_surface = game_sprite.getImage()  # get the player sprite surface

pygame.display.set_icon(game_sprite_surface) # use the same player surface object as the icon for the game window

rect_background = Rect(0, 0, 660, 660)
game_bg_sprite = BgSprite(bg_sprite, rect_background)
game_bg_surface = game_bg_sprite.getImage()  # get the background sprite surface

pygame.mixer_music.load('Music/winternight.ogg')
pygame.mixer_music.play(-1)

player_pos = mt.Vector2(width/2, height/2) # initialize the position of the player sprite

player_draw_pos = mt.Vector2(player_pos.x , player_pos.y)
bg_draw_pos = mt.Vector2(0 , 0)

# player logic variables
speed_x = 0.1
speed_y = 0.1
MOVE_RIGHT = 1
MOVE_LEFT = 2
MOVE_UP = 3
MOVE_DOWN = 4
direction_x = 0
direction_y = 0


while True:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.mixer_music.stop()
            sys.exit()

        # detect key press event for the up, down, left and the right key
        if event.type == KEYDOWN:

            if event.key == K_LEFT:
                direction_x = MOVE_LEFT
            elif event.key == K_RIGHT:
                direction_x = MOVE_RIGHT

            if event.key == K_UP:
                direction_y = MOVE_UP
            elif event.key == K_DOWN:
                direction_y = MOVE_DOWN

        elif event.type == KEYUP:
            if event.key == K_LEFT:
                direction_x = 0
            elif event.key == K_RIGHT:
                direction_x = 0

            if event.key == K_UP:
                direction_y = 0
            elif event.key == K_DOWN:
                direction_y = 0

    # set new position and detect the boundary of the game scene
    if (direction_x == MOVE_LEFT):
        if(player_pos.x > 0):
            player_pos.x -= speed_x
    elif (direction_x == MOVE_RIGHT):
        if(player_pos.x + player_width < width):
            player_pos.x += speed_x

    if (direction_y == MOVE_UP):
        if (player_pos.y > 0):
            player_pos.y -= speed_y
    elif (direction_y == MOVE_DOWN):
        if (player_pos.y + player_height < height):
            player_pos.y += speed_y

    player_draw_pos = mt.Vector2(player_pos.x, player_pos.y) # the new vector position of the player object

    screen.blit(game_bg_surface, bg_draw_pos)
    screen.blit(game_sprite_surface, player_draw_pos)
    pygame.display.flip()

With that we are now ready to move on to the next chapter where we will then create missile for the player object to launch from the launch pad.

Pygame loads image and background graphic on game scene

After a few days of rest, today I have continued my pygame project again and will keep on working on my new pygame projects without stopping anymore starting from today. Today I have created two game sprite classes to render the player and the background on the game scene.

The player sprite class is almost the same as the background sprite class, the only reason I have created two game sprite classes is because I want to create extra custom methods for the background sprite class.

The player class (GameSprite.py) will look like this.

import pygame

class GameSprite(object):

    def __init__(self, image, rect):
        self.image = image
        self.rect = rect
        self.sprite = pygame.image.load(image).convert_alpha() # return a pygame surface object

    def getImage(self):  # this method will return a subsurface which is the child of the self.sprite surface
        return self.sprite.subsurface(self.rect)

The background class (BgSprite.py) is almost the same for now.

import pygame

class BgSprite(object):

    def __init__(self, image, rect):
        self.image = image
        self.rect = rect
        self.sprite = pygame.image.load(image).convert() # return a pygame surface object

    def getImage(self):  # this method will return a subsurface which is the child of the self.sprite surface
        return self.sprite.subsurface(self.rect)

Here is the modify version of the main file, the background and the player image has been displayed.

import sys, pygame
from pygame import math as mt
from pygame.locals import *
from GameSprite import GameSprite
from BgSprite import BgSprite

pygame.init()
size = width, height = 660, 660
pygame.display.set_caption("Hello World") # set the title of the window
screen = pygame.display.set_mode(size)

pygame.mixer_music.load('Music/winternight.ogg')
pygame.mixer_music.play(-1)

player_sprite = 'Asset/player.png'
bg_sprite = 'Asset/bg.png'

player_pos = mt.Vector2(width/2, height/2) # initialize the position of the player sprite

rect = Rect(0, 0, 40, 40)  # the rectangle object uses to clip the sprite area
game_sprite = GameSprite(player_sprite, rect)
game_sprite_surface = game_sprite.getImage()  # get the player sprite surface

rect = Rect(0, 0, 660, 660)
game_bg_sprite = BgSprite(bg_sprite, rect)
game_bg_surface = game_bg_sprite.getImage()  # get the background sprite surface

player_draw_pos = mt.Vector2(player_pos.x , player_pos.y)
bg_draw_pos = mt.Vector2(0 , 0)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.mixer_music.stop()
            sys.exit()

    screen.blit(game_bg_surface, bg_draw_pos)
    screen.blit(game_sprite_surface, player_draw_pos)
    pygame.display.flip()

Run the above program will get this outcome.

Display the player and the background
Display the player and the background

The files under the project file explorer will now look like this.

PyCharm file explorer
PyCharm file explorer

In the next session we will deal with keyboard input so we can move the player around the game scene.

Pygame Music player demo

In this article we are going to play the background music with the help of the pygame.mixer_music module. We will first load the soundtrack then play it repeatedly. We can also play the background music with the help of pygame.mixer module which you can read the entire solution in this article but now we will use the pygame.mixer_music module to load and play the background soundtrack instead.

Inside the main python file enter below lines of code.

pygame.mixer_music.load('Music/winternight.ogg') # load winternight.ogg music file inside the Music folder
pygame.mixer_music.play(-1) # play the music again and again

Then make sure to stop the background music when the game has been terminated.

pygame.mixer_music.stop()

The entire program looks like this.

import sys, pygame
from AirStrikeColor import AirStrikeColor #from AirStrikeColor.py import AirStrikeColor class

pygame.init()
size = width, height = 600, 600
pygame.display.set_caption("Hello World") # set the title of the window
screen = pygame.display.set_mode(size)

pygame.mixer_music.load('Music/winternight.ogg')
pygame.mixer_music.play(-1)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.mixer_music.stop()
            sys.exit()

    screen.fill(AirStrikeColor(120, 150, 130, 255).correct_gamma(0.5))
    pygame.display.flip()

You can refer to the previous article on the other part of the program which you have missed out entirely!

Here is the new file explorer structure.

All the files under file explorer
All the files under file explorer

There are two things I cannot get it going when using the pygame.mixer_music module.

1) The wav file format is not supported by this module.
2) pygame.mixer_music.queue(file) method which uses to play another song after the first one is not working.

With that we will end this tutorial and get ready for the next one.

Pygame’s Color class demo

Today I have paid a visit to the Pygame document page to revise all the pygame classes one by one because I have already forgotten all of them. In order to create a game with Pygame I will need to get familiar with these classes again. In this article I will write a simple python class which extends the pygame.Color class to demonstrate the use of the pygame Color class. Since most of the time our game will deal with graphic instead of color we do not actually need this class that much but it is good to go through it so we will get familiar with it if we really need to use it later on.

As usual, I open up the PyCharm which is the official ide for my pygame development project to continue with the previously created game project. I am not going to repeat the PyCharm feature which I have already mentioned in my previous article so if you do miss out my previous article then you can read the first chapter of this pygame development project here (Setting up PyCharm for Pygame development in Windows 10 OS). I also assume you are familiar with python because before you can create a game with pygame you will need to have a very strong python programming background.

Now lets create the extension of the Color class, we will create a new python file, make sure you are clicking on the project folder then goto File->New->Python File and give it any name you wish to.

This will be the class which will extend the Pygame Color class, the good thing we create an extension of the Color class is that we can now add in more custom made functions into this class later on if we need it.

Here is our new AirStrikeColor class.

from pygame import Color

class AirStrikeColor(Color):

    def __init__(self, r=255, g= 255, b= 255, a=255):
        Color.__init__(self, r, g, b ,a)

As you can see we have created a default value for all four elements (red, green, blue and alpha) so if the programmer does not enter any value when creating the AirStrikeColor class then this new object will use the default values instead.

Alright, that is about it, we will visit this class again to add in more functions if we need it but for now we can use all the functions of the pygame.Color class in our project as usual.

Next step is to import this new class into the main python file I have created previously. We will now go back to the main python file and import the new class.

from AirStrikeColor import AirStrikeColor #from AirStrikeColor.py import AirStrikeColor class

Also we need to take out the

from pygame import Color

statement because we do not need the main Color class anymore.

Now as usual we will replace the Color class statement with AirStrikeColor class statement like this.

screen.fill(AirStrikeColor())

Run the program again and it works!

Pygame window
Pygame window

Now replace the statement above with own values.

screen.fill(AirStrikeColor(120, 150, 130, 255).correct_gamma(0.5))
New window
New window

If you don’t know where is the main python file please refer back to my previous article.

With that we have concluded this second chapter of our pygame development journal and will now getting ready for the third one.

Setting up PyCharm for Pygame development in Windows 10 OS

It has been for a while since I have stopped writing about Pygame related topic on this website and today I will start to write about it again because there are 5 ongoing gaming projects that I have developed recently using Pygame and I would really like to show you one of them in this website from start to finish. If you want to know all about this project make sure you visit this website every week to see the latest post about my latest Pygame project.

I have selected PyCharm as the Python IDE for my next Pygame development which is not surprise at all because it is the only real deal in the market when it comes to the best IDE for Python application development. I have considered using Eclipse before because Eclipse is indeed the best IDE when it comes to writing and developing application but unfortunately Eclipse does not have the stand alone version just for the software development in Python, we will need to install PyDev plugin in Eclipse before we can develop application written with Python. So PyCharm is the one to go for. Basically PyCharm consists of the Community and Professional version. If you need Full-featured IDE for Python & Web development then go for the paid Professional version, I will use the free Community version for my Pygame development because the free version is more than enough if you just need a Lightweight IDE for Python & Scientific development. Go ahead to www.jetbrains.com then decide which version of PyCharm you would like to install.

After you have downloaded PyCharm then follow the step by step installation instructions to install this IDE on windows 10 os.

Next is to install Pygame, open up the windows command prompt and type in

pip install Pygame==1.9.4

to download and install Pygame from pypi.org and that is it!

Now it is time to see whether Pygame has been installed successfully or not, Launch PyCharm then go to the File menu and select New Project.

Provide the Project folder name together with the folder location and click on the create button.

Provide the folder name
Provide the folder name

One last thing you will need to do before you can start coding and that is to set the location of the project interpreter, so go ahead and select File->Settings then type ‘interpreter’ into the search box on the left pane and select the location on your disk where you have installed the Python program on the right pane then click the Apply and OK button.

Select Python Program
Select Python Program

Now lets create a python file, write some code and run pygame. Right click on the project folder under file explorer then select New->Python File from the pop up. Type a name for your python file with .py extension into the Name field then click on the ok button.

Create new python file
Create new python file

That is it, now click on the empty python file you have just created on the left pane and enter below code into the code editor.

select the empty python file
Select the empty python file
import sys, pygame
from pygame import Color

pygame.init()
size = width, height = 600, 600
screen = pygame.display.set_mode(size)

while True:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill(Color(25, 100, 200, 255))
    pygame.display.flip()

Next goto the Run menu then select Run ‘file name’, PyCharm will first debug the python program and if there is no error then it will run the program and this is what we will see. The code will be automatically saved each time you have debugged the program.

The outcome of the program
This Pygame code will create a game window which will terminate the program when you click on the ‘x’ button on top of the window

OK so much for today, just to remind you all that I will write a new Pygame development series story on this website from start to finish so do come back again to read more Pygame development stories on this website under the Pygame category. If you like this post then don’t forget to share it!