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

Python文本游戏胜负判断逻辑故障:进入反派房间无正确输出

问题修复方案

核心问题排查与修复步骤

1. 修正变量作用域问题

如果你的Inventory是全局定义的列表,但在处理房间移动/物品收集的函数里没声明global Inventory,函数内会创建局部变量,导致全局的物品列表根本没更新,判断自然失效。
修复示例:

Inventory = []  # 全局物品列表

def enter_food_court():
    global Inventory  # 必须声明使用全局变量
    if len(Inventory) == 6:
        print("集齐所有物品,你成功击败外星人!游戏胜利!")
        exit()
    else:
        print("物品没凑齐,外星人抓住了你!游戏失败!")
        exit()

2. 避免物品重复收集

如果收集逻辑没做去重,玩家可能重复拿同一个物品,导致Inventory长度虚高,实际有效物品不足6件。
修复示例:

def collect_item(item):
    global Inventory
    if item not in Inventory:
        Inventory.append(item)
        print(f"你拿到了{item}!当前物品数:{len(Inventory)}/6")
    else:
        print("这个物品你已经有了!")

3. 确保判断逻辑触发时机正确

必须把len(Inventory)的判断放在玩家进入Food Court的瞬间,不能放在其他分支或循环外。比如在处理玩家移动指令的分支里直接执行判断:

while True:
    user_input = input("输入操作:").strip().lower()
    if user_input.startswith("go to food court"):
        # 进入前立刻检查物品数量
        if len(Inventory) == 6:
            print("恭喜!你带着全部道具制服外星人,游戏胜利!")
            break
        else:
            print("道具不足,你被外星人捕获,游戏结束!")
            break
    # 其他房间移动、物品收集逻辑

4. 确认物品总数匹配

检查游戏内设定的可收集物品是否正好是6件,避免出现物品总数不对导致判断永远不成立的情况。

简化修复后的完整示例代码

Inventory = []
# 固定6件可收集物品
required_items = ["激光笔", "能量电池", "隐身斗篷", "解毒剂", "通讯器", "等离子刀"]

def main():
    while True:
        print("\n当前位置:走廊")
        action = input("操作选项:go to [房间]/collect [物品]/quit:").lower().strip()
        
        if action == "quit":
            print("游戏退出")
            break
        
        elif action.startswith("go to"):
            target_room = action.split("go to")[-1].strip()
            if target_room == "food court":
                # 用物品列表长度代替硬编码6,更灵活
                if len(Inventory) == len(required_items):
                    print("你集齐所有道具,成功击败外星反派!游戏胜利!")
                    break
                else:
                    print("物品没凑齐,你被外星人抓住了,游戏失败!")
                    break
            else:
                print(f"你进入了{target_room}")
        
        elif action.startswith("collect"):
            item = action.split("collect")[-1].strip()
            if item in required_items:
                if item not in Inventory:
                    Inventory.append(item)
                    print(f"获得{item}!当前进度:{len(Inventory)}/6")
                else:
                    print("这个物品已经在背包里了!")
            else:
                print("这里没有这个物品!")

if __name__ == "__main__":
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:15:44