由于某种原因,我的while循环在两次尝试后停止,我无法找出是什么问题。。。 它应该是一个蚂蚁农场,在那里你可以选择繁殖和制造新的蚂蚁等等。 我只是不明白为什么它停了。。。 我的代码是:
import random
class Colony(object):
workerAnts = 0
list = []
temp = []
foodAmount = 10
def breedWorker(self):
if Colony.foodAmount < 5:
print "Sorry! You do not have enough food to create a new worker ant!"
else:
Colony.foodAmount -= 5
Colony.workerAnts += 1
Colony.list.append("ant")
def step(self):
number = 'ant'
for number in Colony.list:
a = Ant()
a.forage()
if Colony.foodAmount > 0:
Colony.foodAmount -= 1
if Colony.foodAmount < len(Colony.list):
for number in Colony.list[Colony.foodAmount+1:]:
Ant.health -= 1
def purge(self):
number = 'ant'
for number in Colony.list:
if Ant.health > 0:
Colony.temp.append("ant")
Colony.list = Colony.temp
class Ant(object):
health = 10
def forage(self):
if Ant.health == 0:
Colony.workerAnts -= 1
if random.randint(0,100) > 95:
Ant.health = 0
print "Ant has died from a horrible accident!"
Colony.workerAnts -= 1
elif random.randint(0,100) < 40:
newFood = random.randint(1,5)
print "Ant has found %s food!!" % newFood
Colony.foodAmount += newFood
elif random.randint(0,100) < 5:
Ant.health = 10
Colony.foodAmount += 10
print "You've found sweet nectar! Your ant has returned to full health and has brought 10 food back to the colony!"
else:
print "Ant returned empty-handed!"
def main():
queen = Colony()
queen2 = Ant()
while queen.workerAnts > 0 or queen.foodAmount >= 5:
print "========================================================"
print """
Your colony has %s ants and %s food, Your Majesty.\nWhat would you like to do?\n0: Do nothing.\n1: Breed worker. (Costs 5 food.)""" % (queen.workerAnts, queen.foodAmount)
answer = int(raw_input(">"))
if answer != 1 and answer != 0:
print "Sorry, invalid input!"
if answer == 0:
queen.step()
queen.purge()
if answer == 1:
print "Breeding Worker..."
queen.breedWorker()
queen.step()
queen.purge()
if queen.workerAnts <= 0 and queen.foodAmount < 5:
print "I'm sorry! Your colony has died out!"
您使
Ant.health
成为一个类变量(在所有Ant实例之间共享)。在一旦一只蚂蚁的健康值变为0,它们就会全部死亡。在
这是一个改进版。下面的代码是python2和python3兼容的,我认为修复了所有错误!在
__init__(self, ...)
),也没有初始化对象的属性ants.append(Ant(self))
从Colony创建Ant;Ant的构造函数应具有签名“definit(self,Colony):”好吧,这是因为
def purge(self)
中的以下一行:第一次运行}都指向内存中的同一个数组。所以第二次运行},循环永远不会退出,因为它总是有一个新成员。在
purge()
,它使Colony.list
和{purge()
,你进入了一个无限循环,在这个循环中,for number in Colony.list:
执行Colony.temp.append("ant")
,这实际上也增加了{在python中,
for
循环为给定对象创建迭代器(如果它还不是迭代器)。在每次迭代中,python都会调用迭代器的next()
方法(在本例中为list)。如果next()
不能产生一个新的值进行迭代,它将引发StopIteration
,循环退出。别担心,这个异常是由for
语句自动处理的。在您的例子中,Colony.list.next()
总是会找到一个新值(因为您刚刚附加了它),并且永远不会到达末尾。在要修复代码,请尝试切片。这意味着复制数组,而不是将两个名称指向同一个数组:
^{pr2}$相关问题 更多 >
编程相关推荐