HomePython Page 4 - PyGame for Game Development: Sprite Groups and Collision Detection
Explaining the Collision Code - 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.
It seems like a lot of code, but most of it should be familiar to you. We start out by creating the StickMan sprite class and the sprite erasing function. We then create three non-playable and non-moving sprites and add them each to a group, followed by the player's character and its own group. After we draw each sprite, we enter the game loop. Here, we check to see whether the user has pushed a key. If he or she has, we update the player sprite accordingly.
With the updated positions, we then move on to the collision tests. As I mentioned before, there are three methods that are responsible for this. The first is spritecollide, and it accepts three arguments. The first is a sprite, and the second is a group. If the two collide and the third argument is set to True, then the colliding sprites are removed from the group. The method returns a list of the colliding sprites. The second method is groupcollide, and it accepts two groups and two boolean values. If the first boolean value is set to True, then the colliding sprites in the first group are removed. If the second is set to True, then the colliding sprites in the second group are removed. A dictionary is returned with the sprites of the first group as the keys and the colliding sprites as the values. The last method is spritecollideany. It simply checks to see whether a sprite collides with a group, and it returns a boolean value. Since it doesn't do anything too special, like removing sprites, then it is the fastest.
Next, we check to see whether the player sprite still belongs to a group and hasn't been removed by a collision method. If it has been removed, then we exit the game. Otherwise, we move the player and update the other sprites if we need to.
Conclusion
PyGame provides an easy interface to graphical tasks (as well as other tasks) for use in Python-powered games or even applications. Fonts are simple to load and display text in, and it's easy to load images and display them to a Surface object—the graphical building block of PyGame applications. Moreover, sprites can be easily created and used to simplify the drawing process and provide a more object-oriented approach to it, and sprite groups provide an efficient way to organize sprites and accomplish tasks such as collision detection. If you are looking to build a simple game in Python or an application with a unique interface, consider using PyGame.