在上周的作业中,我们要做一个简单的游戏,可以移动房间。我已经调整到我的游戏代码的代码,它似乎工作正常,即使与‘项目‘添加到我的字典。一旦我尝试添加到库存并引用库存列表到字典键,我就会得到一个“不可散列”错误。我查了一下,但唯一的方法来清 debugging 误是使用一个元组,但一个元组是不可变的,所以我不能添加到库存,至少在我的理解。任何指导或建议都非常感谢!
def player_instructions():
# main menu and game commands
print('Move Commands: go North, go South, go West, go East')
print("Add to inventory: get 'item name'.")
print('-' * 50)
print('A Paladin Adventure Game.') # game opening greeting
print('Collect 7 items to win the game,')
print('or be destroyed by the Vampire Lord.')
print('-' * 50)
# dictionary for rooms and movement between
castle_rooms = {'Entry Hall': {'East': 'Great Hall', 'South': 'Solar', 'Item': ''},
'Great Hall': {'West': 'Entry Hall', 'South': 'Boudoir',
'North': 'Kitchen', 'East': 'Cabinet', 'Item': 'Silver Mail'},
'Solar': {'North': 'Entry Hall', 'East': 'Boudoir', 'Item': 'Stake'},
'Boudoir': {'North': 'Great Hall', 'West': 'Solar', 'Item': 'Holy Water'},
'Kitchen': {'East': 'Larder', 'South': 'Great Hall', 'Item': 'Mallet'},
'Larder': {'West': 'Kitchen', 'Item': 'Potion of Cleansing'},
'Cabinet': {'West': 'Great Hall', 'North': 'Garderobe', 'South': 'Bedchamber',
'Item': 'Blessed Sword'},
'Garderobe': {'South': 'Cabinet', 'Item': 'Torch'}
}
current_room = 'Entry Hall' # define starting room
inventory = [] # define string for inventory
def player_commands(command, direction): # function for moving rooms
global current_room # declare current room as global
global inventory # declare inventory as global
if command == 'go':
if direction in castle_rooms[current_room]: # establishing valid direction
current_room = castle_rooms[current_room][direction]
elif direction not in castle_rooms[current_room]: # error message for invalid direction
print("You can't go that way")
current_room = current_room
elif command == 'get':
if direction in current_room:
inventory.append(direction)
current_room = current_room
else:
print('Invalid command') # error message for invalid command
current_room = current_room
return current_room, inventory
while current_room != 'Bedchamber': # while loop for gameplay
player_instructions()
print('You are in the {}.'.format(current_room))
if castle_rooms[current_room]['Item'] not in inventory:
print('You see {} in the room.'.format(castle_rooms[current_room]['Item']))
else:
pass
user_input = input('What will you do next?').split()
command = user_input[0]
direction = user_input[1] if len(user_input) > 1 else ''
current_room = player_commands(command, direction)
这是到目前为止的全部代码,一切正常,直到我尝试添加一个单独的播放器库存。我还没有添加游戏结束代码,所以我意识到我有一个无限循环,但我试图使库存工作之前,我添加了结束,因为库存必须包括所有项目赢得。
2条答案
按热度按时间f4t66c6m1#
当你“得到”一个物品时,你想把它附加到你的物品清单上,并把它从房间里移走。
尝试以下操作:
如果你在第56行附近得到一个错误,那么(基于你的原始代码)可能是:
如果一个房间没有一个项目,那么这将抛出一个关键字错误。尝试将该代码替换为:
下面是一个更完整的示例:
n53p2ov02#
所以我和一个懂python的朋友一起工作,他教了我一些非常好的新东西,给代码添加颜色,他还帮助我解决了我的库存问题,我认为内联注解解释了它的大部分内容,我很高兴它能运行得很好。