python生新年快乐烟花
时间: 2025-01-05 08:23:13 浏览: 18
### 实现新年快乐烟花动画效果
为了创建一个生动的新年快乐烟花动画效果,可以利用 Python 的 Pygame 库。Pygame 是一个非常适合制作游戏和其他多媒体应用程序的库,能够轻松处理图形、声音以及用户输入。
#### 初始化 Pygame 和设置屏幕参数
首先需要初始化 Pygame 并设定好显示窗口大小以及其他必要的配置项:
```python
import pygame as pg
from random import randint, choice
pg.init()
screenWidth, screenHeight = 800, 600
screen = pg.display.set_mode((screenWidth, screenHeight))
clock = pg.time.Clock()
# 设置背景颜色为黑色
bg_color = (0, 0, 0)
# 加载字体并渲染文字
font = pg.font.SysFont("comicsansms", 72)
text = "Happy New Year!"
text_color = (255, 190, 200)
rendered_text = font.render(text, True, text_color)
```
#### 创建烟花类
定义 `Firework` 类来表示单个烟花的行为模式,包括上升过程中的移动逻辑及其爆炸后的粒子散射行为:
```python
class Firework:
def __init__(self):
self.color = (randint(0, 255), randint(0, 255), randint(0, 255))
self.x = randint(50, screenWidth - 50)
self.y = screenHeight + 30
self.speed_y = -(randint(10, 20))
# 粒子列表用于存储爆炸产生的碎片位置和速度向量
self.particles = []
def update(self):
if not self.exploded():
self.move_upward()
else:
self.spread_particles()
def move_upward(self):
self.y += self.speed_y
# 当达到一定高度时触发爆炸
if self.y < screenHeight / 2 and len(self.particles) == 0:
self.explode()
def explode(self):
for _ in range(randint(50, 100)):
angle = radians(randint(-360, 360))
speed_x = cos(angle) * randint(5, 15)
speed_y = sin(angle) * randint(5, 15)
particle = Particle(self.x, self.y, speed_x, speed_y, self.color)
self.particles.append(particle)
def spread_particles(self):
remaining_particles = []
for p in self.particles:
p.update()
if p.alive():
remaining_particles.append(p)
self.particles = remaining_particles
def exploded(self):
return len(self.particles) > 0 or self.y >= screenHeight / 2
class Particle:
def __init__(self, x, y, vx, vy, color):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.color = color
self.life = 10
def update(self):
self.x += self.vx
self.y -= self.vy
self.life -= 1
def alive(self):
return self.life > 0
```
#### 更新与绘制循环
最后,在主程序中通过不断刷新画面帧率的方式让烟花持续发射,并且当所有烟花结束之后退出循环:
```python
def main_loop():
fireworks = [Firework() for _ in range(3)]
while True:
screen.fill(bg_color)
for event in pg.event.get():
if event.type == pg.QUIT:
quit()
# 绘制文本
screen.blit(rendered_text, ((screenWidth-rendered_text.get_width())//2,
(screenHeight-rendered_text.get_height()-100)//2))
updated_fireworks = []
for fw in fireworks:
fw.update()
if not fw.exploded():
pg.draw.circle(screen, fw.color, (fw.x, int(fw.y)), 5)
elif any([p.alive() for p in fw.particles]):
for p in fw.particles:
pg.draw.circle(screen, p.color, (int(p.x), int(p.y)), 2)
updated_fireworks.append(fw)
fireworks.extend([Firework()]*(len(updated_fireworks)-len(fireworks)))
fireworks = updated_fireworks[:]
pg.display.flip()
clock.tick(60)
if __name__ == "__main__":
try:
main_loop()
except Exception as e:
print(e)
```
此代码片段展示了如何构建基本的新年快乐烟花动画效果[^1]。当然还可以进一步优化和完善这个项目,比如加入更多样化的视觉特效或是增加交互功能等。
阅读全文