Add simple turtle graphics generator
This commit is contained in:
parent
30da19afd6
commit
d0e64ae692
54
svgturtle.py
Normal file
54
svgturtle.py
Normal file
|
@ -0,0 +1,54 @@
|
|||
import math
|
||||
import sys
|
||||
|
||||
class SvgTurtle():
|
||||
def __init__(self, homex=0, homey=0):
|
||||
self.homex = homex
|
||||
self.homey = homey
|
||||
self.cvtangle = math.tau/360
|
||||
self.reset()
|
||||
|
||||
def penup(self):
|
||||
self.pen = False
|
||||
|
||||
def pendown(self):
|
||||
self.pen = True
|
||||
|
||||
def forward(self, distance):
|
||||
if self.pen and (self.path == ''):
|
||||
self.path = "M %.2f,%.2f" % (self.x,self.y)
|
||||
dx = distance*math.cos(self.heading)
|
||||
dy = distance*math.sin(self.heading)
|
||||
self.x += dx
|
||||
self.y += dy
|
||||
if self.pen:
|
||||
if abs(dy) < .01:
|
||||
self.path += " h %.2f" % dx
|
||||
elif abs(dx) < .01:
|
||||
self.path += " v %.2f" % dy
|
||||
else:
|
||||
self.path += " l %.2f,%.2f" % (dx, dy)
|
||||
elif self.path != '':
|
||||
self.path += " m %.2f, %.2f" % (dx, dy)
|
||||
|
||||
def back(self, distance):
|
||||
self.forward(-distance)
|
||||
|
||||
def left(self, angle):
|
||||
self.right(-angle)
|
||||
|
||||
def right(self, angle):
|
||||
self.heading = (self.heading + angle*self.cvtangle) % math.tau
|
||||
|
||||
def to_s(self):
|
||||
return self.path
|
||||
|
||||
def home(self):
|
||||
self.x = self.homex
|
||||
self.y = self.homey
|
||||
self.heading = 0
|
||||
|
||||
def reset(self):
|
||||
self.path = ''
|
||||
self.pen = True
|
||||
self.home()
|
Loading…
Reference in New Issue
Block a user