# # Jay Summet # CS 1301 - Object Oriented Programming Example # Released to the public domain, November 2007 # # This example represents two days of class time, see the previous # animals.py file for the first day of class time. from myro import * ENV_SIZE = 50 animals = [] class Animal(object): xLoc = 0 yLoc = 0 moveSpeed = 3 def __init__(self, X=0, Y=0): self.xLoc = X self.yLoc = Y def __str__(self): return "Animal at: " + str(self.xLoc) +","+ str(self.yLoc) def action(self): self.move() def move(self): from random import choice moveX = choice( [ -self.moveSpeed, 0, self.moveSpeed]) moveY = choice( [ -self.moveSpeed, 0, self.moveSpeed]) self.xLoc = self.xLoc + moveX self.yLoc = self.yLoc + moveY 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 def drawOnPicture(self, Pic): pix = getPixel(Pic, self.xLoc, self.yLoc) setRed(pix,255) setBlue(pix,255) setGreen(pix,255) pix = getPixel(Pic,self.xLoc+1, self.yLoc+1) setRed(pix,255) setBlue(pix,255) setGreen(pix,255) def lookForFood(self): for animal in animals: if ( self.xLoc == animal.xLoc) and (self.yLoc == animal.yLoc): return(animal) return None def eatFood(self, animal): animals.remove(animal) class Rabit(Animal): def drawOnPicture(self, Pic): Animal.drawOnPicture(self, Pic) pix = getPixel(Pic, self.xLoc+1, self.yLoc) setBlue(pix,255) pix = getPixel(Pic,self.xLoc, self.yLoc+1) setBlue(pix,255) class Fox(Animal): moveSpeed = 6 def drawOnPicture(self, Pic): Animal.drawOnPicture(self, Pic) pix = getPixel(Pic, self.xLoc+1, self.yLoc) setRed(pix,255) pix = getPixel(Pic,self.xLoc, self.yLoc+1) setRed(pix,255) def action(self): self.move() food = self.lookForFood() if (food != None): foodType = type(food) if str(foodType) == "": #only eat rabits! self.eatFood(food) print "Ate a Rabit at (", self.xLoc, "," ,self.yLoc, ")!" class Bear(Animal): moveSpeed = 2 def drawOnPicture(self,Pic): for x in range(5): for y in range(5): pix = getPixel(Pic,self.xLoc+x, self.yLoc+y) setRed(pix,255) setGreen(pix,255) setBlue(pix,0) for i in range(50): animals.append( Rabit(ENV_SIZE/2,ENV_SIZE/2)) for i in range(50): animals.append( Fox(ENV_SIZE/3,ENV_SIZE/3)) #for i in range(10): # animals.append( Bear(ENV_SIZE/5, ENV_SIZE/5) ) #Five pixels extra because some animals "draw big" display = makePicture(ENV_SIZE+5,ENV_SIZE+5) def countRabits(aList): counter = 0 for animal in aList: if str( type(animal)) == "": counter = counter + 1 return counter for i in range(25): copyPic = copyPicture(display) for ani in animals: ani.drawOnPicture(copyPic) ani.action() print countRabits(animals), "Rabits remaining!" show(copyPic) wait(0.5)