文本游戏中Get [Item Name]命令失效问题求助
问题排查与修复
核心问题
你代码里的命令验证逻辑是硬匹配commands列表的内容,但commands里的get [item name]只是提示模板,玩家实际输入的get Invincibility bracelet这类具体命令根本不在列表中,会直接触发"Invalid command"提示,根本走不到后续的get命令处理逻辑。
另外,commands里的go North等具体方向命令也存在扩展性问题,但这不是当前的核心故障点,优先解决get命令的bug。
修复步骤
- 重构命令验证逻辑:放弃硬匹配
commands列表的方式,改为按命令类型判断:- 先识别
exit命令 - 再判断是否是
go开头的方向命令,验证方向是否在当前房间的可用方向中 - 最后判断是否是
get开头的物品命令 - 剩余输入判定为无效命令
- 先识别
- 优化提示文本:将
commands列表里的具体方向命令改为go [direction],让提示更符合实际输入逻辑。
修改后的完整代码
# A dictionary for the created text game # The dictionary links a room to other rooms. current_room = "Grand Hall" inventory = [] rooms = { "Grand Hall": {"South": "Alderaan", "North": "Hoth", "East": "Naboo", "West": "Mustafar"}, "Alderaan": {"North": "Grand Hall", "East": "Tatooine"}, "Tatooine": {"West": "Alderaan"}, "Mustafar": {"East": "Grand Hall"}, "Hoth": {"East": "Kashyyyk", "South": "Grand Hall"}, "Kashyyyk": {"West": "Hoth"}, "Naboo": {"North": "Dagobah", "West": "Grand Hall"}, "Dagobah": {"South": "Naboo"} } room_items = { "Grand Hall": ["Invincibility bracelet"], "Alderaan": ["Soul Stone"], "Tatooine": ["Death Stone"], "Mustafar": ["Chaos Stone"], "Hoth": ["Genesis Stone"], "Kashyyyk": ["Evolution Stone"], "Naboo": ["Nightmare Stone"], "Dagobah": ["War Stone"] } commands = ["go [direction]", "get [item name]", "exit"] # Define a function to display the available commands def show_valid_commands(): print("Available commands:") for cmd in commands: print("- " + cmd) # Define a function to display the player's status def show_status(): print("You are currently in the " + current_room) print("Inventory: " + str(inventory)) print("Items in this room: " + str(room_items.get(current_room, []))) # Start the game loop while True: # Display the current status and available commands show_status() show_valid_commands() # Get input from the player command = input("What would you like to do? ").strip() # Handle exit command first if command == "exit": break # Handle go [direction] command if command.startswith("go "): direction = command[3:].strip() # Validate direction if direction in rooms[current_room]: current_room = rooms[current_room][direction] else: print("There's no room in that direction. Please choose another direction.") continue # Handle get [item name] command if command.startswith("get "): item_name = command[4:].strip() if item_name in room_items.get(current_room, []): room_items[current_room].remove(item_name) inventory.append(item_name) print(f"You picked up the {item_name}.") else: print(f"There is no {item_name} in this room.") continue # Invalid command fallback print("Invalid command. Please enter a valid command.") # Output a message to let the player know the game has ended print("You have exited the game.")
额外优化点
- 给输入增加
.strip()处理,避免玩家输入前后空格导致的匹配失败 - 调整命令处理顺序,逻辑更清晰,减少冗余判断
内容的提问来源于stack exchange,提问作者Matthew Reyna
相关产品推荐
相关产品推荐

