使用Python Turtle绘制Y形分形树
分形是一种永无止境的模式。分形是无限复杂的模式,在不同的尺度上具有自相似性。它们是通过在一个持续的反馈循环中不断地重复一个简单的过程而产生的。在递归的驱动下,分形是动态系统的图像–混沌的图片。
在这篇文章中,我们将使用Python中的递归技术绘制一棵彩色的Y形分形树。
示例:
深度水平的输出:(a)14(b)12
使用到的模块
turtle: turtle库使用户能够使用命令绘制图片或形状,为他们提供一个虚拟画布。turtle带有Python的标准库。它需要一个支持Tk的Python版本,因为它使用tkinter来绘制图形。
使用到的函数:
- fd(x) : 将光标向前移动x像素。
- rt(x), lt(x) : 将光标的方向分别向右和向左旋转x度。
- colormode() : 将颜色模式改为rgb。
- pencolor(r, g, b) : 设置Turtle笔的颜色。
- speed() : 设置Turtle的速度。
步骤 :
- 我们先画一个 “Y “形,作为基础(第1层)树。然后,”Y “的两个分支作为其他两个 “Y “的基点(第2层)。
- 这个过程是递归重复的,Y的大小随着水平的提高而减少。
- 树木的着色是按级别进行的:最底层的颜色最深,最顶层的颜色最浅。
在下面的实现中,我们将绘制一棵大小为80、级别为7的树。
from turtle import * speed('fastest') # turning the turtle to face upwards rt(-90) # the acute angle between # the base and branch of the Y angle = 30 # function to plot a Y def y(sz, level): if level > 0: colormode(255) # splitting the rgb range for green # into equal intervals for each level # setting the colour according # to the current level pencolor(0, 255//level, 0) # drawing the base fd(sz) rt(angle) # recursive call for # the right subtree y(0.8 * sz, level-1) pencolor(0, 255//level, 0) lt( 2 * angle ) # recursive call for # the left subtree y(0.8 * sz, level-1) pencolor(0, 255//level, 0) rt(angle) fd(-sz) # tree of size 80 and level 7 y(80, 7)
输出 :
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com