Search code examples
pythonturtle-graphicsfractals

Drawing a fractal tree in Python


I am trying to draw a fractal tree in Python, which has 3 branches. I know how to draw a tree with 2 branches, but with three branches...not sure Tried to find examples, but couldn`t. Only found examples of trees with two branches. Does anybody have any ideas how to do that?

For 2 branches tree I used the following code:

import turtle
def tree(f_lenght, min_lenght=10):
    """
    Draws a tree with 2 branches using recursion
    """
    turtle.forward(f_lenght)
    if f_lenght > min_lenght:
        turtle.left(45)
        tree(0.6*f_lenght, min_lenght)
        turtle.right(90)
        tree(0.6*f_lenght, min_lenght)
        turtle.left(45)
    turtle.back(f_lenght)

turtle.left(90)
tree(100)
turtle.exitonclick()

Solution

  • Here is an expanded example. Using your method to make branches, it is very easy to make them overlap so I added a few parameters to help with that. Feel free to play around with the code, but this is an example of arbitrary levels of recursion.

    import turtle
    def tree(f_length, spray=90., branches=2, f_scale=0.5, f_scale_friction=1.4, min_length=10):
        """
        Draws a tree with 2 branches using recursion
        """
        step = float(spray / (branches - 1))
        f_scale /= f_scale_friction
        turtle.forward(f_length)
        if f_length > min_length:
            turtle.left(spray / 2)
            tree(f_scale * f_length, spray, branches, f_scale, f_scale_friction, min_length)
            for counter in range(branches - 1):
                turtle.right(step)
                tree(f_scale * f_length, spray, branches, f_scale, f_scale_friction, min_length)
            turtle.left(spray / 2)
        turtle.back(f_length)
    
    turtle.left(90)
    tree(80, spray=120, branches=4)
    turtle.exitonclick()