跳到正文

科技·工程

地图迷宫

Chenguoyao44约 60 分钟
原文

这是 2025年11月24日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月15日
篇幅
约 60 分钟

版本

  1. v2当前
  2. v1

v1.02 迷宫逃生游戏 - 规则与地图场景梳理 一、核心玩法 玩家在 20x20 的迷宫中,需避开 3 只鬼魂,找到并停留在门的位置 1 回合即可获胜;过程中可拾取道具箱获得道具,用道具辅助逃生或对抗鬼魂。 二、地图场景详情

  1. 地图基础信息 尺寸:20x20 网格(横向 x 轴 0-19,纵向 y 轴 0-19) 核心元素及功能: 元素 字符 作用 玩家 P 可通过 W/S/A/D 移动、空格等待、数字键使用道具,被鬼魂触碰则失败 鬼魂 G 活跃状态下向玩家移动,冻结 / 死亡状态不可移动,触碰玩家直接导致游戏失败 墙 # 不可穿透、不可移动到上方,阻断视野(潜望镜除外) 地板 . 可正常移动,无特殊效果 道具箱 C 共 45 个,拾取后随机获得 1 种道具,拾取后变为地板 门 D 逃生目标,初始隐藏,需停留在上方 1 回合获胜(地图道具可临时显示位置) 视野盲区 空格 玩家视野外或被墙阻挡的区域,不显示任何元素(地图道具显示的门除外)
  2. 场景生成规则 玩家初始位置:随机生成在左上角区域(x0-9,y0-9) 门初始位置:随机生成在右下角区域(x10-19,y10-19),与玩家初始位置对角,避免开局直接相遇 墙:共 80 个,随机生成但不阻断玩家到门的核心通路(x+y 在 10-25 之间的区域不生成墙),确保玩家有逃生路径 道具箱:共 45 个,随机生成在地板上,不会覆盖玩家、门或墙的位置 鬼魂初始位置:3 只鬼魂随机生成,满足 3 个条件:① 与玩家初始距离≥15 格;② 与玩家位置连通(有路径可达);③ 3 只鬼魂位置互不重复 三、核心规则(角色 + 道具 + 胜负条件)
  3. 玩家规则 移动:W(上,y-1)、S(下,y+1)、A(左,x-1)、D(右,x+1),不可穿墙 等待:按空格键可停留 1 回合,不移动但消耗回合数 道具:背包最多容纳 10 个道具,按数字键 1-9 使用对应位置的道具(使用后消耗道具) 拾取:移动到道具箱(C)位置自动拾取,获得随机道具
  4. 鬼魂规则 状态 触发条件 效果 活跃 初始状态 / 复活后 随机选择 x 或 y 方向向玩家移动,无法穿墙,也不会移动到其他活跃鬼魂的位置 冻结 玩家使用保命符 持续 3 回合,期间不可移动,不攻击玩家 死亡 被玩家用石子击中 持续 8 回合,期间不显示、不移动、不攻击,复活后回到死亡位置并解除冻结 复活 死亡倒计时结束(8 回合) 恢复活跃状态,位置重置为死亡时的坐标
  5. 道具规则(共 5 种,道具箱随机产出) 道具 数量 效果说明 持续回合 使用后提示 探测仪 10 显示所有存活鬼魂的位置和与玩家的距离,不穿墙但无视野范围限制 1 ✅ 显示所有存活鬼魂位置和距离 保命符 10 冻结所有存活鬼魂,使其无法移动和攻击 3 ✅ 所有存活鬼魂冻结 3 回合 潜望镜 10 显示所有存活鬼魂位置,视野范围扩大到 8 格,且可穿透墙壁(无视野阻挡) 1 ✅ 8 格视野 + 穿墙 + 显示所有鬼魂 地图 5 显示门的位置,不受视野和墙壁阻挡 1 ✅ 门的位置已显示(持续 1 回合) 石子 10 使用后需选择发射方向(W/S/A/D),沿直线发射,无法穿透墙壁: ① 击中鬼魂→鬼魂死亡 8 回合; ② 碰墙 / 出边界→发射失败 -(一次性) 💥 击中鬼魂 /🪨 发射失败
  6. 视野规则 默认可视范围:以玩家为中心,5 格半径(直线距离≤5) 视野阻挡:默认情况下,墙会阻断视野(被墙挡住的区域即使在 5 格内也显示为盲区) 特殊视野:潜望镜生效时,视野范围扩大到 8 格,且可穿透墙壁(无视野阻挡) 鬼魂显示:① 无道具时,仅在玩家视野内且无墙阻挡才显示;② 探测仪 / 潜望镜生效时,所有存活鬼魂强制显示
  7. 胜负条件 结果 触发条件 结束提示 获胜 玩家移动到门(D)的位置,并停留 1 回合(winWaitTurn≥1) 🎉 恭喜你!成功逃生! 失败 玩家与活跃鬼魂的位置完全重合(被鬼魂抓住) 💀 游戏结束!被鬼魂抓住了! 退出 玩家按 Q 键 👋 游戏已退出! 四、游戏流程逻辑 初始化:生成地图(墙、道具箱、门)→ 生成玩家、3 只不重复且远离玩家的鬼魂→ 隐藏光标 主循环:绘制游戏界面→ 检测玩家输入(移动 / 使用道具 / 退出)→ 更新道具持续回合→ 更新鬼魂状态(冻结倒计时 / 死亡复活)→ 鬼魂移动(活跃状态下)→ 检测胜负条件 输入处理: 移动 / 等待 / 退出:直接执行对应操作,消耗 1 回合 使用道具:数字键选择道具,石子需额外选择发射方向,使用后消耗 1 回合(生效道具占用道具槽,最多同时生效 4 个) 五、关键限制 背包上限:最多 10 个道具,背包满时无法拾取新道具 生效道具槽上限:最多同时生效 4 个道具,无空槽时新道具会替换同类型已生效道具 石子发射:仅能横向(左右)或纵向(上下)发射,无法斜向发射,且不能穿透墙壁
