我正试图从维基百科中制作this fractal plant(例7)。然而,即使我使用相同的规则,我最终会看到更像树的东西。这是代码:
def fraktal_plante(padde, depth):
Xmerke(padde, depth-1) # X
def Xmerke(padde, depth):
if depth > 0:
padde.forward(12)
padde.right(25)
pos1 = padde.position()
head1 = padde.heading()
Xmerke(padde, depth-1)
padde.up()
padde.goto(pos1)
padde.setheading(head1)
padde.down()
padde.left(25)
Xmerke(padde, depth-1)
padde.up()
padde.goto(pos1)
padde.setheading(head1)
padde.down()
padde.left(25)
padde.forward(12)
pos2 = padde.position()
head2 = padde.heading()
padde.left(25)
padde.forward(12)
Xmerke(padde, depth-1)
padde.up()
padde.goto(pos2)
padde.setheading(head2)
padde.down()
padde.right(25)
Xmerke(padde, depth-1)
def Fmerke (padde, depth):
if depth > 0:
padde.forward(12)
padde.forward(12)
你能帮帮我吗?我是python的新手,所以请以简单的方式解释!
答案 0 :(得分:6)
我认为您拥有树的原因是.forward()
步骤过大。请尝试使用paddle.forward(1)
代替12
。
对于它的价值,这是我从维基百科的描述中写的:
import turtle
import sys
def generate(n, result='[X]'):
for _ in range(n):
# rule #2
result = result.replace('F', 'FF')
# rule #1
result = result.replace('X', 'F-[[X]+X]+F[+FX]-X')
return result
def draw(cmds, size=2):
stack = []
for cmd in cmds:
if cmd=='F':
turtle.forward(size)
elif cmd=='-':
turtle.left(25)
elif cmd=='+':
turtle.right(25)
elif cmd=='X':
pass
elif cmd=='[':
stack.append((turtle.position(), turtle.heading()))
elif cmd==']':
position, heading = stack.pop()
turtle.penup()
turtle.setposition(position)
turtle.setheading(heading)
turtle.pendown()
else:
raise ValueError('Unknown Cmd: {}'.format(ord(cmd)))
turtle.update()
def setup():
turtle.hideturtle()
turtle.tracer(1e3,0)
turtle.left(90)
turtle.penup()
turtle.goto(0,-turtle.window_height()/2)
turtle.pendown()
setup()
plant = generate(6)
draw(plant, 2)
turtle.exitonclick()