烟花代码编程python

admin 51 0

# 烟花代码编程python

在Python中,我们可以使用一些图形库来创建一个模拟烟花的动画,这样的代码通常使用Pygame库,这是一个为制作2D游戏而设计的库,但也可以用来创建一些基本的图形动画。

你需要安装Pygame库,在你的终端或命令行中,输入以下命令来安装:

pip install pygame

以下是一个简单的Python代码示例,用来模拟烟花效果:

import pygame
import random

# 设置屏幕大小和帧率
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# 烟花粒子类
class Particle:
    def __init__(self, start_x, start_y, direction_x, direction_y, size, speed):
        self.x = start_x
        self.y = start_y
        self.direction_x = direction_x
        self.direction_y = direction_y
        self.size = size
        self.speed = speed

    def move(self):
        # 根据速度和方向移动粒子
        self.x += self.direction_x * self.speed
        self.y += self.direction_y * self.speed

    def draw(self, screen):
        # 在屏幕上画出粒子
        pygame.draw.circle(screen, WHITE, (int(self.x), int(self.y)), self.size)

# 初始化Pygame和屏幕
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Firework Simulation")
clock = pygame.time.Clock()

# 创建烟花粒子集合
particles = []
for _ in range(100):
    particles.append(Particle(random.randint(0, SCREEN_WIDTH), SCREEN_HEIGHT, random.uniform(-1, 1), random.uniform(-1, 0), 5, random.uniform(1, 3)))

# 主循环
running = True
while running:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # 当鼠标点击时,创建一个新的烟花粒子并添加到集合中
            particles.append(Particle(event.pos[0], event.pos[1], random.uniform(-1, 1), random.uniform(-1, 0), 5, random.uniform(1, 3)))
            
    screen.fill(BLACK)  # 清空屏幕颜色
    for particle in particles:
        particle.move()  # 移动粒子
        particle.draw(screen)  # 在屏幕上画出粒子
    pygame.display.flip()  # 更新屏幕显示内容