Python使用Turtle绘制分形树
2020/02/25
Python使用Turtle绘制分形树
效果如下:
Code:
1 ''' 2 作者:清扬 3 功能:利用递归绘制分型树 4 版本:1.0 5 日期:2020/02/25 6 ''' 7 8 import turtle 9 10 def draw_branch(branch_length): 11 ''' 12 绘制分型树 13 :param branch_length: 14 :return: 15 ''' 16 if branch_length > 5: 17 if branch_length > 10: 18 turtle.pensize(10) 19 turtle.color('brown') 20 else: 21 turtle.pensize(5) 22 turtle.color('green') 23 24 # 绘制右侧树枝 25 turtle.forward(branch_length) 26 27 28 print('向前',branch_length) 29 turtle.right(20) 30 print('右转 20') 31 draw_branch(branch_length-15) 32 33 # 绘制左侧树枝 34 turtle.left(40) 35 print('左转 40') 36 draw_branch(branch_length-15) 37 38 #返回之前的树枝上 39 print('右转 20') 40 turtle.right(20) 41 42 turtle.penup() 43 turtle.backward(branch_length) 44 turtle.pendown() 45 46 print('向后',branch_length) 47 48 def main(): 49 ''' 50 主函数 51 ''' 52 turtle.left(90) 53 turtle.penup() 54 turtle.backward(200) 55 turtle.pendown() 56 turtle.color('brown') 57 print('左转 90') 58 turtle.speed(5000) 59 draw_branch(100); 60 turtle.exitonclick() 61 62 if __name__ == '__main__': 63 main()