C++
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#include <math.h>
#include <string.h>

// 游戏常量定义
#define MAP_SIZE 20          // 20x20 地图
#define WALL_COUNT 80        // 墙数量
#define CABINET_COUNT 45     // 道具箱数量(增加5个)
#define PLAYER_CHAR 'P'      // 玩家角色
#define GHOST_CHAR 'G'       // 鬼魂角色
#define WALL_CHAR '#'        // 墙
#define FLOOR_CHAR '.'       // 地板
#define CABINET_CHAR 'C'     // 道具箱
#define DOOR_CHAR 'D'        // 门
#define BLIND_CHAR ' '       // 视野盲区
#define HIDDEN_GHOST_CHAR ' '// 鬼魂隐藏时
#define GHOST_NUM 3          // 鬼魂数量
#define MIN_INIT_DISTANCE 15 // 初始距离
#define PLAYER_VIEW 5        // 默认可视范围
#define VIEW_8 8             // 潜望镜视野
#define PROBE_TURN 1         // 探测仪持续回合
#define AMULET_TURN 3        // 保命符持续回合
#define PERISCOPE_TURN 1     // 潜望镜持续回合
#define MAP_TURN 1           // 地图持续回合
#define STONE_TURN 8         // 鬼魂复活时间(8回合)
#define BUF_SIZE 4096        // 绘制缓冲区大小

// 道具类型枚举(新增石子)
typedef enum ItemTypeEnum {
    NONE,        // 无道具
    PROBE,       // 探测仪(显示所有鬼魂+距离)
    AMULET,      // 保命符(冻结鬼魂)
    PERISCOPE,   // 潜望镜(显示所有鬼魂+穿墙+大视野)
    MAP_ITEM,    // 地图(显示门)
    STONE        // 石子(攻击鬼魂,使其死亡8回合)
} ItemType;

// 道具数量定义(探测仪从15改为10,新增石子10个)
#define PROBE_COUNT 10
#define AMULET_COUNT 10
#define PERISCOPE_COUNT 10
#define MAP_ITEM_COUNT 5
#define STONE_COUNT 10

// 位置结构体
typedef struct PositionStruct {
    int x;
    int y;
} Position;

// 背包结构体
typedef struct BackpackStruct {
    ItemType items[10]; // 最多10个道具
    int count;          // 当前道具数
} Backpack;

// 生效道具结构体
typedef struct ActiveItemStruct {
    ItemType type;          // 道具类型
    int remainingTurns;     // 剩余回合
} ActiveItem;

// 鬼魂状态结构体(新增死亡/复活相关)
typedef struct GhostStateStruct {
    Position pos;           // 位置
    int frozen;             // 冻结状态(0=未冻结)
    int dead;               // 死亡状态(0=存活,1=死亡)
    int reviveTimer;        // 复活计时器(死亡时倒计时)
    Position deathPos;      // 死亡位置(复活后回到该位置)
} Ghost;

// 全局变量
char map[MAP_SIZE][MAP_SIZE];    // 地图
Position player;                 // 玩家位置
Ghost ghosts[GHOST_NUM];         // 鬼魂状态(替换原Position数组)
Position door;                   // 门位置
Backpack backpack;               // 背包
ActiveItem activeItems[4];        // 生效道具(最多4个)
int doorFound;                   // 门是否显示(地图道具)
int winWaitTurn;                 // 门上等待回合
int isUsingItem;                 // 是否刚使用道具
char lastMsg[100];               // 临时提示信息

