Python 简单的烟花代码
时间: 2024-09-13 21:00:33 浏览: 42
在Python中,你可以使用`pygame`这个库来制作简单的烟花效果。`pygame`是一个用于创建游戏的跨平台Python模块集合,它提供了一些绘图和声音处理的功能。以下是一个简单的烟花代码示例,它展示了如何使用`pygame`创建一个窗口,并在窗口中随机生成烟花效果。
```python
import pygame
import random
from pygame.locals import *
# 初始化pygame
pygame.init()
# 设置屏幕大小
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('简单烟花效果')
# 定义颜色
WHITE = (255, 255, 255)
colors = [
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 255, 0),
(255, 0, 255),
(0, 255, 255),
(255, 255, 255)
]
# 烟花粒子类
class FireworkParticle:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.radius = random.randint(2, 4)
self.velocity = [random.uniform(-1, 1), random.uniform(-1, 1)]
self.lifetime = random.randint(50, 150)
def update(self):
self.x += self.velocity[0]
self.y += self.velocity[1]
self.lifetime -= 1
self.velocity[1] += 0.05 # gravity effect
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
def is_alive(self):
return self.lifetime > 0
# 烟花类
class Firework:
def __init__(self):
self.particles = []
self.color = random.choice(colors)
self.x = random.randint(0, WIDTH)
self.y = HEIGHT
self.height = random.randint(HEIGHT//4, HEIGHT//2)
self.exploded = False
def explode(self):
for _ in range(100):
self.particles.append(FireworkParticle(self.x, self.height, self.color))
def update(self):
if not self.exploded:
self.y -= 5
if self.y <= self.height:
self.explode()
self.exploded = True
else:
for particle in self.particles:
particle.update()
self.particles = [p for p in self.particles if p.is_alive()]
def draw(self, screen):
if not self.exploded:
pygame.draw.circle(screen, self.color, (self.x, self.y), 5)
else:
for particle in self.particles:
particle.draw(screen)
# 主循环
clock = pygame.time.Clock()
fireworks = [Firework() for _ in range(5)]
running = True
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == QUIT:
running = False
for firework in fireworks:
firework.update()
firework.draw(screen)
fireworks = [fw for fw in fireworks if len(fw.particles) > 0] + [Firework() for _ in range(random.randint(0, 2))]
pygame.display.flip()
clock.tick(30)
pygame.quit()
```
在运行这段代码之前,请确保你已经安装了`pygame`库。你可以使用pip安装它:
```bash
pip install pygame
```
这段代码创建了一个窗口,并在窗口中随机生成了烟花效果。每个烟花上升到一定高度后会爆炸成多个粒子,模拟了烟花爆炸的效果。你可以根据自己的需求修改颜色、速度、大小等参数来调整烟花的效果。
阅读全文