Python Pygame (Game Development Library)
Python is the most popular programming language or nothing wrong to say that it is the next-generation programming language. In every emerging field in computer science, Python makes its presence actively. Python has vast libraries for various fields such as Machine Learning (Numpy, Pandas, Matplotlib), Artificial intelligence (Pytorch, TensorFlow), and Game development (Pygame,Pyglet).
In this tutorial, we are going to learn about game development using the Pygame (Python library)
Prerequisites for Pygame:
Before learning about pygame, we need to understand what kind of game we want to develop.
Install pygame in Windows
Before installing Pygame, Python should be installed in the system, and it is good to have 3.6.1 or above version because it is much friendlier to beginners, and additionally runs faster. There are mainly two ways to install Pygame, which are given below:
1. Installing through pip: The good way to install Pygame is with the pip tool (which is what python uses to install packages). The command is the following:
2. Installing through an IDE: The second way is to install it through an IDE and here we are using Pycharm IDE. Installation of pygame in the pycharm is straightforward. We can install it by running the above command in the terminal or use the following steps:
To check whether the pygame is properly installed or not, in the IDLE interpreter, type the following command and press Enter:
If the command runs successfully without throwing any errors, it means we have successfully installed Pygame and found the correct version of IDLE to use for pygame programming.
Install pygame in Mac
The steps are following to install pygame in Mac
Note: If you are using the different version of Python, download the last link.
Simple pygame Example
Here is the simple program of pygame which gives a basic idea of the syntax.
After successful execution it will give the following window as an output:
Let's understand the basic syntax of the above program line by line:
import pygame - This provides access to the pygame framework and imports all functions of pygame.
pygame.init() - This is used to initialize all the required module of the pygame.
pygame.display.set_mode((width, height)) - This is used to display a window of the desired size. The return value is a Surface object which is the object where we will perform graphical operations.
pygame.event.get()- This is used to empty the event queue. If we do not call this, the window messages will start to pile up and, the game will become unresponsive in the opinion of the operating system.
pygame.QUIT - This is used to terminate the event when we click on the close button at the corner of the window.
pygame.display.flip() - Pygame is double-buffered, so this shifts the buffers. It is essential to call this function in order to make any updates that you make on the game screen to make visible.
The pygame Surface is used to display any image. The Surface has a pre-defined resolution and pixel format. The Surface color is by default black. Its size is defined by passing the size argument.
Surfaces can have the number of extra attributes like alpha planes, color keys, source rectangle clipping, etc. The blit routines will attempt to use hardware acceleration when possible; otherwise, they will use highly enhanced software blitting methods.
Times are represented in millisecond (1/1000 seconds) in pygame. Pygame clock is used to track the time. The time is essential to create motion, play a sound, or, react to any event. In general, we don't count time in seconds. We count it in milliseconds. The clock also provides various functions to help in controlling the game's frame rate. The few functions are the following:
This function is used to update the clock. The syntax is the following:
This method should be called once per frame. It will calculate how many milliseconds have passed since the previous call. The framerate argument is optional to pass in the function, and if it is passed as an argument then the function will delay to keep the game running slower than the given ticks per second.
The tick_busy_loop() is same as the tick(). By calling the Clock.tick_busy_loop(20) once per frame, the program will never run at more than 20 frames per second. The syntax is the following:
The get_time() is used to get the previous tick. The number of a millisecond that isdra passed between the last two calls in Clock.tick().
The pygame blit is the process to render the game object onto the surface, and this process is called blitting. When we create the game object, we need to render it. If we don't render the game objects and run the program, then it will give the black window as an output.
Blitting is one of the slowest operations in any game so, we need to be careful to not to blit much onto the screen in every frame. The primary function used in blitting is blit(), which is:
This function is used to draw one image into another. The draw can be placed with the dest argument. The dest argument can either be a pair of coordinates representing the upper left corner of the source.
Pygame Adding Image
To add an image on the window, first, we need to instantiate a blank surface by calling the Surface constructor with a width and height tuple.
The above line creates a blank 24-bit RGB image that's 100*100 pixels with the default black color.
For the transparent initialization of Surface, pass the SRCALPHA argument.
Consider the following example to display image on the surface:
Rect is used to draw a rectangle in Pygame. Pygame uses Rect objects to store and manipulate rectangular areas. A Rect can be formed from a combination of left, top, width, and height values. It can also be created from Python objects that are already a Rect or have an attribute named "rect".
The rect() function is used to perform changes in the position or size of a rectangle. It returns the new copy of the Rect with the affected changes. No modification happens in the original rectangle.
The Rect object has various virtual attributes which can be used to move and align the Rect:
The dimension of the rectangle can be changed by assigning the size, width, or height. All other assignment moves the rectangle without resizing it.
If the width or height is a non-zero value of Rect, then it will return True for a non-zero test. Some methods return a Rect with 0 sizes to represent an invalid rectangle.
Let's create a Rectangle on the pygame window using the Rect:
After execution of the above code, it will display the rectangle on the pygame window.
Pygame KEYDOWN and KEYUP detect the event if a key is physically pressed and released. KEYDOWN detects the key press and, KEYUP detects the key release. Both events (Key press and Key release) have two attributes which are the following:
Consider the following example of the key press and key release.
Let's have a look the another example
In the above code, the rectangle will be displayed on the pygame window.
When we press the Down key, the rectangle is reshaped in the downwards. The output is the following:
Pygame provides geometry functions to draw simple shapes to the surface. These functions will work for rendering to any format to surfaces. Most of the functions accept a width argument to signify the size of the thickness around the edge of the shape. If the width is passed 0, then the shape will be solid(filled).
All the drawing function takes the color argument that can be one of the following formats:
Draw a rectangle
The following functions are used to draw a rectangle on the given surface.
Draw a polygon
The following functions are used to draw a polygon on the given surface.
Note: - If the len(points) < 3 or points is not a sequence or points does not contain number pair, then it will raise the Value Error
Draw an ellipse
The following functions are used to draw an ellipse on the given surface.
Draw a straight line
This method is used to draw a straight line on the given surface. There are no endcaps.
Draw a Circle
Below are the functions, which are used to draw a circle on the given surface.
Draw an elliptical arc
Below functions are used to draw an elliptical arc on the given surface.
There are three conditions for start_angle and stop_angle parameter:
Let's consider an example:
Pygame Text and Font
Pygame also provides facilities to render the font and text. We can load fonts from the system by using the pygame.font.SysFont() function. Pygame comes with the built-in default font which can be accessed by passing the font name or None. There are many functions to help to work with the font.
The font objects are created with pygame.font.Font().The actual font objects do most of the works done with fonts. Font objects are generally used to render the text into new Surface objects. Few important font functions are the following:
This function is used to draw text on a new Surface. Pygame has no facility to draw text on the existing Surface. This creates a new Surface with the specified text render on it. The syntax is the following:
This function is used to determine the number of space or positioning needed to render text. It can also be used for word-wrapping and other layout effects. The syntax is the following:
This function is used for bold rending of text. The syntax is following:
Let's consider the following example:
Note- It is necessary to remember that the certain font must be installed on the user's computer. If you don't know whether fonts install or not, pygame has the following function to enumerate all the fonts available on the machine:
There is another function to instantiate the default system font:
Using any above functions, we can work with the attractive font in game.
Pygame Sprite and Collision detection
A pygame sprite is a two-dimensional image that is part of the large graphical scene. Usually, a sprite will be some object in the scene.
One of the most advantages of working with sprites is the ability to work with them in groups. We can easily move and draw all the sprites with the one command if they are in the group.
The Sprite module contains the various simple classes to be used within the games. It is optional to use Sprite classes and different group classes when using pygame.
Pygame provides sprites and sprite groups that help for collision detection. Collision detection is the process when two objects on the screen collide each other. For example, if a player is hit by the enemy's bullet, then it may lose a life or, the program need to know when the player touches a coin so that they automatically picked up.
Let's consider the following example:
After pressing the arrow keys, one rectangle will collide with another rectangle then output is:
Python provide another game library named pyglet which is cross-platform windowing and multimedia library for Python. It is used to developing games and other visually rich applications. It supports user interface event handling, windowing, OpenGL graphics, loading images and videos, and playing sounds and music.
Few features of pyglet are the following:
Installation of pyglet is simple; it can be installed by typing the following command.
Consider the following example.
Comparison between Pygame and Pyglet
In this tutorial, we have discussed the simple game development programming approach by installing the open-source module pygame into Python 3 programming environment.