Python文本游戏输入有效方向却同时输出True和False的解决方法
文本游戏输入有效方向仍同时打印True和false的问题解决
我正在开发一款文本游戏,但发现即使玩家输入有效的移动方向,代码中的'True'和'false'语句都会被打印出来。我尝试在for循环前将用户输入capitalize,但仍然无法解决问题,陷入了困境。
原代码如下:
# A dictionary for the simplified dragon text game # The dictionary links a room to other rooms. rooms = { 'Great Hall': {'South': 'Bedroom'}, 'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'}, 'Cellar': {'West': 'Bedroom'} } exit_game = False current_area = 'Great Hall' movement = ['North', 'East', 'South', 'West', 'Exit'] direction = '' # player direction will be defined by player input print('Movement: North, East, South, West, or Exit.') print('-' * 50) while direction != 'exit' and direction != 'Exit': # prints available direction # print(*rooms[current_area].keys()) # prints available room # print(*rooms[current_area].values()) # prints both # print('To your ', *rooms[current_area].keys(),' is the ', *rooms[current_area].values(), '.', sep='') # --------------------------------------------- print('Your are in the: ', current_area, '.', sep='') print('To your ', *rooms[current_area].keys(), ' is the ', *rooms[current_area].values(), '.', sep='') direction = input('Which way do you want to move?') print('You entered:', direction) direction = direction.capitalize() for value in rooms.values(): if direction in value: print('True') elif direction not in value: print('false') break print('-' * 50)
问题原因
核心问题出在遍历所有房间方向字典的for value in rooms.values()循环:
- 这个循环会检查所有房间的可用方向,而不是仅当前所在房间的
- 比如在Great Hall输入South时,第一次循环检测到Great Hall的字典包含South,打印True;但第二次循环会检查Bedroom的字典,里面没有South,就会触发
elif打印false并终止循环,导致两种结果都被输出 - 同时原代码没有处理房间移动逻辑和Exit指令的退出逻辑,功能不完整
解决方案
直接去掉无用的全局循环,只检查当前房间的可用方向,同时补充完整的游戏逻辑:
修正后的代码:
# A dictionary for the simplified dragon text game # The dictionary links a room to other rooms. rooms = { 'Great Hall': {'South': 'Bedroom'}, 'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'}, 'Cellar': {'West': 'Bedroom'} } current_area = 'Great Hall' movement = ['North', 'East', 'South', 'West', 'Exit'] print('Movement: North, East, South, West, or Exit.') print('-' * 50) while True: print('You are in the: ', current_area, '.', sep='') # 格式化打印当前房间的可用方向与对应房间 for dir_name, room_name in rooms[current_area].items(): print(f'To your {dir_name} is the {room_name}.') direction = input('Which way do you want to move? ') print('You entered:', direction) direction = direction.capitalize() if direction == 'Exit': print('Exiting game...') break elif direction in rooms[current_area]: # 更新当前所在房间 current_area = rooms[current_area][direction] print('Valid move!') else: print('Invalid direction, try again.') print('-' * 50)
关键修正点
- 移除遍历所有房间的循环,仅检查
rooms[current_area](当前房间的方向字典) - 补充Exit指令处理,输入Exit直接退出游戏
- 有效方向时更新当前房间位置,给出明确提示
- 无效方向时输出错误提示,避免混淆
- 优化可用方向的打印格式,每个方向对应一行,可读性更强
内容的提问来源于stack exchange,提问作者Prince L
相关产品推荐
相关产品推荐

