import pygame
import random
import math
# 初始化pygame
pygame.init()
# 设置屏幕尺寸
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("烟花效果")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
# 定义烟花粒子类
class Particle:
def __init__(self, x, y, color, vx, vy, size):
self.x = x
self.y = y
self.color = color
self.vx = vx
self.vy = vy
self.size = size
self.life = 255 # 粒子生命周期(透明度)
def update(self):
self.x += self.vx
self.y += self.vy
self.vy += 0.1 # 重力效果
self.life -= 5 # 生命周期递减
if self.life < 0:
self.life = 0
def draw(self, screen):
alpha = self.life / 255
color = (self.color[0], self.color[1], self.color[2], alpha)
pygame.draw.circle(screen, color, (int(self.x), int(self.y)), self.size)
# 定义烟花类
class Fireworks:
def __init__(self, x, y):
self.x = x
self.y = y
self.particles = []
self.explode()
def explode(self):
num_particles = 100
for _ in range(num_particles):
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(5, 15)
vx = speed * math.cos(angle)
vy = speed * math.sin(angle)
size = random.randint(2, 5)
color = random.choice(COLORS)
self.particles.append(Particle(self.x, self.y, color, vx, vy, size))
def update(self):
for particle in self.particles:
particle.update()
if particle.life == 0:
self.particles.remove(particle)
def draw(self, screen):
for particle in self.particles:
particle.draw(screen)
# 主循环
running = True
clock = pygame.time.Clock()
fireworks_list = []
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
fireworks_list.append(Fireworks(x, y))
# 更新烟花和粒子
for fireworks in fireworks_list[:]:
fireworks.update()
if not fireworks.particles: # 如果没有粒子了,就移除这个烟花对象
fireworks_list.remove(fireworks)
# 绘制
screen.fill(BLACK)
for fireworks in fireworks_list:
fireworks.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
烟花