Python Turtle draw fractal tree understanding recursion

Recursive thinking

Recursion can turn a complex problem into a smaller problem similar to the original problem. By calling yourself, you can find the conditions to finally solve the problem and return when the judgment conditions are met.

Understanding recursion through fractal trees

We can find that the branches of the tree are all the same and have the same structure

First consider the simple bottom two branches, we can let the turtle go up an initial distance at the beginning

def draw_tree(size):
    if size > SIZE_TREE:  # 如果size在范围内,那么可以画树
        # 右边

        turtle.forward(size)     # 先向前走size
        turtle.right(20)         # 右转20°
        draw_tree(size / 1.5)    # 再继续右转 长度减半 走不动时往左边转40°
        # 左边
        turtle.left(40)         # 左转40°
        draw_tree(size / 1.5)   # 画左边的树 长度减半 走不动时 右转20回到原来角度

        # 回到之前的树枝
        turtle.right(20)
        turtle.backward(size) # 退回去画的是原来的长度

Follow the steps like this

We can set the speed of the turtle in the main function to make it slower, so that we can see the track:

You can change the color of the last branch

"""
    作者:MO
    功能:绘制分形树
    版本:1.0
    日期:2019/3/05
"""
import turtle

SIZE_TREE = 10

def draw_tree(size):
    if size > SIZE_TREE:
        # 右边

        turtle.forward(size)
        turtle.right(20)
        draw_tree(size / 1.5)
        # 左边
        turtle.left(40)
        draw_tree(size / 1.5)

        # 回到之前的树枝
        turtle.right(20)
        # 给最后的树枝画绿色
        if size / 2 <= SIZE_TREE:
            turtle.color('green')
        else:
            turtle.color('brown')
        turtle.backward(size)

def main():
    turtle.speed(1)
    turtle.hideturtle()
    turtle.penup()
    # 方向向上
    turtle.left(90)
    turtle.backward(100)
    turtle.showturtle()
    # 画笔隐形
    # 画笔有效
    turtle.pendown()
    turtle.pensize(2)
    turtle.color('brown')
    # 给出根的长度
    draw_tree(50)

if __name__ == '__main__':
    main()
turtle.done()

Guess you like

Origin www.linuxidc.com/Linux/2020-04/162886.htm