pygame问题加载图像(精灵) [英] pygame issue loading images (sprites)

查看:50
本文介绍了pygame问题加载图像(精灵)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

"""
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启动器打开文件时,出现以下错误消息:

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

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

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

推荐答案

这实际上不是pygame的问题,而是加载文件的一般问题.尝试打开文件以进行读取,您可能会遇到相同的问题:

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

您正在使用相对"图像文件.这意味着您的程序将在该文件的当前工作目录下查找.您可以通过检查os.getcwd()来了解什么.另一种路径是OS X上的绝对"路径.这仅表示以斜杠开头的路径.

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.

我常用的技巧是加载相对于我的游戏源代码的图像.例如,如果dude.png与python代码位于同一目录中,那么您总是可以这样找到它:

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.

这篇关于pygame问题加载图像(精灵)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