How to make the path to songs in pygame relative

后端 未结 1 771
遇见更好的自我
遇见更好的自我 2021-01-27 00:24

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

相关标签:
1条回答
  • 2021-01-27 00:56

    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

    0 讨论(0)
提交回复
热议问题