用python画分形树的详细解析_Python入门案例(二):分形树的绘制

一、分形树的绘制V1.0

主要知识点:turtle库绘制简单图形while循环# -*- coding:utf-8 -*-

"""

@author:Angel

@file:pentagram_V1.0.py

@time:2018/11/13 21:39

@1.0功能:五角星的绘制

"""

import turtle

def main():

# 计数器

count = 1

while count <= 5:

turtle.forward(200)

turtle.right(144)

count = count + 1

turtle.exitonclick()

if __name__ == '__main__':

main()

绘制的图形:

9a6508c079f7325473f5fda8c62bc92f.png

二、分形树的绘制V2.0

主要知识点:自定义函数+while循环# -*- coding:utf-8 -*-

"""

@author:Angel

@file:pentagram_V2.0.py

@time:2018/11/13 21:39

@1.0功能:五角星的绘制

@2.0新增功能:重复不同大小五角星的绘制

"""

import turtle

def draw_pentagram(size):

# 五角星绘制函数

# 计数器

count = 1

# 五角星的绘制

while count <= 5:

turtle.forward(size)

turtle.right(144)

count = count + 1

def main():

# 图形设置

turtle.penup()

turtle.backward(100)

turtle.pendown()

turtle.pensize(2)

turtle.pencolor('red')

# 初始大小

size = 100

while size <= 200:

draw_pentagram(size)

size = size + 25

turtle.exitonclick()

if __name__ == '__main__':

main()

绘制的图形:

1e3c3b36c976e87a8db0376161a87837.png

三、分形树的绘制V3.0

主要知识点:递归函数# -*- coding:utf-8 -*-

"""

@author:Angel

@file:pentagram_V3.0.py

@time:2018/11/13 21:39

@1.0功能:五角星的绘制

@2.0新增功能:重复不同大小五角星的绘制

@3.0新增功能:函数与循环结合(递归函数)绘制2.0的图形

"""

import turtle

def draw_recursive_pentagram(size):

# 迭代绘制五角星

# 计数器

count = 1

# 五角星的绘制

while count <= 5:

turtle.forward(size)

turtle.right(144)

count = count + 1

# 五角星绘制完成,更新参数

size += 25

if size <= 200:

draw_recursive_pentagram(size)

def main():

# 图形设置

turtle.penup()

turtle.backward(100)

turtle.pendown()

turtle.pensize(2)

turtle.pencolor('red')

# 初始大小

size = 100

# 调用递归函数

draw_recursive_pentagram(size)

turtle.exitonclick()

if __name__ == '__main__':

main()

绘制的图形:

f9d69d9d43fc497438329d46177e1554.png

四、分形树的绘制V4.0

主要知识点:递归函数的实际运用# -*- coding:utf-8 -*-

"""

@author:Angel

@file:pentagram_V4.0.py

@time:2018/11/13 21:39

@1.0功能:五角星的绘制

@2.0新增功能:重复不同大小五角星的绘制

@3.0新增功能:函数与循环结合(递归函数)绘制2.0的图形

@4.0新增功能:利用递归函数绘制分形树

"""

import turtle

def draw_branch(branch_length):

# 绘制分形树

if branch_length > 5:

# 绘制右侧树枝

turtle.forward(branch_length)

print('向前', branch_length)

turtle.right(20)

print('右转 20')

draw_branch(branch_length - 15)

# 绘制左侧树枝

turtle.left(40)

print('左转 40')

draw_branch(branch_length - 15)

# 返回之前的树枝

turtle.right(20)

print('右转 20')

turtle.backward(branch_length)

print('向后', branch_length)

def main():

# 图形设置

turtle.left(90)

turtle.penup()

turtle.backward(260)

turtle.pendown()

turtle.pensize(1)

turtle.pencolor('red')

# 调用递归函数

draw_branch(120)

turtle.exitonclick()

if __name__ == '__main__':

main()

绘制的图形:

fba31a27d28a757a73db18b7587b7ae9.png

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值