Change the image in the list according to time in pygame

Viewed 67

I put some pictures in the list. As time goes by, the list index increases, so I hope these pictures change. But I hope the game ends when the index of the list grows to the end. I want to turn the index back to zero so that the game ends right away. But error messages keep popping up like this.

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

Is there any way to solve this problem?

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 Answers

Solution 1:

You need to check whether self.index is greater than or equal to len(self.images). The valid indices of a list of length 5 are 0, 1, 2, 3 and 4:

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

Solution 2:

If you want to show the last image for a longer period, you need to clamp the index when you get it form the list:

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