HomePython Page 2 - PyGame for Game Development: Sprite Groups and Collision Detection
Explaining the Group Class - Python
In this second part of a tutorial covering PyGame, you will learn how to manage entire groups of sprites. You'll also learn how to test for collisions within your applications.
We start off by creating our StickMan sprite class with __init__ and update methods. Then, we define a function that will be responsible for clearing the previous position of sprites. This will be used later on in the code by the sprite group. Next, we create three sprites and then a sprite group named stickGroup from the Group class. We add our sprites to this group and then define some special attributes that hold the direction the sprites will be moving, the y-position of the sprites and the height of the sprites. Since the sprites will be moving in unison, we can do this. We then create an event that will be added to the event queue every one hundred milliseconds. This will be used to trigger screen updates. In our loop, if the event is found in the event queue, we update the y-position of the sprites (actually, the stickGroup's y attribute, which is later passed to the sprites), making adjustments and changing the direction if needed.
Now we begin to see the magic of sprite groups. In a single method call, we clear the sprites. We pass screen and our eraseSprite function we defined earlier. Two arguments, the surface to be drawn on and the area that needs to be cleared, are passed to the eraseSprite function. We then update the sprites in another method call, passing the new y-position. This simply calls the update method of each of the sprites. Finally, we blit the sprites and update the changed rectangles.
Of course, the benefit doesn't end there. Notice how the section of our script that gets the updated rectangles is multiple lines long. This is easy fixed by using the RenderUpdates sprite group class rather than the Group class.
We can also get rid of StickMan's old attribute, since it is no longer needed. RenderUpdates finds the old positions automatically and throws them into the list of updated rectangles.
PyGame also contains a class called GroupSingle that can contain only a single sprite. When a new sprite is added, the old one removed. Normally, a sprite is removed from a group using the remove method. You can also empty the sprite group entirely:
If none of PyGame's sprite group classes suit you, it's always possible to subclass an existing class and tweak it to fit your needs. This way, you can modify existing methods and create new ones that are more specific to your application.