Dbirkeland
Dbirkeland

Reputation: 51

How to make fractal plants with l-system in turtle graphics?

I am trying to make this fractal plant (Example 7) from Wikipedia. However, even though I use the same rules I end up with something that looks more like a tree. Here is the code:

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)

Can you help me? I am new to python so please explain in an easy way!

Upvotes: 2

Views: 5275

Answers (1)

Robᵩ
Robᵩ

Reputation: 168626

I think the reason you have a tree is your .forward() step is too large. Try paddle.forward(1) instead of 12.

For what it is worth, here is what I wrote from the wikipedia description:

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

Upvotes: 6

Related Questions