ClassyTurtles

From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search

Simple Turtle Graphics implemented in Python / PIL with a Class:

import Image, [[ImageDraw]]
import math

def deg2rad (deg):
	return ((deg / 360.0) * (math.pi * 2))

class Turtle:
	
	def __init__(self, draw):
		self.draw = draw
		self.x = 100
		self.y = 100
		self.heading = 0
	
	def forward (self, steps):
		turtleheadingradians = deg2rad(self.heading)
		newx = self.x + (math.cos(turtleheadingradians) * steps)
		newy = self.y - (math.sin(turtleheadingradians) * steps)
		self.draw.line((self.x, self.y, newx, newy))
		self.x = newx
		self.y = newy
	
	def left (self, angle):
		self.heading += angle

	def backward (self, steps):
		self.forward(-steps)

	def right(self, angle):
		self.left(-angle)

	def nsided (self, n, steps):
		for i in range(n):
			self.forward(steps)
			self.left(360/n)


if (__name__ == "__main__"):
	im = Image.new("RGB", (640, 480))
	draw = [[ImageDraw]].Draw(im)
	t = Turtle(draw)
	t.x = 320; t.y = 240
	t.nsided(5, 100)
	
	im.show()