python炫酷煙花表白的源代碼分享

天天敲代碼的朋友,有沒有想過代碼也可以變得很酷炫又浪漫?今天就教大家用Python模擬出綻放的煙花,工作之余也可以隨時(shí)讓程序?yàn)樽约悍乓粓?chǎng)煙花秀。

在白銀區(qū)等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站 網(wǎng)站設(shè)計(jì)制作按需網(wǎng)站設(shè)計(jì),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站設(shè)計(jì),全網(wǎng)整合營(yíng)銷推廣,外貿(mào)網(wǎng)站建設(shè),白銀區(qū)網(wǎng)站建設(shè)費(fèi)用合理。

python炫酷煙花表白的源代碼分享

python炫酷煙花表白源代碼

這個(gè)有趣的小項(xiàng)目并不復(fù)雜,只需一點(diǎn)可視化技巧,100余行Python代碼和程序庫(kù)Tkinter,最后我們就能達(dá)到下面這個(gè)效果:

python炫酷煙花表白的源代碼分享

學(xué)完本教程后,你也能做出這樣的煙花秀。

整體概念梳理

我們的整個(gè)理念比較簡(jiǎn)單。

python炫酷煙花表白的源代碼分享

如上圖示,我們這里通過讓畫面上一個(gè)粒子分裂為X數(shù)量的粒子來模擬爆炸效果。粒子會(huì)發(fā)生“膨脹”,意思是它們會(huì)以恒速移動(dòng)且相互之間的角度相等。這樣就能讓我們以一個(gè)向外膨脹的圓圈形式模擬出煙花綻放的畫面。經(jīng)過一定時(shí)間后,粒子會(huì)進(jìn)入“自由落體”階段,也就是由于重力因素它們開始?jí)嬄涞降孛?,仿若綻放后熄滅的煙花。

(推薦學(xué)習(xí):編程學(xué)習(xí)課程)

基本知識(shí):用Python和Tkinter設(shè)計(jì)煙花

這里不再一股腦把數(shù)學(xué)知識(shí)全丟出來,我們邊寫代碼邊說理論。首先,確保你安裝和導(dǎo)入了Tkinter,它是Python的標(biāo)準(zhǔn) GUI 庫(kù),廣泛應(yīng)用于各種各樣的項(xiàng)目和程序開發(fā),在Python中使用 Tkinter 可以快速的創(chuàng)建 GUI 應(yīng)用程序。

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之外,為了能讓界面有漂亮的背景,我們也導(dǎo)入PIL用于圖像處理,以及導(dǎo)入其它一些包,比如time,random和math。它們能讓我們更容易的控制煙花粒子的運(yùn)動(dòng)軌跡。

Tkinter應(yīng)用的基本設(shè)置如下:

root = tk.Tk()

為了能初始化Tkinter,我們必須創(chuàng)建一個(gè)Tk()根部件(root widget),它是一個(gè)窗口,帶有標(biāo)題欄和由窗口管理器提供的其它裝飾物。該根部件必須在我們創(chuàng)建其它小部件之前就創(chuàng)建完畢,而且只能有一個(gè)根部件。

w = tk.Label(root, text="Hello Tkinter!")

這一行代碼包含了Label部件。該Label調(diào)用中的第一個(gè)參數(shù)就是父窗口的名字,即我們這里用的“根”。關(guān)鍵字參數(shù)“text”指明顯示的文字內(nèi)容。你也可以調(diào)用其它小部件:Button,Canvas等等。

w.pack()
root.mainloop()

接下來的這兩行代碼很重要。這里的打包方法是告訴Tkinter調(diào)整窗口大小以適應(yīng)所用的小部件。窗口直到我們進(jìn)入Tkinter事件循環(huán),被root.mainloop()調(diào)用時(shí)才會(huì)出現(xiàn)。在我們關(guān)閉窗口前,腳本會(huì)一直在停留在事件循環(huán)。

將煙花綻放轉(zhuǎn)譯成代碼

現(xiàn)在我們?cè)O(shè)計(jì)一個(gè)對(duì)象,表示煙花事件中的每個(gè)粒子。每個(gè)粒子都會(huì)有一些重要的屬性,支配了它的外觀和移動(dòng)狀況:大小,顏色,位置,速度等等。

