pygame issue loading images (sprites)

十年热恋 提交于 2020-12-31 06:09:17

问题


This is the code:

"""
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)

When I try and open the file with python launcher I get this error message:

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

I am running a ported 64 bit version of pygame, by the way. I use Komodo Edit 8 on OS X Mountain Lion with Python 2.7.5


回答1:


This is not really a pygame issue, but a general problem with loading files. You could get the same problem just trying to open the file for reading:

f = open("resources/images/dude.png")

You are using a "relative" to the image file. This means your program will look under the current working directory for this file. You can know what that is by checking os.getcwd(). The other type of path is an "absolute" path on OS X. This just means a path that starts with a slash.

A common trick I use is to load the images relative to my game source code. For example, if the dude.png is in the same directory as the python code, you could always find it like this:

base_path = os.path.dirname(__file__)
dude_path = os.path.join(base_path, "dude.png")
player = pygame.image.load(dude_path)

Hopefully this helps. You can probably find more information under general questions about loading files and file paths.



来源:https://stackoverflow.com/questions/17126521/pygame-issue-loading-images-sprites

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!