# -*- coding: utf8 -*-
"""
绘制分形树
"""
import turtledeflection_angle = 20 # 树枝与树干夹角
trunk_min_length = 5 # 树干最小长度
trunk_step_length = 10 # 树干每次递减长度
trunk_length = 80 # 初始树干长度
treetop_length = 30 # 树梢部分长度
treetop_color = 'green' # 主树干颜色
treetrunk_color = 'brown' # 树梢部分颜色
pen_size = 10 # 画笔初始宽度
pen_step_size = 2 # 画笔每次递减宽度
pen_min_size = 1 # 画笔最小宽度def DrawFractalTree(trunk_length, pen_size):if trunk_length >= trunk_min_length:turtle.pensize(pen_size if pen_size > pen_min_size else pen_min_size)# 画笔颜色turtle.pencolor((treetop_color, treetrunk_color)[trunk_length > treetop_length])# 画树干turtle.fd(trunk_length)# 绘制右侧树枝turtle.rt(deflection_angle)DrawFractalTree(trunk_length - trunk_step_length, pen_size - pen_step_size)# 绘制中间树枝turtle.lt(deflection_angle)DrawFractalTree(trunk_length - trunk_step_length, pen_size - pen_step_size)# 绘制左侧树枝turtle.lt(deflection_angle)DrawFractalTree(trunk_length - trunk_step_length, pen_size - pen_step_size)# 返回树干起始点turtle.rt(deflection_angle)turtle.penup()turtle.bk(trunk_length)turtle.pendown()def main():# 绘制速度 范围[0,10]turtle.speed(10)# 初始画笔位置 turtle.penup()turtle.left(90)turtle.backward(250)turtle.pendown()# 执行绘制DrawFractalTree(trunk_length, pen_size)turtle.exitonclick()if __name__ == '__main__':main()