'''
particles 類
粒子在空中隨機(jī)生成隨機(jī),變成一個(gè)圈、下墜、消失
屬性:
    - id: 粒子的id
    - x, y: 粒子的坐標(biāo)
    - vx, vy: 在坐標(biāo)的變化速度
    - total: 總數(shù)
    - age: 粒子存在的時(shí)長(zhǎng)
    - color: 顏色
    - cv: 畫布
    - lifespan: 最高存在時(shí)長(zhǎng)
'''
class part:
    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
        self.x = x
        self.y = y
        self.initial_speed = explosion_speed
        self.vx = vx
        self.vy = vy
        self.total = total
        self.age = 0self.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

如果我們回過頭想想最開始的想法,就會(huì)意識(shí)到必須確保每個(gè)煙花綻放的所有粒子必須經(jīng)過3個(gè)不同的階段,即“膨脹”“墜落”和“消失”。 所以我們向粒子類中再添加一些運(yùn)動(dòng)函數(shù),如下所示:

def update(self, 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.vx = move_x/(float(dt)*1000)
        self.vy = move_y/(float(dt)*1000)
        self.cv.move(self.cid, move_x, move_y)
    # 以自由落體墜落
    elif self.alive():
        move_x = cos(radians(self.id*360/self.total))
        # we technically don't need to update x, y because move will do the job
        self.cv.move(self.cid, self.vx + move_x, self.vy+GRAVITY*dt)
        self.vy += GRAVITY*dt
    # 如果粒子的生命周期已過,就將其移除
    elif self.cid is not None:
        cv.delete(self.cid)
        self.cid = None

當(dāng)然,這也意味著我們必須定義每個(gè)粒子綻放多久、墜落多久。這部分需要我們多嘗試一些參數(shù),才能達(dá)到最佳視覺效果。

# 定義膨脹效果的時(shí)間幀
def expand (self):
    return self.age <= 1.2
# 檢查粒子是否仍在生命周期內(nèi)
def alive(self):
    return self.age <= self.lifespan

使用Tkinter模擬

現(xiàn)在我們將粒子的移動(dòng)概念化,不過很明顯,一個(gè)煙花不能只有一個(gè)粒子,一場(chǎng)煙花秀也不能只有一個(gè)煙花。我們下一步就是讓Python和Tkinter以我們可控的方式向天上連續(xù)“發(fā)射”粒子。

到了這里,我們需要從操作一個(gè)粒子升級(jí)為在屏幕上展現(xiàn)多個(gè)煙花及每個(gè)煙花中的多個(gè)粒子。

我們的解決思路如下:創(chuàng)建一列列表,每個(gè)子列表是一個(gè)煙花,其包含一列粒子。每個(gè)列表中的例子有相同的x,y坐標(biāo)、大小、顏色、初始速度。

numb_explode = randint(6,10)
# 為所有模擬煙花綻放的全部粒子創(chuàng)建一列列表
for point in range(numb_explode):
    objects = []
    x_cordi = randint(50,550)
    y_cordi = randint(50, 150)       
    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 = part(cv, idx = i, total = total_particles, explosion_speed = explosion_speed, x = x_cordi, y = y_cordi, 
        color=color, size = size, lifespan = uniform(0.6,1.75))
        objects.append(r)
explode_points.append(objects)

我們下一步就是確保定期更新粒子的屬性。這里我們?cè)O(shè)置讓粒子每0.01秒更新它們的狀態(tài),在1.8秒之后停止更新(這意味著每個(gè)粒子的存在時(shí)間為1.6秒,其中1.2秒為“綻放”狀態(tài),0.4秒為“墜落”狀態(tài),0.2秒處于Tkinter將其完全移除前的邊緣狀態(tài))。

total_time = .0
# 在1.8秒時(shí)間幀內(nèi)保持更新
while total_time < 1.8:
    sleep(0.01)
    tnew = time()
    t, dt = tnew, tnew - t
    for point in explode_points:
        for part in point:
            part.update(dt)
    cv.update()
    total_time += dt

