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

Python文本房间游戏代码调整求助:无法正常切换房间

修复Python文本房间游戏的移动问题

你的代码已经正确定义了所有房间的连接关系,但问题出在移动逻辑的硬编码和嵌套输入上,导致只能处理部分方向,无法实现自由往返。以下是最小改动的修复方案:

问题分析

  1. 原代码通过嵌套的if-elif硬编码方向跳转,只处理了少数方向,完全没利用已定义好的rooms字典
  2. 嵌套的input()调用打破了循环的正常流程,导致后续移动逻辑混乱

修改后的代码

rooms = {
    'Attic': {'South': 'Living Room'},  # 去掉房间名前的空格,避免匹配失败
    'Living Room': {'East': 'Foyer', 'West': 'Dining Room', 'North': 'Attic'},
    'Foyer': {'North': 'Bedroom', 'South': 'Front Porch', 'West': 'Living Room'},
    'Bedroom': {'South': 'Foyer'},
    'Dining Room': {'East': 'Living Room', 'North': 'Kitchen', 'South': 'Basement'},
    'Kitchen': {'South': 'Dining Room'},
    'Basement': {'North': 'Dining Room'},
    'Front Porch': {'North': 'Foyer'},
}

def possible_moves():
    moves = rooms[location].keys()
    print("Options:", *moves)

location = 'Attic'

while True:
    print('You are in the', location)
    possible_moves()
    # 统一输入格式,兼容大小写和前后空格
    direction = input("Which way would you like to go? ").strip().capitalize()

    if direction == 'Exit':
        print('Thank you for playing!')
        break
    # 利用rooms字典动态判断方向有效性,直接获取目标房间
    elif direction in rooms[location]:
        location = rooms[location][direction]
    else:
        print('Invalid direction!')

关键改动说明

  1. 修正Attic中Living Room的空格问题,确保房间名完全匹配
  2. 删除所有嵌套的input()和硬编码的房间跳转,让while循环统一处理每一步操作
  3. 对输入方向做格式统一处理,不管用户输入小写、大写还是带空格,都能正确匹配字典中的方向键
  4. 直接通过rooms字典动态判断方向是否有效、获取目标房间,所有预设的房间连接都会生效,实现自由往返

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:45:25