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!

Download Eclipse SimRel 2018-09 edition then create a new blank scene with JavaFx in Windows 10

It has been a while since I have stopped developing game for windows 10 and android phone but starting from today I have decided to get really busy and spend most of my time writing articles as well as develop a few new games and applications at the same time for android phone as well as windows 10. Do follow this blog as well as my other blog codingdirectional.info to read all the brand new game and application development articles starting from today (November 5 2018) onward.

Here are what I have in mind for my new game development projects:

1) Develop 1 to 5 laptop games with JavaFx.
2) Develop 1 to 5 laptop games with pygame (a python framework for game development).
3) Develop 1 to 5 android games using Unity, AndEngine as well as purely Java code.

So there it is, it will be a very busy working days to me starting from today.

This article will become the starting point for one of the five games that I will create using JavaFx, if you want to follow the development of this new JavaFx game then don’t forget to follow the game development article in the JavaFx category of this website. The game which creates with pygame will be put under the Pygame category which you can also read it on this same website.

Ok, without wasting any time lets get started with our new JavaFx game development. Here are the things we need before we can start writing the JavaFx game.

1) I will use Java version 8 instead of 11 because Java 8 is the most stable version of Java at this moment. So you will need to go ahead and download the Java SE Development Kit 8u192 (includes JRE) if you have not yet installed one in your windows os already. After you have downloaded the JDK packages go ahead and follow the step by step set up instructions to install Java SDK on the windows os and we will then be ready for step number two.

2) The are lots of great tools that we can use to write a Java program but my best favorite is always Eclipse because I am the fan of Eclipse since I was a young man and until now Eclipse is still my best choice when it comes to picking an IDE for game development. So go ahead and Download Eclipse SimRel 2018-09 edition installer then start to download and install the Eclipse IDE for Java Developers to your Windows 10 OS.

Eclipse Installer
Eclipse Installer

3) After you have installed this latest version of Eclipse just go ahead and launch it, make sure you have have specified the location where to save your projects folder at the first time of your launch.

4) You will be greeted with the welcome screen after you have successfully launched the new Eclipse SimRel 2018-09, click ‘x’ at the top left of the welcome scene to exit it. We need one last step before we can use JavaFx to create a game, we need to install the JavaFX Tooling and Runtime for Eclipse and OSGi software, so go ahead and click on the Help menu then select Install New Software, then on the new pop up click on the Add button to create a new repository, give it a name under the Name field and enter this url http://download.eclipse.org/efxclipse/updates-released/3.3.0/site/ into the Location field and wait for Eclipse to download that Software. You will need to restart Eclipse once the software package has been installed.

5) After you have restarted Eclipse it is time to create a new JavaFx Project, go to the File menu then select New->Project->JavaFx->JavaFx Project then click on the Next button.

JavaFx Project
JavaFx Project

Next fill in the project name then click on the Finish button.

JavaFx Project
Create JavaFx Project

6) Now the java project has been created with a blank ui scene. Look at the file explorer panel of the Eclipse IDE and you should have seen the following file’s structure at the moment.

Click on Main.java file
Click on Main.java file

Select the Main.java file and you will see this file content on the coding panel.

package application;
	
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;


public class Main extends Application {
	@Override
	public void start(Stage primaryStage) {
		try {
			BorderPane root = new BorderPane();
			Scene scene = new Scene(root,400,400);
			scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
			primaryStage.setScene(scene);
			primaryStage.show();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		launch(args);
	}
}

Click the green arrow button at the top of Eclipse to run the project. If everything goes smoothly then you will see below scene pop up.

Empty JavaFx scene
Empty JavaFx scene

Next look at the file explorer again, do you notice there is a css file inside the application folder? This is where you can set style for the ui. Do you notice this line of code at the above program?

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

This means that the scene and all the nodes under that scene will use that same style sheet above.

Now lets modified the above program a little. First we will reset the size of the window, make it non resizable and change the title of that window. Add in or change the code under the start function as follows.

primaryStage.setTitle("Hello World!");
primaryStage.setResizable(false);

Scene scene = new Scene(root,600,600);

Next we will add in a button at the center of the BorderPane’s node, add in an event listener to that button which will terminate the program and close the ui if we click on the button.

Button btn = new Button();
btn.setText("Close");
btn.setOnAction(new EventHandler<ActionEvent>() {
		        @Override public void handle(ActionEvent e) {
			    	System.out.print("close");
			        System.exit(0);
		}});
root.setCenter(btn);

Next lets open the application.css file then set the style for the ui background as well as the button. There is no different between JavaFx css property as compared with the normal one except we will need to prefix it with -fx-. Here is the content of the entire style sheet which you can easily figure it out what is it doing.

* {
    -fx-background-color: #000000;
}

.button {
    -fx-pref-width: 300pt;
    -fx-pref-height:60pt;
    -fx-text-fill: #ffffff;
    -fx-font-family: "Verdana";
    -fx-font-size: 36pt ;
    -fx-background-color: #008000;
    -fx-border-color: #ffffff;
    -fx-border-radius: 10;
    -fx-background-radius: 5;
    -fx-padding: 5;
}

In order for the button to use the button class in the above style sheet you will need this line of code under the start function.

btn.getStyleClass().add("button");

Here are the revise version of the code.

package application;
	
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;


public class Main extends Application {
	
	@Override
	public void start(Stage primaryStage) {
		try {
			primaryStage.setTitle("Hello World!");
			primaryStage.setResizable(false);
			Button btn = new Button();
			btn.setText("Close");
			btn.setOnAction(new EventHandler<ActionEvent>() {
			    @Override public void handle(ActionEvent e) {
			    	System.out.print("close");
			        System.exit(0);
			}});
			btn.getStyleClass().add("button");
			BorderPane root = new BorderPane();
			root.setCenter(btn);
			Scene scene = new Scene(root,600,600);
			scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
			primaryStage.setScene(scene);
			primaryStage.show();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		launch(args);
	}
}
The new window ui
The new window ui

Besides clicking on the button you can also press the ‘x’ button on the top of the pop up window to terminate the program.

With that we have finished the first chapter of the JavaFx game development article and get ready for the second one.

What we have learned from this article.

1) Setting up SimRel 2018-09 edition.
2) Install e(fx)clipse.
3) Run the program.

It will be a very busy day for me as I am now getting ready to develop my new game scene for this new game.