Python 实例 - Day3 - Spirograph 万花尺(完结)
文章目录
- 数学知识
- 万花尺方程
- 数学原理视频讲解
- 利用turtle画圆
- 创建螺线
- Spiro 构造函数
数学知识
三角函数:
在一个直角三角形中,设∠C=90°,∠A, B, C 所对的边分别记作 a,b,c,那么对于锐角∠A,它的对边 a 和斜边 c 的比值 a/c 叫做∠A的正弦,记作 sinA;它的邻直角边 b 和斜边 c 的比值 b/c 叫做∠A的余弦,记作 cosA;它的对边 a 和邻直角边 b 的比值 a/b 叫做∠A的正切,记作 tanA
θ
θ 希腊字母
Θ 西塔
Theta(大写Θ,小写θ),在希腊语中,是第八个希腊字母.
大写的Θ是:
粒子物理学中pentaquark用Θ+来表示
小写的θ是:
数学上常代表平面的角
万花尺方程
数学原理视频讲解
https://www.bilibili.com/video/BV1w7411q7xH
利用turtle画圆
半径为r的圆的方程
x = r* cos(θ)
y = r* sin(θ)
# Draw the circle by turtle
import math
import turtledef drawCircleTurtle(x,y,r):# Move the turtle to the jumping-off pointturtle.up()turtle.setpos(x+r,y)turtle.down()# Draw the circlefor i in range(0,365,5): # 从0到360,每隔5步循环 i是角度参数a = math.radians(i) # 将角度转化为弧度#print(a)# python中sin和cos都是以弧度为参数,所以需要转化为弧度.turtle.setpos(x+r*math.cos(a), y+r*math.sin(a))print(x+r*math.cos(a))drawCircleTurtle(100,100,50)
turtle.mainloop()
输出结果:
创建螺线
- turtle 模块用于绘图
- pillow python图像库(PIL)的一个分支,用于保存螺线图像
Spiro 构造函数
#万花尺
import sys , random,argparse
import turtle
import numpy as np
import math
from PIL import Image
from datetime import datetime
from fractions import gcd# a class for draw a spirograph
class Spiro:def __init__(self,xc,yc,col,R,r,l):self.t = turtle.Turtle()self.t.shape('turtle')self.step = 5self.drawingComplete = Falseself.setparams(xc,yc,col,R,r,l)self.restart()# set the parametersdef setparams(self,xc,yc,col,R,r,l):# the Spirograph paramentersself.xc = xcself.yc = ycself.R = int(R)self.r = int(r)self.l = lself.col = col# reduce r/R to its smallest form by dividing with the GCDgcdVal = math.gcd(self.r, self.R) #gcd 最大公约数 greatest common divisorself.nRot = self.r//gcdVal # //取整数# get ratio of radii (获得半径曲率)self.k = r/float(R)#set the colorself.t.color(*col)#store the current angleself.a = 0#restart the drawingdef restart(self):#set the flagself.drawingComplete = False#show the turtleself.t.showturtle()#go to the first pointself.t.up()R, k, l = self.R, self.k, self.la = 0.0x = R*((1-k)*math.cos(a) + l*k*math.cos((1-k)*a/k))y = R*((1-k)*math.sin(a) + l*k*math.sin((1-k)*a/k))self.t.setpos(self.xc +x, self.yc + y)self.t.down()#draw the whole thingdef draw(self):#draw the rest of the pointsR, k, l = self.R, self.k, self.lfor i in range(0, 360*self.nRot + 1, self.step):a = math.radians(i)x = R * ((1 - k) * math.cos(a) + l * k * math.cos((1 - k) * a / k))y = R * ((1 - k) * math.sin(a) + l * k * math.sin((1 - k) * a / k))self.t.setpos(self.xc + x, self.yc + y)#drawing is now done so hide the turtle cursorself.t.hideturtle()#update by one setupdef update(self):#skip the rest of the steps if doneif self.drawingComplete:return#increment the angleself.a += self.step#draw a stepR, k, l = self.R, self.k, self.l#set the anglea = math.radians(self.a)x = self.R * ((1 - k) * math.cos(a) + l * k * math.cos((1 - k) * a / k))y = self.R * ((1 - k) * math.sin(a) + l * k * math.sin((1 - k) * a / k))self.t.setpos(self.xc + x, self.yc +y)#if drawing is complete, set the flagif self.a >= 360*self.nRot:self.drawingComplete = True#drawing is now done so hide the turtle cursorself.t.hideturtle()def clear(self):self.t.clear()# a class fro animating Spirographs
class SpiroAnimator:#constructordef __init__(self, N):#set the timer value in millisecondsself.deltaT = 10#get the window dimensionsself.width = turtle.window_width()self.height = turtle.window_height()#Create the Spiro objectsself.spiros = []for i in range(N):#generate random parametersrparams = self.genRandomParams()#set the Spiro Parametersspiro = Spiro(*rparams)self.spiros.append(spiro)#call timerturtle.ontimer(self.update, self.deltaT)#restart spiro drawingdef restart(self):for spiro in self.spiros:#clearspiro.clear()#generate random parametersrparams = self.genRandomParams()#set the spiro paramentersspiro.setparams(*rparams)#restart drawingspiro.restart()
# generate random parametersdef genRandomParams(self):width, height = self.width, self.heightR = random.randint(50, min(width, height) // 2)r = random.randint(10, 9 * R // 10)l = random.uniform(0.1, 0.9)xc = random.randint(-width // 2, width // 2)yc = random.randint(-height // 2, height // 2)col = (random.random(),random.random(),random.random())return (xc, yc, col, R, r, l)def update(self):#update all spirosnComplete = 0for spiro in self.spiros:#updatespiro.update()#count completed spirosif spiro.drawingComplete:nComplete += 1#restart if all spiros are completeif nComplete == len(self.spiros):self.restart()#call the timerturtle.ontimer(self.update, self.deltaT)#toggle turtle cursor on and offdef toggleTurtles(self):for spiro in self.spiros:if spiro.t.isvisible():spiro.t.hideturtle()else:spiro.t.shwoturtle()# save drawing as PNG file
def saveDrawing():#hide the turtle cursorturtle.hideturtle()#generate unique filenamesdateStr = (datetime.now()).strftime("%d%b%Y-%H%M%S")fileName = 'Spiro-' + dateStrprint('saving drawing to %s.eps/png' % fileName)#get the tkinter canvascanvas = turtle.getcanvas()#save the drawing as a postscript imagecanvas.postscript(file = fileName +'.eps')#use the Pillow module to convert the postscript image file to PNGimg = Image.open(fileName + '.eps')img.save(fileName + '.png', 'png')#show the turtle cursorturtle.showturtle()
#main() function
def main():# use sys.argv if neededprint('generating spirograph...')#create parserdescStr = '''This program drawsSpirographs using the Turtle module.When run with no arguments, this program draws random Spirographs.Terminology:R:radius of outer circler: radius of inner circlel: ratio of hole distance to r'''parser = argparse.ArgumentParser(description=descStr)parser.add_argument('--sparams',nargs=3,dest='sparams',required=False,help='The three arguments in sparams: R,r,l.')#parse argsargs= parser.parse_args()#set the width of the drawing window to 80 percent of the screen widthturtle.setup(width=0.8)#set the cursor shape to turtleturtle.shape('turtle')#set the title to Spirographs!turtle.title('Spirographs!')#add the key handler to save our drawingsturtle.onkey(saveDrawing,'s')#start listeningturtle.listen()#hide the main turtle cursorturtle.hideturtle()#check for any arguments sent to --sparams and draw the Spirographif args.sparams:params = [float(x) for x in args.sparams]#draw the Spirograph with the given paramenterscol = (0.0,0.0,0.0)spiro = Spiro(0,0,col,*params)spiro.draw()else:#create the animator objectspiroAnim = SpiroAnimator(4)#add a key handler to toggle the turtle cursorturtle.onkey(spiroAnim.toggleTurtles,'t')#add a key handler to restart to restart the animationturtle.onkey(spiroAnim.restart,'space')# start the turtle main loopturtle.mainloop()
#call main
if __name__=='__main__':main()
Python 实例 - Day3 - Spirograph 万花尺(完结)相关推荐
- Python 实例 - Day1 -Turtle五环 (完结)
利用Turtle库画五环 第一次利用学到的和百度的知识,通过自己的思考做出了加强版程序,奥里给!!! 第一版简易版 import turtle from turtle import Screen sc ...
- python接收输入的一行字符只统计数字的个数,Python(统计字符),python实例,输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数...
Python(统计字符),python实例,输入一行字符,分别统计出其中英文字母.空格.数字和其它字符的个数 题目:输入一行字符,分别统计出其中英文字母.空格.数字和其它字符的个数. 程序分析:利用 ...
- Python实例浅谈之三Python与C/C++相互调用
参考:http://blog.csdn.net/taiyang1987912/article/details/44779719 Python实例浅谈之三Python与C/C++相互调用 二.Pytho ...
- python写文件读文件-Python 实例:读写文件
原标题:Python 实例:读写文件 读写文件是最常见的IO操作.内置了读写文件的函数,用法和的读写文件非常类似.在磁盘上读写文件的功能都是由提供的,现代不允许普通的程序直接操作磁盘,所以,读写文件就 ...
- 使用docker安装部署Spark集群来训练CNN(含Python实例)
使用docker安装部署Spark集群来训练CNN(含Python实例) 本博客仅为作者记录笔记之用,不免有很多细节不对之处. 还望各位看官能够见谅,欢迎批评指正. 博客虽水,然亦博主之苦劳也. 如需 ...
- python现有两个磁盘文件a和b_有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中Python实例...
有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中Python实例 题目:有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并( ...
- Python实例讲解 -- 磁盘文件的操作
在文件夹里有六十多个RM格式的视频文件,我现在需要把它们的文件名都提取出来,并去掉文件的扩展名,以便放到需要的网页里. 应该有什么软件可以完成这个简单的要求,可是一时间到哪里去找这 样一个符合要求的软 ...
- python抽签代码_Python(抽签问题),python实例,
Python(抽签问题),python实例, 题目:两个乒乓球队进行比赛,各出三人.甲队为a,b,c三人,乙队为x,y,z三人.已抽签决定比赛名单.有人向队员打听比赛的名单.a说他不和x比,c说他不和 ...
- arcgis python 教程-按区域消除--arcgis python实例教程
按区域消除--arcgis python实例教程 目的:对应细碎多边形,合并到周围的大多边形中,同时要求在同一个区域.例如对于处理多个县组成的图斑,某一个县的细碎多边形不能合并到别的县 使用方法: 工 ...
最新文章
- A. 位运算符的应用---管理一组事务的开关状态
- Science: 四万张大脑图像首次揭示人脑白质的基因基础
- 网站排名优化看技巧!
- 【c#】关于c#中data控件的简单用法介绍
- 数据库分区分表以及读写分离
- gradle docker_带有Gradle的Docker容器分为4个步骤
- 牛客 数学实验(模拟)
- Mysql 5.7 的‘虚拟列’是做什么?
- stm32 PWM互补输出
- DataGrid多层表头设计
- [二分搜索|快速选择] leetcode 4 寻找两个正序数组的中位数
- lodop简单入门教程
- 相同源代码的html文件在本地和服务器端被浏览器请求时,显示的效果不一样!!!...
- python中可变参数*args传入函数时的存储方式为,Python函数可变参数(*args,**kwargs)详解...
- 你的设备中缺少重要的安全和质量修复_2020华富管道非开挖修复工程施工欢迎前来咨询...
- logstash之output插件-输出数据到控制台、file文件、elasticsearch、redis
- python实现multi函数参数个数不限、返回所有参数乘积_实现multi( )函数,参数个数不限,返回所有参数的乘积。_学小易找答案...
- 【中医学】9 方剂-3
- 三张简图搞懂GBDT
- Arthur van Hoff