这是代码:
"""
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 和 Python 2.7.5 上使用 Komodo Edit 8
最佳答案
这不是真正的 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)
希望这对您有所帮助。您可能会在有关加载文件和文件路径的一般问题下找到更多信息。
关于image - pygame问题加载图像( Sprite ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17126521/