pygame.error: 文件不是windows.bmp文件(已查看其他类似问题但未成功)
我刚开始接触pygame,正在看一本叫《用Python和Pygame开始游戏开发》的书。我几乎把书里的示例代码都敲了一遍,但总是出现同样的错误:“pygame错误:文件不是windows.bmp文件”。我想像书里那样加载jpg/png格式的图片。我确定我在正确的目录下,想用的图片格式和书里的示例是一样的。我也查过解决办法,但没有一个对我有效。
书里的代码如下(我用的是python 2.7.4,Ubuntu 13.04,还有(我想)pygame 1.2.15):
background_image_filename = 'sushiplate.jpg'
mouse_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
这是我目前的代码版本:
import os.path
background = os.path.join('Documents/Python/Pygame','Background.jpg')
cursor_image = os.path.join('Documents/Python/Pygame','mouse.png')
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
谢谢你的帮助 :)
1 个回答
1
我几乎可以肯定,你的路径设置是错的。在你的代码中,你使用了相对路径,这意味着pygame在你的工作目录的子文件夹中寻找你的资源(也就是你运行代码的那个文件夹)。
下面是我认为你应该如何组织文件的示例,以及你的代码在寻找什么。在这个例子中,你会在 /home/your_username/Documents/my_games
(或者 ~/Documents/my_games
)这个目录下打开命令提示符,并运行 python your_game_script.py
。
|---home
|---your_username
|---Documents
|---some_subfolder
|---my_games
|---your_game_script.py
|---Documents
|---Python
|---Pygame
|---Background.jpg
|---mouse.png
这样是可以工作的,但我怀疑你的文件夹并不是这样设置的,这就是它不工作的原因。如果你在和你的游戏脚本同一个文件夹里运行一个交互式的 python
提示符,试试下面的命令:
import os
os.path.isfile('Documents/Python/Pygame/Background.jpg')
os.path.isfile('Documents/Python/Pygame/mouse.png')
我猜结果会是假的,意味着在那个子文件夹里找不到文件。我建议你按照以下结构来组织你的游戏文件:
|---my_game
|---your_game_script.py
|---images
|---Background.jpg
|---mouse.png
然后在 your_game_script.py
中,你可以用以下方式加载文件:
background = 'images/Background.jpg' #relative path from current working dir
cursor_image = 'images/mouse.png' #relative path from current working dir
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()