exitcode
exitcode

Reputation: 111

pygame issue loading images (sprites)

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

Upvotes: 3

Views: 3222

Answers (1)

Peter Shinners
Peter Shinners

Reputation: 3766

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.

Upvotes: 1

Related Questions