// 函数声明(新增石子相关函数)
void initGame();                 // 初始化游戏
void initBackpack();             // 初始化背包
void initActiveItems();          // 初始化生效道具
void initMap();                  // 初始化地图
void initCharacters();           // 初始化角色(玩家+鬼魂+门)
int addToBackpack(ItemType type); // 添加道具到背包
int useItemFromBackpack(int index); // 使用道具
void useStone();                 // 使用石子(新增)
int fireStone(int dir);          // 发射石子(新增)
int isPositionOccupied(Position pos); // 检查位置是否被其他鬼魂占用(新增)
void waitForEnter();             // 等待回车
void updateActiveItems();        // 更新生效道具回合
void updateGhostsState();        // 更新鬼魂状态(新增:处理复活)
int hasActiveItem(ItemType type); // 检查道具是否生效
int shouldShowGhost(Ghost ghost); // 判断鬼魂是否显示(修改参数类型)
double calculateDistance(Position a, Position b); // 计算距离
int isValidPosition(int x, int y); // 位置是否合法
int isBlocked(Position from, Position to); // 是否被墙阻挡
int isConnected(Position start, Position end); // 两点是否连通
Position getRandomPosition();    // 获取随机合法位置
int isPlayerCaught();            // 玩家是否被抓
int isPlayerWin();               // 玩家是否获胜
void movePlayer(int dx, int dy); // 移动玩家
void moveGhosts();               // 移动鬼魂
void drawGame();                 // 绘制游戏(无闪核心)
void hideCursor();               // 隐藏光标
void gameLoop();                 // 游戏主循环

// 隐藏光标(兼容所有Windows编译器)
void hideCursor() {
    CONSOLE_CURSOR_INFO cci;
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleCursorInfo(hOut, &cci);
    cci.bVisible = FALSE; // 隐藏光标
    SetConsoleCursorInfo(hOut, &cci);
}

// 初始化背包
void initBackpack() {
    backpack.count = 0;
    memset(backpack.items, NONE, sizeof(backpack.items));
}

// 初始化生效道具
void initActiveItems() {
    memset(activeItems, NONE, sizeof(activeItems));
    for (int i = 0; i < 4; i++) {
        activeItems[i].remainingTurns = 0;
    }
}

// 初始化地图
void initMap() {
    // 1. 全图初始化为地板
    for (int i = 0; i < MAP_SIZE; i++) {
        for (int j = 0; j < MAP_SIZE; j++) {
            map[i][j] = FLOOR_CHAR;
        }
    }

    // 2. 随机玩家和门位置(对角区域,避免开局相遇)
    player.x = rand() % 10;
    player.y = rand() % 10;
    door.x = 10 + rand() % 10;
    door.y = 10 + rand() % 10;
    map[door.x][door.y] = DOOR_CHAR;

    // 3. 生成墙(不阻断玩家到门的路径)
    int wallCount = 0;
    while (wallCount < WALL_COUNT) {
        int x = rand() % MAP_SIZE;
        int y = rand() % MAP_SIZE;

        // 跳过玩家、门、核心通路区域
        if ((x == player.x && y == player.y) || (x == door.x && y == door.y)) {
            continue;
        }
        if ((x + y) >= 10 && (x + y) <= 25) { // 核心通路,不生成墙
            continue;
        }

        // 临时放墙,检查是否阻断路径
        map[x][y] = WALL_CHAR;
        if (isConnected(player, door)) {
            wallCount++; // 不阻断,保留墙
        } else {
            map[x][y] = FLOOR_CHAR; // 阻断,移除墙
        }
    }

    // 4. 生成道具箱(45个,增加5个)
    int cabinetCount = 0;
    while (cabinetCount < CABINET_COUNT) {
        int x = rand() % MAP_SIZE;
        int y = rand() % MAP_SIZE;
        if (map[x][y] == FLOOR_CHAR) {
            map[x][y] = CABINET_CHAR;
            cabinetCount++;
        }
    }
}

// 检查位置是否被其他鬼魂占用(新增)
int isPositionOccupied(Position pos) {
    for (int i = 0; i < GHOST_NUM; i++) {
        if (ghosts[i].pos.x == pos.x && ghosts[i].pos.y == pos.y) {
            return 1; // 已被占用
        }
    }
    return 0; // 未被占用
}

// 初始化角色(玩家+鬼魂+门)
void initCharacters() {
    // 初始化鬼魂位置(随机、不重复、远离玩家、且与玩家连通)
    for (int i = 0; i < GHOST_NUM; i++) {
        int tryCount = 0;
        Position pos;
        do {
            pos = getRandomPosition();
            tryCount++;
            if (tryCount > 1000) { // 防止死循环
                pos.x = MAP_SIZE - 1 - i; // 确保不重复
                pos.y = MAP_SIZE - 1 - i;
                break;
            }
        } while (calculateDistance(player, pos) <= MIN_INIT_DISTANCE || 
                 !isConnected(player, pos) || 
                 isPositionOccupied(pos)); // 新增:检查是否被其他鬼魂占用
        
        // 初始化鬼魂状态
        ghosts[i].pos = pos;
        ghosts[i].frozen = 0;
        ghosts[i].dead = 0;
        ghosts[i].reviveTimer = 0;
        ghosts[i].deathPos = pos;
    }

    doorFound = 0;       // 门初始不显示
    winWaitTurn = 0;     // 初始未在门上
    isUsingItem = 0;     // 初始未使用道具
    memset(lastMsg, 0, sizeof(lastMsg)); // 清空提示
}

// 初始化游戏(统一入口)
void initGame() {
    srand((unsigned int)time(NULL)); // 随机种子
    initBackpack();
    initActiveItems();
    initMap();
    initCharacters();
    hideCursor(); // 隐藏光标,减少闪动
}

