【python】python爱心代码【附源码】

ops/2024/10/10 11:14:41/

欢迎来到英杰社区icon-default.png?t=N7T8https://bbs.csdn.net/topics/617804998

一、实现效果:

        3692fec4d8a5412f9cdfa62be039e572.gif

 二、准备工作

(1)、导入必要的模块:

       代码首先导入了需要使用的模块:requests、lxml和csv。

python">import requests
from lxml import etree
import csv

        如果出现模块报错

c124a1693bfc457ba1f2909ee9d299fc.png

        进入控制台输入:建议使用国内镜像源

python">pip install 模块名称 -i https://mirrors.aliyun.com/pypi/simple

         我大致罗列了以下几种国内镜像源:

python">清华大学
https://pypi.tuna.tsinghua.edu.cn/simple阿里云
https://mirrors.aliyun.com/pypi/simple/豆瓣
https://pypi.douban.com/simple/ 百度云
https://mirror.baidu.com/pypi/simple/中科大
https://pypi.mirrors.ustc.edu.cn/simple/华为云
https://mirrors.huaweicloud.com/repository/pypi/simple/腾讯云
https://mirrors.cloud.tencent.com/pypi/simple/

firework

python">class firework:def __init__(self, x, y, color):self.x = xself.y = yself.color = colorself.radius = 1self.speed = random.uniform(0.5, 1.5)self.angle = math.radians(random.randint(0, 360))self.vx = self.speed * math.cos(self.angle)self.vy = self.speed * math.sin(self.angle)self.age = 0self.alive = Trueself.particles = []

这个类表示了一个烟花对象,它有以下属性:

  • xy:当前烟花的坐标。

  • color:当前烟花的颜色。

  • radius:当前烟花的半径。

  • speed:当前烟花的速度。

  • angle:当前烟花的运动角度。

  • vxvy:当前烟花的速度在 x 和 y 方向上的分量。

  • age:当前烟花已经存在的时间。

  • alive:当前烟花是否还存活。

  • particles:当前烟花爆炸后生成的粒子列表。

colorChange 函数

python">def colorChange(color, age):r, g, b = colorif age > 255:age = 255if age <= 85:return (r+age, g, b)elif age <= 170:return (r, g+age-85, b)else:return (r, g, b+age-170)

这个函数用于计算烟花的颜色,它接受两个参数:

  • color:当前烟花的颜色。

  • age:当前烟花已经存在的时间。

根据 age 的值,逐渐改变颜色的 R、G、B 分量来实现颜色的渐变效果。具体来说,如果 age 小于等于 85,则只改变红色分量,否则如果 age 小于等于 170,则同时改变红色和绿色分量,否则同时改变红色、绿色和蓝色分量。

appendFirework 函数

python">def appendFirework():f = firework(random.randint(100, w-100), h, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))fireworks.append(f)root.after(random.randint(100, 1000), appendFirework)

这个函数用于递归生成烟花对象,并在画布上显示烟花效果。具体来说,它做了以下几件事情:

  • 创建一个新的 firework 对象,随机指定其坐标、颜色、速度和角度等属性。

  • 将新的烟花对象添加到 fireworks 列表中。

  • 随机生成 100 到 1000 毫秒的时间,之后再次调用 appendFirework 函数,实现递归生成烟花对象。

heart_function 函数

python">def heart_function(theta):x = 16 * math.sin(theta) ** 3y = 13 * math.cos(theta) - 5 * math.cos(2*theta) - 2 * math.cos(3*theta) - math.cos(4*theta)return (x, -y)

这个函数用于计算心形图案上的点坐标,它接受一个参数 theta,表示当前点所在的极角。具体来说,它使用一组极坐标方程来计算出心形图案上的点坐标,然后将其转换为笛卡尔坐标系下的坐标值并返回。

scatter_inside 函数

python">def scatter_inside(p, speed):x, y = p.posvx, vy = p.veldist = math.hypot(x, y)if dist < 1:dist = 1dx = x / distdy = y / distforce = (10 / (dist ** 2)) * speeddvx = force * dxdvy = force * dyp.vel = (vx+dvx, vy+dvy)

这个函数用于实现心形内部的扩散效果,它接受两个参数:

  • p:当前粒子对象。

  • speed:扩散速度。

首先根据当前粒子的位置计算出一个向心力,然后根据该力的大小和方向改变粒子的速度,从而实现向外扩散的效果。

shrink 函数

python">def shrink(p, speed):x, y = p.posvx, vy = p.veldist = math.hypot(x, y)if dist < 1:dist = 1dx = x / distdy = y / distforce = (-10 / (dist ** 2)) * speeddvx = force * dxdvy = force * dyp.vel = (vx+dvx, vy+dvy)

