1

Im working on a simple Snake game in python, and its working as intended here at home, but when I put the code on github, it doesn't find the path to the songs, I want to make this path relative, intead of absolute so it works on every computer.

Here is the part of the code for the song files -

 def game_sound(s):
        """ Include the game sfx and music"""
        if s == 0:
            pygame.mixer.music.load("background.ogg")
            pygame.mixer.music.play(-1)
        elif s == 1:
            pygame.mixer.Sound("eating.wav").play()
        elif s == 2:
            pygame.mixer.Sound("game-over.wav").play()

TL - DR- It works here at home and nowhere else, Im trying to find a way to fix that by making the path relative I just dont know how. Can someone help?

Mateus
  • 47
  • 1
  • 3
  • 6

1 Answers1

2

Standard method is to find real path to folder with application

import os, sys

APP_FOLDER = os.path.dirname(os.path.realpath(sys.argv[0]))

And later use it to create real path to file

full_path = os.path.join(APP_FOLDER, "eating.wav")

pygame.mixer.Sound(full_path).play()

Or you have to change "current working directory" (CWD) to application folder.

os.chdir(APP_FOLDER)

pygame.mixer.Sound("eating.wav").play()

You can check current working directory with

print(os.getcwd())

BTW: without this method problem is not only when you run on different computer but also when you run from different folder on the same computer - so it makes problem when you create shortcut/icon on desktop which executes program as python game_folder/game.py

furas
  • 134,197
  • 12
  • 106
  • 148