You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

文本游戏房间移动功能问题:无法更新当前房间及方向输出格式异常

文本游戏房间移动功能问题:无法更新当前房间及方向输出格式异常

嘿,别着急,我帮你看看这两个问题——其实都是代码里的小细节没处理好,很容易解决的!

问题1:每次移动后总是回到Great Hall

你代码里的核心问题是**current_room = 'Great Hall'放在了while循环的里面**,这意味着每次循环都会把当前房间重置回大厅,不管你之前移动到哪里了。只要把这个初始化语句移到while循环外面,就能让current_room在循环里保持更新啦。

问题2:方向显示成dict_keys的奇怪格式

rooms[current_room].keys()返回的是字典键的视图对象,直接打印就会显示成dict_keys(['South'])这种不友好的样子。我们可以用', '.join()把它转换成逗号分隔的字符串,比如', '.join(rooms[current_room].keys()),这样输出就会变成South或者North, East这种清晰的格式了。

修改后的完整代码

rooms = {
    'Great Hall': {'South': 'Bedroom'},
    'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
    'Cellar': {'West': 'Bedroom'}
}


def move_room(user_input, current_room):
    valid_directions = rooms[current_room].keys()
    if user_input in valid_directions:
        next_room = rooms[current_room][user_input]
        print("You have moved to", next_room)
        return next_room
    else:
        print("There is no exit that way.")
        return current_room


def main():
    # 把当前房间初始化放在循环外面,避免每次重置
    current_room = 'Great Hall'
    while True:
        print('You are in the', current_room)
        # 把dict_keys转换成友好的字符串格式
        print('You can move', ', '.join(rooms[current_room].keys()))
        user_input = input("Enter a direction:")
        if user_input != 'exit':
            current_room = move_room(user_input, current_room)
        else:
            print("Goodbye")
            break


if __name__ == '__main__':
    main()

测试效果

现在运行代码,你移动到Bedroom后,会显示:

You are in the Bedroom
You can move North, East
Enter a direction:

完全符合你的需求啦!另外你之前尝试用全局变量的思路其实没必要,只要把current_room放在循环外,在循环里直接更新它就足够了,这样代码更整洁也符合函数封装的原则。

备注:内容来源于stack exchange,提问作者Abyssal Cleric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:13:00