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' 83player = 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 88enemies = pygame.sprite.Group() 89all_sprites = pygame.sprite.Group() 90all_sprites.add(player) 91 92# Variable to keep the main loop running 93running = 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 115screen.fill((0, 0, 0)) 116 117# Draw all sprites 118for entity in all_sprites: 119 screen.blit(entity.surf, entity.rect) 120 121# Flip everything to the display 122pygame.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
gwhitelum on May 9, 2020
I’m getting an error at the end of lesson “Creating Sprite Groups” error as follows:
Python is asking for an iterable but Player is an object. and yes my player object is lowercase and the Player class is uppercase. (my IDE is PyCharm)
Since I’m stuck I’ll look at other tutorials.
Thanks for the help