校园简易文字游戏开发求助:无法接收移动方向输入
问题解决:简易文字房间游戏交互逻辑修正
问题根源
你的代码用了两层for循环直接遍历所有房间和方向,这会一次性输出所有内容,而非实现交互式的房间移动逻辑。要达成预期效果,需要维护当前所在房间的状态,通过循环接收用户输入来动态更新房间状态。
修正后的代码
rooms = { 'Great Hall': {'South': 'Bedroom'}, 'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'}, 'Cellar': {'West': 'Bedroom'} } print('Welcome To The Room Game') print('Move Commands: South, North, East, West, exit') print('---------------------------------------------------------------') # 初始化当前房间为起始点Great Hall current_room = 'Great Hall' # 进入游戏循环 while True: # 显示当前房间 print(f'You are in the {current_room}') # 提示输入移动指令 move = input('Enter your move: ').strip().capitalize() # 处理退出指令 if move == 'Exit': print('Thanks for playing!') break # 处理有效移动方向 if move in rooms[current_room]: current_room = rooms[current_room][move] print(f'Moving {move}...') else: # 无效指令提示 print('Invalid move! Please enter a valid direction or "exit".')
关键改动说明
- 新增
current_room变量维护当前所在房间的状态,起始设为Great Hall - 用
while True循环实现持续交互,直到用户输入exit退出游戏 - 使用
input()函数接收用户移动指令,替代原代码中一次性遍历输出的逻辑 - 增加指令有效性判断:输入为当前房间存在的方向时,更新
current_room;否则提示错误 - 补充
exit退出逻辑,触发后结束游戏循环
运行效果示例
Welcome To The Room Game Move Commands: South, North, East, West, exit --------------------------------------------------------------- You are in the Great Hall Enter your move: South Moving South... You are in the Bedroom Enter your move: exit Thanks for playing!
内容的提问来源于stack exchange,提问作者Coder
相关产品推荐
相关产品推荐

