好的!我为你准备了使用 Python 内置的 `turtle` 库制作烟花秀的完整代码。这个方案无需安装任何额外库,适合初学者快速实现。
## **🎆 Turtle 烟花秀完整代码**
```python
import turtle
import random
import math
# ====== 初始化设置 ======
# 创建画布
screen = turtle.Screen()
screen.bgcolor("black") # 黑色背景模拟夜空
screen.title("Python Turtle 烟花秀")
screen.setup(width=1000, height=700)
screen.tracer(0) # 关闭自动刷新,手动控制以获得更流畅动画
# 隐藏默认海龟
turtle.hideturtle()
# ====== 烟花粒子类 ======
class FireworkParticle:
def __init__(self, x, y, color):
self.turtle = turtle.Turtle()
self.turtle.hideturtle()
self.turtle.penup()
self.turtle.color(color)
self.turtle.shape("circle")
self.turtle.shapesize(0.3, 0.3) # 粒子大小
self.turtle.speed(0)
# 初始位置
self.x = x
self.y = y
self.turtle.goto(x, y)
self.turtle.showturtle()
# 物理属性
angle = random.uniform(0, 2 * math.pi) # 随机角度
speed = random.uniform(2, 8) # 随机速度
self.dx = math.cos(angle) * speed # x方向速度
self.dy = math.sin(angle) * speed # y方向速度
# 生命周期
self.life = 100 # 粒子寿命
self.gravity = 0.1 # 重力
self.resistance = 0.98 # 空气阻力
self.size = 0.3 # 初始大小
# 颜色渐变
self.color = color
self.color_fade = 1.0
# ====== 烟花管理类 ======
class FireworkManager:
def __init__(self):
self.particles = [] # 存储所有粒子
self.colors = [
"red", "yellow", "blue", "green",
"purple", "orange", "cyan", "pink",
"white", "gold", "magenta", "lime"
]
def create_firework(self, x=None, y=None):
"""在指定位置创建烟花爆炸"""
if x is None:
x = random.randint(-400, 400) # 随机x位置
if y is None:
y = random.randint(-200, 200) # 随机y位置
# 随机选择主颜色
main_color = random.choice(self.colors)
# 创建爆炸粒子
particle_count = random.randint(50, 120)
for _ in range(particle_count):
# 为每个粒子添加一些颜色变异
color_variation = random.randint(-30, 30)
r = min(255, max(0, self.get_color_value(main_color, 'r') + color_variation))
g = min(255, max(0, self.get_color_value(main_color, 'g') + color_variation))
b = min(255, max(0, self.get_color_value(main_color, 'b') + color_variation))
# 创建粒子
particle = FireworkParticle(x, y, self.rgb_to_hex(r, g, b))
self.particles.append(particle)
def get_color_value(self, color_name, channel):
"""获取颜色的RGB值(简化版)"""
colors = {
"red": (255, 0, 0),
"yellow": (255, 255, 0),
"blue": (0, 0, 255),
"green": (0, 255, 0),
"purple": (128, 0, 128),
"orange": (255, 165, 0),
"cyan": (0, 255, 255),
"pink": (255, 192, 203),
"white": (255, 255, 255),
"gold": (255, 215, 0),
"magenta": (255, 0, 255),
"lime": (0, 255, 0)
}
if color_name in colors:
if channel == 'r':
return colors[color_name][0]
elif channel == 'g':
return colors[color_name][1]
elif channel == 'b':
return colors[color_name][2]
return 255
def rgb_to_hex(self, r, g, b):
"""将RGB转换为turtle可识别的颜色格式"""
return f"#{r:02x}{g:02x}{b:02x}"
def update_particles(self):
"""更新所有粒子的状态"""
particles_to_remove = []
for particle in self.particles:
# 应用物理效果
particle.dx *= particle.resistance # 空气阻力
particle.dy *= particle.resistance
particle.dy -= particle.gravity # 重力
# 更新位置
particle.x += particle.dx
particle.y += particle.dy
particle.turtle.goto(particle.x, particle.y)
# 更新生命周期
particle.life -= 1
particle.color_fade = particle.life / 100 # 透明度渐变
# 粒子逐渐缩小
particle.size *= 0.97
if particle.size > 0.05:
particle.turtle.shapesize(particle.size, particle.size)
# 如果粒子生命结束,标记为待移除
if particle.life <= 0 or particle.size <= 0.05:
particles_to_remove.append(particle)
# 移除已死亡的粒子
for dead_particle in particles_to_remove:
dead_particle.turtle.clear()
dead_particle.turtle.hideturtle()
self.particles.remove(dead_particle)
return len(self.particles) # 返回当前活跃粒子数
# ====== 文字显示 ======
def show_info():
"""显示提示信息"""
info = turtle.Turtle()
info.hideturtle()
info.penup()
info.color("white")
info.goto(0, 300)
info.write("Turtle 烟花秀", align="center", font=("Arial", 24, "bold"))
info.goto(0, 270)
info.write("点击屏幕任意位置发射烟花", align="center", font=("Arial", 14))
info.goto(0, -320)
info.write("按空格键自动发射 | 按ESC键退出", align="center", font=("Arial", 12))
# ====== 主程序 ======
def main():
# 显示信息
show_info()
# 创建烟花管理器
manager = FireworkManager()
# 初始化几个烟花
for _ in range(3):
manager.create_firework()
# 自动发射标志
auto_launch = True
# ====== 事件处理函数 ======
def on_click(x, y):
"""鼠标点击事件:在点击位置创建烟花"""
manager.create_firework(x, y)
def toggle_auto_launch():
"""空格键事件:切换自动发射模式"""
nonlocal auto_launch
auto_launch = not auto_launch
print(f"自动发射: {'开启' if auto_launch else '关闭'}")
def exit_program():
"""ESC键事件:退出程序"""
screen.bye()
print("烟花秀结束!")
# 绑定事件
screen.onclick(on_click)
screen.onkey(toggle_auto_launch, "space")
screen.onkey(exit_program, "Escape")
screen.listen()
# ====== 主动画循环 ======
frame_count = 0
try:
while True:
# 随机自动发射烟花
if auto_launch and frame_count % 30 == 0: # 每30帧发射一次
if random.random() < 0.3: # 30%概率发射
manager.create_firework()
# 更新所有粒子
active_particles = manager.update_particles()
# 更新屏幕显示
screen.update()
# 控制帧率
turtle.delay(5)
frame_count += 1
# 如果粒子太少,自动补充
if active_particles < 20 and auto_launch:
manager.create_firework()
except turtle.Terminator:
pass # 正常退出
# ====== 启动程序 ======
if __name__ == "__main__":
print("=" * 50)
print("Turtle 烟花秀启动!")
print("操作说明:")
print("1. 点击屏幕任意位置 - 在该位置发射烟花")
print("2. 按空格键 - 切换自动发射模式")
print("3. 按ESC键 - 退出程序")
print("=" * 50)
main()
turtle.done()
```
## **🎯 运行说明**
### **1. 运行方式**
- 直接复制代码到 Python 文件中(如 `firework.py`)
- 运行:`python firework.py`
### **2. 操作控制**
| 操作 | 功能 |
|------|------|
| **鼠标点击** | 在点击位置发射烟花 |
| **空格键** | 切换自动发射模式(开/关) |
| **ESC键** | 退出程序 |
### **3. 效果特点**
- 🎨 **多彩烟花**:随机生成12种不同颜色的烟花
- ⭐ **物理模拟**:包含重力、空气阻力、速度衰减
- 🔥 **粒子效果**:每个烟花由50-120个粒子组成
- 🌟 **渐变消失**:粒子会逐渐变小、变淡直到消失
- 🔄 **自动模式**:可开启自动随机发射烟花
### **4. 自定义调整**
你可以修改以下参数来调整效果:
```python
# 在 FireworkParticle 类中:
self.life = 100 # ← 增大此值延长粒子存在时间
self.gravity = 0.1 # ← 调整重力大小
self.resistance = 0.98 # ← 调整阻力(接近1阻力越小)
# 在 create_firework 方法中:
particle_count = random.randint(50, 120) # ← 调整粒子数量
speed = random.uniform(2, 8) # ← 调整粒子初始速度
```
## **💡 进阶建议**
如果想进一步优化效果,可以考虑:
1. **添加拖尾效果**:为每个粒子绘制轨迹线
2. **多重爆炸**:粒子在消失前再次小爆炸
3. **形状烟花**:控制粒子角度,形成心形、圆形等特定形状
4. **声音效果**:配合 `winsound` 模块(仅Windows)添加爆炸音效
需要我解释代码的任何部分,或者想要其他特效(如心形烟花、节日主题烟花等),请随时告诉我!