所以,我只是在用 Python 做一些編碼,我正在創建一個簡單的蛇游戲。我想知道是否可以創建可變數量的物件。這是一個例子:
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?
uj5u.com熱心網友回復:
把它們放在一個串列中:
enemies = []
while True:
enemies.append(Enemy(100))
time.sleep(60)
并通過 for 回圈訪問它們:
for enemy in enemies:
do_something(enemy)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341629.html
