#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pygame
import random
import time # 导入time模块
# 设置窗口尺寸
WIDTH, HEIGHT = 800, 600
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# 初始化pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Fireworks")
# 定义Firework(烟花)类
class Firework:
def __init__(self):
self.x = random.randint(50, WIDTH - 50)
self.y = HEIGHT
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.speed = random.randint(5, 12)
def move(self):
self.y -= self.speed
def explode(self, sparks):
for _ in range(50):
spark = Spark(self.x, self.y, self.color)
sparks.append(spark)
def draw(self, screen):
pygame.draw.circle(screen, self.color, (self.x, self.y), 3)
# 定义Spark(火花)类
class Spark:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.speedx = random.uniform(-1, 1) * 8
self.speedy = random.uniform(-1, 1) * 8
self.age = 0
def move(self):
self.x += self.speedx
self.y += self.speedy
self.speedy += 0.2
self.age += 1
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 2)
# 主循环
clock = pygame.time.Clock()
fireworks = []
sparks = []
running = True
start_time = pygame.time.get_ticks() # 获取程序开始的时间
total_run_time = 60 * 3 # 设置程序总运行时间为3分钟
current_run_time = 0 # 当前程序运行时间
while current_run_time < total_run_time: # 循环条件改为判断当前运行时间是否小于总运行时间
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(BLACK)
# 创建新烟花
if random.random() < 0.02:
fireworks.append(Firework())
# 更新和绘制烟花
for firework in fireworks:
firework.move()
firework.draw(screen)
if firework.y < random.randint(50, HEIGHT // 2):
firework.explode(sparks)
fireworks.remove(firework)
# 移动和绘制火花
for spark in sparks:
spark.move()
spark.draw(screen)
if spark.age > 100:
sparks.remove(spark)
pygame.display.flip()
clock.tick(60)
# 更新程序当前运行时间
current_run_time = (pygame.time.get_ticks() - start_time) / 1000 # 转换为秒
time.sleep(0.1) # 添加时间延迟,让程序暂停0.1秒
pygame.quit()