""" jungle.py Version 0.2 -- foxes eat bunnies example By K. Urner, 4D Solutions Given the with assistance from: Andre Roberge """ from random import randint from time import sleep class Mammal (object): """ Every mammal knows how to initialize and update itself, which includes moving a bit on the XY plain. """ def __init__(self, name, eco): self.name = name self.stomach = [] self.alive = True self.eco = eco self.timetolive = 100 self.clock = 0 self.xpos = randint(-3,3) self.ypos = randint(-3,3) def update(self): self.clock += 1 if self.clock >= self.timetolive: self.die() self.alive = False else: self.move() def move(self): self.xpos += randint(-1, 1) self.ypos += randint(-1, 1) class Bunny (Mammal): """ Bunnies have the dubious feature of being eatable (edible). Plus they simply die of old age when the life clock runs out. Assume bunnies nibble -- you could add a method. """ def iseaten(self, fox): self.alive = False print '%s is eaten by %s.' % (self, fox) def die(self): print '%s dies of old age.' % self def __repr__(self): return 'Bunny %s age: %s @ (%s, %s)' % (self.name, self.clock, self.xpos, self.ypos) class Fox (Mammal): """ If a fox lands on the same (x,y) as a bunny, it eats the bunny. """ # Andre Roberge: add the following (I think :-) def update(self): Mammal.update(self) self.eat() def eat(self): # idea: you could have eating a bunny extend the life clock for bunny in self.eco.bunnies.values(): if (self.xpos == bunny.xpos) and (self.ypos == bunny.ypos): self.stomach.append( bunny ) bunny.iseaten(self) def newfox(self): # Student suggestion: two foxes, same square begets new fox # Two bunnies same square begets three new bunnies # This is just a stub, not a completed project for fox in self.eco.foxes.values(): if (self.xpos == fox.xpos) and (self.ypos == fox.ypos) and self.name <> fox.name: print "New fox is born" def die(self): print '%s dies of old age.' % self def __repr__(self): return 'Fox %s age: %s @ (%s, %s)' % (self.name, self.clock, self.xpos, self.ypos) class Ecosystem(object): """ The bunnies and foxes all live in an ecosystem... """ def __init__(self): self.bunnies = {} self.foxes = {} def update(self): """ Update everyone, then see who's still alive and who needs to be popped from the ecosystem """ # state change for bunny in self.bunnies.values(): bunny.update() for fox in self.foxes.values(): fox.update() # cull for i, bunny in self.bunnies.items(): if not bunny.alive: self.bunnies.pop(i) for i, fox in self.foxes.items(): if not fox.alive: self.foxes.pop(i) def main(): eco = Ecosystem() for i in range(100): eco.bunnies[i] = Bunny(i, eco) for i in range(10): eco.foxes[i] = Fox(i, eco) print 'Bunnies:', eco.bunnies print 'Foxes: ', eco.foxes for cycle in range(200): sleep(0.1) eco.update() if __name__ == '__main__': main()