# # Jay Summet # CS 1301 - Object Oriented Programming Example # Released to the public domain, November 2008 # # # 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 > ENV_SIZE -1: self.xLoc = ENV_SIZE -1 if self.xLoc < 0: self.xLoc = 0 if self.yLoc > ENV_SIZE -1: self.yLoc = ENV_SIZE -1 if self.yLoc < 0: self.yLoc = 0 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(100,100) myRabit.setDisplay(MyDisplay) animals.append(myRabit) for i in range(10): myFox = Fox(110,110) myFox.setDisplay(MyDisplay) animals.append(myFox) for i in range(2): myBear = Bear(110,110) 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!"