0

So i've started making a game in Pygame and am trying to import an png of a rock into my game. When I try to to run the game to make sure there are no issues before I blit it onto the screen, it says,

FileNotFoundError: No file '../graphics/test/rock.png' found in working directory

My file setup is, Game > Code > Main.py.

I have tried these:

self.image = pygame.image.load('../graphics/test/rock.png').convert_alpha()

and

self.image = pygame.image.load('/Users/(My name...)/Documents/PythonProjects/Games/Game/graphics/test/rock.png')

the second one worked but it's too long to continously type out. Thanks in advance...

furas
  • 134,197
  • 12
  • 106
  • 148
Quantum
  • 21
  • 3
  • you can always assign long path to variable and later use this variable. OR you can create function which will get filename and it will return full path. – furas Aug 16 '22 at 02:24

2 Answers2

0

You could use the built-in pathlib, set a graphics directory and then join for each image load.

import pathlib
graphics_dir = pathlib.Path("/Users/(My name...)/Documents/PythonProjects/Games/Game/graphics/test/")
image = pygame.image.load(graphics_dir.joinpath("rock.png").convert_alpha()
import random
  • 3,054
  • 1
  • 17
  • 22
0

You can always assign long path to variable and later use this variable.

import os

BASE = '/Users/(My name...)/Documents/PythonProjects/Games/Game'

self.image = pygame.image.load( os.path.join(BASE, 'graphics/test/rock.png') ).convert_alpha()

Or you can create function which will get relative path and it will return full path

BASE = '/Users/(My name...)/Documents/PythonProjects/Games/Game'

def get_image(path)
    return pygame.image.load( os.path.join(BASE, path) ).convert_alpha()

self.image = get_image('graphics/test/rock.png')

Second version can also keep information in some global dictionary and check if you already loaded image.

BASE = '/Users/(My name...)/Documents/PythonProjects/Games/Game'

resources = {}

def get_image(path)
    if path not in resources:
        resources[path] = pygame.image.load( os.path.join(BASE, path) ).convert_alpha()
    return resources[path]

self.image = get_image('graphics/test/rock.png')

To make it even more useful you can generate BASE using __file__ and it should work even if you move all to different folder

BASE = os.path.dirname( os.path.dirname(os.path.abspath(__file__)) )

Because you keep main.py in subfolder so it may need double dirname to move parent folder (../)

BASE = os.path.dirname( os.path.dirname(os.path.abspath(__file__)) )
furas
  • 134,197
  • 12
  • 106
  • 148