python语言:烟花效果实现
生活随笔
收集整理的這篇文章主要介紹了
python语言:烟花效果实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、用tkinter實現一個實現煙花的程序
import tkinter as tk from PIL import Image, ImageTk from time import time, sleep from random import choice, uniform, randint from math import sin, cos, radians colors = ['red', 'blue', 'yellow', 'white', 'green', 'orange', 'purple', 'seagreen', 'indigo', 'cornflowerblue'] class fireworks:def __init__(self, cv, idx, total, explosion_speed, x=0., y=0., vx=0., vy=0., size=2., color='red', lifespan=2, **kwargs):self.id = idx# 煙花綻放 x 軸self.x = x# 煙花綻放 x 軸self.y = yself.initial_speed = explosion_speed# 外放 x 軸速度self.vx = vx# 外放 y 軸速度self.vy = vy# 綻放的粒子數self.total = total# 已停留時間self.age = 0# 顏色self.color = color# 畫布self.cv = cvself.cid = self.cv.create_oval(x - size, y - size, x + size, y + size,fill=self.color)self.lifespan = lifespan# 更新數據def update(self, dt):self.age += dt# 粒子膨脹if self.alive() and self.expand():move_x = cos(radians(self.id * 360 / self.total)) * self.initial_speedmove_y = sin(radians(self.id * 360 / self.total)) * self.initial_speedself.cv.move(self.cid, move_x, move_y)self.vx = move_x / (float(dt) * 1000)# 膨脹到最大下落elif self.alive():move_x = cos(radians(self.id * 360 / self.total))self.cv.move(self.cid, self.vx + move_x, self.vy + 0.5 * dt)self.vy += 0.5 * dt# 過期移除elif self.cid is not None:cv.delete(self.cid)self.cid = None# 定義膨脹效果的時間幀def expand(self):return self.age <= 1.5# 檢查粒子是否仍在生命周期內def alive(self):return self.age <= self.lifespandef ignite(cv):t = time()# 煙花列表explode_points = []wait_time = randint(10, 100)# 爆炸的個數numb_explode = randint(6, 10)for point in range(numb_explode):# 爆炸粒子列表objects = []# 爆炸 x 軸x_cordi = randint(50, 550)# 爆炸 y 軸y_cordi = randint(50, 150)speed = uniform(0.5, 1.5)size = uniform(0.5, 3)color = choice(colors)# 爆炸的綻放速度explosion_speed = uniform(0.2, 1)# 爆炸的粒子數半徑total_particles = randint(10, 50)for i in range(1, total_particles):r = fireworks(cv, idx=i, total=total_particles, explosion_speed=explosion_speed, x=x_cordi, y=y_cordi,vx=speed, vy=speed, color=color, size=size,lifespan=uniform(0.6, 1.75))# 添加進粒子列表里objects.append(r)# 把粒子列表添加到煙花列表explode_points.append(objects)total_time = .0# 在 1.8 秒時間幀內保持更新while total_time < 1.8:# 讓畫面暫停 0.01ssleep(0.01)# 刷新時間tnew = time()t, dt = tnew, tnew - t# 遍歷煙花列表for point in explode_points:# 遍歷煙花里的粒子列表for item in point:# 更新時間item.update(dt)# 刷新頁面cv.update()total_time += dtroot.after(wait_time, ignite, cv)if __name__ == "__main__":root = tk.Tk()# 繪制一個畫布cv = tk.Canvas(root, height=400, width=600)# 背景圖image = Image.open("D001.jpg")photo = ImageTk.PhotoImage(image)# 在畫板上繪制一張圖片cv.create_image(0, 0, image=photo, anchor='nw')cv.pack()root.protocol(colors)root.after(100, ignite, cv)# 生成窗口root.mainloop()二、實現效果?
總結
以上是生活随笔為你收集整理的python语言:烟花效果实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python图像编程:实现弹球游戏
- 下一篇: 语音识别:时间序列的Smith–Wate