您使Ant.health成为一个类变量(在所有Ant实例之间共享)。在
一旦一只蚂蚁的健康值变为0,它们就会全部死亡。在
这是一个改进版。下面的代码是python2和python3兼容的,我认为修复了所有错误!在import random
import sys
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
rng = xrange
else:
# Python 3.x
inp = input
rng = range
def get_int(prompt, lo=None, hi=None):
"""
Prompt until an integer value in [lo..hi] is entered, then return it
"""
while True:
try:
val = int(inp(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError:
pass
class InsufficientFoodError(Exception):
pass
class Colony:
def __init__(self, workers=0, food=10):
self.food = food + Ant.cost * workers
self.ants = []
for i in rng(workers):
self.add_ant()
def add_ant(self):
try:
self.ants.append(Ant(self))
except InsufficientFoodError as e:
print(e)
def step(self):
# all ants eat, then all ants forage:
for ant in self.ants:
ant.eat()
for ant in self.ants:
ant.forage()
# bring out yer dead!
self.ants = [ant for ant in self.ants if ant.is_alive()]
def add_food(self, amount):
self.food += amount
def take_food(self, amount):
amt = min(amount, self.food)
self.food -= amt
return amt
def num_ants(self):
return len(self.ants)
class Ant:
cost = 5
max_health = 10
def __init__(self, colony):
# try to get enough food to produce an ant
food = colony.take_food(Ant.cost)
if food < Ant.cost:
# Failed! return any taken food and throw an error
colony.add_food(food)
raise InsufficientFoodError('The colony does not have enough food to make a new Ant')
else:
# Success!
self.colony = colony
self.health = Ant.max_health
def eat(self):
if self.health > 0:
self.health -= 1 - self.colony.take_food(1)
if self.health == 0:
print("An ant starved to death.")
def forage(self):
if self.is_alive():
dice = random.randint(0, 100)
if dice <= 5:
self.health = Ant.max_health
self.colony.add_food(10)
print("You've found sweet nectar! Your ant has returned to full health and has brought 10 food back to the colony!")
elif dice <= 40:
found_food = random.randint(1, 5)
self.colony.add_food(found_food)
print("Ant has found {} food!".format(found_food))
elif dice <= 95:
print("Ant returned empty-handed!")
else:
self.health = 0
print("Ant has died from a horrible accident!")
def is_alive(self):
return self.health > 0
def main():
colony = Colony()
while True:
print(
"========================================================\n"
"\n"
"Your colony has {ants} ants and {food} food, Your Majesty.\n"
"What would you like to do?\n"
" 1: Do nothing\n"
" 2: Breed worker (costs {cost} food)"
.format(ants=colony.num_ants(), cost=Ant.cost, food=colony.food)
)
opt = get_int("> ", 1, 2)
if opt == 2:
print("Breeding Worker...")
colony.add_ant()
colony.step()
if colony.num_ants() == 0 and colony.food < Ant.cost:
print("I'm sorry! Your colony has died out!")
break
if __name__=="__main__":
main()