How to fix mistake linked with creature of animation?

Viewed 29

I have already found site giving information about how to make a animation of sprite. There are many mistakes, so some of them fixed, however, 1 mistake couldn't fix. Fix, please!

    def __init__(self):
        super(MySprite, self).__init__()
        self.images = []
        self.images.append(pygame.image.load('mouse_level1.1.png'))
        self.images.append(pygame.image.load('mouse_level1.1.png'))
        self.images.append(pygame.image.load('mouse_level1.1.png'))
 
        self.index = 0
 
        self.image = self.images[self.index]
 
        self.rect = pygame.Rect(5, 5, 150, 198)
 
    def update(self):
        self.index += 1
 
        if self.index > len(self.images):
            self.index = 0
        
        self.image = self.images[self.index]

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

1 Answers

The first thing (not related to the subject), you are loading the same picture mouse_level1.1.png several times:

self.images.append(pygame.image.load('mouse_level1.1.png'))

Your animation will be still and not changing in this case.

The second thing, your array has only 3 elements, with indexes 0, 1 and 2. And your index exceeds this max range and cannot be equal to the len(self.images) (i.e cannot be equal to 3)

Update this code:

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

to

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