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

如何为Python文本类游戏添加房间可移动方向提示功能?

Python文本收集游戏:添加房间可移动方向提示

我为课程编写了一款Python文本类收集物品游戏,玩家可在不同房间间移动并收集物品。现在希望实现玩家进入房间时自动显示当前房间可前往的方向,避免玩家盲目猜测或额外添加地图。以下是游戏核心代码:

def main():
    inventory = []  # A list for the player to store their items
    # Dictionary of the Rooms and which directions are to be taken for each room.
    # This links one room to the other rooms.
    rooms = {
        'Lobby': {'East': 'Gym'},
        'Gym': {'West': 'Lobby', 'South': 'Pool area', 'item': 'Dumbbell'},
        'Pool area': {'North': 'Gym', 'East': 'Restaurant', 'West': 'Playroom', 'South': 'Your Room',
                      'item': 'Sunscreen'},
        'Restaurant': {'West': 'Pool area', 'North': 'Bathrooms', 'item': 'Cloth Napkin'},
        'Bathrooms': {'South': 'Restaurant', 'item': 'Toilet Roll'},
        'Playroom': {'East': 'Pool area', 'South': 'Supply Closet', 'item': 'Deck of Cards'},
        'Supply Closet': {'North': 'Playroom', 'item': 'Uniform'},
        'Your Room': {'North': 'Pool area', 'East': 'Suite', 'item': 'Laptop'},
        'Suite': {'West': 'Your Room'}}

    current_room = 'Lobby'  # Set the current room to begin the gameplay loop.
    show_menu()
    while current_room != 'Exit':  # If the current room is not the exit the user can continue to the next room.
        item = show_status(current_room, inventory, rooms)  # Displays the current room and items in inventory.
        moves = rooms[current_room]
        # The player will be prompted for which move they want to make.
        player_move = input("Enter 'go North, South, East or West' to move, or get Item, or 'Exit': ")

        if player_move == 'Exit':  # The user will exit the game.
            current_room = 'exit'
            break  # Stops the game from continuing.

        elif player_move.split()[-1] in rooms[current_room]:  # Valid command from the user.
            current_room = rooms[current_room][player_move.split()[-1]]
            # The player will move from one room to the other.

        elif player_move.split()[0].capitalize() == "Get":  # Command to collect item to inventory.
            if player_move == "get " + item:
                get_item(item, inventory, rooms, current_room)
                # The item in the current room will be put in the inventory.
                print(item, "collected")  # Tells the player that the item was collected.
            else:
                print("Invalid command")

        else:  # Set the invalid move command.
            print("Invalid Move. There's no room to the {}".format(player_move))
        print("^" * 20)  # Set separating line.

        if len(inventory) == 7:  # Amount of items required to win the game.
            print('Congratulations! You have collected all items and now can move to the Suite'
                  'to face off the politician!')
            print('You have defeated the Corrupt Politician')
            print('Thanks for playing')
            break  # The game will end after collecting all items.


main()

实现方案

要自动显示当前房间的可移动方向,只需在展示房间状态时,提取当前房间字典中除item外的所有键(即方向)并展示即可。以下是修改后的中文版本代码,同时优化了指令逻辑和提示文本:

def main():
    inventory = []  # 玩家物品背包
    # 房间字典:键为房间名,值包含可移动方向和物品
    rooms = {
        '大厅': {'东': '健身房'},
        '健身房': {'西': '大厅', '南': '泳池区', '物品': '哑铃'},
        '泳池区': {'北': '健身房', '东': '餐厅', '西': '游戏室', '南': '你的房间',
                  '物品': '防晒霜'},
        '餐厅': {'西': '泳池区', '北': '卫生间', '物品': '餐巾布'},
        '卫生间': {'南': '餐厅', '物品': '卫生纸'},
        '游戏室': {'东': '泳池区', '南': '储物间', '物品': '扑克牌'},
        '储物间': {'北': '游戏室', '物品': '制服'},
        '你的房间': {'北': '泳池区', '东': '套房', '物品': '笔记本电脑'},
        '套房': {'西': '你的房间'}}

    current_room = '大厅'  # 初始房间设为大厅
    # show_menu() 假设该函数已实现游戏菜单展示
    while current_room != 'Exit':
        item = show_status(current_room, inventory, rooms)
        # 提取当前房间的可移动方向(过滤掉'物品'键)
        available_directions = [direction for direction in rooms[current_room] if direction != '物品']
        # 显示可前往方向
        if available_directions:
            print(f"当前可前往的方向:{'、'.join(available_directions)}")
        else:
            print("当前房间没有可前往的方向!")
        
        # 玩家输入指令
        player_move = input("请输入指令:'go 北/南/东/西' 移动,'get 物品名' 收集物品,或输入'Exit'退出:")

        if player_move == 'Exit':  # 退出游戏
            current_room = 'Exit'
            break

        # 处理移动指令
        move_parts = player_move.split()
        if len(move_parts) >= 2 and move_parts[0].lower() == 'go':
            direction = move_parts[-1]
            if direction in rooms[current_room]:
                current_room = rooms[current_room][direction]
            else:
                print(f"无效移动!该方向没有房间。")
        # 处理收集物品指令
        elif len(move_parts) >= 2 and move_parts[0].lower() == 'get':
            target_item = ' '.join(move_parts[1:])
            if target_item == item:
                get_item(item, inventory, rooms, current_room)
                print(f"{item} 已收集!")
            else:
                print("无效指令!当前房间没有该物品。")
        else:  # 无效指令处理
            print("无效指令,请重新输入。")
        
        print("^" * 20)  # 分隔线

        # 收集全7件物品触发胜利条件
        if len(inventory) == 7:
            print('恭喜!你已收集所有物品,现在可以前往套房对抗腐败政客了!')
            print('你击败了腐败政客!')
            print('感谢游玩!')
            break

# 辅助函数:展示当前房间状态和背包
def show_status(current_room, inventory, rooms):
    print(f"\n当前房间:{current_room}")
    print(f"背包物品:{inventory if inventory else '空'}")
    # 返回当前房间的物品(无物品则返回空字符串)
    return rooms[current_room].get('物品', '')

# 辅助函数:收集物品到背包并移除房间内的物品
def get_item(item, inventory, rooms, current_room):
    inventory.append(item)
    del rooms[current_room]['物品']

main()

修改说明

  1. 方向提示功能:通过列表推导式过滤房间字典中的物品键,提取所有可移动方向,用中文格式展示给玩家,进入房间时自动显示。
  2. 中文本地化:将房间名、方向、物品名及提示文本全部改为中文,提升玩家体验。
  3. 指令逻辑优化:拆分移动和收集指令的判断逻辑,减少误判,提示文本更清晰。
  4. 辅助函数补全:补全了原代码中未展示的show_status和get_item函数,确保代码可直接运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:05:17