// 扫雷 —— 用 **C#** 写的手机小游戏（网格推理）
// Minesweeper — a small phone game written in **C#** (grid deduction)
//
// 玩法（与 `Examples/c/app/minesweeper.c` / `Examples/python/app/minesweeper.py` 同一套）：
// Gameplay (same rules as the C / Python versions):
//   · 9×9 共 10 颗雷；点格子翻开，数字是周围 8 格的雷数；
//   · 9x9 with ten mines; tap a cell to reveal it, the number counts mines in the surrounding 8 cells;
//   · 翻到 0 会**连锁展开**；顶部按钮切到「插旗」模式再点就是标雷；
//   · revealing a 0 **floods** outward; the top button switches to "flag" mode and taps then mark mines;
//   · 把所有非雷格子翻开即通关，踩到雷就结束；结束后按 ESC / R 重开。
//   · revealing every non-mine cell wins, stepping on a mine ends it; ESC / R restarts.
//
// ## C# 这一路的写法约束（见 `Examples/csharp/app/snake.cs` 文件头）
// ## Style constraints on this C# path (see the header of `Examples/csharp/app/snake.cs`)
//
//   · 常量写**数字**；颜色写**负数十进制**；
//   · constants are **numbers**; colours are **negative decimals**;
//   · 数字转字符串走本文件的 `numToStr()` / `digit()`（不借 C 的运行库）；
//   · numbers to strings go through `numToStr()` / `digit()` here (not C's runtime library);
//   · 循环更新写 `i = i + 1`。
//   · loop updates are written `i = i + 1`.
//
// 跑法 —— 手机：`vml run examples/csharp/minesweeper.cs`
// How to run — on the phone: `vml run examples/csharp/minesweeper.cs`
// 跑法 —— 桌面：`vmlcli Examples/csharp/minesweeper.cs --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/csharp/minesweeper.cs --screen 480x640 --frames /tmp/fr`

// 显式引用 UI 库：`ui_*` 的声明在 `Lib/csharp/VmlUi.cs`（tools/GenLib 生成，别手改）。
// Explicit reference to the UI library: `ui_*` is declared in `Lib/csharp/VmlUi.cs` (generated by tools/GenLib; don't hand-edit).
using Vml.Ui;

class MinesweeperGame
{
    // ── 常量（源：Lib/c/vml_ui.h）──
    // ── Constants (source: Lib/c/vml_ui.h) ──
    const int MSG_KEYDOWN = 1;
    const int MSG_MOUSEDOWN = 4;
    const int MSG_TOUCHDOWN = 6;
    const int MSG_TIMER = 9;
    const int MSG_WINDOWCLOSE = 10;
    const int MSG_WINDOWRESIZE = 11;

    const int KEY_ESCAPE = 27;
    const int KEY_R = 82;

    const int ANCHOR_LEFT = 0;
    const int ANCHOR_CENTER = 1;

    const int MAX_FRAMES = 4000;
    const int GW = 9;
    const int GH = 9;
    const int MINES = 10;
    const int CELLS = 81;            // GW * GH
    const int QUEUE_MAX = 81;

    const int C_BG = -15724520;      // 0xFF101018
    const int C_HIDDEN = -14013898;  // 0xFF2A2A36
    const int C_OPEN = -15066588;    // 0xFF1A1A24
    const int C_FLAG = -2069424;     // 0xFFE06C50
    const int C_TEXT = -1513232;     // 0xFFE8E8F0
    const int C_DIM = -6643536;      // 0xFF9AA0B0
    const int C_MINE = -2069424;     // 0xFFE06C50

    static int lang;
    static int sw = 360;
    static int sh = 620;
    static int cell = 30;
    static int ox = 20;
    static int oy = 96;

    static int[] mine = new int[CELLS];
    static int[] openCell = new int[CELLS];
    static int[] flag = new int[CELLS];
    static int[] queueX = new int[QUEUE_MAX];
    static int[] queueY = new int[QUEUE_MAX];
    static int opened = 0;
    static int dead = 0;
    static int won = 0;
    static int flagMode = 0;
    static int frames = 0;
    static int seed = 20261117;

    // 数字 → 字符串（不借标准库的字符串转换，见文件头）
    // Number → string (do not borrow the standard library's string conversion; see the header)
    static string numToStr(int v)
    {
        if (v == 0) return "0";
        string s = "";
        int neg = 0;
        if (v < 0) { neg = 1; v = 0 - v; }
        while (v > 0)
        {
            int d = v % 10;
            s = digit(d) + s;
            v = v / 10;
        }
        if (neg != 0) s = "-" + s;
        return s;
    }

