# 初始化
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('烟花效果')
# 焰火发射
particles = [] # 焰火粒子
def firework(x, y):
num_particles = 100 # 每次发射的粒子数量
for _ in range(num_particles):
direction = random.uniform(0, 2 * math.pi) # 随机方向
speed = random.uniform(2, 6) # 随机速度
particles.append({
'x': x,
'y': y,
'vx': math.cos(direction) * speed,
'vy': math.sin(direction) * speed,
'color': colorlib.randcolorTuple(),
'size': random.uniform(1, 4), # 粒子的初始大小
'life': random.uniform(100, 200) # 粒子的生命周期
})
# 更新屏幕
def update_screen():
global particles
screen.fill((0, 0, 0)) # 填充黑色背景
for particle in particles[:]:
particle['x'] += particle['vx']
particle['y'] += particle['vy']
particle['life'] -= 5
coordinate = particle['x'], particle['y']
radius = particle['size'] * particle['life'] / 100.0
pygame.draw.circle(screen, particle['color'], coordinate, radius)
if particle['life'] <= 0 or particle['y'] > screen_height:
particles.remove(particle)
# 主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# 每隔一段时间发射一次烟花
if random.randint(0, 2)==0: # 发射随机时间
firework(random.randint(0, screen_width), random.randint(0, screen_height//3*2))
update_screen()
pygame.display.flip() # 更新整个屏幕
pygame.time.Clock().tick(60) # 控制帧率
pygame 烟花效果
完整代码
import pygame
import random
import math
import colorlib
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置标题
pygame.display.set_caption('烟花效果')
# 焰火粒子
particles = []
# 焰火发射
def firework(x, y):
num_particles = 100 # 每次发射的粒子数量
for _ in range(num_particles):
direction = random.uniform(0, 2 * math.pi) # 随机方向
speed = random.uniform(2, 6) # 随机速度
particles.append({
'x': x,
'y': y,
'vx': math.cos(direction) * speed,
'vy': math.sin(direction) * speed,
'color': colorlib.randcolorTuple(),
'size': random.uniform(1, 4), # 粒子的初始大小
'life': random.uniform(100, 200) # 粒子的生命周期
})
# 更新屏幕
def update_screen():
global particles
screen.fill((0, 0, 0)) # 填充黑色背景
for particle in particles[:]:
particle['x'] += particle['vx']
particle['y'] += particle['vy']
particle['life'] -= 5
coordinate = particle['x'], particle['y']
radius = particle['size'] * particle['life'] / 100.0
pygame.draw.circle(screen, particle['color'], coordinate, radius)
if particle['life'] <= 0 or particle['y'] > screen_height:
particles.remove(particle)
# 主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# 每隔一段时间发射一次烟花
if random.randint(0, 2)==0: # 发射随机时间
firework(random.randint(0, screen_width), random.randint(0, screen_height//3*2))
update_screen()
pygame.display.flip() # 更新整个屏幕
pygame.time.Clock().tick(60) # 控制帧率