// 添加道具到背包
int addToBackpack(ItemType type) {
    if (backpack.count >= 10) {
        strcpy(lastMsg, "❌ 背包已满!无法拾取道具!");
        return 0;
    }
    backpack.items[backpack.count++] = type;
    return 1;
}

// 发射石子(新增)
int fireStone(int dir) {
    // dir:0=上,1=下,2=左,3=右
    int dx = 0, dy = 0;
    switch (dir) {
        case 0: dy = -1; break; // 上(y减小)
        case 1: dy = 1;  break; // 下(y增大)
        case 2: dx = -1; break; // 左(x减小)
        case 3: dx = 1;  break; // 右(x增大)
    }

    int x = player.x + dx;
    int y = player.y + dy;

    // 沿方向发射,直到碰到墙或边界
    while (isValidPosition(x, y)) {
        // 检查是否击中鬼魂
        for (int i = 0; i < GHOST_NUM; i++) {
            if (!ghosts[i].dead && ghosts[i].pos.x == x && ghosts[i].pos.y == y) {
                // 击中鬼魂,设置死亡状态
                ghosts[i].dead = 1;
                ghosts[i].reviveTimer = STONE_TURN;
                ghosts[i].deathPos = ghosts[i].pos; // 记录死亡位置
                sprintf(lastMsg, "💥 石子击中G%d!鬼魂死亡,%d回合后复活!", i+1, STONE_TURN);
                return 1;
            }
        }

        // 碰到墙,停止发射
        if (map[x][y] == WALL_CHAR) {
            strcpy(lastMsg, "🪨 石子碰到墙壁,发射失败!");
            return 0;
        }

        // 继续前进
        x += dx;
        y += dy;
    }

    // 超出边界,发射失败
    strcpy(lastMsg, "🪨 石子超出边界,发射失败!");
    return 0;
}

// 使用石子(新增)
void useStone() {
    strcpy(lastMsg, "🪨 请选择发射方向:W(上) S(下) A(左) D(右)");
    drawGame(); // 显示方向选择提示

    // 等待玩家选择方向
    char key;
    while (1) {
        if (kbhit()) {
            key = getch();
            if (key == 'w' || key == 'W') {
                fireStone(0);
                break;
            } else if (key == 's' || key == 'S') {
                fireStone(1);
                break;
            } else if (key == 'a' || key == 'A') {
                fireStone(2);
                break;
            } else if (key == 'd' || key == 'D') {
                fireStone(3);
                break;
            } else {
                strcpy(lastMsg, "❌ 无效方向!请选择 W/S/A/D 发射方向");
                drawGame();
                Sleep(500);
            }
        }
        Sleep(50);
    }
}

// 使用背包道具
int useItemFromBackpack(int index) {
    if (index < 0 || index >= backpack.count) {
        strcpy(lastMsg, "❌ 道具编号无效!");
        return 0;
    }

    ItemType type = backpack.items[index];
    // 移除道具(向前移位)
    for (int i = index; i < backpack.count - 1; i++) {
        backpack.items[i] = backpack.items[i + 1];
    }
    backpack.count--;

    // 处理石子道具(单独处理,需要选择方向)
    if (type == STONE) {
        useStone();
        isUsingItem = 1;
        return 1;
    }

    // 其他道具处理
    // 查找空的生效道具槽
    int slotIndex = -1;
    for (int i = 0; i < 4; i++) {
        if (activeItems[i].type == NONE) {
            slotIndex = i;
            break;
        }
    }
    // 无空槽则替换同类型道具
    if (slotIndex == -1) {
        for (int i = 0; i < 4; i++) {
            if (activeItems[i].type == type) {
                slotIndex = i;
                break;
            }
        }
    }
    if (slotIndex == -1) {
        strcpy(lastMsg, "❌ 生效道具槽已满!无法使用道具!");
        return 0;
    }

    // 生效道具
    activeItems[slotIndex].type = type;
    switch (type) {
        case AMULET:
            activeItems[slotIndex].remainingTurns = AMULET_TURN;
            for (int i = 0; i < GHOST_NUM; i++) {
                if (!ghosts[i].dead) { // 只冻结存活的鬼魂
                    ghosts[i].frozen = AMULET_TURN;
                }
            }
            strcpy(lastMsg, "✅ 使用了保命符!所有存活鬼魂冻结3回合!");
            break;
        case MAP_ITEM:
            activeItems[slotIndex].remainingTurns = MAP_TURN;
            doorFound = 1;
            strcpy(lastMsg, "✅ 使用了地图!门的位置已显示(持续1回合)!");
            break;
        case PROBE:
            activeItems[slotIndex].remainingTurns = PROBE_TURN;
            strcpy(lastMsg, "✅ 使用了探测仪!显示所有存活鬼魂位置和距离(持续1回合)!");
            break;
        case PERISCOPE:
            activeItems[slotIndex].remainingTurns = PERISCOPE_TURN;
            strcpy(lastMsg, "✅ 使用了潜望镜!显示所有存活鬼魂+8格视野+穿墙(持续1回合)!");
            break;
        default:
            break;
    }

    isUsingItem = 1;
    return 1;
}

