# L-15 MCS 275 Mon 18 Feb 2008 : turtle.py

from Tkinter import *
import math

class TurtleGraphics:
   """
   GUI for turtle graphics
   """
   def __init__(self,wdw,dimension):
      """
      Defines a Canvas, puts the turtle in the middle,
      sets the buttons turn and move, along with labels
      and entry fields, provided with default values.
      """
      wdw.title('turtle graphics')
      self.dim = dimension # dimension of the canvas
      self.angle = math.pi/2
      self.jump = 20
      self.c = Canvas(wdw,width=self.dim,\
        height=self.dim,bg ='white')
      # turn button, with label and entry for angle
      self.c.grid(row=0,column=0,columnspan=4)
      self.b0 = Button(wdw,text='turn',\
        command = self.Turn)
      self.b0.grid(row=1,column=0,columnspan=2,sticky=W+E)
      self.L0 = Label(wdw,text="angle:",justify=RIGHT)
      self.L0.grid(row=2,column=0)
      self.e0 = Entry(wdw)
      self.e0.grid(row=2,column=1,sticky=W+E)
      self.e0.insert(INSERT,self.angle)
      # move button, with label and entry for jump
      self.b1 = Button(wdw,text='move',\
        command = self.Move)
      self.b1.grid(row=1,column=2,columnspan=2,sticky=W+E)
      self.L1 = Label(wdw,text="jump:",justify=CENTER)
      self.L1.grid(row=2,column=2)
      self.e1 = Entry(wdw)
      self.e1.grid(row=2,column=3,sticky=W+E)
      self.e1.insert(INSERT,self.jump)
      # initial coordinates of the turtle
      self.x = self.dim/2
      self.y = self.dim/2
      self.dir = 0
      self.DrawTurtle()

   def DrawTurtle(self):
      """
      Draws the turtle on the canvas.
      """
      self.c.delete('turtle')
      x = self.x; y = self.y
      self.c.create_oval(x-6,y-6,x+6,y+6,width=1,\
        outline='black',fill='green',tags='turtle')
      self.c.delete('arrow')
      dx = 10*math.cos(self.dir)
      dy = 10*math.sin(self.dir)
      self.c.create_line(x,y,x+dx,y+dy,width=2,\
        tags='arrow')

   def Turn(self):
      """
      Makes the turtle turn clockwise.
      """
      self.angle = float(self.e0.get())
      self.dir = self.dir + self.angle
      self.DrawTurtle()

   def Move(self):
      """
      Moves the turtle in the current direction.
      """
      self.jump = float(self.e1.get())
      dx = self.jump*math.cos(self.dir)
      dy = self.jump*math.sin(self.dir)
      x = self.x; y = self.y
      nx = x + dx; ny = y + dy
      self.x = nx; self.y = ny
      self.DrawTurtle()
      self.c.create_line(x,y,nx,ny,width=2)
  
def main():
   top = Tk()
   dimension = 400 # dimension of the canvas
   show = TurtleGraphics(top,dimension)
   top.mainloop()

if __name__ == "__main__": main()
