如何使pygame中的歌曲路径相对 [英] How to make the path to songs in pygame relative

查看:112
本文介绍了如何使pygame中的歌曲路径相对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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- 它在家里和其他地方都有效,我试图找到一种方法来解决这个问题,通过使路径相对我只是不知道如何.有人可以帮忙吗?

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?

推荐答案

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

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()

或者您必须将当前工作目录" (CWD) 更改为应用程序文件夹.

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

os.chdir(APP_FOLDER)

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

您可以使用

print(os.getcwd())

<小时>

顺便说一句:如果没有这种方法,问题不仅在于您在不同的计算机上运行,​​而且在于您在同一台计算机上的不同文件夹中运行时 - 因此在桌面上创建快捷方式/图标时会出现问题它以 python game_folder/game.py


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

这篇关于如何使pygame中的歌曲路径相对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