鱼在pygame游泳

时间:2013-04-18 05:46:50

标签: python-2.7 pygame python-imaging-library gif

我想使用python pygame模块制作2D" fishtank"。

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

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

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

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

1 个答案:

答案 0 :(得分: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