Python嵌套字典键引用问题及游戏物品拾取验证需求
文本冒险游戏嵌套字典物品拾取问题解决方案
核心问题拆解
- 无需显式指定外层房间键名:通过当前房间变量直接访问内层
item键,避免硬编码房间名称 - 输入验证:校验玩家输入的物品是否存在于当前房间的物品列表中,仅允许拾取当前房间的物品
修正后的代码实现
假设你的游戏中已维护current_room变量跟踪玩家当前位置,player_inventory存储玩家背包,rooms是嵌套字典结构的房间数据:
原出错代码(示例)
# 硬编码外层房间键,无法动态适配当前房间 if item in rooms['hall']['items']: rooms['hall']['items'].remove(item) player_inventory.append(item) else: print("这个房间里没有这个物品!")
修正后的代码
# 用current_room直接访问当前房间的物品,无需显式指定外层键 def pick_up_item(item): # 输入验证:检查物品是否在当前房间 if item in current_room['items']: current_room['items'].remove(item) player_inventory.append(item) print(f"你拾取了{item}!") else: print(f"当前房间没有{item},无法拾取!")
关键逻辑说明
- 动态引用当前房间:
current_room是指向rooms字典中当前房间对象的引用,直接调用current_room['items']即可获取当前房间的物品列表,无需写死外层房间键名(比如rooms['hall']) - 输入验证逻辑:通过
in运算符判断玩家输入的物品是否存在于当前房间的items列表中,只有存在时才执行拾取操作,否则给出提示
完整游戏代码示例(简化版)
# 房间数据:嵌套字典 rooms = { 'hall': { 'name': '大厅', 'description': '一个宽敞的大理石大厅,门口通向街道', 'items': ['钥匙', '手电筒'], 'exits': {'north': 'bedroom'} }, 'bedroom': { 'name': '卧室', 'description': '一张柔软的大床,窗边有个衣柜', 'items': ['钱包', '笔记本'], 'exits': {'south': 'hall'} } } # 玩家状态 current_room = rooms['hall'] player_inventory = [] # 游戏主循环 while True: print(f"\n当前位置:{current_room['name']}") print(current_room['description']) if current_room['items']: print(f"房间里的物品:{', '.join(current_room['items'])}") print(f"你的背包:{', '.join(player_inventory) if player_inventory else '空'}") command = input("\n输入指令(go [方向]/get [物品]/quit):").lower().split() if not command: continue if command[0] == 'quit': print("游戏结束!") break elif command[0] == 'go': if len(command) < 2: print("请输入方向!") continue direction = command[1] if direction in current_room['exits']: current_room = rooms[current_room['exits'][direction]] print(f"你走向了{direction}方向") else: print("那个方向走不通!") elif command[0] == 'get': if len(command) < 2: print("请输入要拾取的物品!") continue item = command[1] # 执行拾取逻辑 if item in current_room['items']: current_room['items'].remove(item) player_inventory.append(item) print(f"你拾取了{item}!") else: print(f"当前房间没有{item},无法拾取!") else: print("无效指令,请重新输入!")
内容的提问来源于stack exchange,提问作者Kyle Kozar
相关产品推荐
相关产品推荐

