新年祝福烟花python代码
时间: 2024-12-31 14:36:03 浏览: 14
### Python 新年烟花效果代码示例
为了实现新年祝福烟花效果,可以利用 `pygame` 库来创建一个生动的视觉体验。下面是一个完整的代码示例,该程序不仅展示了基本的烟花爆炸效果,还加入了颜色渐变和简单的声音效果。
#### 安装依赖库
首先需要安装所需的库:
```bash
pip install pygame
```
#### 导入必要的模块并初始化设置
```python
import random
import math
import pygame
from pygame.locals import *
# 初始化 Pygame 和混音器用于播放声音
pygame.init()
pygame.mixer.init()
# 设置屏幕尺寸和其他全局变量
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
black = (0, 0, 0)
# 加载音效文件
explosion_sound = pygame.mixer.Sound('sounds/explosion.wav')
```
#### 创建烟花类
定义一个表示单个烟花的对象模型,其中包含了位置、速度以及生命周期等属性。
```python
class Firework:
def __init__(self):
self.color = tuple(random.randint(0, 255) for _ in range(3)) # 随机生成初始颜色
self.x = random.randint(50, width - 50)
self.y = height + 10
self.speed_y = -(random.random() * 7 + 4)
self.age = 0
def update(self):
"""更新状态"""
self.y += self.speed_y
self.age += 1
if self.age >= 60 or self.y < -10:
explosion_sound.play() # 当达到最大年龄或飞出顶部时触发爆炸声
particles.append(ParticleGroup(self.x, self.y, self.color))
fireworks = []
particles = []
def draw_firework():
global fireworks
new_fireworks = []
screen.fill(black)
for fw in fireworks[:]:
fw.update()
if fw.age < 60 and fw.y > -10:
new_fireworks.append(fw)
# 绘制上升中的烟火
pygame.draw.circle(screen, fw.color, (int(fw.x), int(fw.y)), 3)
fireworks = new_fireworks[:]
```
#### 添加粒子系统以模拟爆炸后的碎片
通过引入额外的 Particle 类及其集合 ParticleGroup 来处理每次爆炸产生的多个小颗粒。
```python
class Particle:
def __init__(self, x, y, color):
angle = random.uniform(0, 2*math.pi)
speed = random.uniform(2, 7)
self.vx = math.cos(angle)*speed
self.vy = math.sin(angle)*speed
self.x = x
self.y = y
self.size = random.randint(4, 9)
self.life_span = random.randint(20, 40)
self.color = list(color)
self.fade_rate = [(c/float(self.life_span)) for c in self.color]
class ParticleGroup(list):
def __init__(self, x, y, base_color):
super().__init__()
num_particles = random.randint(30, 50)
for i in range(num_particles):
p = Particle(x, y, base_color)
self.append(p)
def draw_particles():
remaining_particles = []
for particle in particles:
alive_members = [p for p in particle if all([v>=0 for v in p.color])]
for member in alive_members:
member.x += member.vx
member.y += member.vy
# 更新颜色(淡出)
member.color[:] = [max(c-member.fade_rate[i], 0) for i,c in enumerate(member.color)]
pygame.draw.rect(screen, member.color,
Rect(int(member.x)-member.size//2,int(member.y)-member.size//2,member.size,member.size))
if any(alive_members):
remaining_particles.append(particle)
del particles[:]
particles.extend(remaining_particles)
```
#### 主循环逻辑控制
最后,在主事件循环内不断刷新画面帧率,并随机添加新的烟花实例直到用户关闭窗口为止。
```python
running = True
while running:
clock.tick(30)
for event in pygame.event.get():
if event.type == QUIT:
running = False
if not bool(fireworks) or random.random()<0.05:
fireworks.append(Firework())
try:
draw_firework()
draw_particles()
pygame.display.flip()
except Exception as e:
print(e)
break
pygame.quit()
```
阅读全文