문제

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()
도움이 되었습니까?

해결책

A couple of ideas:

  • You never set angle to the new angle (newa) in your ]-handler.
  • Your conditional is wrong according to the comment, newa>0 would turn it left if the angle is positive.
  • Are you sure rt handles negative angles well?
  • You could simplify your code a lot if you use pop instead, and pushed a tuple or somesuch of the state.
  • An index of -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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top