以下是一個簡單的Python煙花代碼示例:
import pygame
import random
# 初始化pygame
pygame.init()
# 設(shè)置屏幕尺寸
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
# 創(chuàng)建煙花粒子組
particles = pygame.sprite.Group()
# 游戲循環(huán)
running = True
while running:
# 處理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 創(chuàng)建新煙花
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()
運行以上代碼后,會打開一個窗口,窗口中會隨機(jī)產(chǎn)生煙花粒子,形成煙花效果。可以根據(jù)需要自行調(diào)整煙花粒子的屬性,如大小、顏色、速度等。