0

我想使用 python pygame 模块制作一个 2D 的“鱼缸”。

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

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

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

如果这不起作用,我还可以将 gif 文件分成几个静态帧,并循环地让每个帧显示在屏幕上。后一张贴的时候,前一张需要去掉,怎么去掉?

4

1 回答 1

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
于 2013-04-18T05:52:10.097 回答