【发布时间】:2014-03-10 20:50:33
【问题描述】:
由于某种原因,我的 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!"
【问题讨论】:
-
对于初学者,你不要在任何地方调用 main()
-
而不是
def main():写if __name__ == '__main__':。 -
你的代码很乱,很难理解。我敢打赌这个问题与您使用类名(如变量)这一事实有关。在你的
Colony类中,你不应该做Colony.foodAmount之类的东西,只需使用foodAmount。 -
或许你应该和this question's OP合作
-
一个非常重要的一点是你不应该做例如
elif random.randint(0,100)- 每次都会得到一个新的随机数!此外,< 40和< 5都将是True,这不是为事件分配概率的正确方法。
标签: python loops while-loop