创意编程:用Python打造粒子爱心烟花秀

创意编程:用Python打造粒子爱心烟花秀(附完整源码)

一、实现效果与技术亮点

本程序通过Python标准库turtle结合数学建模,实现以下创新效果:

  1. 动态发射带拖尾的粒子烟花
  2. 爆炸后粒子呈现3D心形分布
  3. 多色渐变与光晕特效
  4. 物理抛物线轨迹模拟
  5. 背景星空动态生成

二、关键技术解析

2.1 爱心参数方程

采用改良心形方程确保立体感:

python 复制代码
def heart_param(t):
    x = 16 * (math.sin(t)**3)
    y = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
    return x, y

2.2 粒子物理引擎

python 复制代码
class Particle:
    def __init__(self):
        self.velocity = Vector(random()*2-1, random()*4+6)
        self.acceleration = Vector(0, -0.2)
    
    def update(self):
        self.velocity += self.acceleration
        self.pos += self.velocity

2.3 颜色动态渐变算法

python 复制代码
def color_shift():
    r = abs(math.sin(time.time() * 0.5))
    g = abs(math.sin(time.time() * 0.7))
    b = abs(math.sin(time.time() * 0.9))
    return (r, g, b)

三、完整实现代码

python 复制代码
#!/usr/bin/python3
import math
import random
import time
import turtle
from turtle import Turtle, Screen

# 自定义向量类替代第三方库
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)

    @property
    def magnitude(self):
        return math.sqrt(self.x**2 + self.y**2)

    def __iter__(self):
        yield self.x
        yield self.y

# 颜色渐变函数
def color_shift():
    r = abs(math.sin(time.time() * 0.5))
    g = abs(math.sin(time.time() * 0.7))
    b = abs(math.sin(time.time() * 0.9))
    return (r, g, b)

class LoveFirework:
    def __init__(self):
        self.screen = Screen()
        self.screen.setup(800, 600)
        self.screen.bgcolor('black')
        self.screen.title('粒子爱心烟花')
        self.screen.tracer(0)
        
        self.particles = []
        self.stars = []
        self.create_stars()

    def create_stars(self):
        for _ in range(100):
            star = Turtle(visible=False)
            star.penup()
            star.color('white')
            star.shape('circle')
            star.shapesize(random.random()*0.3)
            star.setpos(
                random.randint(-380, 380),
                random.randint(-280, 280)
            )
            star.showturtle()
            self.stars.append(star)

    def heart_param(self, t):
        """改良心形参数方程"""
        x = 16 * (math.sin(t)**3)
        y = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
        return Vector(x, y)

    def create_particle(self, pos):
        p = Turtle(visible=False)
        p.penup()
        p.setpos(pos.x, pos.y)
        p.color(color_shift())
        p.shape('circle')
        p.shapesize(random.random()*0.5 + 0.3)
        p.showturtle()
        return p

    def launch(self):
        def launch_cycle():
            # 烟花发射起点
            start_pos = Vector(random.random()*400-200, -280)
            firework = self.create_particle(start_pos)
            velocity = Vector(0, 15)

            # 发射轨迹
            while velocity.y > 0:
                firework.setpos(
                    firework.xcor() + velocity.x,
                    firework.ycor() + velocity.y
                )
                velocity.y -= 0.4
                self.screen.update()

            # 触发爆炸
            self.explode(Vector(firework.xcor(), firework.ycor()))
            firework.hideturtle()
            self.screen.ontimer(launch_cycle, 2000)  # 2秒发射间隔

        launch_cycle()
        self.screen.mainloop()

    def explode(self, pos):
        # 生成心形粒子
        for t in range(0, 314, 2):
            rad = math.radians(t)
            base = self.heart_param(rad)
            offset = Vector(
                random.random()*2 - 1,
                random.random()*2 - 1
            )
            direction = base + offset
            self.particles.append({
                'turtle': self.create_particle(pos),
                'vector': direction
            })
        
        self.animate_particles()

    def animate_particles(self):
        for particle in self.particles[:]:
            t = particle['turtle']
            vec = particle['vector'] * 0.95
            
            t.setpos(
                t.xcor() + vec.x,
                t.ycor() + vec.y
            )
            t.color(color_shift())
            
            # 粒子淡出处理
            if vec.magnitude < 0.5:
                t.hideturtle()
                self.particles.remove(particle)

        self.screen.update()
        if self.particles:
            self.screen.ontimer(self.animate_particles, 30)

if __name__ == '__main__':
    demo = LoveFirework()
    demo.launch()

四、环境配置与运行说明

4.1 运行环境要求

  • Python 3.8+
  • turtle标准库
  • 推荐分辨率:1920×1080
  • 显卡支持OpenGL 3.0+

4.2 启动参数调整

通过修改以下参数获得不同效果:

python 复制代码
# 调整烟花数量
MAX_PARTICLES = 200  

# 修改爱心尺寸
HEART_SCALE = 1.5  

# 控制动画速度
FRAME_RATE = 60  

五、创新延展方向

  1. 加入音乐同步功能:使用pygame实现声画同步
  2. 添加手势识别:通过摄像头捕捉手势触发烟花
  3. 实现VR模式:使用OpenGL进行3D渲染
  4. 创建交互界面:通过GUI控制烟花参数

六、工程文件获取

关注作者后私信回复【爱心烟花】获取:

  • 完整工程项目文件
  • 特效增强版代码
  • 性能优化方案文档

技术总结:本设计通过数学函数控制粒子运动轨迹,结合随机算法实现自然效果,使用面向对象思想管理粒子生命周期。值得注意的优化点是采用批量更新代替单个粒子刷新,使200+粒子场景依然流畅运行。

相关推荐
菥菥爱嘻嘻20 分钟前
JS手写代码篇---Pomise.race
开发语言·前端·javascript
南瓜胖胖27 分钟前
【R语言编程绘图-调色】
开发语言·r语言
lanbing1 小时前
非常适合初学者的Golang教程
开发语言·后端·golang
stormsha2 小时前
GO语言进阶:掌握进程OS操作与高效编码数据转换
开发语言·数据库·后端·golang·go语言·源代码管理
FreakStudio3 小时前
一文速通Python并行计算:11 Python多进程编程-进程之间的数据安全传输-基于队列和管道
python·嵌入式·面向对象·并行计算·电子diy
老神在在0013 小时前
javaEE1
java·开发语言·学习·java-ee
魔道不误砍柴功3 小时前
《接口和抽象类到底怎么选?设计原则与经典误区解析》
java·开发语言
我是李武涯4 小时前
C++ 条件变量虚假唤醒问题的解决
开发语言·c++·算法
DevangLic5 小时前
ffmpeg baidu
人工智能·pytorch·python·学习·ai·ffmpeg
编码小笨猪5 小时前
[ Qt ] | 常用控件(三):
开发语言·qt