In this lesson, you’ll learn about the
sprite.Group class, and add your
Enemy objects to them. You’ll create two different
- The first
Groupwill hold every
Spritein the game.
- The second
Groupwill hold just the
Here’s what that looks like in code:
82 # Create the 'player' 83 player = Player() 84 85 # Create groups to hold enemy sprites and all sprites 86 # - enemies is used for collision detection and position updates 87 # - all_sprites is used for rendering 88 enemies = pygame.sprite.Group() 89 all_sprites = pygame.sprite.Group() 90 all_sprites.add(player) 91 92 # Variable to keep the main loop running 93 running = True
When you call
Sprite is removed from every
Group to which it belongs. This removes the references to the
Sprite as well, which allows Python’s garbage collector to reclaim the memory as necessary.
Now that you have an
all_sprites group, you can change how objects are drawn. Instead of calling
.blit() on just
Player, you can iterate over everything in
114 # Fill the screen with black 115 screen.fill((0, 0, 0)) 116 117 # Draw all sprites 118 for entity in all_sprites: 119 screen.blit(entity.surf, entity.rect) 120 121 # Flip everything to the display 122 pygame.display.flip()
Now, anything put into
all_sprites will be drawn with every frame, whether it’s an enemy or the player.
For more information about the
sprite.Group class, check out the
Become a Member to join the conversation.