Sprite Groups While managing sprites individually may be ideal for small applications, think about managing dozens of sprites in more complex applications. Obviously, there has to be a way to efficiently manage all of them, and sprite groups do just that. The definition of a sprite group is pretty simple and true to the term. Sprite groups are simply groups of sprites that are related in some way. Sprites can also belong to multiple groups, rather than just being limited to one group. Besides providing a convenient way to iterate over related sprites, some sprite groups contain special features to aid with development, which we'll take a look at later. First, though, let's put together a simple program that uses a sprite group to move three stick men up and down the screen.
We'll start with the most basic sprite group, the Group class: import pygame class StickMan(pygame.sprite.Sprite): # We'll just accept the x-position here pygame.sprite.Sprite.__init__(self) # The x-position remains the same self.old = self.rect # Define a function to erase old sprite positions pygame.init() # Create the three stick men # Create a group and add the sprites # Add a variable for the direction, y-position and height of the # Create a blank piece of background pygame.display.update() # Create an event that will appear ever 100 milliseconds while True: for event in pygame.event.get(): # Check for our update event # Update the y-position # Check if we have gone off the screen # Clear the old sprites # Update the sprites # Blit the sprites # Create a list to store the updated rectangles # Get the updated rectangles
blog comments powered by Disqus |
|
|
|
|
|
|
|