// 等待回车继续
void waitForEnter() {
    printf("\n按回车键继续...");
    char ch;
    do {
        ch = getch();
    } while (ch != 13); // 13是Enter键ASCII码
    // 清除回车提示(覆盖绘制)
    printf("\r                     ");
}

// 更新生效道具回合
void updateActiveItems() {
    for (int i = 0; i < 4; i++) {
        if (activeItems[i].type != NONE) {
            if (activeItems[i].remainingTurns <= 1) {
                // 道具效果结束
                switch (activeItems[i].type) {
                    case PROBE:
                        strcpy(lastMsg, "❌ 探测仪效果结束!仅视野内鬼魂可见!");
                        break;
                    case AMULET:
                        strcpy(lastMsg, "❌ 保命符效果结束!鬼魂恢复移动!");
                        break;
                    case PERISCOPE:
                        strcpy(lastMsg, "❌ 潜望镜效果结束!视野恢复正常!");
                        break;
                    case MAP_ITEM:
                        strcpy(lastMsg, "❌ 地图效果结束!门隐藏!");
                        doorFound = 0;
                        break;
                    default:
                        break;
                }
                activeItems[i].type = NONE;
                activeItems[i].remainingTurns = 0;
            } else {
                activeItems[i].remainingTurns--;
            }
        }
    }
}

// 更新鬼魂状态(处理复活,新增)
void updateGhostsState() {
    for (int i = 0; i < GHOST_NUM; i++) {
        if (ghosts[i].dead) {
            ghosts[i].reviveTimer--;
            if (ghosts[i].reviveTimer <= 0) {
                // 复活:回到死亡位置,恢复存活状态
                ghosts[i].dead = 0;
                ghosts[i].pos = ghosts[i].deathPos;
                ghosts[i].frozen = 0; // 复活后解除冻结
                sprintf(lastMsg, "👻 G%d复活了!小心!", i+1);
            }
        }
    }
}

// 检查道具是否生效
int hasActiveItem(ItemType type) {
    for (int i = 0; i < 4; i++) {
        if (activeItems[i].type == type) {
            return 1;
        }
    }
    return 0;
}

// 判断鬼魂是否显示(修改参数类型为Ghost)
int shouldShowGhost(Ghost ghost) {
    if (ghost.dead) {
        return 0; // 死亡鬼魂不显示
    }

    // 道具生效:显示所有存活鬼魂
    if (hasActiveItem(PROBE) || hasActiveItem(PERISCOPE)) {
        return 1;
    }

    // 无道具:仅显示视野内+无阻挡的存活鬼魂
    int viewRange = hasActiveItem(PERISCOPE) ? VIEW_8 : PLAYER_VIEW;
    double dist = calculateDistance(player, ghost.pos);
    int inView = (dist <= viewRange); // 在视野内
    int blocked = isBlocked(player, ghost.pos); // 无阻挡

    return (inView && !blocked);
}

// 计算两点距离
double calculateDistance(Position a, Position b) {
    int dx = a.x - b.x;
    int dy = a.y - b.y;
    return sqrt((double)(dx*dx + dy*dy));
}

// 位置是否合法(在地图内+不是墙)
int isValidPosition(int x, int y) {
    return (x >= 0 && x < MAP_SIZE && y >= 0 && y < MAP_SIZE && map[x][y] != WALL_CHAR);
}

// 两点间是否被墙阻挡
int isBlocked(Position from, Position to) {
    if (hasActiveItem(PERISCOPE)) {
        return 0; // 潜望镜穿墙
    }

    // 水平方向
    if (from.y == to.y) {
        int minX = (from.x < to.x) ? from.x : to.x;
        int maxX = (from.x > to.x) ? from.x : to.x;
        for (int x = minX + 1; x < maxX; x++) {
            if (map[x][from.y] == WALL_CHAR) {
                return 1;
            }
        }
    }
    // 垂直方向
    else if (from.x == to.x) {
        int minY = (from.y < to.y) ? from.y : to.y;
        int maxY = (from.y > to.y) ? from.y : to.y;
        for (int y = minY + 1; y < maxY; y++) {
            if (map[from.x][y] == WALL_CHAR) {
                return 1;
            }
        }
    }
    // 斜向视为无阻挡
    else {
        return 0;
    }
    return 0;
}

// BFS判断两点是否连通(确保路径存在)
int isConnected(Position start, Position end) {
    int visited[MAP_SIZE][MAP_SIZE] = {0}; // 访问标记
    Position queue[MAP_SIZE * MAP_SIZE];   // BFS队列
    int front = 0, rear = 0;

    queue[rear++] = start;
    visited[start.x][start.y] = 1;

    // 四个方向
    int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    while (front < rear) {
        Position p = queue[front++];
        if (p.x == end.x && p.y == end.y) {
            return 1; // 连通
        }

        for (int i = 0; i < 4; i++) {
            int nx = p.x + dirs[i][0];
            int ny = p.y + dirs[i][1];
            if (isValidPosition(nx, ny) && !visited[nx][ny]) {
                visited[nx][ny] = 1;
                queue[rear++] = (Position){nx, ny};
            }
        }
    }
    return 0; // 不连通
}

