找回密码
 中文实名注册
搜索
查看: 6|回复: 0

动态烟花

[复制链接]

4

主题

6

回帖

915

积分

高级会员

积分
915
发表于 昨天 17:34 | 显示全部楼层 |阅读模式
[Python] 纯文本查看 复制代码
import pygame
import random
import math

# 初始化
pygame.init()
WIDTH, HEIGHT = 900, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("动态烟花")

clock = pygame.time.Clock()

# 颜色池
COLORS = [
    (255, 50, 50),
    (50, 255, 50),
    (50, 50, 255),
    (255, 255, 50),
    (255, 50, 255),
    (50, 255, 255),
    (255, 255, 255)
]

# 粒子类
class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        angle = random.uniform(0, 2 * math.pi)
        speed = random.uniform(2, 7)
        self.vx = math.cos(angle) * speed
        self.vy = math.sin(angle) * speed
        self.color = color
        self.life = random.randint(40, 80)
        self.gravity = 0.05

    def update(self):
        self.vy += self.gravity
        self.x += self.vx
        self.y += self.vy
        self.life -= 1

    def draw(self, surface):
        if self.life > 0:
            alpha = max(self.life / 80, 0)
            r, g, b = self.color
            color = (int(r * alpha), int(g * alpha), int(b * alpha))
            pygame.draw.circle(surface, color, (int(self.x), int(self.y)), 2)

# 烟花类
class Firework:
    def __init__(self):
        self.x = random.randint(100, WIDTH - 100)
        self.y = HEIGHT
        self.target_y = random.randint(100, HEIGHT // 2)
        self.speed = random.uniform(6, 9)
        self.color = random.choice(COLORS)
        self.exploded = False
        self.particles = []

    def update(self):
        if not self.exploded:
            self.y -= self.speed
            if self.y <= self.target_y:
                self.explode()
        else:
            for p in self.particles:
                p.update()
            self.particles = [p for p in self.particles if p.life > 0]

    def explode(self):
        self.exploded = True
        for _ in range(120):
            self.particles.append(Particle(self.x, self.y, self.color))

    def draw(self, surface):
        if not self.exploded:
            pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), 3)
        else:
            for p in self.particles:
                p.draw(surface)

# 主循环
fireworks = []
running = True

while running:
    clock.tick(60)
    screen.fill((10, 10, 20))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 自动生成烟花
    if random.random() < 0.03:
        fireworks.append(Firework())

    for fw in fireworks:
        fw.update()
        fw.draw(screen)

    fireworks = [fw for fw in fireworks if not (fw.exploded and not fw.particles)]

    pygame.display.flip()

pygame.quit()
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 中文实名注册

本版积分规则

快速回复 返回顶部 返回列表