2

我们刚刚开始在 uni 编程。我们的任务之一是在 Python 中使用带有海龟的 L 系统创建分形树。这个:

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

如您所见,它很混乱。我想知道如何让乌龟记住它的位置和标题“[”,然后再返回它“]”。

我对此真的很陌生,所以请以清晰易懂的方式回答。

4

1 回答 1

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()
于 2013-10-01T22:04:34.437 回答