用python一起來看流星雨


 

  源代碼如下(遇上篇煙花代碼幾乎一樣,參數值稍微不一樣):

# -*- coding: utf-8 -*-
# Nola

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


# # 初始化tkinter 創建根部件 必須在創建其他部件之前創建 且只有一個
# root = tk.Tk()
# # Label部件
# w = tk.Label(root, text="Hello Tkinter!")
# # pack告訴tkinter調整窗口大小適應所用的小部件
# w.pack()
# root.mainloop()
# 模擬重力
GRAVITY = 0.05
colors = ['red', 'blue', 'pink', 'white', 'green', 'orange', 'purple', 'seagreen', 'indigo', 'cornflowerblue']

class Part(object):
    """
    particles 類
    粒子在空中隨機生成,變成一個圈,下墜,消失
    """
    def __init__(self, cv, idx, total, explosion_speed, x=0., y=0., vx=0., vy=0., size=2., color='red', lifespan=2, **kwargs):
        """
        :param cv: 畫布
        :param idx: 粒子的id
        :param total: 總數
        :param explosion_speed: 粒子初始速度
        :param x: 粒子的橫坐標
        :param y: 粒子的縱坐標
        :param vx: 粒子在x軸上的變化速度
        :param vy: 粒子在y軸上的變化速度
        :param size: 大小
        :param color: 顏色
        :param lifespan: 最高存在時長
        :param kwargs:
        """
        self.id = idx
        self.x = x
        self.y = y
        self.initial_speed = explosion_speed
        self.vx = vx
        self.vy = vy
        self.total = total
        self.age = 0
        self.color = color
        self.cv = cv
        self.cid = self.cv.create_oval(
            x - size, y - size, x + size,
            y + size, fill=self.color
        )
        self.lifespan = lifespan

    def update(self, dt):
        """
        粒子運動函數,膨脹
        :param dt:
        :return:
        """
        self.age += dt
        if self.alive() and self.expand():
            move_x = cos(radians(self.id*360 / self.total)) * self.initial_speed
            move_y = sin(radians(self.id*360 / self.total)) * self.initial_speed
            # self.vy = move_y / (float(dt)*1000)
            self.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 + GRAVITY*dt)
            self.vy += GRAVITY * dt

        # 移除超過最高時長的粒子
        elif self.cid is not None:
            self.cv.delete(self.cid)
            self.cid = None


    def alive(self):
        """
        檢查粒子是否在最高存在時長內
        :return: bool
        """
        return self.age <= 1.2

    def expand(self):
        """
        定義膨脹效果時間幀
        :return: bool
        """
        return self.age <= self.lifespan


def simulate(cv):
    """
    循環調用保持不停
    :param cv: 畫布
    :return:
    """
    numb_explode = randint(6, 10)
    wait_time = randint(10, 100)
    explode_points = []
    t = time()
    # 為所有模擬煙花綻放的全部粒子創建一個列表
    for point in range(numb_explode):
        objects = []
        x_cordi = randint(50, 550)
        y_cordi = randint(50, 150)
        speed = uniform(0.5, 1.5)
        size = uniform(1, 3)  # 隨機生成一個0.5-3之間的實數
        color = choice(colors)
        explosion_speed = uniform(0.2, 1)
        total_particals = randint(5, 50)
        for i in range(1, total_particals):
            r = Part(cv, idx=1, total=total_particals, 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)

    # 設置每個粒子沒0.01秒更新狀態  生命周期1.8秒  1.6秒存活(1.2秒綻放,0.4秒墜落,0.2秒移除)
    total_time = .0
    # 在1.8秒時間幀內保持更新
    while total_time < 1.8:
        sleep(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 += dt
    # 循環調用
    root.after(wait_time, simulate, cv)

def close(*ignore):
    """
    退出程序,關閉窗口
    :param ignore:
    :return:
    """
    global root
    root.quit()

if __name__ == '__main__':
    # 初始化tkinter 創建根部件
    root = tk.Tk()

    cv = tk.Canvas(root, height=400, width=600)
    # 繪制一個黑色背景
    cv.create_rectangle(0, 0, 600, 600, fill='black')
    # 使用背景圖片
    # image = Image.open('./image.png')
    # photo = ImageTk.PhotoImage(image)
    # cv.create_image(0, 0, image=photo, anchor='nw')
    cv.pack()

    root.protocol('WM_DELETE_WINDOW', close)
    # 1秒后開始條約simulate()
    root.after(100, simulate, cv)
    root.mainloop()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM