从房间获取物品功能实现故障求助
从房间获取物品功能实现故障求助
看起来你在做文本冒险类的小游戏对吧?这种明明逻辑捋顺了但代码要么不执行要么报错的感觉真的超挫败!先看看你给出的房间数据:
room = { 'Main Entry': {'East': 'Main Floor'}, 'Main Floor': {'North': 'North Hall', 'South': 'South Hall', 'East': 'Clothes Store', 'West': 'Main Entry', 'item': 'Gas Mask'}, 'South Hall': {'East': 'Food Court', 'North': 'Main Floor', 'item': 'Knowledge of Toa'} }
你没把获取物品的函数代码贴出来,但这类功能踩坑的点其实挺固定的,我给你捋几个常见问题和解决思路:
- 没判断房间内是否存在物品:如果直接写取物品的逻辑,没先检查当前房间字典里有没有
item这个键,大概率会触发KeyError报错 - 物品转移后没从房间移除:就算成功把物品加到背包,房间里还留着同款物品,既不符合游戏逻辑,也可能导致后续重复拾取的问题
- 没跟踪玩家当前所在房间:得有个变量比如
current_room来记录玩家位置,不然函数根本不知道该从哪个房间取物品
给你写个简单的可运行示例,你可以对照着调整自己的代码:
# 初始化房间、玩家位置和背包 room = { 'Main Entry': {'East': 'Main Floor'}, 'Main Floor': {'North': 'North Hall', 'South': 'South Hall', 'East': 'Clothes Store', 'West': 'Main Entry', 'item': 'Gas Mask'}, 'South Hall': {'East': 'Food Court', 'North': 'Main Floor', 'item': 'Knowledge of Toa'} } current_room = 'Main Entry' inventory = [] def get_item(): global current_room, inventory # 先检查当前房间有没有可拾取的物品 if 'item' in room[current_room]: target_item = room[current_room]['item'] # 把物品加入背包 inventory.append(target_item) # 从房间移除已拾取的物品 del room[current_room]['item'] print(f"你成功拿到了【{target_item}】!当前背包物品:{inventory}") else: print("这个房间里没有能拿的东西哦!") # 测试流程:先移动到主楼层,再执行拾取 current_room = 'Main Floor' get_item()
你可以对照这个示例排查自己的代码:比如是不是没正确声明全局变量(如果用了全局的位置和背包变量),或者物品存在性的判断逻辑写错了,又或者没处理房间物品的移除。如果还是解决不了,把你的获取物品函数代码贴出来,我再帮你揪细节!
备注:内容来源于stack exchange,提问作者The Trickster
相关产品推荐
相关产品推荐

