pythonpygameselfos.walk

IndexError: list index out of range pygame


It says that the list index is out of range, and I don't know why. Does anyone know how to fix the problem?

Code for thing I'm importing

from os import walk
import pygame

def import_folder(path):
    surface_list = []

    for _, __, img_files in walk(path):
        for image in img_files:
            full_path = path + '/' + image
            image_surf = pygame.image.load(full_path).convert_alpha()
            surface_list.append(image_surf)

    return surface_list

Code for thing I'm using it in:

import pygame
from support import import_folder

class Player(pygame.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.import_character()
        self.frame_index = 0
        self.animation_speed = 0.15
        self.image = self.animations['run'][self.frame_index]
        
        # Player Movement

        self.direction = pygame.math.Vector2(0, 0)
        self.speed = 8
        self.gravity = 0.8
        self.jump_speed = -16

    def import_character(self):
        character_path = '../graphics/character/'
        self.animations = {'idle':['idle'], 'run':[], 'jump':[], 'fall':[]}

        for animation in self.animations.keys():
            full_path = character_path + animation
            self.animations[animation] = import_folder(full_path)

Full Error Code (starting from Traceback):

Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\PlatformerGame.py", line 
13, in <module>
level = level(level_map, window)
File "C:\Users\Daniel\Desktop\level.py", line 11, in 
__init__
self.setup_level(level_data)
File "C:\Users\Daniel\Desktop\level.py", line 27, in 
setup_level
player_sprite = Player((x, y))
File "C:\Users\Daniel\Desktop\player.py", line 10, in 
__init__
self.image = self.animations['run'][self.frame_index]
IndexError: list index out of range

Solution

  • Your image files are not loaded properly. If the file path is not correct wrong, walk(path) returns nothing.
    It is not enough to put the files in the same directory or sub directory of the project. You also need to set the working directory. The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python script.
    The name and path of the file can be retrieved with __file__ and the current working directory can be changed with os.chdir(path).

    Add the following at the beginning of the main code to set the working directory to the same as the main script's directory:

    import os
    os.chdir(os.path.dirname(os.path.abspath(__file__)))