Home > Blockchain >  How can I create objects in Python, that I don't know the quantity of?
How can I create objects in Python, that I don't know the quantity of?

Time:10-30

So, I am just doing some coding in Python and I am creating a simple snake game. I was wondering if it is possible to create a variable amount of objects. This is an example:

class Enemy:
    def __init__(hp):
        self.hp = hp
        print("hp")
#So if I say, create an enemy every minute. I could use time, but then if the game lasts for 10 minutes or an hour, the number of enemies spawned will differ. How would I be able to tackle that?
#This is the only option I could think of, but this wouldn't work:
while running: #as long as the game is running
    enemy = Enemy(100) #Instantiating object
    time.sleep(60) #Sleep for 60 seconds
#This wouldn't work because the objects would need to have a different name. How can I actually do this?

CodePudding user response:

Put them in a list:

enemies = []
while True:
    enemies.append(Enemy(100))
    time.sleep(60)

and access them via a for loop:

for enemy in enemies:
    do_something(enemy)
  • Related