利用Python Pygame放個(gè)煙花
uu們,有多久沒放煙花了?今年你所在的地方允許放煙花么?既然我們不能線下放,那么我們就在線上放個(gè)夠吧,先上最后效果圖
老規(guī)矩,先導(dǎo)包,導(dǎo)入pygame,Python Pygame 是一款專門為開發(fā)和設(shè)計(jì) 2D 電子游戲而生的軟件包,它支 Windows、Linux、Mac OS 等操作系統(tǒng),具有良好的跨平臺(tái)性。
import pygame from random import randint, uniform, choice import math
Pygame 繪制煙花的基本原理
1、發(fā)射階段:在這一階段煙花的形狀是線性向上,通過設(shè)定一組大小不同、顏色不同的點(diǎn)來模擬“向上發(fā)射” 的運(yùn)動(dòng)運(yùn)動(dòng),運(yùn)動(dòng)過程中 5個(gè)點(diǎn)被賦予不同大小的加速度,隨著時(shí)間推移,后面的點(diǎn)會(huì)趕上前面的點(diǎn),最終所有點(diǎn)會(huì)匯聚在一起,處于綻放準(zhǔn)備階段。
2、煙花綻放:煙花綻放這個(gè)階段,是由一個(gè)點(diǎn)分散多個(gè)點(diǎn)向不同方向發(fā)散,并且每個(gè)點(diǎn)的移動(dòng)軌跡可需要被記錄,目的是為了追蹤整個(gè)綻放軌跡。
3、煙花凋零,此階段負(fù)責(zé)描繪綻放后煙花的效果,綻放后的煙花,而在每一時(shí)刻點(diǎn)的下降速度和亮度(代碼中也叫透明度)是不一樣的,因此在代碼里,將煙花綻放后將每個(gè)點(diǎn)賦予兩個(gè)屬性:分別為重力向量和生命周期,來模擬煙花在不同時(shí)期時(shí)不同的展現(xiàn)效果。
首先設(shè)置全局變量,例如重力向量,窗口大小,Trail 的顏色列表(多為灰色或白色)以及不同狀態(tài)下 Trail 之間間隔,gravity設(shè)置重力變量,DISPLAY_width和heigh控制窗口的長和寬
vector = pygame.math.Vector2 #重力變量 gravity = vector(0, 0.3) #控制窗口的大小 DISPLAY_WIDTH = DISPLAY_HEIGHT = 800 #顏色選項(xiàng) trail_colours = [(45, 45, 45), (60, 60, 60), (75, 75, 75), (125, 125, 125), (150, 150, 150)] dynamic_offset = 1 static_offset = 3
代碼整體部分將煙花封裝為三個(gè)類(類是面向?qū)ο笳Z言的程序設(shè)計(jì)中的概念,是面向?qū)ο缶幊痰幕A(chǔ)):
Firework : 整體部分
class Firework: def __init__(self): # 隨機(jī)顏色 self.colour = (randint(0, 255), randint(0, 255), randint(0, 255)) self.colours = ( (randint(0, 255), randint(0, 255), randint(0, 255)), (randint(0, 255), randint(0, 255), randint(0, 255)), (randint(0, 255), randint(0, 255), randint(0, 255))) self.firework = Particle(randint(0, DISPLAY_WIDTH), DISPLAY_HEIGHT, True, self.colour) # Creates the firework particle self.exploded = False self.particles = [] self.min_max_particles = vector(100, 225) def update(self, win): # 每幀調(diào)用 if not self.exploded: self.firework.apply_force(gravity) self.firework.move() for tf in self.firework.trails: tf.show(win) self.show(win) if self.firework.vel.y >= 0: self.exploded = True self.explode() else: for particle in self.particles: particle.apply_force(vector(gravity.x + uniform(-1, 1) / 20, gravity.y / 2 + (randint(1, 8) / 100))) particle.move() for t in particle.trails: t.show(win) particle.show(win) def explode(self): # amount 數(shù)量 amount = randint(self.min_max_particles.x, self.min_max_particles.y) for i in range(amount): self.particles.append(Particle(self.firework.pos.x, self.firework.pos.y, False, self.colours)) def show(self, win): pygame.draw.circle(win, self.colour, (int(self.firework.pos.x), int(self.firework.pos.y)), self.firework.size) def remove(self): if self.exploded: for p in self.particles: if p.remove is True: self.particles.remove(p) if len(self.particles) == 0: return True else: return False
Particle:煙花粒子(包含軌跡)
class Particle: def __init__(self, x, y, firework, colour): self.firework = firework self.pos = vector(x, y) self.origin = vector(x, y) self.radius = 20 self.remove = False self.explosion_radius = randint(5, 18) self.life = 0 self.acc = vector(0, 0) # trail variables self.trails = [] # stores the particles trail objects self.prev_posx = [-10] * 10 # stores the 10 last positions self.prev_posy = [-10] * 10 # stores the 10 last positions if self.firework: self.vel = vector(0, -randint(17, 20)) self.size = 5 self.colour = colour for i in range(5): self.trails.append(Trail(i, self.size, True)) else: self.vel = vector(uniform(-1, 1), uniform(-1, 1)) self.vel.x *= randint(7, self.explosion_radius + 2) self.vel.y *= randint(7, self.explosion_radius + 2) # 向量 self.size = randint(2, 4) self.colour = choice(colour) # 5 個(gè) tails總計(jì) for i in range(5): self.trails.append(Trail(i, self.size, False)) def apply_force(self, force): self.acc += force def move(self): if not self.firework: self.vel.x *= 0.8 self.vel.y *= 0.8 self.vel += self.acc self.pos += self.vel self.acc *= 0 if self.life == 0 and not self.firework: # 檢查粒子的爆炸范圍 distance = math.sqrt((self.pos.x - self.origin.x) ** 2 + (self.pos.y - self.origin.y) ** 2) if distance > self.explosion_radius: self.remove = True self.decay() self.trail_update() self.life += 1 def show(self, win): pygame.draw.circle(win, (self.colour[0], self.colour[1], self.colour[2], 0), (int(self.pos.x), int(self.pos.y)), self.size) def decay(self): # random decay of the particles if 50 > self.life > 10: # early stage their is a small chance of decay ran = randint(0, 30) if ran == 0: self.remove = True elif self.life > 50: ran = randint(0, 5) if ran == 0: self.remove = True def trail_update(self): self.prev_posx.pop() self.prev_posx.insert(0, int(self.pos.x)) self.prev_posy.pop() self.prev_posy.insert(0, int(self.pos.y)) for n, t in enumerate(self.trails): if t.dynamic: t.get_pos(self.prev_posx[n + dynamic_offset], self.prev_posy[n + dynamic_offset]) else: t.get_pos(self.prev_posx[n + static_offset], self.prev_posy[n + static_offset])
Trail:煙花軌跡
本質(zhì)上是一個(gè)點(diǎn) 。創(chuàng)建 Trail 類,定義 show 方法繪制軌跡 、get_pos 實(shí)時(shí)獲取軌跡坐標(biāo)
class Trail: def __init__(self, n, size, dynamic): self.pos_in_line = n self.pos = vector(-10, -10) self.dynamic = dynamic if self.dynamic: self.colour = trail_colours[n] self.size = int(size - n / 2) else: self.colour = (255, 255, 200) self.size = size - 2 if self.size < 0: self.size = 0 def get_pos(self, x, y): self.pos = vector(x, y) def show(self, win): pygame.draw.circle(win, self.colour, (int(self.pos.x), int(self.pos.y)), self.size) def update(win, fireworks): for fw in fireworks: fw.update(win) if fw.remove(): fireworks.remove(fw) pygame.display.update()
三個(gè)類之間的關(guān)系為:一個(gè)Firework 由多個(gè) Particle 構(gòu)成,而一個(gè) Particle 由多個(gè) Trail 構(gòu)成,最后,寫一個(gè) main 方法來對(duì) pygame 環(huán)境進(jìn)行初始化,例如背景圖片,文字。
def main(): pygame.init() pygame.font.init() pygame.display.set_caption("祝您新年快樂") # 標(biāo)題 background = pygame.image.load("./5.png") # 背景 sound_wav = pygame.mixer.music.load("2.mp3") pygame.mixer.music.play() # 加載背景音樂 pygame.mixer.music.load("./res/音樂文件名") # 循環(huán)播放背景音樂 pygame.mixer.music.play(-1) # 停止背景音樂 pygame.mixer.music.stop() # 加載音效 boom_sound = pygame.mixer.Sound("./res/音效名") # 播放音效 boom_sound.play() boom_sound.stop() myfont = pygame.font.Font("simkai.TTF",80) myfont1 = pygame.font.Font("simkai.ttf", 30) testsurface = myfont.render("虎虎生威",False,(0, 0, 0),(220, 20, 60)) testsurface1 = myfont1.render("", False, (251, 59, 85)) # pygame.image.load("") win = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT)) # win.blit(background) clock = pygame.time.Clock() fireworks = [Firework() for i in range(2)] # create the first fireworks running = True while running: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: # Change game speed with number keys if event.key == pygame.K_1: # 按下 1 fireworks.append(Firework()) if event.key == pygame.K_2: # 按下 2 加入10個(gè)煙花 for i in range(10): fireworks.append(Firework()) if event.key == pygame.K_3: # 按下 3 加入100個(gè)煙花 for i in range(100): fireworks.append(Firework()) win.fill((20, 20, 30)) # draw background win.blit(background,(0,0)) win.blit(testsurface,(200,30)) win.blit(testsurface1, (520,80)) if randint(0, 20) == 1: # 創(chuàng)建新的煙花 fireworks.append(Firework()) update(win, fireworks) pygame.quit() quit() main()
整體到此就結(jié)束了,uu們可以嘗試自己試一下,封裝比較困難,但是定義最后初始化我們可以加入一些我們自己的元素!
到此這篇關(guān)于利用Python Pygame放個(gè)煙花的文章就介紹到這了,更多相關(guān)Python Pygame煙花內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Django實(shí)現(xiàn)將一個(gè)字典傳到前端顯示出來
這篇文章主要介紹了Django實(shí)現(xiàn)將一個(gè)字典傳到前端顯示出來,具有很好的參考價(jià)值,希望2020-04-04python3.8中關(guān)于sklearn問題(win10)
這篇文章主要介紹了python3.8中關(guān)于sklearn問題(win10),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-065種Python統(tǒng)計(jì)次數(shù)方法技巧
這篇文章主要給大家分享的是5種Python統(tǒng)計(jì)次數(shù)方法技巧,文章主要包括字典 dict 統(tǒng)計(jì)、collections.defaultdict 統(tǒng)計(jì)、List count方法、集合(set)和列表(list)統(tǒng)計(jì)、collections.Counter方法,感興趣的小伙伴一起進(jìn)入下面文章內(nèi)容吧2021-11-11Python如何把不同類型數(shù)據(jù)的json序列化
這篇文章主要介紹了Python如何把不同類型數(shù)據(jù)的json序列化,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04Python單元測試及unittest框架用法實(shí)例解析
這篇文章主要介紹了Python單元測試及unittest框架用法實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07matplotlib交互式數(shù)據(jù)光標(biāo)實(shí)現(xiàn)(mplcursors)
這篇文章主要介紹了matplotlib交互式數(shù)據(jù)光標(biāo)實(shí)現(xiàn)(mplcursors),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01