文本类练习游戏二次进入房间的逻辑Bug修复问询
问题分析
你现在的逻辑漏洞在于没有记录「已经给过守卫面包」这个状态——每次进入训练场都只检查背包里有没有面包,但交付后面包被移除,再次进入时第一个条件就触发,把你推回大厅。之前尝试的rooms["Kitchen"]["Item"]判断容易出问题(因为删除Item键后,后续访问会抛出KeyError),first_time_in_room如果没正确持久化状态(比如离开房间就重置)也没用。
修复方案
添加一个独立的状态变量来标记是否已经获得训练场的访问权限,比如has_access_to_training_grounds = False,然后重构判断逻辑:
- 先检查是否已经拥有访问权限,是的话直接进入,跳过所有验证
- 没有权限的情况下,再检查背包里的面包:
- 没面包:被守卫推回
- 有面包:询问是否交付,交付后更新权限状态,同时处理面包和厨房物品
修改后的代码示例
# 初始化状态变量,放在游戏启动的地方(比如Inventory定义附近) has_access_to_training_grounds = False # 训练场相关的判断逻辑替换成下面的 if current_room == "Training Grounds": # 已经有权限,直接进入 if has_access_to_training_grounds: print("The guard nods at you as you enter the Training Grounds.") continue # 还没权限,检查面包 if "Bread" not in Inventory: print("A hungry guard blocks your path and shoves you back into the Great Hall.") current_room = "Great Hall" continue # 有面包,询问是否交付 player_move = input("Would you like to offer the guard bread in exchange for access to the Training Grounds? ").capitalize() if player_move == "Yes": print("The guard lets you enter the Training Grounds.") Inventory.remove("Bread") # 用pop替代del,避免键不存在时报错 rooms["Kitchen"].pop("Item", None) has_access_to_training_grounds = True # 标记权限已获得 elif player_move == "No": print('"Get the hell out of here!"') print("The guard shoves you back into the Great Hall.") current_room = "Great Hall" continue
关键改进点
- 新增
has_access_to_training_grounds状态变量,永久记录权限状态,不会因为面包被移除或房间切换而丢失 - 用
dict.pop("Item", None)替代del rooms["Kitchen"]["Item"],避免厨房没有Item键时抛出异常 - 统一将用户输入转为大写,避免大小写判断问题
- 逻辑层级更清晰:先判断权限,再检查面包,最后处理交付交互
内容的提问来源于stack exchange,提问作者Krondor12
相关产品推荐
相关产品推荐

