In this guide, we will be taking a look at grouping game objects with PyGame. This is useful because most likely you will want to add or remove objects of the same type. Simply using variables to reference objects with won’t cut it. You might use a variable for assigning an instance of the player, but what if you want to add 20 enemies? Unless you name each one with a number after, it won’t work so well. Even if you name each enemy as a separate variable, that’s extremely inefficient. Not to mention, writing many separate variables to represent multiple of the same instance makes your code unmaintainable.
If you’ve been programming with Python for any length of time, you probably know what a list is. Well, if we’re developing a PyGame game, we can put them to good use. Lists are quite flexible, meaning we can add and remove items from them. There are two list methods we will focusing on: append and remove.
Let’s say you have a list defined in the constructor of your game class.
self.enemies = 
Now what if you wanted to add an enemy to this list? Assuming you are creating an instance of the enemy within your game class, you could write the following:
new_enemy = MyEnemy((128, 128), enemy_image)
Then to add it to the list, you can type:
To update the enemies, you could write a for loop, iterating through the enemies list.
for enemy in self.enemies: enemy.update()
To remove enemies, you could have a boolean defined in the enemy class that determines whether the enemy should be removed or not. You can then test if it should be removed within the above for loop. The resulting for loop would look something like so:
for enemy in self.enemies: enemy.can_remove = True if enemy.can_remove: self.enemies.remove(enemy)
The remove method takes in a reference to the instance you wish to remove from the array.
With the append and remove methods, you can almost do anything! Well, pretty much. Being able to store instances in groups, in this case, lists, will really help you on your game development journey.
At this point, you know the importance of grouping game objects with PyGame, as well as the implementation details of doing so! As you develop, you will begin to realize how useful lists really are. If you found this tutorial useful, you may want to consider checking out the rest of this tutorial series. To receive updates regarding new tutorials and courses we publish, be sure to subscribe to our newsletter. If you found this guide valuable, consider sharing it on the social media platform of your choice.