python跨年倒烟花代码
时间: 2024-12-31 21:45:48 浏览: 11
### Python 跨年倒计时烟花效果代码示例
为了实现跨年倒计时并配合烟花效果,可以利用 `pygame` 和 `pyglet` 这样的图形库来创建动画效果。下面提供了一个基于 `pygame` 的简单例子:
```python
import pygame
import random
import sys
from datetime import datetime, timedelta
# 初始化 Pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
# 倒计时时钟设置
start_time = datetime.now() + timedelta(seconds=10) # 设定从当前时间起十秒后的时刻作为结束点
font = pygame.font.Font(None, 74)
def draw_text(text):
text_surface = font.render(str(text), True, white)
return text_surface, text_surface.get_rect(center=(screen_width/2, screen_height/2))
class Firework:
def __init__(self):
self.x = random.randint(50, screen_width - 50)
self.y = screen_height
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.speed = random.uniform(-5, 5)
self.active = False
def update(self):
if not self.active and random.random() < 0.05: # 控制发射频率
self.active = True
if self.active:
self.y -= abs(self.speed)*10
if self.y <= 0 or random.random() < 0.01:
self.explode()
def explode(self):
global particles
for _ in range(100): # 创建爆炸粒子
dx = random.uniform(-3, 3)
dy = random.uniform(-3, 3)
particle_color = tuple([min(c + random.randint(-50, 50), 255) for c in self.color])
particles.append(Particle(self.x, self.y, dx, dy, particle_color))
self.reset()
def reset(self):
self.__init__() # 重置火箭位置
class Particle(Firework):
def __init__(self, x, y, speed_x, speed_y, color):
super().__init__()
self.x = x
self.y = y
self.speed_x = speed_x
self.speed_y = speed_y
self.color = color
self.life = 10
def update(self):
self.x += self.speed_x * 5
self.y += self.speed_y * 5
self.life -= 1
if self.life <= 0:
particles.remove(self)
fireworks = []
particles = []
for i in range(10):
fireworks.append(Firework())
while start_time > datetime.now():
screen.fill(black)
remaining_seconds = int((start_time - datetime.now()).total_seconds())
countdown_text = f"{remaining_seconds}"
txt_surf, txt_rect = draw_text(countdown_text)
screen.blit(txt_surf, txt_rect)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
for firework in fireworks:
firework.update()
if firework.active:
pygame.draw.circle(screen, firework.color, (int(firework.x), int(firework.y)), 5)
for particle in list(particles):
particle.update()
pygame.draw.rect(screen, particle.color, (particle.x, particle.y, 2, 2))
pygame.display.flip()
pygame.time.delay(30)
# 显示新年快乐文字
new_year_wish = "Happy New Year!"
wish_surf, wish_rect = draw_text(new_year_wish)
screen.blit(wish_surf, wish_rect)
pygame.display.flip()
pygame.time.wait(3000)
pygame.quit()
```
此程序实现了基本的倒计时和烟花绽放的效果,在指定的时间内会随机触发烟花上升并在顶部爆裂成多个彩色的小颗粒散开。
阅读全文