python之万花尺

1、使用模块

import sys, random, argparse
import numpy as np
import math
import turtle
import random
from PIL import Image
from datetime import datetime
from math import gcd

依次使用pip下载即可

2、代码

import sys, random, argparse
import numpy as np
import math
import turtle
import random
from PIL import Image
from datetime import datetime
from math import gcd# A class that draws a spirograph
class Spiro:# constructordef __init__(self, xc, yc, col, R, r, l):# create own turtleself.t = turtle.Turtle()# set cursor shapeself.t.shape('turtle')# set step in degreesself.step = 5# set drawing complete flagself.drawingComplete = False# set parametersself.setparams(xc, yc, col, R, r, l)# initiatize drawingself.restart()# set parametersdef setparams(self, xc, yc, col, R, r, l):# spirograph parametersself.xc = xcself.yc = ycself.R = int(R)self.r = int(r)self.l = lself.col = col# reduce r/R to smallest form by dividing with GCDgcdVal = gcd(self.r, self.R)self.nRot = self.r // gcdVal# get ratio of radiiself.k = r / float(R)# set colorself.t.color(*col)# current angleself.a = 0# restart drawingdef restart(self):# set flagself.drawingComplete = False# show turtleself.t.showturtle()# go to 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 rest of 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)# done - hide turtleself.t.hideturtle()# update by one stepdef update(self):# skip if doneif self.drawingComplete:return# increment angleself.a += self.step# draw stepR, k, l = self.R, self.k, self.l# set 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)# check if drawing is complete and set flagif self.a >= 360 * self.nRot:self.drawingComplete = True# done - hide turtleself.t.hideturtle()# clear everythingdef clear(self):self.t.clear()# A class for animating spirographs
class SpiroAnimator:# constructordef __init__(self, N):# timer value in millisecondsself.deltaT = 10# get window dimensionsself.width = turtle.window_width()self.height = turtle.window_height()# create spiro objectsself.spiros = []for i in range(N):# generate random parametersrparams = self.genRandomParams()# set spiro paramsspiro = Spiro(*rparams)self.spiros.append(spiro)# call timerturtle.ontimer(self.update, self.deltaT)# restart sprio drawingdef restart(self):for spiro in self.spiros:# clearspiro.clear()# generate random parametersrparams = self.genRandomParams()# set spiro paramsspiro.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 onesif spiro.drawingComplete:nComplete += 1# if all spiros are complete, restartif nComplete == len(self.spiros):self.restart()# call timerturtle.ontimer(self.update, self.deltaT)# toggle turtle on/offdef toggleTurtles(self):for spiro in self.spiros:if spiro.t.isvisible():spiro.t.hideturtle()else:spiro.t.showturtle()# save spiros to image
def saveDrawing():# hide turtleturtle.hideturtle()# generate unique file namedateStr = (datetime.now()).strftime("%d%b%Y-%H%M%S")fileName = 'spiro-' + dateStrprint('saving drawing to %s.eps/png' % fileName)# get tkinter canvascanvas = turtle.getcanvas()# save postscipt imagecanvas.postscript(file=fileName + '.eps')# use PIL to convert to PNGimg = Image.open(fileName + '.eps')img.save(fileName + '.png', 'png')# show turtleturtle.showturtle()# main() function
def main():# use sys.argv if neededprint('generating spirograph...')# create parserdescStr = """This program draws spirographs using the Turtle module. When run with no arguments, this program draws random spirographs.Terminology:R: radius of outer circle.r: radius of inner circle.l: ratio of hole distance to r."""parser = argparse.ArgumentParser(description=descStr)# add expected argumentsparser.add_argument('--sparams', nargs=3, dest='sparams', required=False,help="The three arguments in sparams: R, r, l.")# parse argsargs = parser.parse_args()# set to 80% screen widthturtle.setup(width=0.8)# set cursor shapeturtle.shape('turtle')# set titleturtle.title("Spirographs!")# add key handler for saving imagesturtle.onkey(saveDrawing, "s")# start listeningturtle.listen()# hide main turtle cursorturtle.hideturtle()# checks args and drawif args.sparams:params = [float(x) for x in args.sparams]# draw spirograph with given parameters# black by defaultcol = (0.0, 0.0, 0.0)spiro = Spiro(0, 0, col, *params)spiro.draw()else:# create animator objectspiroAnim = SpiroAnimator(4)# add key handler to toggle turtle cursorturtle.onkey(spiroAnim.toggleTurtles, "t")# add key handler to restart animationturtle.onkey(spiroAnim.restart, "space")# start turtle main loopturtle.mainloop()# call main
if __name__ == '__main__':main()注意缩进,注意运行需要在命令行进行运行虽然在pycharm上可以运行但是没办法自己挑选参数

3、结果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/2871459.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

Linux环境开发工具之yum

前言 前面我们已经对基本的指令和权限进行了介绍,本期开始我们将介绍常用的开发工具。例如:软件包管理器yum。 本期内容介绍 Linux上安装软件的方式 什么是yum yum的相关操作 yum的本地配置和yum源 一、Linux上安装软件的方式 在介绍Linux上如何安装一…

Docker 安装 Skywalking以及UI界面

关于Skywalking 在现代分布式系统架构中,应用性能监控(Application Performance Monitoring, APM)扮演着至关重要的角色。本文将聚焦于一款备受瞩目的开源APM工具——Apache Skywalking,通过对其功能特性和工作原理的详细介绍&am…

打破数据孤岛,TDengine 与 Tapdata 实现兼容性互认证

当前,传统行业正面临着数字化升级的紧迫需求,但海量时序数据的处理以及数据孤岛问题却日益突出。越来越多的传统企业选择引入时序数据库(Time Series Database,TSDB)升级数据架构,同时,为了克服…

