我们刚开始在uni编程。我们的任务之一是使用L系统创建一个分形树,并在python中使用乌龟。这一个:
1. variables : X F
2. constants : + − [ ]
3. start : X
4. rules : (X → F-[[X]+X]+F[+FX]-X), (F → FF)
5. angle : 25°
代码:
def fraktal_plante(padde, depth):
Xmerke(padde, depth-1) # X
def Xmerke(padde, depth):
if depth > 0:# X ->
padde.forward(10) # F
padde.right(25) # -
padde.setposition()
padde.setheading() # [
padde.setheading() # [
Xmerke(padde, depth-1) # X
padde.heading()
padde.goto() # ]
padde.left(25) # +
Xmerke(padde, depth-1) # X
padde.heading() # ]
padde.left(25) # +
padde.forward(10) # F
padde.setposition()
padde.setheading() # [
padde.left(25) # +
padde.forward(10) # F
Xmerke(padde, depth-1) # X
padde.heading()
padde.goto() # ]
padde.right(25) # -
Xmerke(padde, depth-1) # X
def Fmerke (padde, depth):
if depth > 0: # Y ->
padde.forward(10) # F
padde.forward(10) # F
你可以看到它很乱。我想知道如何让乌龟记住它的位置并标题为“[”然后再返回它“]”。
我对此非常陌生,所以请以清晰易懂的方式回答。
答案 0 :(得分:3)
您可以致电turtle.heading()
获取海龟的当前目标。同样,它的当前位置由turtle.position()
返回。因此,您可以使用它们来保存其当前状态,然后使用这些值来还原它。这是一个简单的例子,说明如何使用它们来做你想做的事情:
from __future__ import print_function
def get_turtle_state(turtle):
""" Return turtle's current heading and position. """
return turtle.heading(), turtle.position()
def restore_turtle_state(turtle, state):
""" Set the turtle's heading and position to the given values. """
turtle.setheading(state[0])
turtle.setposition(state[1][0], state[1][1])
if __name__ == '__main__':
import turtle
tortoise = turtle.Turtle()
saved_state = get_turtle_state(tortoise)
print('saved state:', saved_state) # -> (0.0, (0.00,0.00))
tortoise.forward(100)
tortoise.left(90)
print('changed state:', get_turtle_state(tortoise)) # -> (90.0, (100.00,0.00))
restore_turtle_state(tortoise, saved_state)
print('restored state:', get_turtle_state(tortoise)) # -> (0.0, (0.00,0.00))
turtle.getscreen().ontimer(turtle.bye, 2000) # End script after a delay.
turtle.mainloop()