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

Python文本冒险游戏房间切换问题:location值无法更新

问题修复:Python文本冒险游戏无法更新玩家位置

你的代码存在几个关键问题导致location值无法更新,以下是针对性修复,完全保留你用单独函数定义房间的设计思路:

核心问题分析

  1. 变量作用域错误:房间函数内的location是局部变量,修改后不会影响外部循环中的全局location变量。
  2. 赋值符号误用:Bedroom()和Cellar()函数里用了==(比较运算符)而非=(赋值运算符),根本没修改位置值。
  3. 循环内重置位置:每次外层while True循环都会把location重新设为Great Hall,导致永远停在初始房间。
  4. 函数定义位置不合理:把房间函数放在外层循环内,每次循环都重复定义函数,完全没必要。

修复后的完整代码

# 简化版龙文本游戏的房间字典,关联各个房间的通行方向
rooms = {
        'Great Hall': {'South': 'Bedroom'},
        'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
        'Cellar': {'West': 'Bedroom'}
    }


instructions = '欢迎来到龙文本游戏。你需要在城堡中收集物品,为击败恶龙做准备。\n\n 游戏会提示你可移动的方向。\n\n 使用"move"命令加方向移动,例如:"move East"。\n 使用"grab"命令收集物品,例如:"grab sword"。'

print(instructions)

# 房间函数移到循环外,仅定义一次
def GreatHall():
    move = ['move south']
    move_input = ''
    while move_input not in move:
        print('唯一可选方向是South。你想往哪走?')
        move_input = input().lower()
        if move_input == 'move south':
            print('你从大厅向南走到卧室。\n卧室是宽敞奢华的空间,天花板很高,挂着吊灯,还有一张看起来很舒服的国王床。\n如果不是要打恶龙,你真想睡一觉。')
            return 'Bedroom'  # 返回新位置,让外部变量接收
        else:
            print('无效选项!请重试。')

def Bedroom():
    move = ['move north', 'move east']
    move_input = ''
    while move_input not in move:
        print('你看到刚才进来的北门,房间东角有个看起来阴森的石拱门通向地下。\n入口又冷又暗。')
        move_input = input().lower()
        if move_input == 'move north':
            print('你回到了大厅。')
            return 'Great Hall'
        elif move_input == 'move east':
            print('你沿着黑暗的通道往下走,发现了一个地窖。')
            return 'Cellar'
        else:
            print('无效选项!请重试。')

def Cellar():
    move = ['move west']
    move_input = ''
    while move_input not in move:
        print('地窖里很黑,只有墙上的一个壁灯照明。墙壁渗着水,房间里充满了明显的霉味。\n除了返回卧室的门,没有其他出入口。')
        move_input = input().lower()
        if move_input == 'move west':
            print('你回到了卧室。')
            return 'Bedroom'
        else:
            print('无效选项!请重试。')

# 初始化玩家位置,放在循环外避免每次重置
location = 'Great Hall'
print('你从大厅开始游戏\n')

while True:
    # 根据当前位置调用对应房间函数,接收返回的新位置
    if location == 'Great Hall':
        location = GreatHall()
    elif location == 'Bedroom':
        location = Bedroom()
    elif location == 'Cellar':
        location = Cellar()

关键修改说明

  • 函数移至循环外:避免每次循环重复定义函数,提升运行效率。
  • 函数返回新位置:每个房间函数完成移动操作后返回目标房间名称,让外部location变量接收该值,实现位置更新。
  • 修正赋值逻辑:移除错误的==比较,改用返回值的方式传递位置(若想直接修改全局变量,也可在函数开头加global location,但返回值的方式更符合函数设计规范)。
  • 位置初始化移至循环外:仅在游戏启动时设置一次初始位置,不会被循环重置。
  • 改用elif判断:每次仅匹配一个房间条件,逻辑更高效清晰。

内容的提问来源于stack exchange,提问作者Jacob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:03:16