1

Why does it says that couldn't open shooting_game\player.png on Pygame? Here's my code so far:

import pygame
import os

width, height = 500, 400

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Shooter Game")

player = pygame.image.load(os.path.join("shooter_game", "player.png"))

This gives me a error:

Exception has occurred: error
Couldn't open shooter_game/player.png
  File "C:\python_games\shooter_game\game.py", line 11, in <module>
    player = pygame.image.load(os.path.join("shooter_game", "player.png"))

I maked sure that player.png's folder was in the same folder as game.py's folder.

Can someone help me figure out this problem?

Thanks.

Zachary
  • 21
  • 3

2 Answers2

0

If player.png is in the same folder as game.py, you should look for it in the shooter_game directory:

player = pygame.image.load("player.png")
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Relative paths are based on current working directory, not the script's directory. If you happen to have changed to the script's directory to run it, they are both the same and it works by shear luck. Otherwise you'll get this error. Python scripts have a __file__ variable holding the script's file name. You can leverage that to find the directory.

player = pygame.image.load(os.path.join(
    os.path.dirname(os.path.abspath(__file__))), 
    "player.png")

pathlib has an alternate way of handling file system paths

from pathlib import Path
player = pygame.image.load(Path(__file__).absolute().parent/"player.png")
tdelaney
  • 73,364
  • 6
  • 83
  • 116