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

Python文本类游戏房间物品无法显示问题求助

问题:文本游戏房间物品无法显示

我正在为Python课程开发一款文本类游戏,目前遇到问题:进入房间时无法显示房间内的物品,但可以正常收集物品且背包(inventory)内容能正常展示。调整代码后会触发报错,寻求技术帮助。

原代码

# Welcome message to the player
def prompt():
    print("\t\t\tWelcome to professional wrestling!\n\nVance McMan has locked all wrestlers into an evil "
          "contract.\n\n"
          "You must collect all 6 items and defeat Vance to free all the wrestlers.\n\n"
          f"To move:\t'go {direction}' \n\
          \t 'get item name' \n\n")

    input('Press any key to continue...')


# clear the screen after the welcome message
def clear():
    os.system('cls' if os.name == 'nt' else 'clear')


# dictionary
rooms = {
    'Ring': {'North': 'Gym', 'South': 'Steel Cage', 'East': 'Dressing Room', 'West': 'Office', 'Item': 'Chair'},
    'Office': {'West': 'Ring', 'Boss': 'Vance McMan'},  # villain
    'Gym': {'South': 'Ring', 'East': 'Garage', 'Item': 'RKO Promo Video'},
    'Garage': {'West': 'Gym', 'Item': 'Blueprint'},
    'Steel Cage': {'North': 'Ring', 'East': 'Greenroom', 'Item': 'Mr.Socko'},
    'Green Room': {'West': 'Steel Cage', 'Item': 'StoneCold Beer'},
    'Dressing Room': {'East': 'Ring', 'North': 'Locker Room', 'Item': 'Rics Robe'},
    'Locker Room': {'South': 'Dressing Room'}  # starting room
}

# list of vowels
vowels = ['a', 'e', 'i', 'o', 'u']

# directions
direction = ['north', 'south', 'east', 'west']

# track inventory
inventory = []

# track the current room
current_room = 'Locker Room'

item = rooms[current_room].get('Item')
# results of the players previous move
msg = ''

clear()
prompt()

# gameplay loop until exit
while True:
    clear()
    # display info to player
    print(f"You are in the {current_room}\nInventory : {inventory}\n{' - ' * 27}")

    # display the msg
    print(msg)

    # indicate items
    if 'item' in rooms[current_room].keys():
        nearby_item = rooms[current_room]["item"]

        if nearby_item not in inventory:

            if nearby_item[-1] == 's':
                print(f'You see {nearby_item}')

            elif nearby_item[0] in vowels:
                print(f'You see an {nearby_item}')

            else:
                print(f'You see a {nearby_item}')

    # boss encounter
    if 'Boss' in rooms[current_room].keys():
        # lose
        if len(inventory) < 6:
            print(f"Game over! You lost a fight with {rooms[current_room]['Boss']}")

        # win
        else:
            print(f"You beat {rooms[current_room]['Boss']}")

    # accept the player move as input
    move = input('Which direction will you go?\n')

    # split the move into words
    next_move = move.split(' ')

    # the first word is an action
    action = next_move[0].title()

    if len(next_move) > 1:
        item = next_move[1:]
        direction = next_move[1].title()

        item = ' '.join(item).title()

    # move in between rooms
    if action == 'Go':
        try:
            current_room = rooms[current_room][direction]
            msg = f'You go {direction}.'

        except:
            msg = f'You cannot go that way.'

    # picking up items
    elif action == "Get":
        if item == rooms[current_room]['item']:

            if item not in inventory:
                inventory.append(rooms[current_room]['item'])
                msg = f"{item} retrieved!"

            else:
                msg = f"You already have the {item} in your inventory."

        else:
            msg = f"Cannot find the {item}"

    # exit the game
    if move == 'Exit':
        current_room = 'exit'
        print('Game over. Thank you for playing!')
        break

# any other commands invalid
else:
    msg = f"Invalid command"

问题分析与修复

核心问题:字典键名大小写不匹配

在rooms字典中,物品的键是大写的'Item',但代码中检测和获取物品时用的是小写的'item',导致程序无法识别房间内的物品,这是物品不显示的根本原因。

其他次要问题及修复

  1. 房间名称拼写不一致:Steel Cage的东向是Greenroom(无空格),但字典中对应的房间是Green Room(有空格),会导致移动失败。统一改为Green Room。
  2. direction变量被覆盖:原本direction是存储方向列表的变量,在处理输入时被赋值为单个方向字符串,会影响后续逻辑。将输入中的方向变量改为move_direction避免冲突。
  3. Get操作中的键名错误:同样把rooms[current_room]['item']改为rooms[current_room]['Item']。
  4. Invalid command逻辑位置错误:原本的else块属于while循环,永远不会执行,需要移到循环内处理无效命令。

