Python文本房间游戏代码调整求助:无法正常切换房间
修复Python文本房间游戏的移动问题
你的代码已经正确定义了所有房间的连接关系,但问题出在移动逻辑的硬编码和嵌套输入上,导致只能处理部分方向,无法实现自由往返。以下是最小改动的修复方案:
问题分析
- 原代码通过嵌套的
if-elif硬编码方向跳转,只处理了少数方向,完全没利用已定义好的rooms字典 - 嵌套的
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!')
关键改动说明
- 修正
Attic中Living Room的空格问题,确保房间名完全匹配 - 删除所有嵌套的
input()和硬编码的房间跳转,让while循环统一处理每一步操作 - 对输入方向做格式统一处理,不管用户输入小写、大写还是带空格,都能正确匹配字典中的方向键
- 直接通过
rooms字典动态判断方向是否有效、获取目标房间,所有预设的房间连接都会生效,实现自由往返
内容的提问来源于stack exchange,提问作者Gil Robledo
相关产品推荐
相关产品推荐

