Reputation: 1232
I'm using turtle graphics to reproduce l-systems (TurtleWorld library). The rules I have tried to apply work well when they don't involve going back to a previous saved state, but whenever there is a [ and ] (see rule below), things break and the turtle just draws random bs.
Basically, the IF statement that checks where ']'is present, is where the code breaks, I think. (Also, I know it's not optimized for the moment, I have written a solid IF for clarity's sake...)
EDIT : New code - this whole calculating angle thing was not necessary, as we have get_heading(), which informs us of the angle we're oriented into.
import turtle
turtle.down()
n = 'F'
s1 = 'F'
s2 = 'FF-[-F+F+F]+[+F-F-F]'
#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()
Upvotes: 4
Views: 779
Reputation: 22149
A couple of ideas:
angle
to the new angle (newa
) in your ]
-handler.newa>0
would turn it left if the angle is positive.rt
handles negative angles well?pop
instead, and pushed a tuple or somesuch of the state.-1
is equal to len(lst) - 1
.Example of the pop
-suggestion:
>>> state = []
>>> angle = 90
>>> posx = 10
>>> posy = 15
>>> state.append((angle, posx, posy))
>>> angle = 40
>>> angle, posx, posy = state.pop()
>>> angle
90
Upvotes: 2