大家好,我是菲英。
今天带来一份 python 代码,是简易的烟花小程序。
安装包
pip install pygame
进入正题 - 我们的烟花代码:
import pygame
import random
import math# 初始化pygame
pygame.init()# 设置屏幕大小和标题
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Simple Fireworks")# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)# 烟花粒子类
class Firework:def __init__(self, x, y):self.x = xself.y = yself.particles = []self.color = random.choice([RED, GREEN, BLUE, YELLOW])self.exploding = Falsedef explode(self):ifnot self.exploding:for _ in range(100):angle = random.uniform(0, 2 * math.pi)speed = random.uniform(2, 5)dx = speed * math.cos(angle)dy = speed * math.sin(angle)self.particles.append([self.x, self.y, dx, dy, self.color, random.randint(50, 255)])self.exploding = Truedef update(self):for particle in self.particles:particle[0] += particle[2]particle[1] += particle[3]particle[5] -= 2# 粒子的透明度减小self.particles = [p for p in self.particles if p[5] > 0]def draw(self):for particle in self.particles:pygame.draw.circle(screen, particle[4], (int(particle[0]), int(particle[1])), 3)# 主程序
def main():clock = pygame.time.Clock()fireworks = []running = Truewhile running:screen.fill(BLACK)for event in pygame.event.get():if event.type == pygame.QUIT:running = False# 每隔一段时间生成一个烟花if random.random() < 0.02:fireworks.append(Firework(random.randint(100, 700), random.randint(100, 500)))# 更新并绘制烟花for firework in fireworks:firework.explode()firework.update()firework.draw()pygame.display.flip()clock.tick(60)pygame.quit()if __name__ == "__main__":main()
最后是它的代码说明:
-
Firework 类:每个烟花由多个粒子组成,粒子会在爆炸时向四面八方散开,每个粒子具有位置、速度、颜色和透明度。
-
explode() 方法:用于初始化爆炸粒子,随机生成不同方向和速度的粒子。
-
update() 方法:更新每个粒子的位置,并让透明度逐渐减少,模拟烟花消失的效果。
-
draw() 方法:将每个粒子画在屏幕上。