C++ 笛卡尔树

目录 一、性质二、构建笛卡尔树三、应用四、源码 一、性质 堆性质: 笛卡尔树是一种满足堆性质的树。每个节点包含两个值:键值(key)和优先级值(priority)。在笛卡尔树中,根节点的优先级值最大&am…

C++ 特殊类及单例模式

文章目录 1. 前言2. 不能被拷贝的类3. 不能被继承的类4. 只能在堆上创建对象的类5. 只能在栈上创建对象的类6. 只能创建一个对象的类(单例模式) 1. 前言 在实际场景中,我们在编写类的过程中总会遇到一些特殊情况,比如设计一个类不…

[AutoSar]BSW_Com015 PDUR 模块配置

目录 关键词平台说明一、Abbreviations二、PduRBswModules三、PduRGeneration四、PduRDestPdus4.1 全局PDU ID和本地PDU ID 关键词 嵌入式、C语言、autosar、OS、BSW 平台说明 项目ValueOSautosar OSautosar厂商vector , EB芯片厂商TI 英飞凌编程语言C&#xff0…

[ThinkPHP]Arr返回1

$detailId (int)Arr::get($detail, null); var_dump($detailId); 打印结果:int(1) 原因: vendor/topthink/think-helper/src/helper/Arr.php

水泵房远程监控物联网系统

随着物联网技术的快速发展,越来越多的行业开始利用物联网技术实现设备的远程监控与管理。水泵房作为城市供水系统的重要组成部分,其运行状态的监控与管理至关重要。HiWoo Cloud作为专业的物联网云服务平台,为水泵房远程监控提供了高效、稳定、…

API--10-1--StringJoiner工具类

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 StringJoiner构造函数成员变量公开方法1.构造函数2. add() 添加字符串3. setEmptyValue 输出指定字符串 StringJoiner案例案例1案例2 StringJoiner StringJoiner是…

5 张图带你了解分布式事务 Saga 模式中的状态机

大家好,我是君哥。 状态机在我们的工作中应用非常广泛,今天聊一聊分布式事务中间件 Seata 中 Saga 模式的状态机。 1 状态机简介 状态机是一个数学模型,它将工作中的运行状态和流转规则抽象出来,可以协调相关信号来完成预先设定…

30.HarmonyOS App(JAVA)鸿蒙系统app多线程任务分发器

HarmonyOS App(JAVA)多线程任务分发器 打印时间,记录到编辑框textfield信息显示 同步分发,异步分发,异步延迟分发,分组任务分发,屏蔽任务分发,多次任务分发 参考代码注释 场景介绍 如果应用的业务逻辑比…

Docker进阶教程 - 1 Dockerfile

更好的阅读体验:点这里 ( www.doubibiji.com ) 1 Dockerfile Dockerfile 是做什么的? 我们前面说到,制作镜像的方法主要有两种方式: 使用 docker commit 命令;使用 Dockerfile 文件。 但是…

C语言学习过程总结(16)——指针(4)

一、数组名的理解 我们直接使用%p打印出地址来看看&arr【0】 和 arr的不同: int main() {int arr[10] { 1,2,3,4,5,6,7,8,9,10 };printf("&arr[0] %p\n", &arr[0]);printf("arr %p\n", arr);} 、 很容易看出来两者的输出…

最强AI换脸工具Rope使用教程,Rope整合包下载【全网最全安装步骤】

Rope的汉化整合包(包含模型)以及下面教程所涉及到的所有安装包我都打包好了,需要的小伙伴可以关注文章底部公众号,回复关键词【rope】获取。 AI换脸软件简介必读 Rope 是一个免费开源的 AI 换脸软件,它具有图形化界面…

MySQL之旅

本文字数:11653;估计阅读时间:30 分钟 审校:庄晓东(魏庄) 本文在公众号【ClickHouseInc】首发 介绍 "简单是终级的精致。"- --列奥纳多达芬奇 虽然我们喜欢在 ClickHouse 为用户宣布新功能&#…

【代码】提取图像轮廓坐标并保存为YOLOv8所需的txt格式

该段代码的应用场景为对图像标注过后,想要对图像进行裁切,但是标签不能裁切,所以将原图像按照标签进行二值化后,将二值化后的图像进行裁切,然后使用opencv对裁切后的图像进行处理,识别出白色区域轮廓&#…

用c++实现计数排序、颜色排序问题

3.3.1 计数排序 【问题】 假设待排序记录均为整数且取自区间[0,k],计数排序(count sort)的基本思想是对每一个记录x,确定小于x的记录个数,然后直接将x放在应该的位置。例如,小于x的记录个数是10,则x就位于第11个位置。 【想法】 对于待排序序…

vulnhub-----SickOS靶机

文章目录 1.信息收集2.curl命令反弹shell提权利用POC 1.信息收集 ┌──(root㉿kali)-[~/kali/vulnhub/sockos] └─# arp-scan -l Interface: eth0, type: EN10MB, MAC: 00:0c:29:10:3c:9b, IPv4: 10.10.10.10 Starting arp-scan 1.9.8 with 256…

移动端研发技术的进化历程

移动端研发技术 移动端研发技术主要分为原生开发和跨平台开发。本章主要介绍一下移动开发技术的过去、当下和未来,一步一步介绍移动技术的进化历程。 原生开发 原生应用程序是指某一个移动平台(比如iOS或Android)所特有的应用,使…

【C/C++】C语言开发者必读:迈向C++的高效编程之旅

🧑 作者简介:阿里巴巴嵌入式技术专家,深耕嵌入式人工智能领域,具备多年的嵌入式硬件产品研发管理经验。 📒 博客介绍:分享嵌入式开发领域的相关知识、经验、思考和感悟,欢迎关注。提供嵌入式方…