我对编码还很陌生,并且一直在《 Make Your Own Python Text Adventure》一书的帮助下尝试使用Python 3编写文本冒险程序。但是,当我尝试以当前状态运行游戏时,仍然会收到AttributeError: 'NoneType' object has no attribute 'intro_text'
。
如果玩家移出设置区域(因为尚没有停止该代码的代码),应该会发生这种情况,但是它总是在初始化时发生,这是不应该的。根据本书的建议,我尝试查看世界的“地图”和Player类的起点,但看不到错误。我希望有人的编码眼睛比我能提供的帮助更大。
这是game.py:
from player import Player
import world
def play():
print("Escape from Cave Terror!")
player = Player()
while True:
room = world.tile_at(player.x, player.y)
print(room.intro_text())
action_input = get_player_command()
if action_input in ['n', 'N']:
player.move_north()
elif action_input in ['s', 'S']:
player.move_south()
elif action_input in ['e', 'E']:
player.move_east
elif action_input in ['w', 'W']:
player.move_west()
elif action_input in ['i', 'I']:
player.print_inventory()
elif action_input in ['q', 'Q']:
exit()
else:
print("Invalid action!")
def get_player_command():
return input('Action: ')
play()
这是来自player.py:
import items
class Player:
def __init__(self):
self.inventory = [items.Rock(),
items.Dagger(),
'Gold(5)',
'Crusty Bread']
self.x = 1
self.y = 2
def print_inventory(self):
print('Inventory: ')
for item in self.inventory:
print('*' + str(item))
best_weapon = self.most_powerful_weapon()
print('Your best weapon is your {}'.format(best_weapon))
def most_powerful_weapon(self):
max_damage = 0
best_weapon = None
for item in self.inventory:
try:
if item.damage > max_damage:
best_weapon = item
max_damage = item.damage
except AttributeError:
pass
return best_weapon
def move(self, dx, dy):
self.x += dx
self.y += dy
def move_north(self):
self.move(dx=0, dy=-1)
def move_south(self):
self.move(dx=0, dy=1)
def move_east(self):
self.move(dx=1, dy=0)
def move_west(self):
self.move(dx=-1, dy=0)
这是world.py:
class MapTile:
def __init__(self, x, y):
self.x = x
self.y = y
def intro_text(self):
raise NotImplementedError("Create a subclass instead!")
class StartTile(MapTile):
def intro_test(self):
return """
You find yourself in a cave with a flickering torch on the wall.
You can make out four paths, each equally as dark and foreboding.
"""
class BoringTile(MapTile):
def intro_text(self):
return """
This is a very boring part of the cave.
"""
class VictoryTile(MapTile):
def intro_text(self):
return """
You see a bright light in the distance...
... it grows as you get closer! It's sunlight!
Victory is yours!
"""
world_map = [
[None,VictoryTile(1,0),None],
[None,BoringTile(1,1),None],
[BoringTile(0,2),StartTile(1,2),BoringTile(2,2)],
[None,BoringTile(1,3),None]
]
def tile_at(x, y):
if x < 0 or y < 0:
return None
try:
return world_map[y][x]
except IndexError:
return None
我收到错误而不是起始房间信息:
Escape from Cave Terror!
Traceback (most recent call last):
File "game.py", line 32, in <module>
play()
File "game.py", line 10, in play
print(room.intro_text())
AttributeError: 'NoneType' object has no attribute 'intro_text'