You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python文本冒险游戏动作命令触发unhashable type报错如何解决

问题修复方案

报错根因

你触发TypeError: unhashable type: 'dict'的核心原因是:rooms字典的键均为字符串类型的房间名,而你代码里的current_room本身已经是存储单个房间信息的字典对象,无法作为键传入rooms字典做查询,字典属于不可哈希类型,不能作为字典的键使用。

需要修改的代码点

1. 修正初始物品配置

将原代码中初始化物品的行:

current_items = None

修改为:

current_items = []

避免后续往物品列表添加元素时出现类型错误。

2. 修正移动命令逻辑

原移动命令逻辑存在查询逻辑错误,将原代码:

elif player_action[0] == 'go':
    if player_action[1] in rooms[current_room]:
        current_room = rooms[current_room][player_action[1]]
    else:
        print("You cannot go that way")

修改为:

elif player_action[0] == 'go':
    # 直接判断输入的方向是否存在于当前房间的配置键中
    if player_action[1] in current_room:
        # 先从当前房间拿到目标房间名,再去rooms字典查询对应房间对象
        current_room = rooms[current_room[player_action[1]]]
    else:
        print("You cannot go that way\n")

3. 修正获取物品命令逻辑

原获取物品的判断逻辑完全错误,且直接删除房间item键会导致状态展示报错,将原代码:

elif player_action[0] == 'get':
    if player_action[1] in rooms[current_room]:
        current_items += [player_action[1]]
        print("You got: ", player_action[1])
        del rooms[current_room]['item']
    else:
        print("What exactly were you looking for?")

修改为:

elif player_action[0] == 'get':
    # 判断输入的物品名和当前房间存储的物品是否一致,且房间内有可拾取物品
    if player_action[1] == current_room['item'] and current_room['item'] != 'nothing':
        current_items.append(player_action[1])
        print(f"You got: {player_action[1]}\n")
        # 修改物品标记为无,不要删除键避免状态展示报错
        current_room['item'] = 'nothing'
    else:
        print("What exactly were you looking for?\n")

内容的提问来源于stack exchange,提问作者Joseph Wychico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 07:12:02