python代码变成手机软件_使用Python代码的程序员也浪漫
如上圖示,我們這里通過(guò)讓畫面上一個(gè)粒子分裂為X數(shù)量的粒子來(lái)模擬爆炸效果。粒子會(huì)發(fā)生“膨脹”,意思是它們會(huì)以恒速移動(dòng)且相互之間的角度相等。這樣就能讓我們以一個(gè)向外膨脹的圓圈形式模擬出煙花綻放的畫面。經(jīng)過(guò)一定時(shí)間后,粒子會(huì)進(jìn)入“自由落體”階段,也就是由于重力因素它們開(kāi)始?jí)嬄涞降孛?#xff0c;仿若綻放后熄滅的煙花。
用Python和Tkinter設(shè)計(jì)煙花:基本知識(shí)
這里不再一股腦把數(shù)學(xué)知識(shí)全丟出來(lái),我們邊寫代碼邊說(shuō)理論。首先,確保你安裝和導(dǎo)入了
Tkinter,它是Python的標(biāo)準(zhǔn) GUI 庫(kù),廣泛應(yīng)用于各種各樣的項(xiàng)目和程序開(kāi)發(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
接下來(lái)的這兩行代碼很重要。這里的打包方法是告訴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)狀況:大小,顏色,位置,速度等等。
'''
Generic class for particles
particles are emitted almost randomly on the sky, forming a round of circle (a star) before falling and getting removed
from canvas
Attributes:
- id: identifier of a particular particle in a star
- x, y: x,y-coordinate of a star (point of explosion)
- vx, vy: speed of particle in x, y coordinate
- total: total number of particle in a star
- age: how long has the particle last on canvas
- color: self-explantory
- cv: canvas
- lifespan: how long a particle will last on canvas
- intial_speed: speed of particle at explosion
'''
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 = 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
如果我們回過(guò)頭想想最開(kāi)始的想法,就會(huì)意識(shí)到必須確保每個(gè)煙花綻放的所有粒子必須經(jīng)過(guò)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:
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
# 如果粒子的生命周期已過(guò),就將其移除
elif self.cid is not None:
cv.delete(self.cid)
self.cid = None
當(dāng)然,這也意味著我們必須定義每個(gè)粒子綻放多久、墜落多久。這部分需要我們多嘗試一些參數(shù),才能達(dá)到最佳視覺(jué)效果。
# 定義膨脹效果的時(shí)間幀
def expand (self):
return self.age <= 1.2
# 檢查粒子是否仍在生命周期內(nèi)
def alive(self):
return self.age <= self.lifespan
使用Tkinter模擬
現(xiàn)在我們將粒子的移動(dòng)概念化,不過(guò)很明顯,一個(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秒后才開(kāi)始調(diào)用stimulate
root.after(100, simulate, cv)
root.mainloop
好了,這樣我們就用Python代碼放了一場(chǎng)煙花秀:
本文只是基本版本,等你進(jìn)一步熟悉Tkinter后,還可以添加更多顏色更漂亮的背景照片,讓代碼為你綻放更美的煙花!
本文全部代碼如下:
'''
FIREWORKS SIMULATION WITH TKINTER
*self-containing code
*to run: simply type python simple.py in your console
*compatible with both Python 2 and Python 3
*Dependencies: tkinter, Pillow (only for background image)
*The design is based on high school physics, with some small twists only for aesthetics purpose
'''
import tkinter as tk
#from tkinter import messagebox
#from tkinter import PhotoImage
from PIL import Image, ImageTk
from time import time, sleep
from random import choice, uniform, randint
from math import sin, cos, radians
# gravity, act as our constant g, you can experiment by changing it
GRAVITY = 0.05
# list of color, can choose randomly or use as a queue (FIFO)
colors = ['red', 'blue', 'yellow', 'white', 'green', 'orange', 'purple', 'seagreen', 'indigo', 'cornflowerblue']
'''
Generic class for particles
particles are emitted almost randomly on the sky, forming a round of circle (a star) before falling and getting removed
from canvas
Attributes:
- id: identifier of a particular particle in a star
- x, y: x,y-coordinate of a star (point of explosion)
- vx, vy: speed of particle in x, y coordinate
- total: total number of particle in a star
- age: how long has the particle last on canvas
- color: self-explantory
- cv: canvas
- lifespan: how long a particle will last on canvas
'''
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 = 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):
self.age += dt
# particle expansions
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)
# falling down in projectile motion
elif self.alive:
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
# remove article if it is over the lifespan
elif self.cid is not None:
cv.delete(self.cid)
self.cid = None
# define time frame for expansion
def expand (self):
return self.age <= 1.2
# check if particle is still alive in lifespan
def alive(self):
return self.age <= self.lifespan
'''
Firework simulation loop:
Recursively call to repeatedly emit new fireworks on canvas
a list of list (list of stars, each of which is a list of particles)
is created and drawn on canvas at every call,
via update protocol inside each 'part' object
'''
def simulate(cv):
t = time
explode_points =
wait_time = randint(10,100)
numb_explode = randint(6,10)
# create list of list of all particles in all simultaneous explosion
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 = part(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
# keeps undate within a timeframe of 1.8 second
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
# recursive call to continue adding new explosion on canvas
root.after(wait_time, simulate, cv)
def close(*ignore):
"""Stops simulation loop and closes the window."""
global root
root.quit
if __name__ == '__main__':
root = tk.Tk
cv = tk.Canvas(root, height=600, width=600)
# use a nice background image
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
總結(jié)
以上是生活随笔為你收集整理的python代码变成手机软件_使用Python代码的程序员也浪漫的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: BZOJ 4066 简单题 ——KD-T
- 下一篇: 图论中的基础概念总结