In my previous posts, I introduced how to use PyGame to design 2D games with Python language. Pygame adds functionality on top of the excellent SDL library. User controls the main loop, designs their program functions and different sprites’ interaction. This gives user greater control in creating fully featured games and multimedia programs in the Python language.
Because of the flexibility of PyGame, many people feel that PyGame is a bit too complicated. Even for a simple game, you need to write everything and handle all the stuff ranging from image loading, resizing, creating the main game loop, manging the sprite lists, creating sprite classes, handling all the mouse/keyboard events from the scratch.
If you feel the above steps cumbersome, let me introduce another tool called “PyGame Zero”. As its introdution goes “It is intended for use in education, so that teachers can teach basic programming without needing to explain the Pygame API or write an event loop”.
If you once used PyGame, you will feel the following content is much easier to understand. Now let’s take a look how to use it.
Here, I will not explain how to install Python. You could search Internet to find step-by-step instructions. After installing Python 3.x (I am using Python 3.9.0), we could start installing PyGame Zero.
Step 1: in Command window, type “pip install pygame” and wait for the module to be installed.
Step 2: in Command window, type “pip install pgzero” and wait for the module to be installed.
That is it! Using “pip” makes life much easier, isn’t it?
The Documentation and Reference
You could find all the official documentation of PyGame Zero at this position: https://pygame-zero.readthedocs.io/en/stable/introduction.html. The website contains a page linking to some useful tutorials and resources. You could click this link to see that page.
As I have said, PyGame Zero is based on PyGame. You might want to refer to PyGame documentation here: https://www.pygame.org/docs/ref/key.html
The following sample project is based on a tutorial “Gem Catcher” with links coming from PyGame Zero’s official website. It enhanced the orignal one by adding some new functions. If you would like to access the initial tutorial, here it is: https://aposteriori.trinket.io/game-development-with-pygame-zero#/intro-to-pygame-zero/intro-and-installation.
The final result is shown below:
The following is the code analysis:
At the beginning of the game at line 1, the program asks the user for input. The input text will decide the color of the ship sprite. Please note that this statement should be put before importing pgzrun module. Once the program imports pgzrun module, the PyGame Zero window will pop up and display above the command prompt window, making the program a bit messy.
At line 3 to line 7, this program imports all the necessary modules. The purpose of line 13 and 14 is to reposition the PyGame Zero window. The default PyGame Zero window is positioned with its top left corner at the center of the computer screen. The result is that part of PyGame Zero window is located outside the screen. I believe this is a glitch of PyGame Zero. A better method is to center align it to the computer screen. Line 13 and 14 could help to reposition the PyGame Zero window wherever you would like to.
From line 24 to 35, the program creates three Actor sprites and store them in gems list. Storing similar sprites in a list is a typical way of creating and managing sprites in PyGame Zero programs. Actually, in PyGame, you could also use the sprite list to manage the similar sprites, but PyGame is more flexible and a popular and better way is to create a sprite class to self manage the behavior of the sprite.
In PyGame Zero, to keep things simple, the only way to create a sprite is through calling Actor class. So what does it mean for those input parameters such as “gemyellow”, “gemblue” or “gemred”?
In PyGame Zero, all the images should be input into a sub-folder called “images”. The above “gemyellow”, “gemblue” and “gemred” represent the names of different image files, without the file extension. Pygame Zero can load images in
.jpg formats. PNG is recommended because it will allow high quality images with transparency.
From line 37 to line 39, the program defines three variables. They keep the game score, the status of game (game_over) and the lives of the ship sprite. At line 41, the program calls sounds.background.play(-1) to play the background music for the game. Please note all the sounds should be put in a “sounds” sub-folder under the current project folder. It is the standard directory that Pygame Zero will look in to find your sound files. “background” is the name of the sound file. Input parameter -1 represents to repeat the music indefinitely or until calling sounds.background.stop().
PyGame Zero accepts two types of sound format: ogg and wav. WAV is great for small sound effects, while OGG is a compressed format that is more suited for music.
For the following part, I would like to explain the two most important functions of PyGame Zero. One is update() function and the other is draw() function. The two functions’ names are pre-defined and have special meaning in PyGame Zero. “update()” function is used to change all the sprites’ position, visibility, image updating. It could also be used to handle the keyboard or mouse clicking events or collision condition.
“draw()” function is used to blit the images and text to the main screen surface. Both functions are called automatically by PyGame Zero at a high frequency (usually 30 or more times per second). Because all the sprites are updated and redrawing at the high frequency, our eyes will not catch the redrawing process but see a continuous running smooth video.
From line 49 to line 52, the program checks if user presses Left or Right arrow key, then change ship sprite’s x position accordingly. Remember that we have several gem sprites and they are stored in gems list. For each item in gems list, the program needs to update their y positions and checks if it drops to the bottom of the screen (gem.y > HEIGHT). If it drops beyond the screen, the program reduces its lives by 1 and plays a short sound. If lives value becomes zero, set variable “game_over” to True and play finishing sound.
In the “draw” function from line 70 to line 82, if game_over becomes True, the program draws text in the specified position, color and font size. Otherwise, the program draws each gem, ship and updates the score on the screen.
That is the different responsibility of “draw” and “update” function. The backend logic of PyGame Zero will call “update” and “draw” function in turn to refresh the screen in time.
The above “update” and “draw” forms the core functions of the PyGame Zero program. Without the above two functions, your PyGame Zero program will not run correctly. There are other built-in events such as “on_mouse_move”, “on_mouse_down”, “on_key_down”, etc. You could check event handling hooks topic on its official website. You could also define your own functions freely.
That is all for the brief introduction of PyGame Zero. It is a nice tool to learn game design with Python language. Try the above steps to run your first PyGame Zero program, or if you do not want to bother writing it, here you could find the code for your reference. Keep tuned for our future posts.
Note: All the analysis articles are copyright products of http://www.thecodingfun.com. Anyone re-posting them should credit author and original source. Anyone using them for commercial purposes or translating them into other languages should notify TheCodingFun and get confirmation first. All Rights Reserved.
One thought on “PyGame is too complicated? Try PgZero”
Pingback: A Self-help Guide to Learn Pgzero and Develop Python Games – The Coding Fun