如何使 pygame 中歌曲的路径相对

How to make the path to songs in pygame relative

我正在 python 开发一个简单的 Snake 游戏,它在家里按预期工作,但是当我将代码放在 github 上时,它找不到通往歌曲,我想让这个路径相对,而不是绝对,所以它适用于每台计算机。

这是歌曲文件的部分代码 -

 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- 它在家里工作,在其他任何地方都可以工作,我试图通过使路径成为相对路径来找到解决该问题的方法,我只是不知道该怎么做。有人可以帮忙吗?

标准方法是使用应用程序找到文件夹的真实路径

import os, sys

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

然后用它来创建文件的真实路径

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

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

或者您必须将 "current working directory" (CWD) 更改为应用程序文件夹。

os.chdir(APP_FOLDER)

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

您可以使用

检查当前工作目录
print(os.getcwd())

顺便说一句: 如果没有这种方法,问题不仅会出现在不同计算机上 运行 时,还会出现在同一台计算机上来自不同文件夹的 运行 时- 所以当你在桌面上创建 shortcut/icon 执行程序时会出现问题 python game_folder/game.py