0

我正在尝试在 python中绘制摩尔曲线( https://en.wikipedia.org/wiki/Moore_curve )。我已经绘制了一条希尔伯特曲线,因为希尔伯特与摩尔似乎有更多的资源,但我不清楚如何编辑曲线的后续迭代以使其正确绘制摩尔曲线。

这是希尔伯特曲线的 Python 代码:

def d2xy(n,d):
    t=d
    x=y=0
    s=1
    while s<n:
        rx=1&(t/2)
        ry=1&(t^rx)
        s,x,y,rx,ry=rot(s,x,y,rx,ry)
        x+=s*rx
        y+=s*ry
        t/=4
        s*=2
    return x,y

def rot(n,x,y,rx,ry):
    if ry==0:
        if rx==1:
            x=n-1-x
            y=n-1-y
        x,y=y,x

    return n,x,y,rx,ry

我怎样才能改变它来绘制摩尔曲线?

4

1 回答 1

0

您引用的 Wikipedia 页面详细说明了如何使用海龟图形和 L 系统进行操作。只是按照这些说明,我想出了:

from turtle import Screen, Turtle

AXIOM = 'LFL+F+LFL'

RULES = {
    'L': '-RF+LFL+FR-',
    'R': '+LF-RFR-FL+',
}

DISTANCE = 300
CYCLES = 4

def draw(string, distance):
    for character in string:
        if character == 'F':
            turtle.forward(distance)
        elif character == '+':
            turtle.right(90)
        elif character == '-':
            turtle.left(90)
        else:
            pass  # ignore other characters

def produce(string):
    production = ''

    for character in string:
        if character in RULES:
            production += RULES[character]
        else:
            production += character  # just copy other characters

    return production

screen = Screen()
screen.tracer(False)

turtle = Turtle()
turtle.hideturtle()
turtle.setheading(90)

string = AXIOM

for _ in range(1, CYCLES):
    string = produce(string)

distance = DISTANCE / CYCLES ** 2  # crude estimate, fix this

draw(string, distance)

screen.tracer(True)
screen.exitonclick()

在此处输入图像描述

有趣的是,在实现了我们的 L 系统后,只需更改数据而不是代码,我们还可以制作希尔伯特曲线:

from turtle import Screen, Turtle

AXIOM = 'A'

RULES = {
    'A': '-BF+AFA+FB-',
    'B': '+AF-BFB-FA+',
}

DISTANCE = 300
CYCLES = 6

# ...

在此处输入图像描述

当然,distance变量的计算确实需要一些工作......

于 2020-08-07T06:02:39.403 回答