用PYTHON写一个跨年烟花代码
时间: 2023-12-31 12:24:10 浏览: 140
以下是一个用Python编写的跨年烟花代码的例子:
```python
import tkinter as tk
from PIL import Image, ImageTk
import time
import random
import math
# 创建窗口
window = tk.Tk()
window.title("跨年烟花")
window.geometry("800x600")
# 加载烟花图片
firework_image = Image.open("firework.gif")
firework_frames = []
try:
while True:
firework_frames.append(ImageTk.PhotoImage(firework_image.copy()))
firework_image.seek(len(firework_frames)) # 跳转到下一帧
except EOFError:
pass
# 创建画布
canvas = tk.Canvas(window, width=800, height=600)
canvas.pack()
# 烟花数量
num_fireworks = 10
# 烟花类
class Firework:
def __init__(self, x, y):
self.x = x
self.y = y
self.frame_index = 0
self.exploded = False
self.explosion_radius = random.randint(50, 100)
self.explosion_color = random.choice(["red", "green", "blue", "yellow", "purple", "orange"])
self.explosion_duration = random.uniform(0.5, 1.5)
self.explosion_start_time = time.time()
def draw(self):
if not self.exploded:
canvas.create_image(self.x, self.y, image=firework_frames[self.frame_index])
self.frame_index = (self.frame_index + 1) % len(firework_frames)
else:
elapsed_time = time.time() - self.explosion_start_time
if elapsed_time < self.explosion_duration:
explosion_radius = self.explosion_radius * (elapsed_time / self.explosion_duration)
explosion_alpha = int(255 * (1 - elapsed_time / self.explosion_duration))
canvas.create_oval(self.x - explosion_radius, self.y - explosion_radius,
self.x + explosion_radius, self.y + explosion_radius,
fill=self.explosion_color, outline="", tags="explosion",
alpha=explosion_alpha)
else:
canvas.delete("explosion")
def explode(self):
self.exploded = True
# 创建烟花列表
fireworks = []
for _ in range(num_fireworks):
x = random.randint(100, 700)
y = random.randint(100, 500)
fireworks.append(Firework(x, y))
# 绘制烟花
def draw_fireworks():
canvas.delete("all")
for firework in fireworks:
firework.draw()
window.after(50, draw_fireworks)
# 爆炸烟花
def explode_fireworks():
for firework in fireworks:
firework.explode()
# 开始绘制和爆炸烟花
draw_fireworks()
window.after(3000, explode_fireworks)
# 运行窗口
window.mainloop()
```
阅读全文