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

Python文本游戏elif语句不执行 无法从卧室移动到地窖

问题根源

代码存在3个核心错误,导致玩家永远无法进入Cellar:

  • 连续使用独立if判断当前位置,没有做分支互斥:当你在Bedroom选择East方向时,代码确实会先执行location = 'Cellar'的赋值,但紧接着下一个独立的if location == 'Cellar'判断会立刻触发,直接把位置改回Bedroom,相当于刚进入地窖就被强制传送回卧室。
  • 无效分支判断逻辑错误:direction is not possible_moves用is做判断是比较两个对象的内存地址,不是判断成员关系,这个判断本身永远成立,属于完全冗余的错误逻辑。
  • 循环退出条件写错:while direction != exit里的exit是Python内置函数,和你后面判断的字符串'Exit'没有任何关联,初始循环条件逻辑就不成立。
  • 额外冗余问题:你已经提前定义了rooms字典存储每个房间各方向对应的目的地,完全不需要手写多层if硬编码移动规则,直接查表就能实现移动,代码更简洁也不容易出错。
修复后可运行代码
rooms = {
    'Great Hall': {'South': 'Bedroom'},
    'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
    'Cellar': {'West': 'Bedroom'}
}

location = 'Great Hall'
direction = ""

while True:
    print("\nYou are in the", location)
    possible_moves = rooms[location].keys()
    print("Possible moves:", *possible_moves, "Exit")

    direction = input("Which direction do you wish to go? ").strip().capitalize()
    print("You entered:", direction)

    # 优先判断退出指令
    if direction == 'Exit':
        print("Thank you for playing the game.")
        break
    # 判断是否为合法移动方向
    elif direction in possible_moves:
        # 直接从预定义字典读取目标房间,不需要硬编码多层位置判断
        location = rooms[location][direction]
    # 其余情况均为无效输入
    else:
        print('Invalid direction.')
关键修改说明
  • 把循环改成while True,将退出判断放在输入处理的最前端,避免和Python内置exit函数混淆
  • 删除所有硬编码的位置判断逻辑,直接通过rooms[当前位置][输入方向]获取目标位置,从根源上避免连续if导致的赋值覆盖问题
  • 删除错误的is判断,用elif/else做分支互斥,逻辑链路更清晰
  • 在可移动操作提示里补充了Exit选项,避免玩家不知道退出方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 21:33:19