使用 pygame 包含 cx_Freeze 中的整个文件夹

Include entire folders in cx_Freeze with pygame

我一直在关注如何为 pygame 文件夹进行 cx_freeze 设置的教程。这是我想出的...

import cx_Freeze
executables = [cx_Freeze.Executable("mainGame - Copy.py")]
cx_Freeze.setup(
    name = "Cave",
    version = "1.0",
    author = "Owen Pennington",
    options = {"build_exe": {"packages":["pygame"], "include_files":["floor_heart.wav"]}},
    executables = executables
    )

但是我的其余文件都在文件夹中。然后这些文件夹里面还有文件夹。例如,我有一个文件夹(路径目录)C:CaveGame\Sprites,这个文件夹包含许多其他文件夹,C:CaveGame\Sprites\FloorsC:CaveGame\Sprites\Lava 等...然后我还有一个文件夹 C:CaveGame\Music拥有我所有的音乐文件和音效。我怎样才能让这些都在设置中工作???

您只需要在 options 词典中包含上层目录项:

setup(name='Widgets Test',
      version = '1.0',
      description = 'Test of Text-input Widgets',
      author = "Fred Nurks",
      options = { "build_exe": {"packages":["pygame"], "include_files":["assets/", "music/"] } },
      executables = executables
      )

以上示例将包括文件 assets/images/blah.pngmusic/sounds/sproiiiing.ogg 及其正确的目录。 该顶级文件夹下的所有内容 都被拉入 lib/

当你去加载这些文件时,有必要计算出这些文件的确切路径。但是执行此操作的常规方法不适用于 cxFreeze。在 https://cx-freeze.readthedocs.io/en/latest/faq.html ~

参考常见问题解答
if getattr(sys, 'frozen', False):
    EXE_LOCATION = os.path.dirname( sys.executable ) # frozen
else:
    EXE_LOCATION = os.path.dirname( os.path.realpath( __file__ ) ) # unfrozen

显然您需要模块 sysos.path

然后加载文件时,确定完整路径 os.path.join:

my_image_filename = os.path.join( EXE_LOCATION, "assets", "images", "image.png" )
image = pygame.image.load( my_image_filename ).convert_alpha()

编辑:如果您在 Windows 下构建,您还需要包括 Visual C 运行时:https://cx-freeze.readthedocs.io/en/latest/faq.html#microsoft-visual-c-redistributable-package。将 include_msvcr 添加到 options

options = { "build_exe": { "include_msvcr", "packages":["pygame"] #...