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