Python's turtle library draws fractal trees and snowflake-shaped Koch curves

1. Please use recursive functions to design and draw a fractal tree.

import turtle

p = turtle.Turtle ()
turtle.colormode(255)
p.speed(0)
r=0
g=0
b=0
length=120
size=14

p.home()
p.penup()
p.left(90)
p.backward(length)
p.pendown()
p.pensize(size)
p.forward(length)
#随树枝生长颜色变化
def tree(l,lv):
    l*=3/4
    size=p.pensize()
    p.pensize(size*3/4)
    global r,g,b
    r+=20
    g+=40
    b+=60
    p.pencolor(r%256,g%256,b%256)
#左边树枝运用递归画图
    p.left(45)
    p.forward(l)
    if lv < 14:
        tree(l, lv + 1)
#右边树枝运用递归画图
    p.backward(l)
    p.right(90)
    p.forward(l)
    if lv < 14:
        tree(l, lv + 1)
    p.backward (l)
    p.left(45)
    p.pensize(size)

tree(120,9)
turtle.done()

        Run the legend:

2. Please draw a Koch curve that can express the shape of a snowflake.

import turtle

#定义函数实现科赫曲线绘画
def koch(t, n):
    if n < 5:
        t.fd(n)
        return
    m = n / 3
    koch(t, m)
    t.lt(60)
    koch(t, m)
    t.rt(120)
    koch(t, m)
    t.lt(60)
    koch(t, m)
#定义函数实现雪花
def snowflake(t, n):
    for i in range(3):
        koch(t, n)
        t.rt(120)

bob = turtle.Turtle()
bob.color('black')
bob.penup() #提笔
bob.goto(-150,90) #去点
bob.pendown() #落笔
snowflake(bob, 300) #画雪花

turtle.speed(0)#设置绘画速度
turtle.mainloop()

         Run the legend:

Guess you like

Origin blog.csdn.net/qq_59470001/article/details/132811105