python生日快乐烟花
时间: 2025-06-30 10:15:51 AIGC 浏览: 40
要使用 Python 编写一个“生日快乐”烟花效果的程序,可以结合 `pygame` 和 `turtle` 库实现。以下是一个完整的示例代码,它包括背景音乐、文字显示和动态烟花动画。
### 使用 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("生日快乐烟花")
# 加载背景音乐(确保文件路径正确)
try:
bg_music = pygame.mixer.Sound('bg.mp3')
bg_music.play(-1) # 循环播放
except FileNotFoundError:
print("背景音乐文件未找到,跳过音频部分")
# 颜色定义
colors = [(255, 0, 0), (255, 165, 0), (255, 255, 0), (0, 128, 0),
(0, 0, 255), (75, 0, 130), (238, 130, 238)]
# 烟花粒子类
class Particle:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(2, 5)
self.vx = math.cos(angle) * speed
self.vy = math.sin(angle) * speed
self.life = 100
def move(self):
self.x += self.vx
self.y += self.vy
self.vy += 0.05 # 模拟重力
self.life -= 1
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), 3)
# 烟花类
class Firework:
def __init__(self):
self.x = random.randint(100, width - 100)
self.y = height
self.particles = []
self.color = random.choice(colors)
self.exploded = False
def launch(self):
if not self.exploded:
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 3)
self.y -= 5
if self.y <= random.randint(100, 400):
self.explode()
def explode(self):
self.exploded = True
for _ in range(100):
self.particles.append(Particle(self.x, self.y, self.color))
def update(self):
if self.exploded:
for p in self.particles:
p.move()
p.draw(screen)
# 显示生日祝福语
def show_birthday_text():
font = pygame.font.SysFont("SimHei", 48)
text = font.render("生日快乐!", True, (255, 255, 255))
rect = text.get_rect(center=(width // 2, 50))
screen.blit(text, rect)
# 主循环
clock = pygame.time.Clock()
fireworks_list = []
running = True
while running:
clock.tick(60)
screen.fill((0, 0, 0)) # 黑色背景
show_birthday_text()
# 创建新的烟花
if random.random() < 0.05:
fireworks_list.append(Firework())
# 更新并绘制所有烟花
for fw in fireworks_list:
if not fw.exploded:
fw.launch()
else:
fw.update()
# 移除生命周期结束的烟花
fireworks_list = [fw for fw in fireworks_list if any(p.life > 0 for p in fw.particles)]
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
pygame.quit()
sys.exit()
```
### 说明:
- **背景音乐**:需要准备一个名为 `bg.mp3` 的背景音乐文件,并将其放在与脚本相同的目录下。
- **字体支持中文**:使用了 `SimHei` 字体来渲染“生日快乐”文本,如果系统不支持可替换为其他中文字体。
- **烟花粒子效果**:每个烟花爆炸后会生成多个彩色粒子,模拟真实烟花扩散效果。
- **随机性**:烟花的发射位置、颜色和粒子轨迹都具有一定的随机性,增强视觉多样性。
---
阅读全文
相关推荐



















