2

我正在尝试从维基百科制作这种分形植物(示例 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新手,所以请用简单的方式解释!

4

1 回答 1

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()
于 2013-10-03T15:36:32.750 回答