Python turtle 库 自学5

Turtle(海龟库)

  • 1、递归及旋转圆形的画法
  • 2、递归及分形树的画法

1、递归及旋转圆形的画法

import turtle
import random

pen = turtle.Turtle()
# 创建一支画笔 pen
turtle.colormode(255)
# 先设置 colormode 选项
pen.speed(0)
# 将速度设置为最快


def circle(radius):
    if radius == 200:
        return
    else:
        pen.color(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        pen.circle(radius)
        pen.right(2)
        circle(radius + 1)


circle(50)

turtle.done()
# 让屏幕暂停

2、递归及分形树的画法

import turtle

pen = turtle.Turtle()
# 创建一支画笔 pen
turtle.colormode(255)
# 先设置 colormode 选项
pen.speed(0)
# 将速度设置为最快

r, g, b = 0, 0, 0
length = 120
# 树干的长度
pen_size = 14
# 画笔的粗细
pen.pensize(pen_size)
# 设置画笔的粗细为 pen_size
pen.penup()
# 提起画笔
pen.left(90)
# 画笔左转 90°
pen.backward(length)
# 画笔倒退树干的长度
pen.pendown()
# 放下画笔
pen.forward(length)
# 画出树干


def draw_tree(l, lv):
    # 第一次调用 l = 120
    l = l * 3/4
    # 改变树干长度
    size = pen.pensize()
    # 当前画笔的粗细返回给 size 变量
    pen.pensize(size * 3/4)
    # 改变画笔的粗细

    # 改变颜色
    global r, g, b
    r += 1
    g += 2
    b += 3
    pen.color(r % 200, g % 200, b % 200)

    # 左边枝干
    pen.left(45)
    pen.forward(l)
    # 左边枝干的递归
    if lv < 14:
        draw_tree(l, lv + 1)
    pen.backward(l)
    pen.right(90)

    # 右边枝干
    pen.forward(l)
    # 右边枝干的递归
    if lv < 14:
        draw_tree(l, lv + 1)
    pen.backward(l)
    pen.left(45)
    pen.pensize(size)


draw_tree(length, 13)
# length = 120
turtle.done()
# 让屏幕暂停

你可能感兴趣的:(Python,turtle,库,python,二叉树,turtle)