// 获取随机合法位置(非墙)
Position getRandomPosition() {
    Position p;
    int tryCount = 0;
    do {
        p.x = rand() % MAP_SIZE;
        p.y = rand() % MAP_SIZE;
        tryCount++;
        if (tryCount > 1000) { // 防止死循环
            p.x = 0;
            p.y = 0;
            break;
        }
    } while (map[p.x][p.y] == WALL_CHAR);
    return p;
}

// 玩家是否被鬼魂抓住
int isPlayerCaught() {
    for (int i = 0; i < GHOST_NUM; i++) {
        if (!ghosts[i].dead && player.x == ghosts[i].pos.x && player.y == ghosts[i].pos.y) {
            return 1; // 只有存活的鬼魂能抓玩家
        }
    }
    return 0;
}

// 玩家是否获胜
int isPlayerWin() {
    return (winWaitTurn >= 1);
}

// 移动玩家
void movePlayer(int dx, int dy) {
    int newX = player.x + dx;
    int newY = player.y + dy;

    if (isValidPosition(newX, newY)) {
        player.x = newX;
        player.y = newY;

        // 拾取道具箱
        if (map[player.x][player.y] == CABINET_CHAR) {
            // 道具总数量:探测仪10 + 保命符10 + 潜望镜10 + 地图5 + 石子10 = 45(与道具箱数量一致)
            int total = PROBE_COUNT + AMULET_COUNT + PERISCOPE_COUNT + MAP_ITEM_COUNT + STONE_COUNT;
            int randVal = rand() % total;
            ItemType item;

            if (randVal < PROBE_COUNT) {
                item = PROBE;
                strcpy(lastMsg, "🎁 找到道具箱!获得探测仪!");
            } else if (randVal < PROBE_COUNT + AMULET_COUNT) {
                item = AMULET;
                strcpy(lastMsg, "🎁 找到道具箱!获得保命符!");
            } else if (randVal < PROBE_COUNT + AMULET_COUNT + PERISCOPE_COUNT) {
                item = PERISCOPE;
                strcpy(lastMsg, "🎁 找到道具箱!获得潜望镜!");
            } else if (randVal < PROBE_COUNT + AMULET_COUNT + PERISCOPE_COUNT + MAP_ITEM_COUNT) {
                item = MAP_ITEM;
                strcpy(lastMsg, "🎁 找到道具箱!获得地图!");
            } else {
                item = STONE;
                strcpy(lastMsg, "🎁 找到道具箱!获得石子!");
            }

            addToBackpack(item);
            map[player.x][player.y] = FLOOR_CHAR; // 拾取后变为地板
        }

        // 在门上等待
        if (map[player.x][player.y] == DOOR_CHAR) {
            winWaitTurn++;
            sprintf(lastMsg, "🚪 在门上!等待1回合即可获胜!当前:%d/1", winWaitTurn);
        } else {
            winWaitTurn = 0;
            if (dx == 0 && dy == 0) {
                strcpy(lastMsg, "⏳ 等待1回合!");
            } else {
                memset(lastMsg, 0, sizeof(lastMsg)); // 移动无提示
            }
        }
    } else {
        strcpy(lastMsg, "❌ 无法移动!前方有障碍物!");
    }
}

