类型错误:不可哈希类型:创建基于文本的游戏时的“dict”

问题描述 投票:0回答:1

我正在为学校做一个项目,我必须制作一个游戏,让角色穿过房间收集物品。我不断收到此错误

player_move in rooms[currentRoom]:
TypeError: unhashable type: 'dict'

这是我的代码,我做错了什么?

rooms = {
        'Laundry Room': {'West': 'Basement'}, #Game Starts Here
        'Basement': {'North': 'Kitchen'},
        'Kitchen': {'West': 'Living Room', 'East': 'Dining Room', 'North': 'Bedroom', 'South': 'Basement'},
        'Living Room': {'East': 'Kitchen', 'item': '$100 cash'},
        'Dining Room': {'West': 'Kitchen', 'North': 'Backyard', 'item': '$6 cash'},
        'Bedroom': {'South': 'Kitchen', 'East': 'Bathroom', 'item': '$200 cash'},
        'Bathroom': {'West': 'Bedroom', 'item': '$300 cash'},
        'Backyard': {'South': 'Dining Room', 'item': '$60 cash'} #Return to the Laundry Room via the Basement
}

player_move = ['North', 'South', 'East', 'West']
currentRoom = rooms['Laundry Room']

# While Loop for moving between rooms
while True:


    player_move = input('Enter a move: \n')

    if player_move == 'Exit':
        print('Thanks for playing.')
        # break statement for exiting
        break

    if player_move in rooms[currentRoom]:
        currentRoom = rooms[currentRoom][player_move]

        addItem = input(' \n')

        if 'item' in rooms[currentRoom]:
            game(rooms[currentRoom]['item'])

我尝试了一些解决方案,但都不起作用,我做错了什么?

python dictionary scripting pycharm typeerror
1个回答
2
投票
currentRoom = rooms['Laundry Room']

这里

currentRoom
的值是一个字典
{'West': 'Basement'}

if player_move in rooms[currentRoom]:

因此您在这里测试

player_move
中的
rooms[{'West': 'Basement'}]
是否无效。

所以使用:

currentRoom = 'Laundry Room'
...
if player_move in rooms[currentRoom]:
        currentRoom = rooms[currentRoom][player_move]
# --OR--
currentRoom = rooms['Laundry Room']
...
if player_move in currentRoom:
    currentRoom = currentRoom[player_move]

使用一些

print
语句对调试有很大帮助。

© www.soinside.com 2019 - 2024. All rights reserved.