Python龙文本游戏:无法从Midgard向北移动至Asgard的调试求助
问题:无法从Midgard向北移动至Asgard
我正在为Python新手开发北欧神话主题的“Dragon Text Game”项目,基础代码大多可正常运行,但从起始房间Midgard尝试向北移动到Asgard时,程序总会阻止并打印“You cannot go North from here. Try again.”。我反复检查过字典语法,也用PyCharm的AI辅助排查,但都没找到问题。
相关代码片段
房间字典
realms = { 'Midgard': {'North': 'Asgard', 'South': 'Muspelheim', 'East': 'Vanaheim', 'West': 'Alfheim'}, 'Asgard': {'North': 'Jotunheim', 'South': 'Midgard', 'East': 'Niflheim'} }
北向移动判断与执行函数
DIRECTION_NORTH = 'North' def can_go_north(current_world): return current_world in realms and DIRECTION_NORTH in realms[current_world]
def go_north(current_world): if can_go_north(current_world): updated_world = realms[current_world][DIRECTION_NORTH] print(f'You are now in the realm of {updated_world}.') print(realm_intro[updated_world]) else: updated_world = current_world print("You cannot go North from here. Try again.") return updated_world
主程序逻辑
while current_realm != 'Hel': print("Enter a command. Enter \"Help\" for list of commands.") command = input() if command == "Help": print('Commands: Get Item, Go North, Go South, Go East, Go West, Help, Inventory.') elif command == "Inventory" : print(inventory) print('You have ',len(inventory),' of seven relics.') elif command == "Get Item": get_item(current_realm) elif command == "Go North" : current_realm = go_north(current_realm) else : print("Invalid command. Enter 'Help' for command list.") if current_realm == 'Hel': endgame()
解决方案
最可能的问题是起始的current_realm变量值与字典中的'Midgard'不精确匹配:
- 比如
current_realm被初始化为全小写的'midgard'、带空格的' Midgard',或者其他拼写变体,导致current_world in realms判断为False,进而can_go_north返回False。
调试与验证方法
- 在
go_north函数开头添加调试输出,查看传入的当前区域值:
def go_north(current_world): # 用repr显示变量的精确内容,包括空格、大小写 print(f"当前传入的区域:{repr(current_world)}") if can_go_north(current_world): # 原函数逻辑...
运行后就能看到current_world的实际值,确认是否和字典中的键一致。
- 优化
can_go_north函数,添加更明确的错误提示,快速定位问题:
def can_go_north(current_world): if current_world not in realms: print(f"调试:当前区域「{current_world}」不在realms字典中") return False if DIRECTION_NORTH not in realms[current_world]: print(f"调试:当前区域「{current_world}」没有北向路径") return False return True
只要确保current_realm的初始值是精确的'Midgard'(大小写一致、无多余空格),北向移动就能正常工作。
内容的提问来源于stack exchange,提问作者Randy Dandy
相关产品推荐
相关产品推荐

