在PyGame中使用GIF

问题描述 投票:3回答:1

我阅读了有关如何在PyGame中使用GIF的信息,其中大多数人都说过将GIF拆分为图像,并使用列表渲染它们,我尝试实现这一点,但是得到了一个静态图像。我的猜测是对我来说太快了。我还尝试了一个名为GIFImage here的库,但是它失败了,并产生了相同的静态图像。编辑:静态图片是'idle / idle(4).jpg'

代码:

import pygame
from random import *
pygame.init()
screen = pygame.display.set_mode((400, 300))
running = True
spriteVY = 3
clock = pygame.time.Clock()

idle_imgs = (
    "idle/idle (1).jpg",
    "idle/idle (2).jpg",
    "idle/idle (3).jpg",
    "idle/idle (4).jpg"
)

class MySprite(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.vel = (0, 0)
        self.image = pygame.Surface((100, 200))
        self.image.fill((255, 255, 255))
        self.rect = self.image.get_rect(topleft = (x, y))

class Platform(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((100, 10))
        self.image.fill((142, 212, 25))
        self.rect = self.image.get_rect(topleft = (x, y))

sprite = MySprite(100, 100)
platform = Platform(50, 20)
group = pygame.sprite.Group([sprite, platform])

on_ground = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if pygame.key.get_pressed()[pygame.K_SPACE]: sprite.rect.y -= 20
    if pygame.key.get_pressed()[pygame.K_d]: sprite.rect.x += 10
    if pygame.key.get_pressed()[pygame.K_a]: sprite.rect.x -= 10

    if platform.rect.colliderect(sprite.rect):
        pass
    if sprite.rect.x <= 0:
        sprite.rect.x = 0
    if sprite.rect.x >= 300:
        sprite.rect.x = 300
    if sprite.rect.y < 100:
        on_ground = False
    if sprite.rect.y >= 100:
        spriteVY = 0
        on_ground = True
        sprite.rect.y = 100
    if not on_ground:

        sprite.rect.y += spriteVY
        spriteVY += 1
    screen.fill((0, 0, 0))
    group.draw(screen)
    for img in idle_imgs:
        print(img)
        chosen_img = pygame.image.load(img)
        screen.blit(chosen_img, ((100, 100)))
    pygame.display.flip()
    clock.tick(24)
python pygame gif
1个回答
0
投票

这是相关代码:

for img in idle_imgs:
    print(img)
    chosen_img = pygame.image.load(img)
    screen.blit(chosen_img, ((100, 100)))
pygame.display.flip()
clock.tick(24)

问题相对明确。您将4张图像都抹到了屏幕上,但是直到最后一张图像之后才调用flip()。这意味着最后一个是实际显示的唯一一个。

要绘制的screen曲面在调用flip()之前不会发送到实际的显示曲面,因此除最后一个以外的所有图像都没有实际发送到显示器。

您可以尝试通过将flip()放入for循环来解决该问题,但这也无法真正解决您的问题。它将把图像推到实际的显示,但是它们显示得非常快(这是您当前错误地认为正在发生的事情)。您需要通过调用clock.tick(24)将其降低到帧速率。但这会干扰您的游戏循环。因此,这不是正确的方法。

通常,对于这种事情,我会带有一个标志,指示它是否应该显示空闲循环(当它应该显示它时,它类似于idling = True)。然后,您需要另一个变量来跟踪要显示的当前空闲帧(例如idle_frame之类的内容)。当到达最后一帧(idle_frame == len(idle_imgs))时,将其重置为0,然后重新开始。

© www.soinside.com 2019 - 2024. All rights reserved.