帮我写一个生成烟花的python代码
时间: 2024-02-07 22:04:12 浏览: 25
以下是一个简单的生成烟花效果的Python代码,使用了Pygame库:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置屏幕大小
screen = pygame.display.set_mode((800, 600))
# 设置颜色
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
RED = (255, 0, 0)
ORANGE = (255, 128, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PURPLE = (128, 0, 128)
# 定义烟花类
class Firework:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.exploded = False
self.particles = []
def explode(self):
for i in range(100):
speed = random.randint(1, 10)
angle = random.uniform(0, 2 * 3.14159)
dx = speed * math.sin(angle)
dy = speed * math.cos(angle)
particle = Particle(self.x, self.y, self.color, dx, dy)
self.particles.append(particle)
self.exploded = True
def draw(self):
if not self.exploded:
pygame.draw.circle(screen, self.color, (self.x, self.y), 5)
else:
for particle in self.particles:
particle.draw()
# 定义粒子类
class Particle:
def __init__(self, x, y, color, dx, dy):
self.x = x
self.y = y
self.color = color
self.dx = dx
self.dy = dy
self.lifetime = random.randint(10, 50)
def move(self):
self.x += self.dx
self.y += self.dy
self.lifetime -= 1
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 3)
def is_dead(self):
return self.lifetime <= 0
# 创建烟花列表
fireworks = []
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# 在鼠标位置生成烟花
x, y = event.pos
color = random.choice([YELLOW, RED, ORANGE, GREEN, BLUE, PURPLE])
firework = Firework(x, y, color)
fireworks.append(firework)
# 更新烟花和粒子
for firework in fireworks:
if not firework.exploded:
firework.draw()
if random.random() < 0.01:
firework.explode()
else:
for particle in firework.particles:
particle.move()
particle.draw()
firework.particles = [p for p in firework.particles if not p.is_dead()]
# 更新屏幕
pygame.display.flip()
# 退出Pygame
pygame.quit()
```