Here's a base class for animated sprites which includes code to ensure that the images are only loaded once. It uses a dictionary of image frames keyed against the classname to achieve this.
import pygame, math, random, sys, os
from pygame.locals import *
IMAGE_PATH = '../res/images/'
class AnimationSprite(pygame.sprite.Sprite):
'''Base class for animated sprites'''
# This will hold a dict of frame lists keyed on the sprite's class name
# The images are only ever loaded once
animationFrames = {}
def __init__(self, spriteGroup):
pygame.sprite.Sprite.__init__(self)
self.frameCount = 0
self.animFrameCount = 1
self.loadImages()
frames = AnimationSprite.animationFrames[self.__class__.__name__]
self.image = frames[self.frameCount]
self.rect = self.image.get_rect()
self.spriteGroup = spriteGroup
self.spriteGroup.add(self)
def update(self, events):
'''Called by the SpriteGroup every tick'''
self.doMove(events)
self.frameCount += 1
if not self.frameSkip == 0 and (self.frameCount % self.frameSkip) == 0:
self.animFrameCount += 1
index = self.animFrameCount % self.numberOfFrames
frames = AnimationSprite.animationFrames[self.__class__.__name__]
self.image = frames[index]
def loadImages(self):
'''Load the animation frames from the composite ship image'''
# See if we've already loaded the image for this sprite
if not AnimationSprite.animationFrames.has_key(self.__class__.__name__):
print 'Loading graphics for: ', self.__class__.__name__
compositeImage = pygame.image.load(os.path.join(IMAGE_PATH, self.imageName)).convert_alpha()
rowOffsetY = 0
frames = []
for i in range(0, self.numberOfFrames):
img = compositeImage.subsurface((self.width * i, 0), (self.width, self.height))
frames.append(img)
AnimationSprite.animationFrames[self.__class__.__name__] = frames
0 comments:
Post a Comment