Search code examples
pythonpygamefile-structure

My file structure for a PyGame project throws countless errors - what am I doing wrong?


I'm working on a project for college, and one of the objectives is to have a functioning and efficient file structure to contain the game. In theory, I completely get this. I've made file structure diagrams and begun coding my modules - but almost everything I do seems to throw an error. Here's a sample of my file structure.

/main folder

    main.py

    /gameloop
        mainGameLoop.py
        /images
            background1.png
            background2.png
        /data


    /sprites
        spriteClasses.py
        /images
            image1.png
            image2.png
        /data
            statsSheet1.txt
        

    /menus
        pauseMenu.py
        startMenu.py
        saveMenu.py
        /images
            image3.png
            image4.png
        /data


    /items
        itemClasses.py
        /images
            image5.png
            image6.png
        /data

main.py calls mainGameLoop.py in /gameloop. However, any entities that have been loaded into mainGameLoop.py (such as background images or fonts) cannot be accessed by main.py, and I get an error.

For example, importing mainGameLoop into main.py and calling a showBackground function from it gives the error: "FileNotFoundError: [Errno 2] No such file or directory: 'background1.png'"

Similarly, I want to be able to call pauseMenu from inside mainGameLoop. What's the best way to do this?


Solution

  • It is not sufficient to put the files in the same directory or sub directory. You also need to set the working directory. The resource (image, font, sound, etc.) 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__. The current working directory can be changed with os.chdir(path).
    Put the following at the beginning of your code to set the working directory to the same as the script's directory:

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

    If you do this in main.py, you can access the files from any other module in your project using a relative path. e.g.:

    imag = pygame.image.load('gameloop/images/background.png')