from tkinter import *
from random import randrange


class SimWorld:

    def __init__(self, mainWin,width=500, height=500):
        self.agents = []
        self.width = width
        self.height = height
        self.win = mainWin
        
        self.canvas = Canvas(mainWin, width=self.width,
                             height=self.height, bg = "white")
        self.canvas.pack()

        Button(mainWin, text="Go!", command=self.doAction).pack()

    def addAgent(self, agent):
        self.agents.append(agent)
        agent.setWorld(self)

    def doAction(self):
        for agent in self.agents:
            agent.action()

        self.canvas.after(500, self.doAction)    
        
        


class Animal:
    speed = 5
    color = ""

    def __init__(self, xLoc,yLoc):
        self.xLoc = xLoc
        self.yLoc = yLoc

    def action(self):
        self.randomMove()
        self.speak()

    def speak(self):
        print("hi I'm an Animal!", self.xLoc, self.yLoc)

    def setWorld(self, world):
        self.myWorld = world

        self.draw()

    #This function moves the animal a random direction at it's
    #speed.
    def randomMove(self):
        from random import randrange
        xDelta = randrange( -self.speed, self.speed+1)
        yDelta = randrange(-self.speed, self.speed+1)

        if self.xLoc + xDelta < 0:
            xDelta = -xDelta

        if self.xLoc + xDelta > self.myWorld.width:
            xDelta = -xDelta

        if self.yLoc + yDelta < 0:
            yDelta = -yDelta

        if self.yLoc + yDelta > self.myWorld.height:
            yDelta = -yDelta
            
        self.xLoc = self.xLoc + xDelta
        self.yLoc = self.yLoc + yDelta

        c = self.myWorld.canvas
        c.move(self.iconID, xDelta,yDelta)

        
        #Move the self.iconID on the canvas!
        pass
        
    def draw(self):
        #print("draw!")
        c = self.myWorld.canvas
        bbox = (self.xLoc-4, self.yLoc-4, self.xLoc+4, self.yLoc+4) 
        self.iconID = c.create_oval( bbox, fill= self.color)
        


class Fox(Animal):
    speed = 18
    color = "red"

    def __init__(self,xLoc,yLoc):
        super().__init__(xLoc,yLoc)

    def speak(self):
        print("Fox!", self.xLoc, self.yLoc)

class Rabbit(Animal):
   speed = 3
   color = "white"

   def __init__(self,xLoc,yLoc):
        super().__init__(xLoc,yLoc)

   def speak(self):
       pass
       #print("Rabbit!", self.xLoc, self.yLoc)

class Bear(Animal):
    speed=5
    color = "brown"

    def speak(self):
        pass
        #print("Bear!")


W = Tk()
sw = SimWorld(W, 300,200)

for x in range(50):
   x = randrange(0,299)
   y = randrange(0,199)
   a1 = Bear(x,y)
   sw.addAgent( a1 )
   a2 = Rabbit(x+1,y+1)
   sw.addAgent( a2 )

W.mainloop()


    
