Skip to content

Instantly share code, notes, and snippets.

@newton-migosi
Last active July 20, 2018 11:57
Show Gist options
  • Save newton-migosi/d58101c079533122f2e362207d7cf869 to your computer and use it in GitHub Desktop.
Save newton-migosi/d58101c079533122f2e362207d7cf869 to your computer and use it in GitHub Desktop.
Python script for visualizing L Systems using turtle. Run it online: https://trinket.io/python/a050d41536
import turtle
def main(lString):
wn = turtle.Screen()
kurt = turtle.Turtle()
scheme = makeLSystem(lString)
drawLSystem(kurt, scheme)
def makeLSystem(lString, times=5):
seed = lString.split('\n')[0]
acc = seed
schema = lStringtoDict(lString)
for i in range(times):
acc = parse(acc, schema)
return acc
def lStringtoDict(lString):
lines = [line.split(' ') for line in lString.split('\n')[1:]]
return {line[0] : line[-1] for line in lines}
def parse(scheme, schema):
acc = ''
for ch in scheme:
if ch in schema.keys() :
acc += schema[ch]
continue
acc += ch
return acc
def drawLSystem(t, scheme,angle=25.7):
infoList = []
def convert(t, char, angle, lyst, dist=5):
if char == 'F' : t.forward(dist)
elif char == 'B' : t.backward(dist)
elif char == '+' : t.left(angle)
elif char == '-' : t.right(angle)
elif char == '[' :
lyst.append([t.heading(), t.xcor(), t.ycor()])
elif char == ']' :
tLoc = lyst.pop()
t.seth(tLoc[0])
t.setposition(tLoc[1], tLoc[2])
for char in scheme:
convert(t, char, angle, infoList)
if __name__ == '__main__':
lString = '''H
H --> HFX[+H][-H]
X --> X[-FFF][+FFF]FX'''
main(lString)
### First Line is the seed (and angle) to initialize the system
### Trailing lines are the rules for the L System
### Obtained from : https://runestone.academy/runestone/static/thinkcspy/Strings/Exercises.html
# Hilbert Curve
L
L -> +RF-LFL-FR+
R -> -LF+RFR+FL-
# Dragon Curve
FX 90
X -> X+YF+
Y -> -FX-Y
# Arrowhead Curve
YF 60
X -> YF+XF+Y
Y -> XF-YF-X
# Peano-Gosper Curve
FX 60
X -> X+YF++YF-FX--FXFX-YF+
Y -> -FX+YFYF++YF+FX--FX-Y
# The Sierpinski Triangle
FXF--FF--FF
F -> FF
X -> --FXF++FXF++FXF--
# Garden Herb
H 25.7
H --> HFX[+H][-H]
X --> X[-FFF][+FFF]FX
F 25
F --> F[-F]F[+F]F
X
X --> F[-X]+X
F --> FF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment