文本冒险游戏代码遇KeyError、指令不显示及合规问题求助
问题描述
背景
就职于开发文本类游戏的小型公司,近期提出的文本冒险游戏设计方案获认可,负责开发该游戏。作业核心要求:
- 代码遵循清晰命名规范并添加行内注释
- 必须包含
show_instructions和show_status函数 - 仅使用一个字典存储房间及物品信息
游戏规则:玩家通过命令行指令在房间间移动、收集物品,需在遭遇反派房间前集齐所有物品,每一步需输出游戏状态及物品拾取选项。
当前问题
- 代码不符合作业要求(缺少
show_status函数) - 运行时触发
KeyError回溯错误 - 编写的游戏指令文本未正常显示
完整错误代码
def show_instructions(): # System displays a menu and commands for the user print("You're waking up...") print("*Apple Watch Alarm Starts Blasting*") print("You look down to check why the watch is going off, you then see an amber alert.") print("*WARNING: STATE-WIDE PANDEMIC VIRUS, PLEASE SEEK SHELTER AND AVOID CONTACT WITH THE INFECTED!*") print("While gaining your consciousness back bit by bit, you notice your self in the middle of a Hollywood Hills " "mansion's bathroom, with nothing but a distant echo of grunting and moaning you soon realize a zombie " "outbreak has occurred!") print("In order to make it out successfully from the infected mansion you must collect 5 items and your friend " "David who have all been scattered across the mansion during the party.") print("Move Commands: go South, go North, go East, go West") print("Add to Inventory/Grab: get 'item name'\n") # Main function def main(): # Calling function to display instructions show_instructions() # A dictionary for the zombie survival text game # This dictionary links all 8 rooms to one another rooms = {'Bathroom' : { 'West' : 'Hallway'}, # First Room 'Hallway': { 'East': 'Bathroom', 'South': 'Living Room', 'item' : 'Backpack'}, 'Living Room': { 'North': 'Hallway', 'West': 'Backyard', 'South': 'Office', 'East': 'Kitchen', 'item': 'Gun'}, 'Backyard': { 'East': 'Living Room', 'item': 'Map'}, # Exit room 'Office': { 'North': 'Living Room', 'East': 'Garage', 'item': 'Ammo'}, 'Garage': { 'West': 'Office', 'item': 'David'}, 'Kitchen': { 'West': 'Living Room', 'North': 'Basement', 'item': 'Long steak knife'}, 'Basement': { 'South': 'Kitchen', 'item': 'Zombies'}, # Avoid } # Displays games starting room current_room = 'Bathroom' # System creates an empty list called "inventory" inventory = [] # A loop to simulate the player moving between rooms while True: # If current_room is Backyard then break the loop if current_room == 'Backyard': print("\nYou are in the", current_room) print("You see the Exit!",) if len(inventory) == 6: print("\nCongrats! You have collected all the items and your friend David and have made your way out the infected mansion!") else: print("\nYou don't have everything you need, you won't survive out there... GAME RESTARTING!") break # Printing the current_room print("\nYou are in the", current_room) # Prompts user to pickup the item within the room if rooms[current_room]['item'] != None: print("You see a", rooms[current_room]['item']) opinion = input("get "+rooms[current_room]['item']+"?(Y/N:").upper() # Validating the users input while opinion not in ['Y','N']: print ("Invalid input. Try again") opinion = input("Get "+rooms[current_room]['item']+"?(Y/N): ").upper() if opinion == 'Y': inventory.append(rooms[current_room]['item']) rooms[current_room]['item'] = None else: print("The item in this room has already been grabbed or there was nothing in here") # System prints inventory print("Inventory:", inventory) # System grabs users input for move directions direction = input("Direction to move?(South,North,East,West): ").title() directions = list(rooms[current_room].keys()) directions.remove('item') # Confirming users direction while direction not in directions: print("Invalid direction from "+current_room+". Try another move") direction = input("Direction to move?(East,West,North,South): ").title() # System develops the next_room next_room = rooms[current_room][direction] print("You have now moved to",next_room) print("-------------------------------------------") # Updating current_room current_room = next_room # Printing the games end message print("\nThank you for playing Zombie Mansion Survival!") # Calling main function main()
解决方案
1. 修复KeyError错误
错误原因:初始房间Bathroom未定义item键,代码尝试访问rooms[current_room]['item']时触发KeyError。
解决方法:给所有房间统一添加item键,无物品时设为None:
rooms = { 'Bathroom': {'West': 'Hallway', 'item': None}, # 初始房间无物品 'Hallway': {'East': 'Bathroom', 'South': 'Living Room', 'item': 'Backpack'}, 'Living Room': {'North': 'Hallway', 'West': 'Backyard', 'South': 'Office', 'East': 'Kitchen', 'item': 'Gun'}, 'Backyard': {'East': 'Living Room', 'item': 'Map'}, # 出口房间 'Office': {'North': 'Living Room', 'East': 'Garage', 'item': 'Ammo'}, 'Garage': {'West': 'Office', 'item': 'David'}, 'Kitchen': {'West': 'Living Room', 'North': 'Basement', 'item': 'Long steak knife'}, 'Basement': {'South': 'Kitchen', 'item': 'Zombies'} # 反派房间 }
2. 修复指令未显示问题
错误原因:main()函数中调用show_instructions()的语句存在缩进错误(多了一个空格),Python解释器无法识别为函数内代码。
解决方法:修正缩进,确保与函数内其他代码对齐:
def main(): # 调用指令显示函数 show_instructions() # 修正缩进至与后续代码一致
3. 满足作业要求
添加show_status函数
将分散的状态打印逻辑封装成函数,符合作业要求:
def show_status(current_room, rooms, inventory): """显示当前游戏状态:所在房间、物品信息、库存""" print("\n===== 当前状态 =====") print(f"你现在在: {current_room}") room_item = rooms[current_room]['item'] if room_item and room_item != 'Zombies': print(f"你看到了: {room_item}") elif room_item == 'Zombies': print("警告!房间里有丧尸!") else: print("这个房间已经没有可收集的物品了") print(f"当前库存: {inventory if inventory else '空'}") print("===================")
规范命名与注释
- 变量采用蛇形命名法(如
current_room、inventory),保持风格统一 - 为函数和关键代码块添加清晰中文注释
- 确保仅使用
rooms一个字典存储所有房间及物品信息
完善反派房间逻辑
添加进入丧尸房间的失败判定,符合“遭遇反派前集齐物品”的规则:
# 在循环中添加反派房间判断 if current_room == 'Basement': print("\n你闯进了丧尸房间!被丧尸包围了... GAME OVER!") break
完整修正后代码
def show_instructions(): """显示游戏操作指南和背景故事""" print("你醒了过来...") print("*苹果手表警报疯狂响起*") print("你低头查看警报原因,发现是一条紧急预警。") print("*警告:全州爆发丧尸病毒,请立即寻找避难所,避免接触感染者!*") print("意识逐渐清醒后,你发现自己在好莱坞山豪宅的浴室里,远处传来低沉的嘶吼声——丧尸爆发了!") print("要成功逃离这座被感染的豪宅,你需要收集5件物品和你的朋友大卫,他们都在派对中散落在豪宅各处。") print("移动指令:go South, go North, go East, go West") print("收集物品:get '物品名称'\n") def show_status(current_room, rooms, inventory): """显示当前游戏状态:所在房间、物品信息、库存""" print("\n===== 当前状态 =====") print(f"你现在在: {current_room}") room_item = rooms[current_room]['item'] if room_item and room_item != 'Zombies': print(f"你看到了: {room_item}") elif room_item == 'Zombies': print("警告!房间里有丧尸!") else: print("这个房间已经没有可收集的物品了") print(f"当前库存: {inventory if inventory else '空'}") print("===================") def main(): # 显示游戏指南 show_instructions() # 房间字典:包含房间连接关系和物品信息(符合单字典要求) rooms = { 'Bathroom': {'West': 'Hallway', 'item': None}, # 初始房间 'Hallway': {'East': 'Bathroom', 'South': 'Living Room', 'item': 'Backpack'}, 'Living Room': {'North': 'Hallway', 'West': 'Backyard', 'South': 'Office', 'East': 'Kitchen', 'item': 'Gun'}, 'Backyard': {'East': 'Living Room', 'item': 'Map'}, # 出口房间 'Office': {'North': 'Living Room', 'East': 'Garage', 'item': 'Ammo'}, 'Garage': {'West': 'Office', 'item': 'David'}, 'Kitchen': {'West': 'Living Room', 'North': 'Basement', 'item': 'Long steak knife'}, 'Basement': {'South': 'Kitchen', 'item': 'Zombies'} # 反派房间 } current_room = 'Bathroom' inventory = [] while True: # 触发出口逻辑 if current_room == 'Backyard': print("\n你来到了后院,看到了出口!") if len(inventory) == 6: print("恭喜!你集齐了所有物品和大卫,成功逃离了被感染的豪宅!") else: print("你还没集齐所有必需品,出去也无法存活... 游戏重启!") break # 触发反派房间失败逻辑 if current_room == 'Basement': print("\n你闯进了丧尸房间!被丧尸包围了... GAME OVER!") break # 显示当前状态 show_status(current_room, rooms, inventory) # 物品收集逻辑 room_item = rooms[current_room]['item'] if room_item and room_item != 'Zombies': while True: choice = input(f"是否收集 {room_item}?(Y/N): ").upper() if choice in ['Y', 'N']: break print("输入无效,请输入Y或N") if choice == 'Y': inventory.append(room_item) rooms[current_room]['item'] = None print(f"你收集了 {room_item}!") # 移动逻辑 while True: direction = input("请输入移动方向(South/North/East/West): ").title() # 获取当前房间的有效移动方向(排除item键) valid_directions = [key for key in rooms[current_room].keys() if key != 'item'] if direction in valid_directions: break print(f"从{current_room}无法向{direction}移动,请重新输入") # 更新当前房间 current_room = rooms[current_room][direction] print(f"\n你移动到了 {current_room}") print("-------------------------------------------") print("\n感谢游玩《丧尸豪宅求生》!") # 启动游戏 if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者phendo florez
相关产品推荐
相关产品推荐

