python跨年倒计时烟花代码
时间: 2024-12-31 10:36:54 浏览: 12
### Python 跨年倒计时与烟花效果代码示例
为了实现带有烟花效果的跨年倒计时,可以结合 `pygame` 库来处理图形界面以及动画效果。以下是完整的代码示例:
#### 导入必要的模块
```python
import pygame
import random
import time
from datetime import timedelta, datetime
```
#### 初始化 Pygame 和设置屏幕参数
```python
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('New Year Countdown with Fireworks')
clock = pygame.time.Clock()
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
font = pygame.font.Font(None, 74)
countdown_time = datetime.strptime("2024-01-01 00:00:00", "%Y-%m-%d %H:%M:%S") # 设置目标时间为2024年元旦零点
current_time = datetime.now() # 获取当前时间
time_left = countdown_time - current_time # 计算剩余时间差
```
#### 创建烟花类
```python
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.x = x
self.y = y
self.size = random.randint(4, 8)
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.velocity_x = random.uniform(-3, 3)
self.velocity_y = random.uniform(-7, -5)
def update(self):
self.x += self.velocity_x
self.y += self.velocity_y
self.velocity_y += 0.1
if self.y >= screen_height or self.size <= 0:
particles.remove(self)
self.size *= 0.95
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), int(self.size))
particles = []
def create_firework():
for _ in range(random.randint(50, 100)):
particle = Particle(random.randint(0, screen_width), screen_height)
particles.append(particle)
```
#### 主循环逻辑
```python
running = True
while running and time_left.total_seconds() > 0:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
now = datetime.now()
time_left = countdown_time - now
formatted_time = str(timedelta(seconds=int(time_left.total_seconds())))
text = font.render(formatted_time, True, white)
text_rect = text.get_rect(center=(screen_width/2, screen_height/2))
screen.fill(black)
screen.blit(text, text_rect)
if random.random() < 0.05: # 控制烟花触发频率
create_firework()
for p in list(particles): # 使用list转换防止迭代过程中修改列表引发错误
p.update()
p.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
print("Happy New Year!")
```
此段代码实现了从现在到明年一月一号凌晨之间的倒计时显示,并且每隔一段时间会在屏幕上随机位置生成一组烟花爆炸的效果[^1]。
阅读全文