使用海龟图形恢复 l 系统代码中记录的状态
我正在使用海龟图形来重现 l-系统(TurtleWorld 库)。我尝试应用的规则在不涉及返回到以前保存的状态时效果很好,但是每当有 [ 和 ] (参见下面的规则)时,事情就会中断,海龟只会绘制随机的 bs。
基本上,我认为检查“]”出现位置的 IF 语句就是代码中断的地方。 (另外,我知道它目前还没有优化,为了清楚起见,我已经编写了一个可靠的 IF...)
编辑:新代码 - 这整个计算角度的事情是不必要的,因为我们有 get_heading(),它告诉我们我们所处的角度。
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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一些想法:
]
处理程序中将angle
设置为新角度 (newa
)。newa>0
会将其向左转。pop
代替,并推送一个元组或类似的状态,您可以大大简化代码。-1
等于len(lst) - 1
。pop
-建议示例: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 tolen(lst) - 1
.Example of the
pop
-suggestion: