gpt4 book ai didi

python - 在 PyGame 中使用 GIF

转载 作者:行者123 更新时间:2023-12-05 07:07:57 30 4
gpt4 key购买 nike

我阅读了有关如何在 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)

最佳答案

这是相关代码:

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 个图像 blit 到屏幕,但直到最后一个图像之后才调用 flip()。这意味着最后一个是唯一会显示的。

在调用 flip() 之前,您正在绘制的 screen 表面不会发送到实际显示表面,因此除了最后一个图像外,没有其他图像一个被发送到显示器。

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

通常对于这种事情我会有一个标志指示它是否应该显示空闲循环(类似于 idling = True 当它应该显示它时)。然后您需要另一个变量来跟踪要显示的当前空闲帧(比如 idle_frame)。当它到达最后一帧 (idle_frame == len(idle_imgs)) 时,您将其重置为 0 并重新开始。如果您不想播放空闲动画,请设置 idling == False 并跳过该显示代码。

这应该会给您足够的帮助来自己编写代码。

我注意到其他会导致性能问题的因素。您在列表中有图像的名称。相反,您实际上应该将图像加载到列表中并显示已加载的图像。每次从文件中加载它们是不必要的缓慢。此外,您应该在加载图像后对图像运行 convert()(如果图像具有透明度,则运行 convert_alpha())。这对于加快图像显示速度很重要。您可以阅读 convert()convert_alpha() here .

关于python - 在 PyGame 中使用 GIF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61995907/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com