利用Python繪制端午節(jié)祝福動(dòng)畫
話不多說(shuō),我就先展示效果了,如果想要代碼的可以直接下載代碼包

1.準(zhǔn)備
1.1資源下載
我們下載代碼包解壓后目錄應(yīng)該如下

其中background1~background3分別是3張背景圖片,其中ITCKRIST.TTF是字體文件,端午節(jié).mp3則是背景音樂(lè),端午節(jié).py就是源碼了。
1.2安裝依賴
我們?cè)谡介_始編碼前需要先安裝一些依賴項(xiàng),我在下面的列表中分別展示了依賴及作用
| 庫(kù) | 作用 |
|---|---|
| random | 隨機(jī)數(shù)支持 |
| time | 提供程序暫停 |
| pygame | 提供音樂(lè)播放 |
| pyglet | 讀取圖片 |
| cocos | 菜單,粒子動(dòng)畫 |
我們使用按下win+r,輸入cmd打開終端。

依次輸入命令來(lái)安裝依賴。
pip install -U pygame pip install -U pyglet pip install -U cocos2d
我們可以輸入來(lái)檢查安裝是否成功
pip list
如果動(dòng)手能力比較差的小伙伴可以直接運(yùn)行代碼包中的run.bat來(lái)安裝依賴。失敗的可以自行百度。
2.原理詳解
2.1粒子動(dòng)畫
我們的程序中主要的便是粒子動(dòng)畫。究竟什么是粒子動(dòng)畫?
粒子動(dòng)畫是一種通過(guò)使用許多小的可視元素(粒子)來(lái)創(chuàng)建動(dòng)態(tài)圖像效果的技術(shù)。每個(gè)粒子都有自己的位置、速度、加速度、顏色等屬性,并在時(shí)間上進(jìn)行微調(diào),以產(chǎn)生各種動(dòng)態(tài)效果,如煙霧、火焰、水波、流星等。
其原理基于物理學(xué)和數(shù)學(xué)原理。在粒子動(dòng)畫中,每個(gè)粒子的運(yùn)動(dòng)都可以通過(guò)牛頓力學(xué)描述,如力、速度、加速度等。通常,需要應(yīng)用一些物理效應(yīng),例如引力、摩擦和碰撞來(lái)模擬到達(dá)目標(biāo)時(shí)的行為。
除了物理模型之外,還可以使用數(shù)學(xué)方法產(chǎn)生粒子動(dòng)畫效果。例如,使用噪聲函數(shù)生成隨機(jī)值,以模擬自然環(huán)境中的不規(guī)則性。
總的來(lái)說(shuō),粒子動(dòng)畫是一種非常有趣和令人驚嘆的藝術(shù)形式,能夠創(chuàng)建各種炫酷的視覺(jué)效果。
至于如何實(shí)現(xiàn)粒子動(dòng)畫在后面我會(huì)帶大家實(shí)現(xiàn)。
2.2結(jié)構(gòu)分析
我們的程序由一個(gè)窗口實(shí)現(xiàn)。而窗口則又有2個(gè)場(chǎng)景組成。
菜單層:又公共的background層和MainMenu菜單層組成

主場(chǎng)景:由動(dòng)畫層和背景層組成