这个函数用于实现心形收缩效果,它接受两个参数:

  • p:当前粒子对象。

  • speed:收缩速度。

scatter_inside 函数类似,这个函数也是根据当前粒子的位置计算出一个向心力,然后根据该力的大小和方向改变粒子的速度,从而实现向内收缩的效果。

curve 函数

python">def curve(t):if t < 1:return math.sin(t*math.pi/2)else:return math.sin((2-t)*math.pi/2) * 0.5 + 0.5

这个函数返回一个介于 0 和 4 之间的值,用于控制心形动画的曲线效果。具体来说,它接受一个参数 t,表示当前时间占总动画时间的比例,然后根据 t 的值返回一个介于 0 和 4 之间的值,用于控制心形动画的曲线效果。

Heart

python">class Heart:def __init__(self):self.points = []self.colors = []self.particles = []self.speed = 5self.pos = (w/2, h/2)self.rotation = 0self.scale = 1self._create_heart()
​def _create_heart(self):for i in range(1000):theta = i / 1000 * math.pi * 2r = heart_function(theta)[0]x = r * math.cos(theta)y = r * math.sin(theta)self.points.append((x, y))self.colors.append((random.randint(128, 255), random.randint(0, 128), random.randint(0, 128)))
​def update(self):for p in self.particles:p.update()self.particles = [p for p in self.particles if p.alive]
​if random.random() < 0.3:x, y = self.posdx = random.uniform(-1, 1) * self.speeddy = random.uniform(-1, 1) * self.speedp = Particle((x+dx, y+dy), (dx/4, dy/4))self.particles.append(p)
​self.rotation += 0.001self.scale = curve(self.rotation)
​def draw(self, canvas):cx, cy = self.posfor i, (x, y) in enumerate(self.points):r, g, b = self.colors[i]
​x *= self.scaley *= self.scale
​x, y = rotate(x, y, self.rotation)
​x += cxy += cy
​canvas.create_oval(x-1, y-1, x+1, y+1, fill="#%02x%02x%02x" % (r, g, b), width=0)

这个类用于生成爱心图案及其动态效果,它有以下属性:

  • points:存储心形图案上的所有点的坐标。

  • colors:存储心形图案上的所有点的颜色。

  • particles:存储所有心形收缩和扩散过程中生成的粒子。

  • speed:控制粒子运动速度的参数。

  • pos:控制心形图案位置的参数。

  • rotation:控制心形图案旋转角度的参数。

  • scale:控制心形图案缩放比例的参数。

其中,初始化函数 _create_heart 用于生成心形图案上的所有点和颜色,update 函数用于更新心形图案的动画效果,draw 函数用于在画布上绘制心形图案,并在每一帧更新心形的动态效果。

draw 函数

python">def draw():global fireworks, heartscanvas.delete("all")for f in fireworks:if f.alive:f.draw(canvas)f.update()else:for p in f.particles:if random.random() < 0.5:hearts.append(Heart())fireworks.remove(f)for h in hearts:h.draw(canvas)h.update()root.after(25, draw)

这个函数用于在画布上绘制烟花和心形图案,并在每一帧更新它们的动画效果。具体来说,它做了以下几件事情:

  • 遍历所有烟花对象,如果烟花还存活,则在画布上显示它的效果并更新它的状态;否则将烟花爆炸后生成的粒子转化为心形对象,并将烟花从 fireworks 列表中移除。

  • 遍历所有心形对象,显示它们的效果并更新它们的状态。

  • root 窗口上注册一个定时器,在 25 毫秒之后再次调用 draw 函数,实现连续播放动画的效果。

三、完整代码:

      

