## This is a combination of Listings 9.6, 9.7 (with a bug fix), and ## 9.8 (with minor improvements) from Python Programming in Context by ## Miller and Ranum to serve as a starting point for an MCS-177 ## project. from cTurtle import Turtle ## Listing 9.6 def applyProduction(axiom,rules,n): for i in range(n): newString = "" for ch in axiom: newString = newString + rules.get(ch,ch) axiom = newString return axiom ## Listing 9.7 def drawLS(aTurtle,instructions,angle,distance): stateSaver = [] for cmd in instructions: if cmd == 'F': aTurtle.forward(distance) elif cmd == 'B': aTurtle.backward(distance) elif cmd == '+': aTurtle.right(angle) elif cmd == '-': aTurtle.left(angle) elif cmd == '[': pos = aTurtle.position() head = aTurtle.heading() stateSaver.append((pos,head)) elif cmd == ']': pos,head = stateSaver.pop() aTurtle.up() # this line was not in Listing 9.7 (a bug) aTurtle.setposition(pos) aTurtle.setheading(head) aTurtle.down() # this line was not in Listing 9.7 (a bug) ## Listing 9.8 def lsystem(axiom,rules,depth,initialPosition,heading,angle,length): aTurtle = Turtle() aTurtle.speed(0) # this line improves on Listing 9.8 aTurtle.shape('blank') # this line improves on Listing 9.8 aTurtle.up() aTurtle.setposition(initialPosition) aTurtle.down() aTurtle.setheading(heading) ## The variable "instructions" was called "newRules" in Listing 9.8, ## which was misleading regarding what kind of thing it names. instructions = applyProduction(axiom,rules,depth) drawLS(aTurtle,instructions,angle,length) aTurtle.exitOnClick()