While Loop Ending Early in Python? -
for reason while loop stopping after 2 tries , can't figure out what's wrong... it's supposed ant farm, can choose breed , make new ant, etc. don't understand why it's stopping... here's code:
import random class colony(object): workerants = 0 list = [] temp = [] foodamount = 10 def breedworker(self): if colony.foodamount < 5: print "sorry! not have enough food create new worker ant!" else: colony.foodamount -= 5 colony.workerants += 1 colony.list.append("ant") def step(self): number = 'ant' number in colony.list: = ant() a.forage() if colony.foodamount > 0: colony.foodamount -= 1 if colony.foodamount < len(colony.list): number in colony.list[colony.foodamount+1:]: ant.health -= 1 def purge(self): number = 'ant' 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 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! ant has returned full health , has brought 10 food colony!" else: print "ant returned empty-handed!" def main(): queen = colony() queen2 = ant() while queen.workerants > 0 or queen.foodamount >= 5: print "========================================================" print """ colony has %s ants , %s food, majesty.\nwhat do?\n0: nothing.\n1: breed worker. (costs 5 food.)""" % (queen.workerants, queen.foodamount) answer = int(raw_input(">")) if answer != 1 , 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 , queen.foodamount < 5: print "i'm sorry! colony has died out!"
- you don't have constructors (
__init__(self, ...)) , not initialize object's properties - in methods call object property self.property, not classname.property; in python explicitly pass instance or class object method, convention should 'self' instance, or 'cls' class.
- if want use colony properties in ant object or vice versa, need explicitly pass reference, , store property. sensible create ant colony calling
ants.append(ant(self)); ant's constructor should have signature `def init(self, colony):'
Comments
Post a Comment