HomePython Page 4 - A PyGame Working Example: Starting a Game
Sprite Definitions - Python
In PyGame for Game Development, I showed you the very basics of PyGame's graphical side. However, creating a game with PyGame requires a bit more. All the concepts described before need to be glued together somehow, and new concepts will need to be introduced in order to create a functional game. In this article, we'll do just that by tackling a working example of PyGame's capabilities—a Python-powered game.
Next, we'll need to define the classes for player sprites as well as object sprites. Since the player sprite has no ability to move vertically, it will only have to be moved by its x-position. So, the player class's update method will only need to accept the amount its x-position needs to move. Likewise, because objects will have a static x-position, the object class's update method will only need to accept the amount to update the y-position. Also, our game will move objects by their center positions, not by their upper-left corners. We'll use centerx and centery rather than x and y.
Save the script as gamesprites.py. We'll import it as a module when we need to create the sprites for our game. The Player class accepts three arguments when it is initialized: the player image, its center x-position and its center y-position. Note that the player image will already be loaded onto a Surface object by the level, so there's no need to load it again. The Object class only accepts two arguments, the object's image and the center x-position. Since all objects will start at the top of the screen, there's no need to accept any y-position. The update methods simply accept the amount the sprites need to move, with each class moving in a different direction, as described before. Additionally, the Player class checks to see if the sprite has gone off the screen. If it has, we undo any movement to put it back on the screen.
The Internals
The functional code of the game will make up its own module, and related Python instructions will be grouped into the module's methods. This is so we can customize the game later on by importing the module, calling whatever methods we need to call, and passing whatever level we want to play rather than modifying the internals of the game. Using this method of organizing the game, it's possible to add extra features such as a menu rather than limiting it to one game. This also allows us to create custom “Game Over” or success screens rather than relying on a generic one or modifying the internals to create a more specific one. We could also create either a linear or semi-dynamic campaign by going this route.