// 移动鬼魂
void moveGhosts() {
    for (int i = 0; i < GHOST_NUM; i++) {
        if (ghosts[i].dead || ghosts[i].frozen > 0) {
            if (ghosts[i].frozen > 0) {
                ghosts[i].frozen--;
            }
            continue; // 死亡或冻结的鬼魂不移动
        }

        // 向玩家方向移动(x或y方向随机选)
        int dir = rand() % 2;
        int dx = 0, dy = 0;

        if (dir == 0) {
            dx = (player.x > ghosts[i].pos.x) ? 1 : (player.x < ghosts[i].pos.x) ? -1 : 0;
        } else {
            dy = (player.y > ghosts[i].pos.y) ? 1 : (player.y < ghosts[i].pos.y) ? -1 : 0;
        }

        int newX = ghosts[i].pos.x + dx;
        int newY = ghosts[i].pos.y + dy;
        if (isValidPosition(newX, newY)) {
            // 检查新位置是否被其他存活鬼魂占用
            int occupied = 0;
            for (int j = 0; j < GHOST_NUM; j++) {
                if (i != j && !ghosts[j].dead && ghosts[j].pos.x == newX && ghosts[j].pos.y == newY) {
                    occupied = 1;
                    break;
                }
            }
            if (!occupied) {
                ghosts[i].pos.x = newX;
                ghosts[i].pos.y = newY;
                continue;
            }
        }

        // 无法移动时随机走一步
        int dirs[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
        int r = rand() % 4;
        newX = ghosts[i].pos.x + dirs[r][0];
        newY = ghosts[i].pos.y + dirs[r][1];
        if (isValidPosition(newX, newY)) {
            // 检查新位置是否被其他存活鬼魂占用
            int occupied = 0;
            for (int j = 0; j < GHOST_NUM; j++) {
                if (i != j && !ghosts[j].dead && ghosts[j].pos.x == newX && ghosts[j].pos.y == newY) {
                    occupied = 1;
                    break;
                }
            }
            if (!occupied) {
                ghosts[i].pos.x = newX;
                ghosts[i].pos.y = newY;
            }
        }
    }
}

// 绘制游戏(无闪核心:批量输出+覆盖绘制)
void drawGame() {
    char buf[BUF_SIZE] = {0}; // 缓冲区,批量拼接所有内容
    int idx = 0; // 缓冲区索引

    // 1. 游戏标题和控制说明(新增石子使用说明)
    idx += sprintf(buf + idx, "===== 迷宫逃生游戏 =====\n");
    idx += sprintf(buf + idx, "控制:W(上) S(下) A(左) D(右) 空格(等待) Q(退出)\n");
    idx += sprintf(buf + idx, "道具:按 1-%d 使用(消耗1回合)| 石子使用:选择后按W/S/A/D发射\n", backpack.count > 0 ? backpack.count : 0);

    // 2. 背包信息(新增石子显示)
    idx += sprintf(buf + idx, "背包:");
    if (backpack.count == 0) {
        idx += sprintf(buf + idx, "无");
    } else {
        for (int i = 0; i < backpack.count; i++) {
            if (backpack.items[i] == PROBE) {
                idx += sprintf(buf + idx, "[%d]探测仪 ", i+1);
            } else if (backpack.items[i] == AMULET) {
                idx += sprintf(buf + idx, "[%d]保命符 ", i+1);
            } else if (backpack.items[i] == PERISCOPE) {
                idx += sprintf(buf + idx, "[%d]潜望镜 ", i+1);
            } else if (backpack.items[i] == MAP_ITEM) {
                idx += sprintf(buf + idx, "[%d]地图 ", i+1);
            } else if (backpack.items[i] == STONE) {
                idx += sprintf(buf + idx, "[%d]石子 ", i+1);
            }
        }
    }
    idx += sprintf(buf + idx, "\n");

    // 3. 生效中道具
    idx += sprintf(buf + idx, "生效中道具:");
    int hasActive = 0;
    for (int i = 0; i < 4; i++) {
        if (activeItems[i].type != NONE) {
            hasActive = 1;
            if (activeItems[i].type == PROBE) {
                idx += sprintf(buf + idx, "探测仪(%d回合) ", activeItems[i].remainingTurns);
            } else if (activeItems[i].type == AMULET) {
                idx += sprintf(buf + idx, "保命符(%d回合) ", activeItems[i].remainingTurns);
            } else if (activeItems[i].type == PERISCOPE) {
                idx += sprintf(buf + idx, "潜望镜(%d回合) ", activeItems[i].remainingTurns);
            } else if (activeItems[i].type == MAP_ITEM) {
                idx += sprintf(buf + idx, "地图(%d回合) ", activeItems[i].remainingTurns);
            }
        }
    }
    if (!hasActive) {
        idx += sprintf(buf + idx, "无");
    }
    idx += sprintf(buf + idx, "\n");

    // 4. 鬼魂状态(新增死亡/复活倒计时显示)
    idx += sprintf(buf + idx, "鬼魂状态:");
    for (int i = 0; i < GHOST_NUM; i++) {
        if (ghosts[i].dead) {
            idx += sprintf(buf + idx, "G%d(死亡:%d回合) ", i+1, ghosts[i].reviveTimer);
        } else if (ghosts[i].frozen > 0) {
            idx += sprintf(buf + idx, "G%d(冻结:%d回合) ", i+1, ghosts[i].frozen);
        } else {
            idx += sprintf(buf + idx, "G%d(活跃) ", i+1);
        }
    }
    idx += sprintf(buf + idx, "\n");

    // 5. 探测仪距离提示(只显示存活鬼魂)
    if (hasActiveItem(PROBE)) {
        idx += sprintf(buf + idx, "📡 探测仪显示:存活鬼魂距离 - ");
        int hasAliveGhost = 0;
        for (int i = 0; i < GHOST_NUM; i++) {
            if (!ghosts[i].dead) {
                hasAliveGhost = 1;
                idx += sprintf(buf + idx, "G%d(%.1f格) ", i+1, calculateDistance(player, ghosts[i].pos));
            }
        }
        if (!hasAliveGhost) {
            idx += sprintf(buf + idx, "无 ");
        }
        idx += sprintf(buf + idx, "\n");
    }

    // 6. 临时提示信息(移动/拾取/道具使用)
    if (strlen(lastMsg) > 0) {
        idx += sprintf(buf + idx, "%s\n", lastMsg);
        // 石子使用后不立即清空,保持显示到下一回合
        if (strstr(lastMsg, "🪨") == NULL && strstr(lastMsg, "💥") == NULL) {
            memset(lastMsg, 0, sizeof(lastMsg));
        }
    }

    // 7. 地图边框(上)
    idx += sprintf(buf + idx, "+");
    for (int i = 0; i < MAP_SIZE; i++) {
        idx += sprintf(buf + idx, "-");
    }
    idx += sprintf(buf + idx, "+\n");

    // 8. 地图内容
    int viewRange = hasActiveItem(PERISCOPE) ? VIEW_8 : PLAYER_VIEW;
    int canSeeThrough = hasActiveItem(PERISCOPE);

    for (int y = 0; y < MAP_SIZE; y++) {
        idx += sprintf(buf + idx, "|"); // 左边框
        for (int x = 0; x < MAP_SIZE; x++) {
            // 玩家
            if (x == player.x && y == player.y) {
                idx += sprintf(buf + idx, "%c", PLAYER_CHAR);
                continue;
            }

            // 鬼魂(只显示存活且需要显示的)
            int isGhost = 0;
            for (int i = 0; i < GHOST_NUM; i++) {
                if (!ghosts[i].dead && x == ghosts[i].pos.x && y == ghosts[i].pos.y) {
                    if (shouldShowGhost(ghosts[i])) {
                        idx += sprintf(buf + idx, "%c", GHOST_CHAR);
                    } else {
                        idx += sprintf(buf + idx, "%c", HIDDEN_GHOST_CHAR);
                    }
                    isGhost = 1;
                    break;
                }
            }
            if (isGhost) continue;

            // 地图元素(视野判断)
            double dist = calculateDistance(player, (Position){x, y});
            int inView = (dist <= viewRange);
            int blocked = !canSeeThrough && isBlocked(player, (Position){x, y});

            if (inView && !blocked) {
                idx += sprintf(buf + idx, "%c", map[x][y]); // 可见区域
            } else {
                if (doorFound && x == door.x && y == door.y) {
                    idx += sprintf(buf + idx, "%c", DOOR_CHAR); // 地图道具显示门
                } else {
                    idx += sprintf(buf + idx, "%c", BLIND_CHAR); // 视野盲区
                }
            }
        }
        idx += sprintf(buf + idx, "|\n"); // 右边框
    }

    // 9. 地图边框(下)
    idx += sprintf(buf + idx, "+");
    for (int i = 0; i < MAP_SIZE; i++) {
        idx += sprintf(buf + idx, "-");
    }
    idx += sprintf(buf + idx, "+\n");

    // 10. 底部提示(新增石子说明)
    idx += sprintf(buf + idx, "提示:鬼魂进入视野(无阻挡)会自动显现!道具可显示所有存活鬼魂!\n");
    idx += sprintf(buf + idx, "      石子可横向/纵向发射,无法穿透墙壁,击中鬼魂可使其死亡8回合!\n");
    idx += sprintf(buf + idx, "===========================================\n");

    // 核心:一次性输出所有内容(无闪),并用\r回到顶部覆盖旧内容
    printf("\r%s", buf);
    fflush(stdout); // 强制刷新缓冲区,确保立即显示
}

// 游戏主循环(新增更新鬼魂状态)
void gameLoop() {
    initGame();

    while (1) {
        drawGame(); // 无闪绘制

        // 游戏结束判断
        if (isPlayerCaught()) {
            printf("\n\n💀 游戏结束!被鬼魂抓住了!\n");
            printf("按任意键退出...");
            getch();
            break;
        }
        if (isPlayerWin()) {
            printf("\n\n🎉 恭喜你!成功逃生!\n");
            printf("按任意键退出...");
            getch();
            break;
        }

        // 玩家输入(非阻塞)
        if (kbhit()) {
            char key = getch();
            isUsingItem = 0;

            // 道具使用(1-9)
            if (key >= '1' && key <= '9') {
                int itemIndex = key - '1';
                if (backpack.count == 0) {
                    strcpy(lastMsg, "❌ 背包为空,无法使用道具!");
                    Sleep(500);
                    continue;
                }
                if (itemIndex < backpack.count) {
                    useItemFromBackpack(itemIndex);
                    // 石子使用后不需要等待回车,直接继续
                    if (backpack.items[itemIndex] != STONE) {
                        waitForEnter();
                    }
                } else {
                    sprintf(lastMsg, "❌ 该道具不存在!当前背包只有%d个道具!", backpack.count);
                    Sleep(500);
                    continue;
                }
            } else {
                // 移动/退出控制
                switch (key) {
                    case 'w': case 'W': movePlayer(0, -1); break;
                    case 's': case 'S': movePlayer(0, 1);  break;
                    case 'a': case 'A': movePlayer(-1, 0); break;
                    case 'd': case 'D': movePlayer(1, 0);  break;
                    case ' ': movePlayer(0, 0); break; // 等待
                    case 'q': case 'Q': 
                        printf("\n\n👋 游戏已退出!\n");
                        return;
                    default:
                        strcpy(lastMsg, "❌ 输入无效!请使用 W/S/A/D/空格/Q 或数字键!");
                        Sleep(500);
                        continue;
                }
            }
        } else {
            Sleep(50); // 降低CPU占用
            continue;
        }

        // 更新游戏状态(道具回合+鬼魂状态+鬼魂移动)
        if (!isUsingItem) {
            updateActiveItems();
            updateGhostsState(); // 新增:更新鬼魂复活状态
            moveGhosts();
        } else {
            // 使用道具后也需要更新鬼魂复活状态
            updateGhostsState();
        }
        Sleep(150); // 控制游戏速度,避免过快
    }
}

// 主函数
int main() {
    gameLoop();
    return 0;
}