Search code examples
pythonlistpygameindex-error

List index out of range syntax error


I am creating a 2D fighting via pygame. An error that occurred when I first started coding the game has crept back up on the same line of code from before and I managed to fix it, but this time I am not to sure how to resolve a solution.

class player:
    def __init__(self):
        self.x = 200
        self.y = 300
        self.y_change = 0
        self.ani_speed_init = 8
        self.ani_speed = self.ani_speed_init
        self.ani_stand =glob.glob("characters\\Naruto\\Standing\\naruto_s*.png")
        self.ani_stand.sort()
        self.moving = True
        self.ani_pos=0
        self.ani_max = len(self.ani_stand)-1

The next line of code is where the index out of range error is occurring. This is located in the player1 class in the __init__ subroutine. This line of code loads an image in position 0 of the list.

self.img_stand = pygame.image.load(self.ani_stand[0])
self.ani_walk = glob.glob("characters\\Naruto\\Walk\\naruto_w*.png")
self.ani_walk.sort()
self.ani_pos=0
self.ani_max_walk = len(self.ani_walk)-1

If new frames are added, finds out how many frames there are and when it hits the maximum ammount loops back to Zero in the array of sprites.

self.img_walk = pygame.image.load(self.ani_walk[0])
self.img = pygame.image.load(self.ani_stand[0])
self.jumping = False
self.velocity_index = 0
self.rect = self.img.get_rect()
self.count = 0
self.update(0)

This is the update function in the player 1 class. This section of code is where I previously managed to amend the error the first time.

def update(self,pos):
    if pos != 0: 
        self.ani_speed-=1
        self.x+=pos

        if self.ani_speed == 0:
            self.img = pygame.image.load(self.ani_walk[self.ani_pos])
            self.ani_speed = self.ani_speed_init
            if self.ani_pos == self.ani_max_walk:
                self.ani_pos = 0
            else:
                self.ani_pos += 1

This else block, situated in the update function, was the specific section of code used to resolve a solution but i cant seem to think of anymore logical solutions to fix the error.

else:
    self.ani_speed-=1
    if self.moving: 
        self.ani_speed = self.ani_speed_init
        if self.count==8:
            if self.ani_pos >= self.ani_max:
                self.ani_pos = 1
            else:
                self.ani_pos+=1
        elif self.ani_pos>3:
            self.ani_pos=1

        self.img = pygame.image.load(self.ani_stand[self.ani_pos-1])
gameDisplay.blit(self.img,(self.x,self.y))

Solution

  • The error doesn't have to do anything with Pygame. Your call to glob

    glob.glob("characters\\Naruto\\Standing\\naruto_s*.png")
    

    returns an empty array. Check what directory your script is executed in and whether the files at the specified path actually exist.