How to make the path to songs in pygame relative

浪尽此生 提交于 2021-02-05 09:12:04

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/47729260/how-to-make-the-path-to-songs-in-pygame-relative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!