有没有其他方法可以将图像、声音或字体等资源加载到 Pygame 中?

有没有其他方法可以将图像、声音或字体等资源加载到 Pygame 中?

问题描述:

我正在 pygame 中开发一款游戏,并且我在 itch.io 上发布了我之前的一些游戏.当我加载图像时,我曾经这样做过:

I am working on a game in pygame and I published some of my previous games on itch.io. When I am loading image I used to do it like this:

player = pygame.image.load(r"C:Usersuserfolderfolder1player.png")

但是当我发布游戏时,其他人无法运行该游戏.我该如何解决这个问题?

But when I publish the game, other people can't run the game. How do I fix this?

将图像文件放在与 Python 文件相同的目录中.将当前工作目录更改为文件所在目录.
文件名和路径可以通过__文件__代码>.当前工作目录可以通过 os.getcwd() 获取 并且可以通过 os.chdir(path)代码>:

Place the image file in the same directory as the Python file. Change the current working directory to the directory of the file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path):

import os

sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)

现在您可以使用相对路径来加载文件:

Now you can use a relative path to load the file:

player = pygame.image.load("player.png")