金币动画本身相对简单,就是4张图片不断切换,如图7‑3所示。

图7‑3金币闪烁图片
参考马里奥走路动画的代码,相信完成金币动画并不困难。创建一个金币类,并将其放置在item目录下,代码如下所示:
07\01\Item\FlashingCoinAnimation.py
|
from pygame import Rect from game_globals.Globals import Globals from game_globals.constants import MAP_BLOCK_SIZE
# 闪烁金币动画 class FlashingCoinAnimation(object):
# 帧动画 frames = [Globals.itemImageCache.flashingCoinImg1, Globals.itemImageCache.flashingCoinImg1, Globals.itemImageCache.flashingCoinImg2, Globals.itemImageCache.flashingCoinImg3, Globals.itemImageCache.flashingCoinImg4]
# 构造方法,记录初始坐标 def __init__(self, x, y): self.rect = Rect(x, y, MAP_BLOCK_SIZE, MAP_BLOCK_SIZE) self.frameDuration = 100 # 每帧显示时间,单位为毫秒 self.frameIndex = 0 # 当前帧的下标 self.elapsedTime = 0 # 时间差累计
# 更新动画 def update(self, keys, deltaTime): # 时间差累计 self.elapsedTime += deltaTime
# 切换动画图片 if self.elapsedTime > self.frameDuration: self.elapsedTime -= self.frameDuration # 减去差值 self.frameIndex += 1 if self.frameIndex >= len(self.frames): self.frameIndex = 0
# 显示图片 Globals.screen.blit(self.frames[self.frameIndex], self.rect)
|
请注意,构造方法中没有传递screen对象,因为它在很多地方都被使用,传递参数会很麻烦,所以,我们在游戏初始化时将screen对象放入Globals对象中,便于全局访问。在帧动画中,第一个金色闪亮的图片被使用了两次,是因为它的显示时间稍长。
接下来,我们将一个金币放置到游戏中,代码如下所示:
07\01\Game.py
|
def __init__(self): ……省略…… # 马里奥 self.mario = Mario(10, 100, self.screen)
# 一个金币 from item.FlashingCoinAnimation import FlashingCoinAnimation self.coin = FlashingCoinAnimation(100, 100)
def run(self): ……省略…… # 更新马里奥 self.mario.update(keys, deltaTime)
# 更新金币 self.coin.update(keys, deltaTime) |
在创建马里奥对象时,同时创建一个金币对象,并在更新马里奥对象时也更新金币对象,以此实现金币动画。运行程序,画面如图7‑4所示,金币闪烁效果非常不错。

图7‑4一个闪烁的金币