1

In a game, "Enemies" are created as objects from a class as the level loads.

When the screen refreshes, each need to update their X and Y positions. But since there are multiple enemies, I would need to create a long piece of code telling every enemy object to update.

For example:

enemy1 = Enemy()
enemy2 = Enemy()
enemy3 = Enemy()
...
enemy1.update()
enemy2.update()
enemy3.update()
...

I need a way to create these objects when needed without needing to create a variable for every single one, and a function that will make all the objects in the enemy class update when the screen refreshes.

2 Answers 2

0

You can do something like that:

class Enemy(object):

    def __init__(self):
        pass

    def update(self):
        pass # we will call this function during updates.

enemies = []
for iter in range(10):
    enemies.append(Enemy()) # creating 10 Enemies and appending it into list

for enemy in enemies:
    enemy.update() #updating every enemy in the list

Answer is fairly easy. During creating enemy append it into list. Later, if you need to calculate their x/y position simply iterate over that list. But remember to remove or del enemy from the list if you don't need it anymore.

-edit- Also I would recommend you the book:

Python Programming for the Absolute Beginner

by Michael Dawson. It's very good book. Written for people wanted to learn how to create games in python. You should read it.

0

Pygame provides native support for this situation.

class Enemy(pygame.sprite.Sprite):
    "do useful stuff"
enemies = pygame.sprtie.Group()
for _ in xrange(10): #initialize enemy list
     Enemy(enemies)
enemies.update() #update all the enemies
enemies.update(5, 6) #call the update method on each enemy with the args 5 and 6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.