python跨年烟花倒计时代码
时间: 2024-12-11 17:13:29 浏览: 82
Python跨年烟花代码
以下是一个使用Python和Pygame库实现的跨年烟花倒计时代码示例:
```python
import pygame
import random
import time
# 初始化Pygame
pygame.init()
# 设置屏幕尺寸
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义烟花类
class Firework:
def __init__(self):
self.x = random.randint(0, width)
self.y = height
self.speed = random.uniform(3, 7)
self.color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
self.exploded = False
self.particles = []
def update(self):
if not self.exploded:
self.y -= self.speed
if self.y <= random.randint(50, 300):
self.explode()
else:
for particle in self.particles:
particle[0][1] += particle[1]
particle[0][0] += random.uniform(-1, 1)
particle[2] -= 1
if particle[2] <= 0:
self.particles.remove(particle)
def explode(self):
self.exploded = True
for _ in range(100):
angle = random.uniform(0, 2 * 3.14159)
speed = random.uniform(1, 5)
self.particles.append([(self.x, self.y), (speed * math.cos(angle), speed * math.sin(angle)), random.randint(30, 100)])
def draw(self, surface):
if not self.exploded:
pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), 3)
else:
for particle in self.particles:
pygame.draw.circle(surface, self.color, (int(particle[0][0]), int(particle[0][1])), 2)
# 主程序循环
def main():
clock = pygame.time.Clock()
fireworks = []
countdown = 10 # 倒计时时间(秒)
start_time = time.time()
while True:
current_time = time.time()
elapsed = current_time - start_time
remaining = max(0, countdown - int(elapsed))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
screen.fill(BLACK)
if elapsed > countdown:
# 显示"新年快乐"
font = pygame.font.Font(None, 74)
text = font.render("新年快乐!", True, WHITE)
screen.blit(text, (width//2 - text.get_width()//2, height//2 - text.get_height()//2))
else:
# 生成新的烟花
if random.randint(0, 100) < 2:
fireworks.append(Firework())
# 更新并绘制烟花
for firework in fireworks:
firework.update()
firework.draw(screen)
# 显示倒计时
font = pygame.font.Font(None, 50)
text = font.render(f"倒计时: {remaining}", True, WHITE)
screen.blit(text, (10, 10))
pygame.display.flip()
clock.tick(60)
if __name__ == "__main__":
main()
```
这段代码实现了一个简单的烟花倒计时程序:
1. 使用Pygame库来创建图形界面和处理图形绘制。
2. 定义了Firework类来模拟烟花,包括上升、爆炸和粒子扩散的效果。
3. 在主循环中,每帧都会更新烟花状态,绘制烟花和倒计时。
4. 当倒计时结束时,会显示"新年快乐!"的文字。
要运行这段代码,你需要先安装Pygame库。可以使用以下命令安装:
```
pip install pygame
```
运行后,你会看到一个黑色背景的窗口,烟花会不断绽放,同时显示倒计时。当倒计时结束时,会显示"新年快乐!"的文字。
阅读全文