Python+Turtle实现绘制勾股树
作者:Leleprogrammer 时间:2023-03-04 21:38:36
这次,我们用Turtle模块结合三角函数,绘制出这样的勾股树:
首先,导入模块
from turtle import *
from math import sin,cos,radians
定义勾股数每次旋转的度数
angle1=70
angle2=90-angle1
定义tree函数,绘制正方形并记录要生成的新的正方形的坐标,计算出新的正方形的度数和边长并绘制,这里采用递归的方式
ln表示边长,mode表示当前正方形是在前一个正方形的左边或右边,h表示朝向,p表示坐标
def tree(ln,mode="left",h=90,p=(0,0)):
pu()
seth(h)
goto(p)
if ln>1:
pd()
for i in range(4):
if i==1 and mode=="left":
pos1=pos()
if i==2 and mode=="left":
pos2=pos()
if i==2 and mode=="right":
pos1=pos()
if i==3 and mode=="right":
pos2=pos()
fd(ln)
right(90)
h=heading()
tree(ln*cos(radians(angle1)),"left",h+angle1 if mode=="left" else h-angle1,pos1)
tree(ln*cos(radians(angle2)),"right",h+90-angle2 if mode=="left" else h-angle2,pos2)
在主程序中设置速度,因为递归很占内存,所以绘制速度会卡顿减缓,所以这里加速1000倍,设置无延迟,笔触颜色为绿色,笔触大小2,抬笔,设置方向,并开始递归,最后隐藏画布并保持窗口显示
speed(0)
tracer(1000)
delay(0)
color("green")
pensize(2)
pu()
seth(90)
tree(70,p=(-100,-300))
ht()
done()
最终代码:
from turtle import *
from math import sin,cos,radians
angle1=45 # 自行修改
angle2=90-angle1
def tree(ln,mode="left",h=90,p=(0,0)):
pu()
seth(h)
goto(p)
if ln>1:
pd()
for i in range(4):
if i==1 and mode=="left":
pos1=pos()
if i==2 and mode=="left":
pos2=pos()
if i==2 and mode=="right":
pos1=pos()
if i==3 and mode=="right":
pos2=pos()
fd(ln)
right(90)
h=heading()
tree(ln*cos(radians(angle1)),"left",h+angle1 if mode=="left" else h-angle1,pos1)
tree(ln*cos(radians(angle2)),"right",h+90-angle2 if mode=="left" else h-angle2,pos2)
speed(0)
tracer(1000)
delay(0)
color("green")
pensize(2)
pu()
seth(90)
tree(70,p=(-100,-300))
ht()
done()
来源:https://blog.csdn.net/leleprogrammer/article/details/125948998
标签:Python,Turtle,勾股树
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
mysql数据库你需要特别注意的23个事项
2010-08-08 08:34:00
pygame多种方式实现屏保操作(自动切换、鼠标切换、键盘切换)
2022-12-08 20:39:49
![](https://img.aspxhome.com/file/2023/7/95187_0s.gif)
如何高效地访问记录集?
2009-11-22 19:25:00
PhpStorm的使用教程(本地运行PHP+远程开发+快捷键)
2024-05-03 15:13:22
![](https://img.aspxhome.com/file/2023/7/129857_0s.png)
Python基于yaml文件配置logging日志过程解析
2022-04-02 10:50:36
SQLServer 日期函数大全(小结)
2024-01-13 05:36:32
Go语言同步与异步执行多个任务封装详解(Runner和RunnerAsync)
2024-05-28 16:14:16
Django的用户模块与权限系统的示例代码
2023-04-27 14:48:23
利用LyScript实现应用层钩子扫描器
2023-01-10 16:28:39
![](https://img.aspxhome.com/file/2023/6/70756_0s.png)
基于Express框架使用POST传递Form数据
2024-06-05 09:52:26
VS CODE 使用SVN插件的方法步骤
2023-05-22 10:39:33
![](https://img.aspxhome.com/file/2023/3/112063_0s.png)
python sys,os,time模块的使用(包括时间格式的各种转换)
2021-02-08 02:31:33
Python如何读写二进制数组数据
2022-01-12 19:35:57
简单的Vue SSR的示例代码
2023-07-02 17:08:46
![](https://img.aspxhome.com/file/2023/9/139949_0s.jpg)
python隐藏终端执行cmd命令的方法
2022-01-09 05:19:37
Python 微信爬虫完整实例【单线程与多线程】
2023-08-19 23:12:58
Python实现企业微信通知机器人的方法详解
2021-03-12 09:56:02
![](https://img.aspxhome.com/file/2023/9/78629_0s.png)
Sysbench多线程性能测试工具
2024-01-20 14:08:57
教你怎么使用sql游标实例分享
2012-07-11 16:14:57
如何使用Python生成Hilbert矩阵
2021-08-09 12:36:08
![](https://img.aspxhome.com/file/2023/8/92438_0s.png)