    static string digit(int d)
    {
        if (d == 0) return "0";
        if (d == 1) return "1";
        if (d == 2) return "2";
        if (d == 3) return "3";
        if (d == 4) return "4";
        if (d == 5) return "5";
        if (d == 6) return "6";
        if (d == 7) return "7";
        if (d == 8) return "8";
        return "9";
    }

    // 确定性伪随机（验收要能复现同一局）
    // Deterministic PRNG (acceptance needs to reproduce the same run)
    static int rnd(int n)
    {
        seed = (seed * 1103 + 12345) % 32768;
        return (seed / 256) % n;
    }

    static void layout()
    {
        sw = ui_scr_get_w();
        sh = ui_scr_get_h();
        if (sw <= 0) sw = 360;
        if (sh <= 0) sh = 620;
        int side = sw - 16;
        if (sw >= sh - 120) side = sh - 130;
        cell = side / GW;
        if (cell < 6) cell = 6;
        ox = (sw - GW * cell) / 2;
        oy = 96;
    }

    static void newGame()
    {
        int i = 0;
        while (i < CELLS)
        {
            mine[i] = 0;
            openCell[i] = 0;
            flag[i] = 0;
            i = i + 1;
        }
        i = 0;
        while (i < MINES)
        {
            int x = rnd(GW);
            int y = rnd(GH);
            if (mine[x * GH + y] == 0)
            {
                mine[x * GH + y] = 1;
                i = i + 1;
            }
        }
        opened = 0;
        dead = 0;
        won = 0;
        flagMode = 0;
        frames = 0;
    }

    // 周围 8 格的雷数
    // How many of the 8 neighbours hold a mine
    static int neighbors(int x, int y)
    {
        int n = 0;
        int dx = -1;
        while (dx <= 1)
        {
            int dy = -1;
            while (dy <= 1)
            {
                if (!(dx == 0 && dy == 0))
                {
                    int nx = x + dx;
                    int ny = y + dy;
                    if (nx >= 0 && ny >= 0 && nx < GW && ny < GH)
                    {
                        if (mine[nx * GH + ny] == 1) n = n + 1;
                    }
                }
                dy = dy + 1;
            }
            dx = dx + 1;
        }
        return n;
    }

    // 连锁展开（显式队列，不用递归）：翻开一个 0，把周围都排队
    // Flood fill (explicit queue, no recursion): revealing a 0 enqueues its neighbours
    static void reveal(int x, int y)
    {
        if (openCell[x * GH + y] != 0 || flag[x * GH + y] != 0) return;
        int head = 0;
        int tail = 0;
        queueX[tail] = x;
        queueY[tail] = y;
        tail = tail + 1;
        while (head < tail)
        {
            int cx = queueX[head];
            int cy = queueY[head];
            head = head + 1;
            if (openCell[cx * GH + cy] != 0) continue;
            if (flag[cx * GH + cy] != 0) continue;
            openCell[cx * GH + cy] = 1;
            opened = opened + 1;
            if (mine[cx * GH + cy] == 1)
            {
                dead = 1;
                return;
            }
            if (neighbors(cx, cy) != 0) continue;
            int dy = -1;
            while (dy <= 1)
            {
                int dx = -1;
                while (dx <= 1)
                {
                    if (!(dx == 0 && dy == 0))
                    {
                        int nx = cx + dx;
                        int ny = cy + dy;
                        if (nx >= 0 && ny >= 0 && nx < GW && ny < GH)
                        {
                            if (openCell[nx * GH + ny] == 0 && flag[nx * GH + ny] == 0)
                            {
                                if (tail < QUEUE_MAX)
                                {
                                    queueX[tail] = nx;
                                    queueY[tail] = ny;
                                    tail = tail + 1;
                                }
                            }
                        }
                    }
                    dx = dx + 1;
                }
                dy = dy + 1;
            }
        }
        if (opened >= GW * GH - MINES) won = 1;
    }

