Python画分形树,主要用递归来实现,更方便的理解递归运行方式。
废话不多说,直接上代码
import turtle
def draw_branch(branch_length):
'''
绘制分形树
'''
# print("kaishi长度 ", branch_length)
if branch_length > 2:
# 绘制右侧树枝
turtle.forward(branch_length)
# print("向前", branch_length)
turtle.right(20)
# print("右转20")
draw_branch(branch_length - 10)
# 绘制左侧树枝
turtle.left(40)
# print("长度 ",branch_length)
draw_branch(branch_length - 10)
# 返回之前的树枝
turtle.right(20)
# print("向右20")
turtle.backward(branch_length)
# print("回退", branch_length)
def main():
"""
主函数
"""
turtle.left(90)
turtle.pencolor('brown')
turtle.penup()
turtle.backward(150)
turtle.pendown()
turtle.speed(0)
draw_branch(90)
turtle.exitonclick()
if __name__ == "__main__":
main()
最终效果图
有任何疑问欢迎沟通