温馨提示×

python烟花代码怎么编写

小亿
117
2023-12-21 20:22:28
栏目: 编程语言

以下是一个简单的Python烟花代码示例:

import pygame
import random

# 初始化pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Fireworks")

# 定义烟花粒子类
class Particle(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((5, 5))
        self.image.fill((255, 255, 255))
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.gravity = 0.2
        self.x_velocity = random.uniform(-1, 1)
        self.y_velocity = random.uniform(-5, -1)

    def update(self):
        self.x_velocity *= 0.99
        self.y_velocity += self.gravity
        self.rect.x += self.x_velocity
        self.rect.y += self.y_velocity

# 创建烟花粒子组
particles = pygame.sprite.Group()

# 游戏循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 创建新烟花
    if random.random() < 0.01:
        x = random.randint(0, screen_width)
        y = screen_height
        particle = Particle(x, y)
        particles.add(particle)

    # 更新粒子位置
    particles.update()

    # 清空屏幕
    screen.fill((0, 0, 0))

    # 绘制粒子
    for particle in particles:
        pygame.draw.rect(screen, (255, 255, 255), particle.rect)

    # 刷新屏幕
    pygame.display.flip()

# 退出游戏
pygame.quit()

运行以上代码后,会打开一个窗口,窗口中会随机产生烟花粒子,形成烟花效果。可以根据需要自行调整烟花粒子的属性,如大小、颜色、速度等。

0