使用乌龟图形和递归的希尔伯特曲线

时间:2018-11-10 22:18:52

标签: python recursion turtle-graphics fractals hilbert-curve

我正在尝试使用python turtle图形和递归来实现L系统生成的希尔伯特曲线。我的代码似乎适用于递归n = 1和n = 2的前两个级别,但除此之外,图形只是纠缠在一起(尽管我能够观察其中的其他模块),而且我似乎无法掌握这里可能出什么问题,我是否需要一些中间步骤来重新生成Hilbert模块以获得更深层次的递归?请在下面查看我的代码,它相对简单:

import turtle

def Hilbert_curve(A,rule,t,n):

    if n>=1:
        if rule:
            t.left(90)
            Hilbert_curve(A,not rule,t, n-1)
            t.forward(A)
            t.right(90)
            Hilbert_curve(A, rule,t, n-1)
            t.forward(A)
            Hilbert_curve(A,rule,t, n-1)
            t.right(90)
            t.forward(A)
            Hilbert_curve(A,not rule,t, n-1)
            t.left(90)
        else:
            t.right(90)
            Hilbert_curve(A,rule,t, n-1)
            t.forward(A)
            t.left(90)
            Hilbert_curve(A,not rule,t, n-1)
            t.forward(A)
            Hilbert_curve(A,not rule,t, n-1)
            t.left(90)
            t.forward(A)
            Hilbert_curve(A, rule,t, n-1)
            t.right(90)

def main():
    A=10
    t=turtle.Turtle()
    my_win=turtle.Screen()
    n=2
    rule=True
    Hilbert_curve(A,rule,t,n)
    my_win.exitonclick()

main()

Hilbert n=2

Hilbert n=3

1 个答案:

答案 0 :(得分:3)

问题出在您的else子句中。 rule已经被倒置到函数中,因此您需要将rule then 子句相同:

    else:
        t.right(90)
        Hilbert_curve(A, not rule, t, n - 1)
        t.forward(A)
        t.left(90)
        Hilbert_curve(A, rule, t, n - 1)
        t.forward(A)
        Hilbert_curve(A, rule, t, n - 1)
        t.left(90)
        t.forward(A)
        Hilbert_curve(A, not rule, t, n - 1)
        t.right(90)

但是,如果我们将rule从布尔值更改为数字parity,即1或-1,然后将parity乘以角度,则可以消除其中的一个原始if语句的两个子句:

from turtle import Screen, Turtle

def hilbert_curve(turtle, A, parity, n):

    if n < 1:
        return

    turtle.left(parity * 90)
    hilbert_curve(turtle, A, - parity, n - 1)
    turtle.forward(A)
    turtle.right(parity * 90)
    hilbert_curve(turtle, A, parity, n - 1)
    turtle.forward(A)
    hilbert_curve(turtle, A, parity, n - 1)
    turtle.right(parity * 90)
    turtle.forward(A)
    hilbert_curve(turtle, A, - parity, n - 1)
    turtle.left(parity * 90)

screen = Screen()

yertle = Turtle()
yertle.speed('fastest')  # because I have no patience

hilbert_curve(yertle, 10, 1, 4)

screen.exitonclick()

enter image description here