Pygame问题:加载图像(精灵)时出现问题。

3
这是代码:

这是代码:

"""
Hello Bunny - Game1.py
By Finn Fallowfield
"""
# 1 - Import library
import pygame
from pygame.locals import *

# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))

# 3 - Load images
player = pygame.image.load("resources/images/dude.png")

# 4 - keep looping through
while 1:
    # 5 - clear the screen before drawing it again
    screen.fill(0)
    # 6 - draw the screen elements
    screen.blit(player, (100,100))
    # 7 - update the screen
    pygame.display.flip()
    # 8 - loop through the events
    for event in pygame.event.get():
        # check if the event is the X button 
        if event.type==pygame.QUIT:
            # if it is quit the game
            pygame.quit() 
            exit(0)

当我尝试使用Python启动器打开文件时,出现以下错误提示:
File "/Users/finnfallowfield/Desktop/Code/Game1.py", line 15, in <module>
    player = pygame.image.load("resources/images/dude.png")
pygame.error: Couldn't open resources/images/dude.png

顺便说一下,我正在运行一个移植的64位pygame版本。我在OS X Mountain Lion上使用Komodo Edit 8和Python 2.7.5。

1个回答

1
这并不是一个pygame问题,而是一个关于文件加载的普遍问题。你可能会在尝试打开读取文件时遇到相同的问题:
f = open("resources/images/dude.png")

你在使用相对路径对图像文件进行操作。这意味着你的程序将在当前工作目录下查找该文件。你可以通过检查os.getcwd()函数来了解当前工作目录。另一种类型的路径是OS X上的“绝对路径”。这仅仅意味着路径以斜杠开头。
我经常使用的一个技巧是相对于游戏源代码加载图像。例如,如果dude.png与python代码在同一个目录中,你总是可以这样找到它:
base_path = os.path.dirname(__file__)
dude_path = os.path.join(base_path, "dude.png")
player = pygame.image.load(dude_path)

希望这能有所帮助。您可以在有关加载文件和文件路径的常见问题下找到更多信息。

好的,谢谢,我会尝试的!编辑:哦等等,现在我遇到了这个错误:File "/Users/finnfallowfield/Desktop/Code/Game1.py", line 15, in <module> basePath = os.path.dirname(file) NameError: name 'os' is not defined - exitcode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接