根据 pygame 中的时间更改列表中的图像

Change the image in the list according to time in pygame

我在列表中放了一些图片。 随着时间的推移,列表索引增加,所以我希望这些图片改变。 但我希望当列表的索引增长到最后时游戏结束。 我想将索引调回零,以便游戏立即结束。 但是错误消息一直这样弹出。

self.image = self.images[self.index]
IndexError: list index out of range

有什么办法可以解决这个问题吗?

class AnimatedSprite(pygame.sprite.Sprite):

    def __init__(self, position):

        super(AnimatedSprite, self).__init__()
        size = (68, 75)

        images = []
        images.append(pygame.image.load('IMG/DinoRun1.png'))
        images.append(pygame.image.load('IMG/DinoRun2.png'))
        images.append(pygame.image.load('IMG/DinoJump.png'))
        images.append(pygame.image.load('IMG/DinoDuck1.png'))
        images.append(pygame.image.load('IMG/DinoDuck2.png'))

        self.rect = pygame.Rect(position, size)
        self.images = [pygame.transform.scale(image, size) for image in images]

        self.index = 0
        self.image = images[self.index]

        self.animation_time = 1
        self.current_time = 0

    def update(self, mt):
        self.current_time += mt

        if self.current_time >= self.animation_time:
            self.current_time = 0

            self.index += 1
            if self.index == len(self.images):
                done = True
                run = False
            if self.index > len(self.images):
                self.index = 0


            self.image = self.images[self.index]

解决方案 1:

您需要检查 self.index 是否大于或等于 len(self.images)。长度为 5 的列表的有效索引是 0、1、2、3 和 4:

if self.index >= len(self.images):
    self.index = 0

解决方案 2:

如果你想显示最后一张图片更长的时间,你需要在从列表中获取它时限制索引:

self.image = self.images[min(self.index, len(self.images) - 1)]