2013-04-18 89 views
0

我想使用python pygame模块来制作2D“fishtank”。鱼游在pygame

基本上我会加载一个jpg图像作为背景,并加载描绘鱼游动的gif动画图像并使其移动。

我知道如何制作静态图片移动,但如何在图片本身制作动画时使图片移动。

我有PIL安装,确定是否需要使用它。

如果这不起作用,我也可以将gif文件拆分成几个静态帧并循环使它们每个都显示在屏幕上。当后者发布时,前者需要删除,如何删除?

回答

0

下面是我在名称中使用获取类pygame的动画工作:

class Animation(pygame.sprite.Sprite): 
    def __init__(self, img, fps = 6): 
     # Call the parent class (Sprite) constructor 
     pygame.sprite.Sprite.__init__(self) 

     # Slice source image to array of images 
     self.images = self.loadSliced(img) 

     # Track the time we started, and the time between updates. 
     # Then we can figure out when we have to switch the image. 
     self._start = pygame.time.get_ticks() 
     self._delay = 1000/fps 
     self._last_update = 0 
     self._frame = 0 
     self.image = self._images[self._frame] 

def loadSliced(w, h, filename): 
    """ 
    Pre-conditions: 
     Master can be any height 
     Sprites frames must be the same width 
     Master width must be len(frames)*frames.width 

    Arguments: 
     w -- Width of a frame in pixels 
     h -- Height of a frame in pixels 
     filename -- Master image for animation 
    """ 
    images = [] 

    if fileExists(img, "Animation Master Image"): 
     master_image = pygame.image.load(filename).convert_alpha() 
     master_width, master_height = master_image.get_size() 
     for i in range(int(master_width/w)): 
      images.append(master_image.subsurface((i*w, 0, w, h))) 
    return images 

def update(self, t): 
    # Note that this doesn't work if it's been more than self._delay 
    # time between calls to update(); we only update the image once 
    # then. but it really should be updated twice 

    if t - self._last_update > self._delay: 
     self._frame += 1 
     if self._frame >= len(self._images): 
      self._frame = 0 
      self.image = self._images[self._frame] 
      self._last_update = t 
     self.image = self._images[self._frame] 
     self._last_update = t 

def getFrame(self, screen): 
    # Update Frame and Display Sprite 
    self.update(pygame.time.get_ticks()) 
    return self.image 
+0

看起来不错 - 你能补充一点,就是介绍如何你在做什么帮助OP? – GHC 2013-04-18 06:09:41

+0

让我检查一下,非常感谢分享。 – 2013-04-18 08:15:44

+0

@GHC:他从单个图像创建** spritesheet **。然后使用定时器来切换'图像'。 – ninMonkey 2013-04-18 17:18:41