    static void draw()
    {
        ui_2d_clear(C_BG);

        // 顶栏：模式按钮 + 剩余雷数
        // Top bar: mode button + mines left
        int btnW = sw / 3;
        ui_2d_rect(8, 44, btnW, 36, flagMode != 0 ? C_FLAG : C_HIDDEN, 1, 0, 8);
        if (flagMode != 0)
        {
            if (lang == 0) ui_2d_text(8 + btnW / 2, 62, "插旗模式", C_BG, 13, ANCHOR_CENTER);
            else ui_2d_text(8 + btnW / 2, 62, "Flag mode", C_BG, 13, ANCHOR_CENTER);
        }
        else
        {
            if (lang == 0) ui_2d_text(8 + btnW / 2, 62, "翻开模式", C_TEXT, 13, ANCHOR_CENTER);
            else ui_2d_text(8 + btnW / 2, 62, "Reveal mode", C_TEXT, 13, ANCHOR_CENTER);
        }

        int flags = 0;
        int i = 0;
        while (i < CELLS)
        {
            if (flag[i] != 0) flags = flags + 1;
            i = i + 1;
        }
        ui_2d_text(sw - 10, 52, numToStr(MINES - flags), C_FLAG, 16, 2);
        if (lang == 0) ui_2d_text(sw - 10, 72, "剩余雷数", C_DIM, 10, 2);
        else ui_2d_text(sw - 10, 72, "mines left", C_DIM, 10, 2);

        int x = 0;
        while (x < GW)
        {
            int y = 0;
            while (y < GH)
            {
                int px = ox + x * cell;
                int py = oy + y * cell;
                int idx = x * GH + y;
                if (openCell[idx] != 0)
                {
                    if (mine[idx] != 0)
                    {
                        ui_2d_rect(px + 1, py + 1, cell - 2, cell - 2, C_MINE, 1, 0, 2);
                    }
                    else
                    {
                        ui_2d_rect(px + 1, py + 1, cell - 2, cell - 2, C_OPEN, 1, 0, 2);
                        int n = neighbors(x, y);
                        if (n > 0)
                        {
                            ui_2d_text(px + cell / 2, py + cell / 2 + 5, numToStr(n), C_TEXT, cell / 2, ANCHOR_CENTER);
                        }
                    }
                }
                else
                {
                    ui_2d_rect(px + 1, py + 1, cell - 2, cell - 2, C_HIDDEN, 1, 0, 3);
                    if (flag[idx] != 0)
                    {
                        ui_2d_circle(px + cell / 2, py + cell / 2, cell / 4, C_FLAG, 1, 0);
                    }
                }
                y = y + 1;
            }
            x = x + 1;
        }

        int by = oy + GH * cell + 26;
        if (dead != 0)
        {
            if (lang == 0) ui_2d_text(sw / 2, by, "踩雷了，ESC 重来", C_MINE, 14, ANCHOR_CENTER);
            else ui_2d_text(sw / 2, by, "Boom - ESC to restart", C_MINE, 14, ANCHOR_CENTER);
        }
        else if (won != 0)
        {
            if (lang == 0) ui_2d_text(sw / 2, by, "扫清了！ESC 再来", C_TEXT, 14, ANCHOR_CENTER);
            else ui_2d_text(sw / 2, by, "Cleared! ESC for a new board", C_TEXT, 14, ANCHOR_CENTER);
        }
        else
        {
            if (lang == 0) ui_2d_text(sw / 2, by, "点格子翻开 / 点顶部按钮插旗", C_DIM, 11, ANCHOR_CENTER);
            else ui_2d_text(sw / 2, by, "Tap a cell / tap the top button to flag", C_DIM, 11, ANCHOR_CENTER);
        }
        ui_2d_present();
    }

    static void tap(int tx, int ty)
    {
        if (tx >= 8 && tx <= 8 + sw / 3 && ty >= 44 && ty <= 80)
        {
            if (flagMode != 0) flagMode = 0;
            else flagMode = 1;
            return;
        }
        int x = (tx - ox) / cell;
        int y = (ty - oy) / cell;
        if (x < 0 || y < 0 || x >= GW || y >= GH) return;
        if (dead != 0 || won != 0) return;
        int idx = x * GH + y;
        if (flagMode != 0)
        {
            if (openCell[idx] == 0)
            {
                if (flag[idx] != 0) flag[idx] = 0;
                else flag[idx] = 1;
            }
            return;
        }
        reveal(x, y);
    }

    static void Main()
    {
        lang = ui_scr_get_language();
        if (lang == 0) ui_win_open("扫雷", 0, 0);
        else ui_win_open("Minesweeper", 0, 0);

        ui_scr_set_keep_on(1);
        layout();
        newGame();

        int tid = ui_timer_set(80, 0);
        int done = 0;
        while (done == 0 && ui_win_is_closed() == 0)
        {
            int t = ui_msg_fetch_wait(0);
            if (t == 0) { draw(); continue; }

            if (t == MSG_TOUCHDOWN || t == MSG_MOUSEDOWN)
            {
                tap(ui_msg_get_a(), ui_msg_get_b());
            }

            if (t == MSG_KEYDOWN)
            {
                int k = ui_msg_get_a();
                if (k == KEY_ESCAPE || k == KEY_R)
                {
                    newGame();
                }
            }

            if (t == MSG_TIMER)
            {
                frames = frames + 1;
                if (frames >= MAX_FRAMES) done = 1;
            }

            if (t == MSG_WINDOWRESIZE)
            {
                layout();
            }

            if (t == MSG_WINDOWCLOSE)
            {
                done = 1;
            }

            draw();
        }

        ui_timer_kill(tid);
        ui_scr_set_keep_on(0);
        ui_win_close();
    }
}
