Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.

Sprite Groups

In this lesson, you’ll learn about the sprite.Group class, and add your Player and Enemy objects to them. You’ll create two different Group objects:

  1. The first Group will hold every Sprite in the game.
  2. The second Group will hold just the Enemy objects.

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 .kill(), the 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 all_sprites:

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 pygame documentation.

Comments & Discussion

Become a Member to join the conversation.