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.

Rock Quest

In Rock Quest you move the gaming character with left, right, up and down key to collect rock, you need to compete with the robot and do not let that robot collects more than a certain amount of rocks than you do or else it will be game over. Besides that you will also need to avoid getting hit by the monster. This game will be updated constantly so do visit this website to get the latest information.

More levels will be included from time to time so stay tune!

MightBeIt!

MightBeIt is a simple truck game creates with the javascript version of box2d framework. It is now an offline game and will remain offline unless there are some major changes in the future.

If you have any suggestion regarding this game, submit it through the above twitter tweet!

SkyBased

SkyBased is a fun game where you will use left, right, up and down key on the keyboard to move the spaceship around the canvas and use the spacebar to shoot missile at your enemy. This various levels game will continue getting develop by me and you will get notified on every update through this page. Do enjoy playing this offline game and if you have any suggestion do let me know.

Create browser game without knowing any programming languages

If you want to create a browser game and put it on your own website for others to enjoy but you do not know any web programming languages such as javascript, php or html5 then you will really love GDevelop which is a game development software that will help yourself to create game without even requires you to write a single line of code.

Game development with GDevelop is very fast
Game development with GDevelop is very fast

I have downloaded GDevelop which itself is an open source software and then create my first game with it, all I have to say is that I really like it!

Normally a game developer needs to write code to detect whether a character has landed on a platform or not, but with GDevelop he does not need to do this anymore because he can simply create that detection logic in just a few steps!

Has the players landed on a platform?
Has a player already landed on a platform?

A game developer also does not need to write his own animation loop for a group of game images any more because with just a few simple settings that take only 1 minute or less the animation loop will be fully ready! I still remember it took me around an hour to write the first animation loop for my first game a few years ago.

This is how to set up the animation loop in GDevelop
This is how you set up the animation loop in GDevelop

You can add as many platforms as you need and as many game characters as you wish and as many character-platform relationships that you wish to have using GDevelop’s set up portal.

Character-Platform relationship
Character-Platform relationship

Once you have created your browser game, pack it up and you are ready to put it on your own website for people to enjoy.

Overall speaking GDevelop is a great piece of browser game development software which will help you to create game without needs you to write a single line of game code. If you have not yet downloaded this IDE then go ahead and download it, you will really love this game creation software once you have installed it on your pc 🙂

That is all, if there is time for more stories then I will write an article about creating a full browser game with GDevelop so don’t miss it if you would!