我相信大家已經(jīng)理解窗口的結(jié)構(gòu)了
3.代碼實(shí)現(xiàn)
3.1模塊導(dǎo)入
# 導(dǎo)入必要的模塊和庫(kù) from random import randint from time import sleep import pygame from pygame import init from pygame.mixer import music from cocos.menu import * from cocos.director import director from cocos.scene import Scene from cocos.actions import * from cocos.layer import Layer from cocos.text import Label from cocos.particle_systems import * from cocos.sprite import Sprite from cocos.scenes import * from pyglet.gl import * from pyglet import resource from pyglet.image import Animation
3.2定義公共類
# 音樂(lè)類,用來(lái)管理音樂(lè)播放
class Music:
def __init__(self):
init()
try:
music.load("端午節(jié).mp3")#加載音樂(lè)
except:
print("cannot find mp3")
def play(self):
music.play()
# 自定義的一些粒子效果類
class MySpiral(Spiral):
def __init__(self):
super().__init__()
self.total_particles = randint(300, 500)
self.size = randint(7, 12)
self.duration = randint(13, 20)
self.position = (randint(100, 750), randint(100, 550))
class MyFlower(Flower):
def __init__(self):
super().__init__()
self.total_particles = randint(300, 500)
self.size = randint(12, 18)
self.duration = randint(13, 20)
self.position = (randint(50, 750), randint(50, 550))
class MyFlowerworks(Fireworks):
def __init__(self):
super().__init__()
self.total_particles = randint(300, 500)
self.size = randint(7, 12)
self.duration = randint(13, 20)
self.position = (randint(50, 750), 50)
class MyExplosion(Explosion):
def __init__(self):
super().__init__()
self.total_particles = randint(300, 500)
self.size = randint(7, 12)
self.duration = randint(13, 20)
self.position = (randint(50, 750), randint(50, 550))
# 背景圖層類,用來(lái)加載和繪制背景圖像
class BackgroundLayer(Layer):
def __init__(self):
super().__init__()
try:
self.images = [resource.image("background1.png"),
resource.image("background2.png"),
resource.image("background3.png")]#加載圖片
except:
print("cannot find background image!")
else:
self.image = Animation.from_image_sequence(self.images, 2)
self.idx = randint(0, 2)
def draw(self):#繪制函數(shù)
glPushMatrix()
self.transform()
self.images[self.idx].blit(0, 0)
glPopMatrix()3.3定義菜單
# 菜單圖層類,用來(lái)創(chuàng)建開始游戲的按鈕和倒計(jì)時(shí)
class MenuLayer(Menu):
def __init__(self):
super().__init__("六一快樂(lè)")
self.music = Music()
music.play()
self.time = 0
self.font_title["font_size"] = 64
self.font_title["color"] = (255, 128, 255, 255)
self.menu_halign = CENTER
self.menu_valign = CENTER
self.items = []
self.items.append(MenuItem("Start", self.on_stats))
self.create_menu(self.items, shake(), shake_back())
self.schedule(self.update)
def on_stats(self):
director.push(MainScene())
def update(self, dt):
self.time += dt
if self.time >= 15.0:
director.push(MainScene())
# 菜單場(chǎng)景類,用來(lái)加載菜單圖層和背景圖層
class MenuScene(Scene):
def __init__(self):
super().__init__()
self.add(MenuLayer(), z=1)
self.add(BackgroundLayer(), z=-1)3.4定義主場(chǎng)景
# 游戲圖層類,用來(lái)實(shí)現(xiàn)游戲界面和倒計(jì)時(shí)
class MainLayer(Layer):
is_event_handler = True
def __init__(self):
super().__init__()
# 設(shè)置文字的初始狀態(tài)和動(dòng)畫效果
self.texts = [list("祝各位端午節(jié)快樂(lè)!"), list("讓我們一起歡慶吧!!")]
self.idx1, self.idx2 = 0, 0
self.new_text = ["", ""]
try:
self.text1 = Label(text=self.new_text[0],
font_size=64,
font_name="Kristen ITC",
color=(255, 128, 255, 255),
anchor_x="center",
anchor_y="center", )
except:
print("cannot find font file!")
else:
self.text1.position = (400, 450)
self.text1.do(reversed(RotateBy(20, 1.5)) +
spawn(Repeat(RotateBy(40, 1.5) + reversed(RotateBy(40, 1.5))),
ScaleBy(1.25) + reversed(ScaleBy(1.25))))
self.add(self.text1, z=0)
try:
self.text2 = Label(text=self.new_text[1],
font_size=64,
font_name="Kristen ITC",
color=(255, 128, 255, 255),
anchor_x="center",
anchor_y="center", )
except:
print("cannot find font file!")
else:
self.text2.position = (400, 300)
self.text2.do(reversed(RotateBy(20, 1.5)) +
spawn(Repeat(RotateBy(40, 1.5) + reversed(RotateBy(40, 1.5))),
ScaleBy(1.25) + reversed(ScaleBy(1.25))))
self.add(self.text2, z=0)
# 添加背景圖片,設(shè)置其初始位置
self.background = Sprite(BackgroundLayer().image)
self.background.position = (400, 300)
self.add(self.background, z=-1)
# 通過(guò)循環(huán)添加部分粒子效果
for i in range(randint(15, 21)):
self.systems = [MyFlower(), MyFlowerworks(), MyExplosion()]
for j in range(randint(1, 3)):
self.add(self.systems[randint(0, 2)], z=randint(3, 8))
self.add(MySpiral())
# 設(shè)置倒計(jì)時(shí)值,并設(shè)置定時(shí)器
self.time1 = 0
self.time2 = 0
self.schedule(self.update_systems)
self.schedule(self.update_text)
# 更新文字部分的動(dòng)畫效果,實(shí)現(xiàn)逐字顯示
def update_text(self, dt):
self.time1 += dt
if self.time1 >= 1.0:
if self.idx1 <= len(self.texts[0]) - 1:
self.new_text[0] += self.texts[0][self.idx1]
self.text1.element.text = self.new_text[0]
self.idx1 += 1
if self.idx2 <= len(self.texts[1]) - 1 and self.idx1 >= 8:
self.new_text[1] += self.texts[1][self.idx2]
self.text2.element.text = self.new_text[1]
self.idx2 += 1
self.time1 = 0
# 更新粒子效果,每隔一段時(shí)間添加新的效果
def update_systems(self, dt):
self.time2 += dt
if self.time2 >= randint(15, 20):
for i in range(randint(15, 21)):
self.systems = [MyFlower(), MyFlowerworks(), MyExplosion()]
for j in range(randint(1, 3)):
self.add(self.systems[randint(0, 2)], z=randint(3, 8))
self.time2 = 0
self.add(MySpiral())
# 游戲場(chǎng)景類,用來(lái)加載游戲圖層和背景圖層
class MainScene(Scene):
def __init__(self):
super().__init__()
self.add(MainLayer(), z=2)
self.add(BackgroundLayer(), z=0)3.5創(chuàng)建窗口
if __name__ == '__main__':
director.init(resizable=True, caption="六一快樂(lè)",
width=800, height=600)
director.run(MenuScene())4.完整代碼
# 導(dǎo)入必要的模塊和庫(kù)
from random import randint
from time import sleep
import pygame
from pygame import init
from pygame.mixer import music
from cocos.menu import *
from cocos.director import director
from cocos.scene import Scene
from cocos.actions import *
from cocos.layer import Layer
from cocos.text import Label
from cocos.particle_systems import *
from cocos.sprite import Sprite
from cocos.scenes import *
from pyglet.gl import *
from pyglet import resource
from pyglet.image import Animation
# 音樂(lè)類,用來(lái)管理音樂(lè)播放
class Music:
def __init__(self):
init()
try:
music.load("端午節(jié).mp3")
except:
print("cannot find mp3")
def play(self):
music.play()
# 自定義的一些粒子效果類
class MySpiral(Spiral):
def __init__(self):
super().__init__()
self.total_particles = randint(300, 500)
self.size = randint(7, 12)
self.duration = randint(13, 20)
self.position = (randint(100, 750), randint(100, 550))
class MyFlower(Flower):
def __init__(self):
super().__init__()
self.total_particles = randint(300, 500)
self.size = randint(12, 18)
self.duration = randint(13, 20)
self.position = (randint(50, 750), randint(50, 550))
class MyFlowerworks(Fireworks):
def __init__(self):
super().__init__()
self.total_particles = randint(300, 500)
self.size = randint(7, 12)
self.duration = randint(13, 20)
self.position = (randint(50, 750), 50)
class MyExplosion(Explosion):
def __init__(self):
super().__init__()
self.total_particles = randint(300, 500)
self.size = randint(7, 12)
self.duration = randint(13, 20)
self.position = (randint(50, 750), randint(50, 550))
# 背景圖層類,用來(lái)加載和繪制背景圖像
class BackgroundLayer(Layer):
def __init__(self):
super().__init__()
try:
self.images = [resource.image("background1.png"),
resource.image("background2.png"),
resource.image("background3.png")]
except:
print("cannot find background image!")
else:
self.image = Animation.from_image_sequence(self.images, 2)
self.idx = randint(0, 2)
def draw(self):
glPushMatrix()
self.transform()
self.images[self.idx].blit(0, 0)
glPopMatrix()
# 菜單圖層類,用來(lái)創(chuàng)建開始游戲的按鈕和倒計(jì)時(shí)
class MenuLayer(Menu):
def __init__(self):
super().__init__("六一快樂(lè)")
self.music = Music()
music.play()
self.time = 0
self.font_title["font_size"] = 64
self.font_title["color"] = (255, 128, 255, 255)
self.menu_halign = CENTER
self.menu_valign = CENTER
self.items = []
self.items.append(MenuItem("Start", self.on_stats))
self.create_menu(self.items, shake(), shake_back())
self.schedule(self.update)
def on_stats(self):
director.push(MainScene())
def update(self, dt):
self.time += dt
if self.time >= 15.0:
director.push(MainScene())
# 菜單場(chǎng)景類,用來(lái)加載菜單圖層和背景圖層
class MenuScene(Scene):
def __init__(self):
super().__init__()
self.add(MenuLayer(), z=1)
self.add(BackgroundLayer(), z=-1)
# 游戲圖層類,用來(lái)實(shí)現(xiàn)游戲界面和倒計(jì)時(shí)
class MainLayer(Layer):
is_event_handler = True
def __init__(self):
super().__init__()
# 設(shè)置文字的初始狀態(tài)和動(dòng)畫效果
self.texts = [list("祝各位端午節(jié)快樂(lè)!"), list("讓我們一起歡慶吧!!")]
self.idx1, self.idx2 = 0, 0
self.new_text = ["", ""]
try:
self.text1 = Label(text=self.new_text[0],
font_size=64,
font_name="Kristen ITC",
color=(255, 128, 255, 255),
anchor_x="center",
anchor_y="center", )
except:
print("cannot find font file!")
else:
self.text1.position = (400, 450)
self.text1.do(reversed(RotateBy(20, 1.5)) +
spawn(Repeat(RotateBy(40, 1.5) + reversed(RotateBy(40, 1.5))),
ScaleBy(1.25) + reversed(ScaleBy(1.25))))
self.add(self.text1, z=0)
try:
self.text2 = Label(text=self.new_text[1],
font_size=64,
font_name="Kristen ITC",
color=(255, 128, 255, 255),
anchor_x="center",
anchor_y="center", )
except:
print("cannot find font file!")
else:
self.text2.position = (400, 300)
self.text2.do(reversed(RotateBy(20, 1.5)) +
spawn(Repeat(RotateBy(40, 1.5) + reversed(RotateBy(40, 1.5))),
ScaleBy(1.25) + reversed(ScaleBy(1.25))))
self.add(self.text2, z=0)
# 添加背景圖片,設(shè)置其初始位置
self.background = Sprite(BackgroundLayer().image)
self.background.position = (400, 300)
self.add(self.background, z=-1)
# 通過(guò)循環(huán)添加部分粒子效果
for i in range(randint(15, 21)):
self.systems = [MyFlower(), MyFlowerworks(), MyExplosion()]
for j in range(randint(1, 3)):
self.add(self.systems[randint(0, 2)], z=randint(3, 8))
self.add(MySpiral())
# 設(shè)置倒計(jì)時(shí)值,并設(shè)置定時(shí)器
self.time1 = 0
self.time2 = 0
self.schedule(self.update_systems)
self.schedule(self.update_text)
# 更新文字部分的動(dòng)畫效果,實(shí)現(xiàn)逐字顯示
def update_text(self, dt):
self.time1 += dt
if self.time1 >= 1.0:
if self.idx1 <= len(self.texts[0]) - 1:
self.new_text[0] += self.texts[0][self.idx1]
self.text1.element.text = self.new_text[0]
self.idx1 += 1
if self.idx2 <= len(self.texts[1]) - 1 and self.idx1 >= 8:
self.new_text[1] += self.texts[1][self.idx2]
self.text2.element.text = self.new_text[1]
self.idx2 += 1
self.time1 = 0
# 更新粒子效果,每隔一段時(shí)間添加新的效果
def update_systems(self, dt):
self.time2 += dt
if self.time2 >= randint(15, 20):
for i in range(randint(15, 21)):
self.systems = [MyFlower(), MyFlowerworks(), MyExplosion()]
for j in range(randint(1, 3)):
self.add(self.systems[randint(0, 2)], z=randint(3, 8))
self.time2 = 0
self.add(MySpiral())
# 游戲場(chǎng)景類,用來(lái)加載游戲圖層和背景圖層
class MainScene(Scene):
def __init__(self):
super().__init__()
self.add(MainLayer(), z=2)
self.add(BackgroundLayer(), z=0)
if __name__ == '__main__':
director.init(resizable=True, caption="六一快樂(lè)",
width=800, height=600)
director.run(MenuScene())5.結(jié)語(yǔ)
在這個(gè)端午節(jié)的日子里,讓我們沐浴在傳統(tǒng)文化的氛圍中,品嘗粽子的美味,賽龍舟的熱鬧,感受古老的習(xí)俗和民族精神的魅力。讓我們?cè)谶@個(gè)節(jié)日里,緊緊團(tuán)聚在一起,共同傳承和守護(hù)這個(gè)千年的傳統(tǒng)節(jié)日,祝福所有人都能在端午節(jié)里收獲快樂(lè)和幸福?。?!
以上就是利用Python繪制端午節(jié)祝福動(dòng)畫的詳細(xì)內(nèi)容,更多關(guān)于Python繪制端午節(jié)動(dòng)畫的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
判斷PyTorch是GPU版還是CPU版的方法小結(jié)
PyTorch作為當(dāng)前最流行的深度學(xué)習(xí)框架之一,支持在CPU和GPU(NVIDIA CUDA)上運(yùn)行,所以對(duì)于深度學(xué)習(xí)開發(fā)者來(lái)說(shuō),正確識(shí)別PyTorch版本至關(guān)重要,下面小編將全面介紹如何判斷你的PyTorch安裝版本,并提供詳細(xì)的案例分析和問(wèn)題解決方案,需要的朋友可以參考下2025-04-04
python生成指定長(zhǎng)度的隨機(jī)數(shù)密碼
這篇文章主要介紹了python生成指定長(zhǎng)度的隨機(jī)密碼示例,密碼使用數(shù)字和字母組合,大家參考使用吧2014-01-01
python 哈希表實(shí)現(xiàn)簡(jiǎn)單python字典代碼實(shí)例
這篇文章主要介紹了python 哈希表實(shí)現(xiàn)簡(jiǎn)單python字典代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
Python plt.imshow函數(shù)及其參數(shù)使用
plt.imshow()是Matplotlib庫(kù)中的一個(gè)函數(shù),主要用于顯示圖像或矩陣數(shù)據(jù),本文主要介紹了Python plt.imshow函數(shù)及其參數(shù)使用,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02
Python實(shí)現(xiàn)對(duì)比兩張圖片并標(biāo)記差異
這篇文章主要為大家詳細(xì)介紹了使用Python對(duì)比兩張CAD圖并標(biāo)記差異的解決方案,文中的示例代碼簡(jiǎn)潔易懂,具有一定的借鑒價(jià)值,有需要的小伙伴可以參考一下2025-04-04
PyQt5 實(shí)現(xiàn)給無(wú)邊框widget窗口添加背景圖片
這篇文章主要介紹了PyQt5 實(shí)現(xiàn)給無(wú)邊框widget窗口添加背景圖片的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03
Python連接數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)查詢的操作代碼
這篇文章主要介紹了Python連接數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)查詢的操作代碼,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-06-06
對(duì)python中的 os.mkdir和os.mkdirs詳解
今天小編就為大家分享一篇對(duì)python中的 os.mkdir和os.mkdirs詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10

