简体   繁体   English

在 Python 中绘制摩尔曲线

[英]Plotting Moore Curve in Python

I'm trying to plot a Moore curve ( https://en.wikipedia.org/wiki/Moore_curve ) in python.我正在尝试 python 中的 plot 摩尔曲线( https://en.wikipedia.org/wiki/Moore_curve )。 I've gotten as far as plotting a Hillbert curve, as there seems to be more resources on Hillbert vs Moore, but it's not clear to me how to edit the subsequent iterations of the curve to make it plot the Moore curve correctly.我已经绘制了一条希尔伯特曲线,因为希尔伯特与摩尔似乎有更多的资源,但我不清楚如何编辑曲线的后续迭代以使其 plot 正确地成为摩尔曲线。

This is the python code for the Hillbert 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

How can I change this to plot the Moore curve?如何将其更改为 plot 摩尔曲线?

The Wikipedia page that you cite spells out how to do it using turtle graphics and an L-system.您引用的 Wikipedia 页面详细说明了如何使用海龟图形和 L 系统进行操作。 Just following those instructions, I came up with:只是按照这些说明,我想出了:

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()

在此处输入图像描述

And the fun part is, having implemented our L-system, by just changing the data, not the code, we can also make the Hilbert curve:有趣的是,在实现了我们的 L 系统后,只需更改数据而不是代码,我们还可以制作希尔伯特曲线:

from turtle import Screen, Turtle

AXIOM = 'A'

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

DISTANCE = 300
CYCLES = 6

# ...

在此处输入图像描述

Of course, the calculation of the distance variable does need a bit of work...当然, distance变量的计算确实需要一些工作......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM