Skip to content

Instantly share code, notes, and snippets.

@goldsamantha
Created August 12, 2015 18:43
Show Gist options
  • Save goldsamantha/69eb8fd082a5399aa00b to your computer and use it in GitHub Desktop.
Save goldsamantha/69eb8fd082a5399aa00b to your computer and use it in GitHub Desktop.
"""
For recursively drawing turtle functions
Samantha Goldstein
April, 2012
"""
import turtle
def main():
turtle.setup(width= 500, height= 500)
turtle.up()
levels = input("How many levels?: ")
turtle.setpos(-250, 0)
#turtle.setpos(0, -250)
turtle.down()
#levels = 3
line_size = float(turtle.window_width())/3**levels
line_size2 = float(turtle.window_width())/(2**(levels+1)-1)
#turtle.setheading(90)
#turtle.setpos(0,0)
#drawCodestring("F[-F]+F", turtle, 50, 30)
cdstring = koch_production("F", levels)
#cdstring = shrub_production("F", levels)
#drawCodestring(cdstring, turtle, line_size2, 25)
drawCodestring(cdstring, turtle, line_size, 60)
turtle.hideturtle()
turtle.exitonclick()
def drawCodestring(cdstring, trtl, size, agl):
state = []
for i in range(len(cdstring)):
if cdstring[i] == 'F':
trtl.forward(size)
elif cdstring[i] == '-':
trtl.left(agl)
elif cdstring[i] == '+':
trtl.right(agl)
elif cdstring[i] == '[':
pos = trtl.pos()
head = trtl.heading()
state.append([head, pos])
elif cdstring[i] == ']':
head, pos = state.pop()
trtl.up()
trtl.setpos(pos)
trtl.down()
trtl.setheading(head)
return
def koch_production(codestring, n):
if n == 0:
#return "F"
return codestring
else:
cd = ""
#codestring = list(codestring)
for i in range(len(codestring)):
if codestring[i] == "F":
cd = cd + "F-F++F-F"
else:
cd = cd + codestring[i]
#for i in range(1,len(codestring)):
#codestring[0] = codestring[0] + codestring[i]
#print
#return koch_production(codestring[0], n-1)
return koch_production(cd, n-1)
def shrub_production(codestring, n):
if n == 0:
return codestring
else:
codestring = list(codestring)
for i in range(len(codestring)):
if codestring[i] == "F":
codestring[i] = "F[-F]F[+F][F]"
for i in range(1, len(codestring)):
codestring[0] = codestring[0] + codestring[i]
return shrub_production(codestring[0], n-1)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment