如何在 pygame 中将 sprite 制作为 gif?

How do I make a sprite as a gif in pygame?

所以我有了一个游戏的想法,你可以在控制直升机的同时躲避抛射物。我想知道您是否可以将精灵显示为 gif,或者类似于两张图像每几分之一秒切换一次。我知道如何让精灵显示为一张图片:

self.surf = pygame.image.load("example.png").convert()

但我想知道这是否有效果:

self.surf = pygame.image.load("example.gif").convert()

不幸的是,它只显示了 gif 中的第一张图片。 这是动图:

编辑:好的,所以我查看了答案并尝试在我的代码中实现它们,但后来一切都太混乱了,我试图做一些更简单的事情。这是我想出的:

    if play == 1:
        self.surf = pygame.image.load("Image2.png").convert()
        pygame.display.update()
        play = 2
        time.sleep(.2)
    if play == 2:
        self.surf = pygame.image.load("Image1.png").convert()
        pygame.display.update()
        play = 1
        time.sleep(.2)

但是,我所做的只是将玩家精灵显示为图像 1。我可以添加什么来使它正常工作吗?

Pygame 不能做 gif,但如果你真的想,你可以逐帧动画,一次一张图片。

PyGame respectively the pygame.image module can only handle non-animated GIFs.
但是在 PyGame 主页上介绍了 GIFImage 库:

This library adds GIF animation playback to pygame.


另一种选择是使用 Pillow library (pip install Pillow).

编写一个函数,可以将 PIL 图像转换为 pygame.Surface:
(另见 PIL and pygame.image

def pilImageToSurface(pilImage):
    mode, size, data = pilImage.mode, pilImage.size, pilImage.tobytes()
    return pygame.image.fromstring(data, size, mode).convert_alpha()

使用 PIL 库逐帧加载 GIF:
(另见 Extracting The Frames Of An Animated GIF Using Pillow

def loadGIF(filename):
    pilImage = Image.open(filename)
    frames = []
    if pilImage.format == 'GIF' and pilImage.is_animated:
        for frame in ImageSequence.Iterator(pilImage):
            pygameImage = pilImageToSurface(frame.convert('RGBA'))
            frames.append(pygameImage)
    else:
        frames.append(pilImageToSurface(pilImage))
    return frames

另见 Load animated GIF 和一个简单的动画 gif 查看器示例:

import pygame
from PIL import Image

def pilImageToSurface(pilImage):
    mode, size, data = pilImage.mode, pilImage.size, pilImage.tobytes()
    return pygame.image.fromstring(data, size, mode).convert_alpha()

def loadGIF(filename):
    pilImage = Image.open(filename)
    frames = []
    if pilImage.format == 'GIF' and pilImage.is_animated:
        for frame in ImageSequence.Iterator(pilImage):
            pygameImage = pilImageToSurface(frame.convert('RGBA'))
            frames.append(pygameImage)
    else:
        frames.append(pilImageToSurface(pilImage))
    return frames
 
pygame.init()
window = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()

gifFrameList = loadGIF("my_gif.gif")
currentFrame = 0

run = True
while run:
    clock.tick(20)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill(0)

    rect = gifFrameList[currentFrame].get_rect(center = (250, 250))
    window.blit(gifFrameList[currentFrame], rect)
    currentFrame = (currentFrame + 1) % len(gifFrameList)
    
    pygame.display.flip()

您可以使用 pygame.Surface 个对象的列表来生成一个 Spritesheet