Advertisement
calcpage

CSH2012 turtleLsystem.py

Apr 19th, 2013
433
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. #!/usr/bin/python
  2. import turtle
  3.  
  4. def createLSystem(numIters,axiom):
  5.     startString = axiom
  6.     endString = ""
  7.     for i in range(numIters):
  8.         endString = processString(startString)
  9.         startString = endString
  10.  
  11.     return endString
  12.  
  13. def processString(oldStr):
  14.     newstr = ""
  15.     for ch in oldStr:
  16.         newstr = newstr + applyRules(ch)
  17.  
  18.     return newstr
  19.  
  20. def applyRules(ch):
  21.     newstr = ""
  22.     if ch == '-':
  23.         newstr = '+RF-LFL-FR+'   # Rule 1
  24.     elif ch=='+':
  25.         newstr = '-LF+RFR+FL-'   # Rule 2
  26.     else:
  27.         newstr = ch    # no rules apply so keep the character
  28.  
  29.     return newstr
  30.  
  31. def drawLsystem(aTurtle,instructions,angle,distance):
  32.     for cmd in instructions:
  33.         if cmd == 'F':
  34.             aTurtle.forward(distance)
  35.         elif cmd == 'B':
  36.             aTurtle.backward(distance)
  37.         elif cmd == '+':
  38.             aTurtle.right(angle)
  39.         elif cmd == '-':
  40.             aTurtle.left(angle)
  41.         else:
  42.             print('Error:', cmd, 'is an unknown command')
  43.  
  44. def main():
  45.     inst = createLSystem(2,"F")   #create the string
  46.     print(inst)
  47.     t = turtle.Turtle()           #create the turtle
  48.     wn = turtle.Screen()
  49.  
  50.     t.up()
  51.     t.back(200)
  52.     t.down()
  53.     t.speed(9)
  54.     drawLsystem(t,inst,90,10)      #draw the picture
  55.                                   #angle 60, segment length 5
  56.     wn.exitonclick()
  57.  
  58. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement