基于Python記錄一場2023的煙花
彈指間,2023已經(jīng)到來,新的一年,祝大家新年快樂,闔家幸福呀~~~
好吧,進(jìn)入正題,2023的到來,肯定少不了煙花吧(外面不讓放炮,那咱們就用python放炮【DOGE】)
首先,需要的外置庫:pygame,pymunk
導(dǎo)入
import pygame from pygame.locals import * import pymunk from pymunk import pygame_util import sys import random as rd import time import math
然后寫一個主程序類,對pygame進(jìn)行初始化,設(shè)置屏幕寬高,設(shè)置標(biāo)題,創(chuàng)建pymunk空間,然后設(shè)置空間的重力為(0,300),然后設(shè)置collision_persistence參數(shù)為0,表示沒有碰撞,畢竟倆煙花也不會撞一起......然后設(shè)置煙花半徑(可以自行修改),創(chuàng)建兩個列表,用于存放煙花爆炸形成的火球和發(fā)射到天空中還沒爆炸的煙花,創(chuàng)建一個colors列表,存放煙花的顏色
class Firework: def __init__(self): pygame.init() self.W,self.H=800,1000 self.screen=pygame.display.set_mode((self.W,self.H)) self.draw_options=pygame_util.DrawOptions(self.screen) pygame.display.set_caption("2023元旦煙花") self.space=pymunk.Space() self.space.gravity=(0,300) self.space.collision_persistence=0 self.fireball_radius=2 self.fire_radius=2 self.fireballs=[] self.colors=[ (255,0,0),(255,127,80),(255,140,0),(255,160,122),(240,128,128),(255,99,71),(255,69,0), (255,105,180),(255,20,147),(208,32,144),(176,48,96),(153,50,204),(255,48,48), (238,44,44),(205,38,38),(255,255,0),(255,215,0),(255,185,15),(238,201,0), (34,139,34),(46,139,87),(60,179,113),(0,255,127) ] self.fires=[]
接下來,進(jìn)行事件監(jiān)聽,按下鼠標(biāo)就可以創(chuàng)建火球
def listen(self): for event in pygame.event.get(): if event.type==QUIT: sys.exit() if event.type==MOUSEBUTTONDOWN: self.create_firework(x=pygame.mouse.get_pos()[0])
然后寫個創(chuàng)建煙花的方法,首先要有個body,設(shè)置body_type為DYNAMIC,因為煙花是動態(tài)的。然后設(shè)置body的位置,x坐標(biāo)為傳參的x坐標(biāo),y坐標(biāo)為屏幕最底部,接下來創(chuàng)建一個shape,形狀為circle,body對應(yīng)的fireball_body傳進(jìn)去就好了,然后設(shè)置radius(半徑),設(shè)置shape的彈性(這個不設(shè)置也可以,沒多大影響),將body和shape添加到空間中,用add添加,然后將煙花對應(yīng)的shape對象、顏色、創(chuàng)建時間、爆炸前持續(xù)時間這四個參數(shù)歸在一個列表,將這個列表添加到fireballs中,最后就是要賦予body沖擊力了,使用apply_impulse_at_local_point方法
def create_firework(self,x): fireball_body=pymunk.Body(mass=1,moment=100,body_type=pymunk.Body.DYNAMIC) fireball_body.position=x,self.H fireball_shape=pymunk.Circle(fireball_body,self.fireball_radius) fireball_shape.elasticity=0.5 self.space.add(fireball_body,fireball_shape) self.fireballs.append([fireball_shape,rd.choice(self.colors),time.time(),rd.uniform(1,2.2)]) # shape,color,startTime,lastTime fireball_body.apply_impulse_at_local_point((0,rd.randint(-730,-500)),(0,0))
然后是draw的代碼(比較多),先是填充背景為黑色,然后使用while循環(huán)遍歷fireballs,將煙花繪制出來,檢查是否到達(dá)了爆炸時間,如果已經(jīng)到達(dá)爆炸時間,那么將這個火球從煙花的列表中刪掉。接下來就要創(chuàng)建炸開來的火花,火花是向不同方向散開的,所以用for循環(huán)遍歷一圈的度數(shù),每隔10°就有一個,length是斜邊長度,然后定義bias偏移量,因為火花散發(fā)力量和距離并不是固定的,所以每一次length都會浮動一點,但始終控制在25~100之間(maximum和minimum),因為apply_impulse_at_local_point發(fā)射出去時傳參是x軸的力量和y軸的力量,所以要使用三角函數(shù)計算臨邊和對邊的長度從而得到apply_impulse_at_local_point傳參的數(shù)值,又因為我們遍歷的是度數(shù)(degree),sin和cos計算的是弧度(radians),所以要先把度數(shù)通過math.radians轉(zhuǎn)化為弧度,再傳參到sin和cos中。計算出來之后,還是創(chuàng)建body和shape并設(shè)置一些基本的參數(shù),添加到空間中,并添加到fires列表中,最后刪除已爆炸的煙花,別忘了變量i需要減1。
上面是對未爆炸的煙花進(jìn)行遍歷,下面我們還需要對爆炸后形成的火花進(jìn)行遍歷,如果超出范圍或已到達(dá)刪除時間就進(jìn)行刪除的操作,邏輯差不多
draw的代碼如下
def draw(self): self.screen.fill((0,0,0)) i=0 while i<len(self.fireballs): fireball,color,startTime,lastTime=self.fireballs[i] pygame.draw.circle(self.screen,color,fireball.body.position,self.fireball_radius) nowTime=time.time() boomTime=startTime+lastTime if nowTime>boomTime: popball=self.fireballs.pop(i) length=50 for degree in range(90,450,10): bias=1 length+=rd.randint(-bias,bias) maximum,minimum=100,25 if length>maximum: length=maximum elif length<minimum: length=minimum radians=math.radians(degree) x_force=math.sin(radians)*length y_force=math.cos(radians)*length body=pymunk.Body(mass=1,moment=100,body_type=pymunk.Body.DYNAMIC) body.position=popball[0].body.position shape=pymunk.Circle(body,self.fire_radius) self.space.add(body,shape) self.fires.append([shape,popball[1],time.time(),rd.uniform(0.5,1.5)]) # shape,color,startTime,lastTime body.apply_impulse_at_local_point((x_force,y_force),(0,0)) self.space.remove(popball[0]) i-=1 i+=1 i=0 while i<len(self.fires): fire,color,startTime,lastTime=self.fires[i] pos=fire.body.position pygame.draw.circle(self.screen,color,pos,self.fire_radius) nowTime=time.time() deleteTime=startTime+lastTime if nowTime>deleteTime: self.fires.pop(i) self.space.remove(fire) i-=1 elif pos[0]<0 or pos[0]>self.W or pos[1]>self.H: self.fires.pop(i) self.space.remove(fire) i-=1 i+=1
寫到這兒,我們的煙花就差不多完成了,最后寫個run
def run(self): clock=pygame.time.Clock() FPS=60 while True: clock.tick(FPS) self.listen() self.draw() self.space.step(1/FPS) pygame.display.update()
運行
if __name__=="__main__": firework=Firework() firework.run()
這樣就好啦!
最終代碼
import pygame from pygame.locals import * import pymunk from pymunk import pygame_util import sys import random as rd import time import math class Firework: def __init__(self): pygame.init() self.W,self.H=800,1000 self.screen=pygame.display.set_mode((self.W,self.H)) self.draw_options=pygame_util.DrawOptions(self.screen) pygame.display.set_caption("2023元旦煙花") self.space=pymunk.Space() self.space.gravity=(0,300) self.space.collision_persistence=0 self.fireball_radius=2 self.fire_radius=2 self.fireballs=[] self.colors=[ (255,0,0),(255,127,80),(255,140,0),(255,160,122),(240,128,128),(255,99,71),(255,69,0), (255,105,180),(255,20,147),(208,32,144),(176,48,96),(153,50,204),(255,48,48), (238,44,44),(205,38,38),(255,255,0),(255,215,0),(255,185,15),(238,201,0), (34,139,34),(46,139,87),(60,179,113),(0,255,127) ] self.fires=[] def listen(self): for event in pygame.event.get(): if event.type==QUIT: sys.exit() if event.type==MOUSEBUTTONDOWN: self.create_firework(x=pygame.mouse.get_pos()[0]) def create_firework(self,x): fireball_body=pymunk.Body(mass=1,moment=100,body_type=pymunk.Body.DYNAMIC) fireball_body.position=x,self.H fireball_shape=pymunk.Circle(fireball_body,self.fireball_radius) fireball_shape.elasticity=0.5 self.space.add(fireball_body,fireball_shape) self.fireballs.append([fireball_shape,rd.choice(self.colors),time.time(),rd.uniform(1,2.2)]) # shape,color,startTime,lastTime fireball_body.apply_impulse_at_local_point((0,rd.randint(-730,-500)),(0,0)) def draw(self): self.screen.fill((0,0,0)) i=0 while i<len(self.fireballs): fireball,color,startTime,lastTime=self.fireballs[i] pygame.draw.circle(self.screen,color,fireball.body.position,self.fireball_radius) nowTime=time.time() boomTime=startTime+lastTime if nowTime>boomTime: popball=self.fireballs.pop(i) length=50 for degree in range(90,450,10): bias=1 length+=rd.randint(-bias,bias) maximum,minimum=100,25 if length>maximum: length=maximum elif length<minimum: length=minimum radians=math.radians(degree) x_force=math.sin(radians)*length y_force=math.cos(radians)*length body=pymunk.Body(mass=1,moment=100,body_type=pymunk.Body.DYNAMIC) body.position=popball[0].body.position shape=pymunk.Circle(body,self.fire_radius) self.space.add(body,shape) self.fires.append([shape,popball[1],time.time(),rd.uniform(0.5,1.5)]) # shape,color,startTime,lastTime body.apply_impulse_at_local_point((x_force,y_force),(0,0)) self.space.remove(popball[0]) i-=1 i+=1 i=0 while i<len(self.fires): fire,color,startTime,lastTime=self.fires[i] pos=fire.body.position pygame.draw.circle(self.screen,color,pos,self.fire_radius) nowTime=time.time() deleteTime=startTime+lastTime if nowTime>deleteTime: self.fires.pop(i) self.space.remove(fire) i-=1 elif pos[0]<0 or pos[0]>self.W or pos[1]>self.H: self.fires.pop(i) self.space.remove(fire) i-=1 i+=1 def run(self): clock=pygame.time.Clock() FPS=60 while True: clock.tick(FPS) self.listen() self.draw() self.space.step(1/FPS) pygame.display.update() if __name__=="__main__": firework=Firework() firework.run()
此時我仿佛聽見你說:一直按鼠標(biāo)手好酸?。?/p>
那沒事,我們改成自動就好啦!
只需要修改一部分內(nèi)容就好
首先需要一個自定義事件(全局變量)
CREATE_FIREBALL=USEREVENT+1
run中while循環(huán)前添加這一行,用來啟動事件循環(huán),第二個參數(shù)是間隔時間,單位是毫秒,可以自己修改
pygame.time.set_timer(CREATE_FIREBALL,120)
將listen改成這樣
def listen(self): for event in pygame.event.get(): if event.type==QUIT: sys.exit() if event.type==CREATE_FIREBALL: self.create_firework(x=rd.randint(0,self.W))
這樣就大功告成啦!
到此這篇關(guān)于基于Python記錄一場2023的煙花的文章就介紹到這了,更多相關(guān)Python煙花內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pytorch dataloader在加載最后一個batch時卡死的解決
這篇文章主要介紹了Pytorch dataloader在加載最后一個batch時卡死的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05Python學(xué)習(xí)筆記之lambda表達(dá)式用法詳解
這篇文章主要介紹了Python學(xué)習(xí)筆記之lambda表達(dá)式用法,結(jié)合實例形式詳細(xì)分析了lambda表達(dá)式的概念、功能、原理、組成及相關(guān)使用技巧,需要的朋友可以參考下2019-08-08Python?Apschedule定時任務(wù)框架的用法詳解
apschedule是一個用python寫的定時處理框架,這篇文章主要為大家詳細(xì)介紹了Apschedule定時任務(wù)框架的用法,感興趣的小伙伴可以跟隨小編一起了解一下2023-06-06python編程實現(xiàn)清理微信重復(fù)緩存文件
這篇文章主要為大家介紹了使用python編程來實現(xiàn)清理微信重復(fù)緩存文件的示例代碼過程,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11pandas.DataFrame的for循環(huán)迭代的實現(xiàn)
本文主要介紹了pandas.DataFrame的for循環(huán)迭代的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02