Restore recorded state in l-system code using turtles

I use tortoise graphics to play l-systems (TurtleWorld library). The rules that I tried to apply work well when they are not related to returning to the previous saved state, but whenever [and] (see the Rule below), everything breaks and the turtle simply draws random letters.

Basically, an IF statement that checks where ']' is is where the code breaks, I think. (In addition, I know that this is not optimized at the moment, I wrote a solid IF for the sake of clarity ...)

EDIT: new code - this whole computational angle is not needed, since we have get_heading () that informs us of which angle we are oriented to.

import turtle turtle.down() n = 'F' s1 = 'F' s2 = 'FF-[-F+F+F]+[+FFF]' #s3 = 'F' #s4 = 'FF' steps = 5 for i in range(steps): n = n.replace(s1,s2) #n = n.replace(s3,s4) a = 25 x = [] y = [] angle = [] for i in n: if i == 'F': turtle.forward(2) if i == '+': turtle.left(a) if i == '-': turtle.right(a) if i=='[': x.append(turtle.xcor()) y.append(turtle.ycor()) angle.append(turtle.heading()) if i==']': turtle.pu() turtle.setpos(x[len(x)-1],y[len(y)-1]) turtle.right(turtle.heading()) turtle.setheading(angle[len(angle)-1]) x.pop() y.pop() angle.pop() turtle.pd() 
+4
source share
1 answer

A few ideas:

  • You never set angle to a new angle ( newa ) in ] -handler.
  • Your conditional is incorrect according to the comment, newa>0 will turn it left if the angle is positive.
  • Are you sure rt handles negative angles well?
  • You can greatly simplify your code by using pop instead, and pushing a tuple or something like state.
  • Index -1 is len(lst) - 1 .

Example pop -suggestion:

 >>> state = [] >>> angle = 90 >>> posx = 10 >>> posy = 15 >>> state.append((angle, posx, posy)) >>> angle = 40 >>> angle, posx, posy = state.pop() >>> angle 90 
+2
source

All Articles