【发布时间】:2020-10-22 08:45:47
【问题描述】:
您好,我目前正在尝试从 Python Crash Course 的第 12 章创建太空入侵。但是,当我尝试将船舶图像添加到游戏中时,我被卡住了。这是外星人入侵的代码:
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
#Overall class to manage game assests and behavior
def __init__(self):
#Initialize the game and create game resources
pygame.init()
self.settings=Settings()
self.screen=pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
pygame.display.set_caption('Alien Invasion')
self.Ship=Ship(self)
def run_game(self):
# Start the main loop for the game
while True:
#Watch for keyboard and mouse events
for event in pygame.event.get():
if event.type==pygame.QUIT :
sys.exit()
#Redraw the screen during each pass through the loop.
self.screen.fill(self.settings.bg_color)
self.Ship.blitme()
#Make the most recently drawn screen visible.
pygame.display.flip()
if __name__=='__main__':
#Make a game instance, and run the game.
ai=AlienInvasion()
ai.run_game()
船号:
import pygame
class Ship:
#A class to manage the ship
def __init__(self, ai_game):
#Initialize the ship and set its starting position
self.screen=ai_game.screen
self.screen_rect=ai_game.screen.get_rect()
#Load the ship image and get its rect.
self.image=pygame.image.load('images/ship.bmp')
self.rect=self.image.get_rect()
#start each new ship at the bottom center of the screen.
self.rect.midbottom=self.screen_rect.midbottom
def blitme(self):
#Draw the ship at its current location
self.scren.bilt(self.image, self.rect)
尝试运行时出现此错误:
Traceback (most recent call last):
File "c:/Users/rico3/OneDrive/Desktop/Python Scripts/Alien Invasion/Alien_Invaders.py", line 39, in <module>
ai=AlienInvasion()
File "c:/Users/rico3/OneDrive/Desktop/Python Scripts/Alien Invasion/Alien_Invaders.py", line 19, in __init__
self.Ship=Ship(self)
File "c:\Users\rico3\OneDrive\Desktop\Python Scripts\Alien Invasion\ship.py", line 12, in __init__
self.image=pygame.image.load('images/ship.bmp')
pygame.error: Couldn't open images/ship.bmp
images 文件夹与 Alien Invasion 文件位于同一文件夹中,但它似乎仍然无法找到 ship 文件。
【问题讨论】:
-
如何启动游戏?图像文件夹与 Alien Invasion 文件位于同一文件夹中是不够的。您还需要将进程的当前目录设置为与 Alien Invasion 文件相同。要检查当前目录是什么,请在调用
pygame.image.load('images/ship.bmp')之前添加:import os; print(os.getcwd())并查看打印的值是否符合您的期望。 -
您的目录分隔符可能有问题。您可以使用
import os和print(os.sep)检查您的操作系统分隔符。如果您的分隔符是反斜杠,那么您必须相应地编辑您的文件路径,同时转义反斜杠。 -
我在 VS 代码终端中启动游戏并使用 Alien Invasion 文件。飞船和外星人入侵的目录匹配,但我仍然收到无法打开的错误。
标签: python image pygame load traceback