// ===== CodeLab: C 语言小游戏③:文本迷宫 =====
// 来源: https://aoerliang.dpdns.org/articles/game-c-maze
// 以下代码片段按文章出现顺序拼接, 共 6 段

// ----- 片段 1 (c) -----
#include <stdio.h>

#define ROWS 10
#define COLS 20

/* 地图: # 墙, . 路, S 起点, E 终点 */
char maze[ROWS][COLS + 1] = {
    "####################",
    "#S........#........#",
    "#.###.####.#.####..#",
    "#.#......#.#.#.....#",
    "#.#.####.#.#.#.###.#",
    "#.#.#....#...#...#.#",
    "#.#.#.######.###.#.#",
    "#...#...........####",
    "#####.#####.########",
    "#.....#..........E.#"
};

int px = 1, py = 1;   /* 玩家位置(列, 行) */

// ----- 片段 2 (c) -----
void print_maze(void) {
    int x, y;
    for (y = 0; y < ROWS; y++) {
        for (x = 0; x < COLS; x++) {
            if (x == px && y == py)
                putchar('@');          /* 玩家所在位置 */
            else
                putchar(maze[y][x]);
        }
        putchar('\n');
    }
}

// ----- 片段 3 (c) -----
cmd = getchar();
while (getchar() != '\n');   /* 吃掉输入后的回车 */

switch (cmd) {
case 'w': case 'W': ny--; break;   /* 上: 行号减 1 */
case 's': case 'S': ny++; break;   /* 下: 行号加 1 */
case 'a': case 'A': nx--; break;   /* 左: 列号减 1 */
case 'd': case 'D': nx++; break;   /* 右: 列号加 1 */
case 'q': case 'Q': return 0;
default: continue;
}

// ----- 片段 4 (c) -----
if (maze[ny][nx] == '#') {
    printf("前面是墙, 走不了!\n");
    continue;          /* 本次输入作废, 重新出方向 */
}

px = nx;
py = ny;

// ----- 片段 5 (c) -----
#include <stdio.h>

#define ROWS 10
#define COLS 20

char maze[ROWS][COLS + 1] = {
    "####################",
    "#S........#........#",
    "#.###.####.#.####..#",
    "#.#......#.#.#.....#",
    "#.#.####.#.#.#.###.#",
    "#.#.#....#...#...#.#",
    "#.#.#.######.###.#.#",
    "#...#...........####",
    "#####.#####.########",
    "#.....#..........E.#"
};

int px = 1, py = 1;

void print_maze(void) {
    int x, y;
    for (y = 0; y < ROWS; y++) {
        for (x = 0; x < COLS; x++) {
            if (x == px && y == py)
                putchar('@');
            else
                putchar(maze[y][x]);
        }
        putchar('\n');
    }
}

int main(void) {
    char cmd;

    printf("文本迷宫: 用 W/A/S/D 移动, 走到 E 即可通关!\n\n");

    while (1) {
        int nx = px, ny = py;
        print_maze();

        printf("方向 (W上 A左 S下 D右, Q退出): ");
        cmd = getchar();
        while (getchar() != '\n');

        switch (cmd) {
        case 'w': case 'W': ny--; break;
        case 's': case 'S': ny++; break;
        case 'a': case 'A': nx--; break;
        case 'd': case 'D': nx++; break;
        case 'q': case 'Q': return 0;
        default: continue;
        }

        if (maze[ny][nx] == '#') {   /* 撞墙检测 */
            printf("前面是墙, 走不了!\n");
            continue;
        }

        px = nx;
        py = ny;

        if (maze[py][px] == 'E') {   /* 到达终点 */
            print_maze();
            printf("恭喜通关! 你成功走出了迷宫!\n");
            break;
        }
    }
    return 0;
}

// ----- 片段 6 (bash) -----
gcc -o maze maze.c
./maze