現(xiàn)在,我們只需將最后兩個(gè)gist合并為一個(gè)能被Tkinter調(diào)用的函數(shù),就叫它simulate()吧。該函數(shù)會(huì)展示所有的數(shù)據(jù)項(xiàng),并根據(jù)我們?cè)O(shè)置的時(shí)間更新每個(gè)數(shù)據(jù)項(xiàng)的屬性。在我們的主代碼中,我們會(huì)用一個(gè)alarm處理模塊after()調(diào)用此函數(shù),after()會(huì)等待一定的時(shí)間,然后再調(diào)用函數(shù)。

我們這里設(shè)置讓Tkinter等待100個(gè)單位(1秒鐘)再調(diào)取simulate。

if __name__ == '__main__':
    root = tk.Tk()
    cv = tk.Canvas(root, height=600, width=600)
    # 繪制一個(gè)黑色背景
    cv.create_rectangle(0, 0, 600, 600, fill="black")
    cv.pack()
    root.protocol("WM_DELETE_WINDOW", close)
    # 在1秒后才開始調(diào)用stimulate()
    root.after(100, simulate, cv)
    root.mainloop()

好了,這樣我們就用Python代碼放了一場(chǎng)煙花秀:

python炫酷煙花表白的源代碼分享

本文只一個(gè)簡(jiǎn)單版本,等進(jìn)一步熟悉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
# 模擬重力
GRAVITY = 0.05
# 顏色選項(xiàng)(隨機(jī)或者按順序)
colors = ['red', 'blue', 'yellow', 'white', 'green', 'orange', 'purple', 'seagreen', 'indigo', 'cornflowerblue']
'''
particles 類
粒子在空中隨機(jī)生成隨機(jī),變成一個(gè)圈、下墜、消失
屬性:
    - id: 粒子的id
    - x, y: 粒子的坐標(biāo)
    - vx, vy: 在坐標(biāo)的變化速度
    - total: 總數(shù)
    - age: 粒子存在的時(shí)長(zhǎng)
    - color: 顏色
    - cv: 畫布
    - lifespan: 最高存在時(shí)長(zhǎng)
'''
class Particle:
    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
        self.x = x
        self.y = y
        self.initial_speed = explosion_speed
        self.vx = vx
        self.vy = vy
        self.total = total
        self.age = 0self.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):
        self.age += dt
        # 粒子范圍擴(kuò)大
        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.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))
            # we technically don't need to update x, y because move will do the job
            self.cv.move(self.cid, self.vx + move_x, self.vy + GRAVITY * dt)
            self.vy += GRAVITY * dt
        # 移除超過最高時(shí)長(zhǎng)的粒子
        elif self.cid is not None:
            cv.delete(self.cid)
            self.cid = None
    # 擴(kuò)大的時(shí)間
    def expand (self):
        return self.age <= 1.2
    # 粒子是否在最高存在時(shí)長(zhǎng)內(nèi)
    def alive(self):
        return self.age <= self.lifespan
'''
循環(huán)調(diào)用保持不停
'''
def simulate(cv):
    t = time()
    explode_points = []
    wait_time = randint(10, 100)
    numb_explode = randint(6, 10)
    # 創(chuàng)建一個(gè)所有粒子同時(shí)擴(kuò)大的二維列表
    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(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 = Particle(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.8s內(nèi)一直擴(kuò)大
    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
    # 循環(huán)調(diào)用
    root.after(wait_time, simulate, cv)
def close(*ignore):
    """退出程序、關(guān)閉窗口"""
    global root
    root.quit()
if __name__ == '__main__':
    root = tk.Tk()
    cv = tk.Canvas(root, height=400, width=600)
    # 選一個(gè)好看的背景會(huì)讓效果更驚艷!
    image = Image.open("./image.jpg")
    photo = ImageTk.PhotoImage(image)
    cv.create_image(0, 0, image=photo, anchor='nw')
    cv.pack()
    root.protocol("WM_DELETE_WINDOW", close)
    root.after(100, simulate, cv)
    root.mainloop()

以上就是python炫酷煙花表白的源代碼分享的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注創(chuàng)新互聯(lián)其它相關(guān)文章!

當(dāng)前標(biāo)題:python炫酷煙花表白的源代碼分享
URL標(biāo)題:http://muchs.cn/article18/johddp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站微信公眾號(hào)、外貿(mào)網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站手機(jī)網(wǎng)站建設(shè)、網(wǎng)站內(nèi)鏈

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁(yè)設(shè)計(jì)公司