Code:
[python]
import math
start = "+++++++++++++X"
iterations = 7 # how many iterations to do
delta = 1.5
# Start: X
# Rules:
# X --> F[T+++++++++X]-F[S-----------!X]RX
def generate(l):
r=""
for x in l: # Go through the list of actions, expand according to rules above
if x == 'F':
r = r + "FF"
elif x == 'X':
r = r + "F[T+++++++++X]-F[S-----------!X]RX"
else:
r = r + x # Copy character over, no expansion
return r
def Draw(f,s):
cur_angle = math.radians(360) # Start angle in radians -- looks best if we start at 90degrees
angle = math.radians(7.2) # we turn left or right by this angle
store = [] # For saving the current position
pos = (400,400) # Start position (in 2D plane)
delta = 1.5
for c in s:
if c == 'F': # means draw forward, number of units
x,y = pos
# compute new position
newx,newy = x + delta*math.cos(cur_angle), y + delta*math.sin(cur_angle)
# draw the line
f.write('<line x1="%.2f" y1="%.2f" x2="%.2f" y2="%.2f" />\n' % (x,y,newx,newy))
pos = (newx,newy) # We move to new position
elif c == 'T':
delta*0.5
elif c == 'S':
delta*0.4
elif c == 'R':
delta*0.6
elif c == '!':
if c == '-':
cur_angle-=angle
if c == '+':
cur_angle+=angle
elif c == '-':
cur_angle += angle
elif c == '+':
cur_angle -= angle
elif c == '[': # means save current position
store.append((pos,cur_angle))
elif c == ']': # get back last saved position, angle
pos,cur_angle = store.pop()
else: # Ignore all others (as per spec)
pass
# Now starts the program proper
end = start
for i in range(0,iterations):
end = generate(end)
f = open("tumble weed.svg", "w")
#Print SVG preamble
f.write("<?xml version='1.0'?>\n")
f.write("<svg xmlns='http://www.w3.org/2000/svg'>\n")
f.write("<g id=\"x\" stroke=\"blue\">\n")
Draw(f,end) # Draw the image
f.write("</g>\n</svg>\n")
f.close()
Comment