修复后的代码

import os  # 补充缺失的os导入

# Welcome message to the player
def prompt():
    print("\t\t\tWelcome to professional wrestling!\n\nVance McMan has locked all wrestlers into an evil "
          "contract.\n\n"
          "You must collect all 6 items and defeat Vance to free all the wrestlers.\n\n"
          "To move:\t'go direction' \n\
          \t 'get item name' \n\n")

    input('Press any key to continue...')


# clear the screen after the welcome message
def clear():
    os.system('cls' if os.name == 'nt' else 'clear')


# dictionary
rooms = {
    'Ring': {'North': 'Gym', 'South': 'Steel Cage', 'East': 'Dressing Room', 'West': 'Office', 'Item': 'Chair'},
    'Office': {'West': 'Ring', 'Boss': 'Vance McMan'},  # villain
    'Gym': {'South': 'Ring', 'East': 'Garage', 'Item': 'RKO Promo Video'},
    'Garage': {'West': 'Gym', 'Item': 'Blueprint'},
    'Steel Cage': {'North': 'Ring', 'East': 'Green Room', 'Item': 'Mr.Socko'},  # 修正房间名称
    'Green Room': {'West': 'Steel Cage', 'Item': 'StoneCold Beer'},
    'Dressing Room': {'East': 'Ring', 'North': 'Locker Room', 'Item': 'Rics Robe'},
    'Locker Room': {'South': 'Dressing Room'}  # starting room
}

# list of vowels
vowels = ['a', 'e', 'i', 'o', 'u']

# directions
directions = ['north', 'south', 'east', 'west']  # 变量名改为directions避免冲突

# track inventory
inventory = []

# track the current room
current_room = 'Locker Room'

item = rooms[current_room].get('Item')
# results of the players previous move
msg = ''

clear()
prompt()

# gameplay loop until exit
while True:
    clear()
    # display info to player
    print(f"You are in the {current_room}\nInventory : {inventory}\n{' - ' * 27}")

    # display the msg
    print(msg)

    # indicate items
    if 'Item' in rooms[current_room].keys():  # 修正键名为大写Item
        nearby_item = rooms[current_room]["Item"]

        if nearby_item not in inventory:
            # 优化冠词判断逻辑,先检查首字母是否为元音,再处理复数
            if nearby_item[0].lower() in vowels:
                print(f'You see an {nearby_item}')
            elif nearby_item[-1].lower() == 's':
                print(f'You see {nearby_item}')
            else:
                print(f'You see a {nearby_item}')

    # boss encounter
    if 'Boss' in rooms[current_room].keys():
        # lose
        if len(inventory) < 6:
            print(f"Game over! You lost a fight with {rooms[current_room]['Boss']}")
            input("Press Enter to exit...")
            break
        # win
        else:
            print(f"You beat {rooms[current_room]['Boss']}! You freed all the wrestlers!")
            input("Press Enter to exit...")
            break

    # accept the player move as input
    move = input('Which direction will you go?\n').strip()

    # reset msg for next iteration
    msg = ''

    # split the move into words
    next_move = move.split(' ')

    # the first word is an action
    action = next_move[0].title()

    move_direction = ''
    target_item = ''

    if len(next_move) > 1:
        if action == 'Go':
            move_direction = next_move[1].title()
        elif action == 'Get':
            target_item = ' '.join(next_move[1:]).title()

    # move in between rooms
    if action == 'Go':
        if move_direction in rooms[current_room]:
            current_room = rooms[current_room][move_direction]
            msg = f'You go {move_direction}.'
        else:
            msg = f'You cannot go that way.'

    # picking up items
    elif action == "Get":
        if 'Item' in rooms[current_room] and target_item == rooms[current_room]['Item']:
            if target_item not in inventory:
                inventory.append(target_item)
                msg = f"{target_item} retrieved!"
            else:
                msg = f"You already have the {target_item} in your inventory."
        else:
            msg = f"Cannot find the {target_item}"

    # exit the game
    elif move.lower() == 'exit':
        print('Game over. Thank you for playing!')
        break

    # any other commands invalid
    else:
        msg = f"Invalid command. Use 'go [direction]' or 'get [item]' or 'exit'."

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:08:13