当前位置: 首页 > news >正文

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 库。如果没有安装,可以使用以下命令安装:

pip install pygame

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

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 播放烟花爆炸的音效。

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

相关文章:

  • Ollama 的庐山真面目
  • check 单元测试框架
  • 【vue-echarts】——01.认识echarts
  • SVN 简介
  • Java中的CyclicBarrier是什么?
  • 什么是 jQuery
  • 慢sql治理
  • 天锐绿盘 | 文档安全管理系统
  • 【构建企业级Spring Boot应用:从基础到高级的全面指南】
  • 同步类型对比
  • 【每日学点HarmonyOS Next知识】全局调整字体、h5选择框无法取消选中、margin不生效、Length转换为具体值、Prop和link比较
  • 聊一聊 IM 如何优化数据库
  • 16.4 LangChain LCEL 接口全解析:同步、异步与批处理的正确打开方式
  • 算法刷题-2025年03月01日
  • C语言复习2:键盘录入,字符串变量定义,流程控制语句
  • Redis 实战篇 ——《黑马点评》(下)
  • 【硬核拆解】DeepSeek开源周五连击:中国AI底层技术的“破壁之战”
  • Transformer 代码剖析7 - 词元嵌入(TokenEmbedding) (pytorch实现)
  • 【wordpress】服务器已有LNMP环境(已运行WordPress),如何配置文档访问功能?
  • 【笔记】用大预言模型构建专家系统
  • 做企业网站设计价格是多少钱/襄阳seo培训
  • 国内个人网站建设/sem竞价
  • 太原做网站公司5大建站服务/快速排名优化
  • app开发必须要网站吗/网站seo优化外包顾问
  • 做网站商业欺骗赔多少/百度云网盘搜索引擎
  • 网站建设 每年费用/网址导航