# # Jay Summet # CS 1301 - Object Oriented Programming Example # Released to the public domain, April 2009 # # # from myro import * ENV_SIZE = 500 class Animal: xLoc = 0 yLoc = 0 moveSpeed = 3 display = None myIcon = None def __init__(self, X, Y): self.xLoc = X self.yLoc = Y def setDisplay(self, NewDisplay): self.display = NewDisplay myP = Point(self.xLoc, self.yLoc) self.myIcon = Circle(myP, 5) self.setColor() self.myIcon.draw(self.display) def setColor(self): pass def action(self): self.move() self.eat() def erase(self): self.myIcon.undraw() def move(self): from random import choice moveX = choice( [-self.moveSpeed,0,self.moveSpeed]) moveY = choice( [-self.moveSpeed,0,self.moveSpeed]) #code to check boundries if self.xLoc + moveX > ENV_SIZE -1: moveX = 0 if self.xLoc + moveX < 0: moveX = 0 if self.yLoc + moveY > ENV_SIZE -1: moveY = 0 if self.yLoc + moveY < 0: moveY = 0 #do the moves self.xLoc = self.xLoc + moveX self.yLoc = self.yLoc + moveY if (self.myIcon != None): self.myIcon.move(moveX,moveY) def identifyFood(self,animal): return False def eat(self): global animals for ani in animals: if (self.identifyFood(ani)): if (ani.xLoc == self.xLoc) and (ani.yLoc == self.yLoc): #print "Found some food at:", self.xLoc, "," , self.yLoc ani.erase() animals.remove(ani) class Rabit(Animal): moveSpeed = 5 def setColor(self): self.myIcon.setFill( color_rgb(0,255,0) ) class Fox(Animal): moveSpeed = 6 def setColor(self): self.myIcon.setFill( color_rgb(255,0,0)) def identifyFood(self,animal): if (str(animal.__class__ ) == "__main__.Rabit"): return True class Bear(Animal): moveSpeed = 2 def setColor(self): self.myIcon.setFill( color_rgb(23,23,23)) def identifyFood(self,animal): if (str(animal.__class__ ) == "__main__.Fox"): return True MyDisplay = GraphWin("Our World", ENV_SIZE, ENV_SIZE) animals = [] for i in range(50): myRabit = Rabit(ENV_SIZE / 4,ENV_SIZE / 4) myRabit.setDisplay(MyDisplay) animals.append(myRabit) for i in range(10): myFox = Fox(ENV_SIZE / 2,ENV_SIZE / 2) myFox.setDisplay(MyDisplay) animals.append(myFox) for i in range(2): myBear = Bear(ENV_SIZE / 3,ENV_SIZE / 3) myBear.setDisplay(MyDisplay) animals.append(myBear) print "made animals!" for i in range(50): for ani in animals: ani.action() wait(0.25) RabitCount = 0 FoxCount = 0 for ani in animals: if str(ani.__class__) == "__main__.Rabit": RabitCount = RabitCount + 1 if str(ani.__class__) == "__main__.Fox": FoxCount = FoxCount + 1 print RabitCount, " Rabits and ", FoxCount, "Foxes remain!"