""" turtle.py Papert's turtle graphics, with a 'turtle' that can turns and moves, drawing a line as it goes. Uses the graphics.py package from Zell's 'Python Programming' text. Colors are strings like 'black', 'red1', 'red3', '#ff0000'. Example of drawing a square : $ python >>> from turtle import Turtle >>> t = Turtle(width=200, height=200) >>> for i in range(4): ... t.move(20) ... t.turn(90) """ from graphics import GraphWin, Point, Line from math import sin, cos, pi class Turtle: """ Turtles can turn, move, and trace a line when their pen is down. """ def __init__(self, width=400, height=400, color="black", background="white" ): title = "Turtle_Graphics" self.window = GraphWin(title, width, height) self.window.setCoords(-width/2, -height/2, width/2, height/2) self.window.setBackground(background) self.color=color self.pi_over_180 = pi/180.0 self.reset() def setColor(self, color): self.color=color def getPenDown(self): return self.penDown def setPenDown(self, state): self.penDown = state def penDown(self): self.penDown = True def penUp(self): self.penDown = False def reset(self): self.x = 0.0 self.y = 0.0 self.angle = 0.0 # in degress self.penDown = True def jump(x=0, y=0): self.x = x self.y = y def turn(self, angle): self.angle += float(angle) def move(self, distance): x = self.x y = self.y d = float(distance) self.x = x + d * cos( self.angle * self.pi_over_180 ) self.y = y + d * sin( self.angle * self.pi_over_180 ) if self.penDown: line = Line(Point(x, y), Point(self.x, self.y)) line.setOutline(self.color) line.draw(self.window)