【Python】 使用pygame库实现新年烟花

祝大家金蛇衔财,蛇来运转

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

复制代码
pip install pygame

接下来是烟花效果的 Python 代码:

复制代码
import pygame
import random
import math
import sys

# 初始化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 Firework:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.size = random.randint(5, 8)
        self.color = random.choice(COLORS)
        self.particles = []
        self.exploded = False

    def update(self):
        if not self.exploded:
            self.y -= 5  # 向上飞
            if self.y < HEIGHT // 2:  # 达到爆炸高度
                self.explode()
        else:
            for particle in self.particles:
                particle.update()

    def draw(self):
        if not self.exploded:
            pygame.draw.circle(screen, self.color, (self.x, self.y), self.size)
        else:
            for particle in self.particles:
                particle.draw()

    def explode(self):
        self.exploded = True
        num_particles = random.randint(50, 100)
        for _ in range(num_particles):
            angle = random.uniform(0, 2 * math.pi)
            speed = random.uniform(2, 6)
            dx = math.cos(angle) * speed
            dy = math.sin(angle) * speed
            color = random.choice(COLORS)
            particle = Particle(self.x, self.y, dx, dy, color)
            self.particles.append(particle)

# 粒子类
class Particle:
    def __init__(self, x, y, dx, dy, color):
        self.x = x
        self.y = y
        self.dx = dx
        self.dy = dy
        self.color = color
        self.size = random.randint(2, 4)
        self.lifetime = random.randint(50, 100)

    def update(self):
        self.x += self.dx
        self.y += self.dy
        self.lifetime -= 1
        if self.lifetime <= 0:
            self.size -= 1
        if self.size <= 0:
            self.size = 0

    def draw(self):
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.size)

# 游戏主循环
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.03:  # 3% 概率生成新烟花
            firework = Firework(random.randint(100, WIDTH - 100), HEIGHT)
            fireworks.append(firework)

        # 更新和绘制所有烟花
        for firework in fireworks[:]:
            firework.update()
            firework.draw()
            if firework.exploded and not firework.particles:  # 爆炸并且所有粒子消失后移除烟花
                fireworks.remove(firework)

        pygame.display.flip()
        clock.tick(60)  # 每秒60帧

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()

代码解释

  1. 烟花类 (Firework)

    • 初始化时设定烟花的起始位置、大小、颜色等。
    • 当烟花飞到一定高度时,会调用 explode() 方法,生成多个粒子。
  2. 粒子类 (Particle)

    • 每个烟花爆炸后都会生成若干个粒子,每个粒子有方向、速度、颜色和生命周期等属性。
    • 粒子会随时间更新位置和大小。
  3. 主循环 (main())

    • 游戏窗口不断更新,生成新的烟花,并且更新已经存在的烟花的状态。
    • 使用 pygame.event.get() 处理退出事件。

运行效果

  • 烟花会从屏幕底部随机位置发射,飞到一定高度后爆炸,产生色彩斑斓的粒子效果,粒子逐渐消散。
  • 每隔一段时间,会有新的烟花生成,模拟一个持续的烟花秀。
相关推荐
爱喝白开水a2 小时前
LangChain 基础系列之 Prompt 工程详解:从设计原理到实战模板_langchain prompt
开发语言·数据库·人工智能·python·langchain·prompt·知识图谱
Neverfadeaway2 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
武子康2 小时前
Java-152 深入浅出 MongoDB 索引详解 从 MongoDB B-树 到 MySQL B+树 索引机制、数据结构与应用场景的全面对比分析
java·开发语言·数据库·sql·mongodb·性能优化·nosql
杰克尼2 小时前
JavaWeb_p165部门管理
java·开发语言·前端
一成码农2 小时前
JavaSE面向对象(下)
java·开发语言
偶尔的鼠标人2 小时前
Avalonia DataGrid 控件的LostFocus事件会多次触发
开发语言·c#
晚风残3 小时前
【C++ Primer】第十二章:动态内存管理
开发语言·c++·c++ primer
_extraordinary_3 小时前
Java Spring日志
java·开发语言·spring
初圣魔门首席弟子3 小时前
【C++ 学习】单词统计器:从 “代码乱炖” 到 “清晰可品” 的复习笔记
开发语言·c++
默默coding的程序猿3 小时前
3.git的分支携带问题是什么?怎么解决?
java·git·python·svn·gitee·github·intellij-idea