Python 如何实现烟花效果的完整代码

文章精选推荐

1 JetBrains Ai assistant 编程工具让你的工作效率翻倍

2 Extra Icons:JetBrains IDE的图标增强神器

3 IDEA插件推荐-SequenceDiagram,自动生成时序图

4 BashSupport Pro 这个ides插件主要是用来干嘛的 ?

5 IDEA必装的插件:Spring Boot Helper的使用与功能特点

6 Ai assistant ,又是一个写代码神器

7 Cursor 设备ID修改器,你的Cursor又可以继续试用了

文章正文

在 Python 中实现烟花特效可以使用 pygame 库来创建图形化界面和动画效果。以下是一个完整的烟花特效实现代码:


1. 安装 pygame

首先,确保你已经安装了 pygame 库。如果没有安装,可以使用以下命令安装:

bash 复制代码
pip install pygame

2. 实现烟花特效的完整代码

python 复制代码
import pygame
import random
import math

# 初始化 pygame
pygame.init()

# 设置屏幕大小
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("烟花特效")

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
COLORS = [
    (255, 0, 0),  # 红色
    (0, 255, 0),  # 绿色
    (0, 0, 255),  # 蓝色
    (255, 255, 0),  # 黄色
    (255, 0, 255),  # 紫色
    (0, 255, 255),  # 青色
]

# 烟花粒子类
class Particle:
    def __init__(self, x, y, color, speed, angle):
        self.x = x
        self.y = y
        self.color = color
        self.speed = speed
        self.angle = angle
        self.age = 0

    def move(self):
        # 根据角度和速度更新粒子的位置
        self.x += math.cos(self.angle) * self.speed
        self.y += math.sin(self.angle) * self.speed
        self.age += 1

    def draw(self):
        # 绘制粒子
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 2)

# 烟花类
class Firework:
    def __init__(self):
        self.x = random.randint(0, WIDTH)
        self.y = HEIGHT
        self.color = random.choice(COLORS)
        self.particles = []
        self.exploded = False

    def explode(self):
        # 爆炸生成多个粒子
        for _ in range(100):
            speed = random.uniform(1, 3)
            angle = random.uniform(0, 2 * math.pi)
            self.particles.append(Particle(self.x, self.y, self.color, speed, angle))
        self.exploded = True

    def move(self):
        if not self.exploded:
            # 烟花上升
            self.y -= 5
            if self.y <= random.randint(100, 300):
                self.explode()
        else:
            # 粒子移动
            for particle in self.particles:
                particle.move()

    def draw(self):
        if not self.exploded:
            # 绘制未爆炸的烟花
            pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 5)
        else:
            # 绘制爆炸后的粒子
            for particle in self.particles:
                particle.draw()

# 主循环
def main():
    clock = pygame.time.Clock()
    fireworks = []

    running = True
    while running:
        screen.fill(BLACK)  # 清屏

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # 添加新的烟花
        if random.random() < 0.05:  # 控制烟花生成频率
            fireworks.append(Firework())

        # 更新和绘制烟花
        for firework in fireworks[:]:
            firework.move()
            firework.draw()
            if firework.exploded and all(particle.age > 50 for particle in firework.particles):
                fireworks.remove(firework)

        pygame.display.flip()  # 更新屏幕
        clock.tick(30)  # 控制帧率

    pygame.quit()

if __name__ == "__main__":
    main()

3. 代码说明

  1. Particle 类

    • 表示烟花爆炸后的单个粒子。
    • 每个粒子有自己的位置、颜色、速度和角度。
    • 通过 move 方法更新粒子的位置,通过 draw 方法绘制粒子。
  2. Firework 类

    • 表示一个烟花。
    • 烟花在未爆炸时会向上移动,达到一定高度后爆炸,生成多个粒子。
    • 通过 explode 方法生成粒子,通过 movedraw 方法更新和绘制烟花。
  3. 主循环

    • 不断生成新的烟花,并更新和绘制所有烟花。
    • 使用 pygame.event.get() 检测退出事件。
    • 通过 clock.tick(30) 控制帧率为 30 FPS。

4. 运行效果

运行代码后,你会看到一个黑色背景的窗口,烟花不断从底部升起并在空中爆炸,形成绚丽的烟花特效。


5. 进一步优化

  • 增加更多颜色 :可以在 COLORS 列表中添加更多颜色。
  • 调整烟花数量 :通过修改 random.random() < 0.05 中的阈值控制烟花生成频率。
  • 添加音效 :使用 pygame.mixer 播放烟花爆炸的音效。

希望这个烟花特效的实现对你有帮助!

相关推荐
码行山野赴时序归途11 分钟前
链表家族收官篇:循环链表
c语言·开发语言·数据结构·链表
泡茶喝茶写代码12 分钟前
量化数据进阶:多维实战篇(第 11 篇):历史涨跌停价:涨跌停序列与止损线测算
java·python·股票数据api·股票数据·股票数据api接口·股票api数据接口·股票量化数据api
景熙552324 分钟前
单体项目编写思路和落地形式
java·开发语言
ikun_文1 小时前
Django开启跨域请求
python·pycharm·django
外收内放1 小时前
Python与AI应用(项目开发实战:AI智能伴侣第三版)
python·学习·ai编程
别动我齐刘海1 小时前
ROS2 Jazzy + C++ 实战路线——进阶学习3
c++·人工智能·vscode·python·算法·机器学习·机器人
Logintern091 小时前
“以一致的顺序获取锁“是预防死锁最核心、最有效的手段
python·postgresql·锁机制
计算机毕设定制辅导-无忧学长1 小时前
《基于SpringBoot的未成年人健康知识科普平台的设计与实现》
java·开发语言·vue.js·spring boot·未成年人健康知识科普平台
打工仔折腾 AI1 小时前
Prometheus 告警推钉钉:从单群 Webhook 到跨网络 Alertmanager 实战
人工智能·后端·python·性能优化
Ivanqhz1 小时前
Ping-Pong 双缓冲
开发语言·人工智能·python·深度学习·mlir