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

Python文本游戏move_rooms函数问题求助:捡物品误判为房间

问题分析与修复方案

核心问题1:拾取物品时current_room被错误赋值

执行get指令时,move_rooms函数返回的是inventory列表,但主程序将返回值赋值给了current_room,导致current_room变成列表类型。后续访问rooms[current_room]时,会因为房间字典的键是字符串而触发错误,表现为“物品被识别为房间”。

修复:get分支执行完成后返回current_room而非inventory。由于inventory是可变对象,函数内的修改会直接作用于外部列表,无需返回。

核心问题2:主循环条件逻辑错误

主循环条件while current_room != 'Exit' or current_room != 'Parlor'永远为真——无论当前房间是Exit还是Parlor,总有一个条件成立,导致循环无法正常终止。

修复:将or改为and,即while current_room != 'Exit' and current_room != 'Parlor',仅当当前房间既不是Exit也不是Parlor时,才继续循环。

其他细节问题修复

  1. 物品匹配逻辑错误:原代码if move[1] not in rooms[current_room].get("Item")会把物品名当成字符序列判断(比如输入get K会匹配Keys),应改为直接判断物品名是否相等:if move[1] != rooms[current_room].get("Item")。
  2. 无效指令未返回当前房间:输入无效指令时,move_rooms未返回current_room,导致current_room被赋值为None,后续触发KeyError。需在所有分支确保返回current_room。
  3. Exit房间格式错误:'Exit': {'exits the game'}是无效字典项,改为'Exit': {}即可,因为Exit是终止条件,无需房间出口。

修改后的完整代码

def give_instructions():
    # print game instructions
    print("Welcome to the game!\n"
          "You were arriving home when attacked by a rival wizard,\n"
          "you wake in a strange cell where the walls meet at impossible angles.\n"
          "You have a sense of impending doom and a massive headache.\n"
          "As your head clears you realize you are in your own home.\n"
          "You must collect 7 items to defeat the wizard in your parlor.\n"
          "To move type 'go North', 'go South', 'go East' or 'go West'\n"
          "To pick up items type 'get' Item name\n"
          "To exit type 'Exit'\n")


def show_status(room, stuff, roomsli):
    # show player their current status(room, room exits and inventory)
    print('You are in {}'.format(room))
    print('Inventory:', stuff)
    if "Item" in roomsli[room]:
        print("{} is in {}".format(roomsli[room].get('Item'), room))
    for direction, room_name in roomsli[room].items():
        if direction != 'Item':
            print("You can exit {} to {}".format(direction, room_name))


def move_rooms(move, current_room, inventory):
    # controls for room movement and inventory
    if move[0] in ['Exit', 'exit']:
        # to exit game
        return 'Exit'
    elif move[0] == 'go':
        # to change rooms or get error if not a good direction
        if move[1] not in rooms[current_room]:
            print("Invalid move\n")
            return current_room
        else:
            current_room = rooms[current_room][move[1]]
            return current_room

    elif move[0] == 'get':
        # to get item, add it to inventory, remove it from rooms, or error if wrong item
        if "Item" not in rooms[current_room] or move[1] != rooms[current_room].get("Item"):
            print("That item is not in this room\n")
            return current_room
        else:
            item = rooms[current_room].get('Item')
            inventory.append(item)
            del rooms[current_room]['Item']
            return current_room
    else:
        # if other move is entered
        print("Invalid move\n")
        return current_room


if __name__ == '__main__':
    # main program
    # room dictionary
    rooms = {
        'Dungeon Cell': {'West': 'Basement'},
        'Basement': {'East': 'Dungeon Cell', 'West': 'Cellar', 'North': 'Grand Hall', 'Item': 'Keys'},
        'Cellar': {'East': 'Basement', 'Item': 'Amulet'},
        'Grand Hall': {'South': 'Basement', 'East': 'Sitting Room', 'West': 'Dining Room', 'North': 'Entryway',
                       'Item': 'Staff'},
        'Sitting Room': {'North': 'Library', 'West': 'Grand Hall', 'Item': 'Cloak'},
        'Library': {'South': 'Sitting Room', 'Item': 'Book'},
        'Dining Room': {'East': 'Grand Hall', 'North': 'Kitchen', 'Item': 'Dusty Cupcake'},
        'Kitchen': {'South': 'Dining Room', 'East': 'Entryway', 'Item': 'Strange Potion'},
        'Entryway': {'West': 'Kitchen', 'South': 'Grand Hall', 'East': 'Parlor'},
        'Parlor': {'West': 'Entryway'},
        'Exit': {}
    }
    # call for instructions
    give_instructions()
    # set current room and start inventory
    current_room = "Dungeon Cell"
    inventory = []
    # main game loop
    while current_room != 'Exit' and current_room != 'Parlor':
        show_status(current_room, inventory, rooms)
        move = input("What is your move?\n").split()
        current_room = move_rooms(move, current_room, inventory)
        # exit game conditional
        if current_room == 'Exit':
            print('You exited the game. Thanks for playing!')
            break
        elif current_room == 'Parlor':
            # room conditional if wizard in room and inventory full
            if len(inventory) == 7:
                print("You use your items to defeat the wizard and regain control of your home.\n"
                      "Congratulations you have won!\n"
                      "Thanks for playing!")
                break
            # room conditional if wizard in room and inventory not full
            else:
                print("The wizard kills you as you are not prepared enough.\n"
                      "You have lost!\n"
                      "Thanks for playing!")
                break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:40:41