【问题标题】:Plotting Moore Curve in Python在 Python 中绘制摩尔曲线
【发布时间】:2020-11-27 04:49:38
【问题描述】:

我正在尝试在 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

如何更改它以绘制摩尔曲线?

【问题讨论】:

  • 请从intro tour 重复on topic 和[如何提问](stackoverflow.com/help/how-to-ask)。 “告诉我如何实现这个功能”不是 Stack Overflow 问题。你必须做出诚实的尝试,然后然后就你的算法或技术提出一个具体的问题。

标签: python fractals space-filling-curve


【解决方案1】:

您引用的 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 变量的计算确实需要一些工作......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2011-05-25
    • 2017-09-11
    • 2017-09-04
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多