python">import math
import random
import threading
import time
from math import sin, cos, pi, log
from tkinter import *
import re# 烟花相关设置
Fireworks = []
maxFireworks = 8
CANVAS_WIDTH = 1080  # 画布的宽
CANVAS_HEIGHT = 600  # 画布的高
CANVAS_CENTER_X = CANVAS_WIDTH / 2  # 画布中心的X轴坐标
CANVAS_CENTER_Y = CANVAS_HEIGHT / 2  # 画布中心的Y轴坐标
IMAGE_ENLARGE = 12  # 放大比例
HEART_COLOR = "pink"  # 心的颜色# 烟花类
class firework(object):def __init__(self, color, speed, width, height):self.radius = random.randint(2, 3)  # 粒子半径为2~3像素self.color = color  # 粒子颜色self.speed = speed  # speed是1.5-3.5秒self.status = 0  # 在烟花未爆炸的情况下,status=0;爆炸后,status>=1;当status>100时,烟花的生命期终止self.nParticle = random.randint(80, 100)  # 粒子数量self.center = [random.randint(0, width - 15), random.randint(0, height - 15)]  # 烟花随机中心坐标self.oneParticle = []  # 原始粒子坐标(100%状态时)self.rotTheta = random.uniform(-1, 2 * math.pi)  # 椭圆平面旋转角self.ellipsePara = [random.randint(30, 40), random.randint(20, 30)]  # 椭圆参数方程:x=a*cos(theta),y=b*sin(theta)theta = 2 * math.pi / self.nParticlefor i in range(self.nParticle):t = random.uniform(-1.0 / 16, 1.0 / 16)  # 产生一个 [-1/16,1/16) 的随机数x, y = self.ellipsePara[0] * math.cos(theta * i + t), self.ellipsePara[1] * math.sin(theta * i + t)  # 椭圆参数方程xx, yy = x * math.cos(self.rotTheta) - y * math.sin(self.rotTheta), y * math.cos(self.rotTheta) + x * math.sin(self.rotTheta)  # 平面旋转方程self.oneParticle.append([xx, yy])self.curParticle = self.oneParticle[0:]  # 当前粒子坐标self.thread = threading.Thread(target=self.extend)  # 建立线程对象
完整代码,见文末

 资料获取,更多粉丝福利,关注下方公众号:“英杰代码编程”获取

       回复"python爱心代码",“爱心代码”,“python爱心” 均可获取完整代码


http://www.ppmy.cn/ops/39139.html

相关文章

java-springboot项目添加swagger2/Knife4j,附注解

文章目录 添加依赖config工作包中新增SwaggerConfig报错注解 环境&#xff1a; jdk1.8 java8 springboot2.6.13 swagger2.9.2 添加依赖 pom.xml <!-- 添加swagger2--><dependency><groupId>io.springfox</groupId><artifactId>springfo…

XML常见解析方式及XXE防御

1.PHP 1.1 SimpleXML SimpleXML是PHP5后提供的一套简单易用的xml工具集,可以把xml转换成方便处理的对象,也可以组织生成xml数据。不过它不适用于包含namespace的xml,而且要保证xml格式完整(well-formed)。它提供了三个方法:simplexml_import_dom、simplexml_load_file、sim…

在51单片机里面学习C语言

在开始前我有一些资料&#xff0c;是我根据网友给的问题精心整理了一份「&#xff23;语言的资料从专业入门到高级教程」&#xff0c; 点个关注在评论区回复“888”之后私信回复“888”&#xff0c;全部无偿共享给大家&#xff01;&#xff01;&#xff01; 说出来你们可能都…

AI助手,为生活和工作增添新体验

在当今科技飞速发展的时代,人工智能(AI)已经渗透到我们生活和工作的方方面面。无论是传统的大型语言模型,还是专注于搜索领域的AI助手,都为我们带来了前所未有的便利和效率。让我们一起来探索这些AI产品的魅力所在。 大型语言模型凭借强大的自然语言处理能力,可以为我们提供多…

力扣顺序表思路讲解

本篇文章&#xff0c;我给大家带来的是顺序表题目讲解&#xff0c;希望大家看完有所收获&#xff0c;废话不多说&#xff0c;我们现在开始 审题 大白话&#xff1a;给了一个数组和一个目标值。如果数组里的两个元素相加 目标值&#xff0c;则返回这两个元素的下标。那么大家需…

WMS仓储管理系统库存分类的详细讲解

在当今日益复杂和快速变化的商业环境中&#xff0c;仓库管理成为了一个企业不可或缺的关键环节。WMS仓储管理系统解决方案凭借其自动化和信息化的优势&#xff0c;为企业带来了革命性的改变&#xff0c;特别是在库存分类方面。接下来&#xff0c;我们将深入探讨WMS仓储管理系统…

选择器、pxcook软件、盒子模型

结构伪类选择器 定义&#xff1a;根据结构的元素关系来查找元素。 <title>Document</title><style>li:first-child{color:aqua ;}li:last-child{color: aqua;}li:nth-child(3){color: aqua;}</style> </head> <body><ul><li>…

js 获取某一天所在周的所有天

封装函数 function getWeekDays(date) {let weekDays [];let day date.getDay() - 1;let startDate new Date(date);startDate.setDate(startDate.getDate() - day);for (let i 0; i < 7; i) {weekDays.push(new Date(startDate));startDate.setDate(startDate.getDate…