实现一段python pygame绘制烟花的代码
时间: 2023-03-24 22:03:36 浏览: 185
以下是绘制烟花的 Python Pygame 代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置窗口大小
screen = pygame.display.set_mode((800, 600))
# 设置窗口标题
pygame.display.set_caption("烟花")
# 定义颜色
BLACK = (, , )
WHITE = (255, 255, 255)
RED = (255, , )
GREEN = (, 255, )
BLUE = (, , 255)
# 定义烟花类
class Firework:
def __init__(self, x, y):
self.x = x
self.y = y
self.color = (random.randint(, 255), random.randint(, 255), random.randint(, 255))
self.radius = 1
self.max_radius = random.randint(50, 100)
self.exploded = False
self.particles = []
def update(self):
if not self.exploded:
self.radius += 1
if self.radius >= self.max_radius:
self.explode()
else:
for particle in self.particles:
particle.update()
self.particles = [particle for particle in self.particles if not particle.dead]
def draw(self, screen):
if not self.exploded:
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
else:
for particle in self.particles:
particle.draw(screen)
def explode(self):
self.exploded = True
for i in range(100):
self.particles.append(Particle(self.x, self.y, self.color))
# 定义烟花粒子类
class Particle:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.radius = 2
self.angle = random.uniform(, 2 * math.pi)
self.speed = random.uniform(1, 5)
self.dead = False
self.life = random.randint(10, 50)
def update(self):
self.life -= 1
if self.life <= :
self.dead = True
self.x += self.speed * math.cos(self.angle)
self.y += self.speed * math.sin(self.angle)
self.radius -= .05
if self.radius <= :
self.dead = True
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(self.radius))
# 创建烟花列表
fireworks = []
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
fireworks.append(Firework(*event.pos))
# 更新烟花
for firework in fireworks:
firework.update()
# 绘制背景
screen.fill(BLACK)
# 绘制烟花
for firework in fireworks:
firework.draw(screen)
# 更新屏幕
pygame.display.flip()
# 退出 Pygame
pygame.quit()
```
希望能对你有所帮助!