基于文本的RPG中如何通过字典更新current_room变量
文本RPG房间切换变量更新问题解决
核心问题
你的代码中current_room是全局变量,next_room()函数仅获取了下一个房间的名称并打印提示,但没有对全局的current_room进行修改,所以循环中始终显示初始房间。
解决方案
方案1:使用global声明修改全局变量
直接在next_room()中声明要操作全局的current_room,赋值后全局变量会同步更新:
def next_room(): global current_room # 声明要修改全局变量 if "Next room" in the_map[current_room]: current_room = the_map[current_room]["Next room"] print(f"\nYou reached the {current_room}!")
方案2:函数返回新房间,调用方更新变量
这种方式避免直接操作全局变量,更符合模块化设计:
首先修改next_room()函数,接收当前房间并返回新房间:
def next_room(current_room): if "Next room" in the_map[current_room]: new_room = the_map[current_room]["Next room"] print(f"\nYou reached the {new_room}!") return new_room return current_room # 无下一个房间时返回原房间
然后在start_game()的调用处更新current_room:
if user_input == "1": current_room = next_room(current_room)
额外提示
你的地图字典存在一处拼写错误:'Destroyed Village'的'Previous room'值写为'The Ruins',应该改为'Ruins',否则后续实现返回上一房间的功能时会无法匹配。
内容的提问来源于stack exchange,提问作者Magnus Xavier
相关产品推荐
相关产品推荐

