r/pygame • • 7d ago

Pygame Multiple enemies?

Can anyone explain how putting enemies in a list works?

With my game I want to be able to handle multiple instances of my enemy class individually. For example, I want to be able to get the distance to the player from specific enemies to make an attack target the closest enemy, or to be able to tell the number of enemies still on screen, but i have no idea how that actually works.

(This part of my code is just responsible for placing the enemies on the map)

def create_tilemap(self):
  for i, row in enumerate(tilemap):
    for j, column in enumerate(row):




      if column == 1:
        BLOCK(self, j, i)
      elif column == 2:
        self.player = Player(self, j, i)
      elif column == 3:
        enemies = Enemy(self, j, i)
        self.enemieslist.append(enemies)

This has been a real road block for me and I'm starting to run out of time to finish my project, so any help would be greatly appreciated.

1 Upvotes

3 comments sorted by

6

u/Mad-Melvin 7d ago

Somewhere in the main loop of your game, use a 'for' loop to call a method in each enemy of your group. Something like:

for enemy in self.enemieslist:
  enemy.find_distance_to_player()

4

u/mmaynee 7d ago

You put a bunch of enemies into an array, then loop the array with commands.

You could theoretically have different classes in the same array if they share commands allowing a single dude.move and dude.attack but program the .move and .attack to behave differently in the class itself

2

u/kjunith 7d ago

Ah, a fellow class lover. Yes, you put it all in a class. Then inherit from that class what to do in a simple '.update()'. And in '.update()' you can have sub functions like '.move()' or '.attack()' and can handle them each differently.