# minesweeper.py —— 扫雷（VML 的 Python 前端）
# minesweeper.py -- Minesweeper (VML's Python frontend)
#
# 与 `Examples/c/app/minesweeper.c` **同一套玩法**：
# Same rules as `Examples/c/app/minesweeper.c`:
#   · 点格子翻开；数字是周围 8 格的雷数；
#   · tap a cell to reveal it; the number counts mines in the surrounding 8 cells;
#   · 翻到 0 会**连锁展开**（显式队列，不用递归）；
#   · revealing a 0 **floods** outward (an explicit queue, no recursion);
#   · 顶部按钮切「插旗模式」再点就是标雷；翻开所有非雷格即通关，踩雷结束。
#   · the top button switches to "flag" mode; revealing every non-mine cell wins, a mine ends it.
#
# ⚠ 本前端没有二维数组 ⇒ 三张棋盘都**平铺**成 `[x * GH + y]`。
# ⚠ This frontend has no 2-D arrays => all three boards are **flat** `[x * GH + y]`.
# ⚠ 坐标/尺寸全用 `//`；`/` 是真除法（float 位型传进 ui_2d_* 会画到屏幕外）。
# ⚠ Coordinates/sizes use `//`; `/` is true division (float bit patterns draw off-screen).

# 显式引入共享库声明（GenLib 生成，勿手写）。
# Explicitly import the shared-library declarations (generated by GenLib, do not hand-write).
# ⚠ 注释行别以 `Import` / `Include` 开头 —— 前端会把整行当 `#include` 指令。
# ⚠ Never start a comment line with `Import` / `Include` -- it becomes a `#include` directive.
import vml_ui

MAX_FRAMES = 4000
GW = 9
GH = 9
MINES = 10
QMAX = GW * GH

C_BG = 0xFF101018
C_HIDDEN = 0xFF2A2A36
C_OPEN = 0xFF1A1A24
C_FLAG = 0xFFE06C50
C_TEXT = 0xFFE8E8F0
C_DIM = 0xFF9AA0B0
C_MINE = 0xFFE06C50

SW = 360
SH = 620
CELL = 36
OX = 18
OY = 96
LANG = 0

mine = [0] * (GW * GH)
opn = [0] * (GW * GH)
flag = [0] * (GW * GH)
qx = [0] * QMAX
qy = [0] * QMAX

opened = 0
dead = 0
won = 0
flag_mode = 0
seed = 20264


def rnd(n):
    # 16 位 LCG：32 位整数下 C 的 32 位 LCG 会溢出、恒返回 0（见 game2048.py 的说明）。
    # 16-bit LCG: the C 32-bit LCG overflows with 32-bit ints and always returns 0
    # (see the note in game2048.py).
    global seed
    seed = (seed * 1103 + 12345) % 32768
    return (seed // 256) % n


def relayout():
    global SW, SH, CELL, OX, OY
    SW = ui_scr_get_w()
    SH = ui_scr_get_h()
    if SW <= 0:
        SW = 360
    if SH <= 0:
        SH = 620
    # 雷区取「宽度」与「扣掉顶栏/底部提示后的高度」里较小的那个 ——
    # 方形小画布上原来的 `SW < SH - 120` 分支会让格子只剩 130px 宽。
    # The field takes the smaller of "width" and "height after the top bar/footer" --
    # the old `SW < SH - 120` branch left only 130px for the field on a square tiny canvas.
    OY = 88
    side = SW - 16
    tall = SH - OY - 40
    if tall < side:
        side = tall
    CELL = side // GW
    if CELL < 6:
        CELL = 6
    OX = (SW - GW * CELL) // 2


def at(x, y):
    return x * GH + y


def neighbors(x, y):
    n = 0
    dy = -1
    while dy <= 1:
        dx = -1
        while dx <= 1:
            if dx != 0 or dy != 0:
                nx = x + dx
                ny = y + dy
                if nx >= 0 and ny >= 0 and nx < GW and ny < GH:
                    if mine[at(nx, ny)] == 1:
                        n = n + 1
            dx = dx + 1
        dy = dy + 1
    return n


def new_game():
    global opened, dead, won, flag_mode
    i = 0
    while i < GW * GH:
        mine[i] = 0
        opn[i] = 0
        flag[i] = 0
        i = i + 1
    i = 0
    while i < MINES:
        x = rnd(GW)
        y = rnd(GH)
        if mine[at(x, y)] == 0:
            mine[at(x, y)] = 1
            i = i + 1
    opened = 0
    dead = 0
    won = 0
    flag_mode = 0


# 连锁展开（用显式队列，不用递归）：翻开一个 0，把周围都排队。
# Flood fill with an explicit queue (no recursion): reveal a 0 and enqueue its neighbours.
def reveal(x, y):
    global opened, dead, won
    if opn[at(x, y)] == 1 or flag[at(x, y)] == 1:
        return
    head = 0
    tail = 0
    qx[tail] = x
    qy[tail] = y
    tail = tail + 1
    while head < tail:
        cx = qx[head]
        cy = qy[head]
        head = head + 1
        if opn[at(cx, cy)] == 1 or flag[at(cx, cy)] == 1:
            continue
        opn[at(cx, cy)] = 1
        opened = opened + 1
        if mine[at(cx, cy)] == 1:
            dead = 1
            return
        if neighbors(cx, cy) != 0:
            continue
        dy = -1
        while dy <= 1:
            dx = -1
            while dx <= 1:
                nx = cx + dx
                ny = cy + dy
                if dx != 0 or dy != 0:
                    if nx >= 0 and ny >= 0 and nx < GW and ny < GH:
                        if opn[at(nx, ny)] == 0 and flag[at(nx, ny)] == 0:
                            if tail < QMAX:
                                qx[tail] = nx
                                qy[tail] = ny
                                tail = tail + 1
                dx = dx + 1
            dy = dy + 1
    if opened >= GW * GH - MINES:
        won = 1


def draw():
    ui_2d_clear(C_BG)

    # 顶栏：模式按钮 + 剩余雷数
    # Top bar: mode button + mines left.
    if flag_mode == 1:
        btn_color = C_FLAG
        btn_text_color = 0xFF101018
        if LANG == 0:
            btn_text = "插旗模式"
        else:
            btn_text = "Flag mode"
    else:
        btn_color = C_HIDDEN
        btn_text_color = C_TEXT
        if LANG == 0:
            btn_text = "翻开模式"
        else:
            btn_text = "Reveal mode"
    ui_2d_rect(8, 44, SW // 3, 36, btn_color, 1, 0, 8)
    ui_2d_text(8 + SW // 6, 62, btn_text, btn_text_color, 13, VML_ANCHOR_CENTER)

    i = 0
    f = 0
    while i < GW * GH:
        if flag[i] == 1:
            f = f + 1
        i = i + 1
    ui_2d_text(SW - 10, 52, str(MINES - f), C_FLAG, 16, VML_ANCHOR_RIGHT)
    if LANG == 0:
        ui_2d_text(SW - 10, 72, "剩余雷数", C_DIM, 10, VML_ANCHOR_RIGHT)
    else:
        ui_2d_text(SW - 10, 72, "mines left", C_DIM, 10, VML_ANCHOR_RIGHT)

    x = 0
    while x < GW:
        y = 0
        while y < GH:
            px = OX + x * CELL
            py = OY + y * CELL
            if opn[at(x, y)] == 1:
                if mine[at(x, y)] == 1:
                    c = C_MINE
                else:
                    c = C_OPEN
                ui_2d_rect(px + 1, py + 1, CELL - 2, CELL - 2, c, 1, 0, 2)
                if mine[at(x, y)] == 0:
                    n = neighbors(x, y)
                    if n > 0:
                        ui_2d_text(px + CELL // 2, py + CELL // 2 + 5,
                                   str(n), C_TEXT, CELL // 2, VML_ANCHOR_CENTER)
            else:
                ui_2d_rect(px + 1, py + 1, CELL - 2, CELL - 2, C_HIDDEN, 1, 0, 3)
                if flag[at(x, y)] == 1:
                    ui_2d_circle(px + CELL // 2, py + CELL // 2, CELL // 4, C_FLAG, 1, 0)
            y = y + 1
        x = x + 1

    if dead == 1:
        if LANG == 0:
            msg = "踩雷了，点一下重来"
        else:
            msg = "Boom - tap to restart"
        ui_2d_text(SW // 2, OY + GH * CELL + 26, msg, C_MINE, 14, VML_ANCHOR_CENTER)
    elif won == 1:
        if LANG == 0:
            msg = "扫清了！点一下再来"
        else:
            msg = "Cleared! Tap for a new board"
        ui_2d_text(SW // 2, OY + GH * CELL + 26, msg, C_TEXT, 14, VML_ANCHOR_CENTER)
    else:
        if LANG == 0:
            msg = "点格子翻开 / 点顶部按钮插旗"
        else:
            msg = "Tap a cell / tap the top button to flag"
        ui_2d_text(SW // 2, OY + GH * CELL + 26, msg, C_DIM, 11, VML_ANCHOR_CENTER)
    ui_2d_present()


def tap(tx, ty):
    global flag_mode
    if dead == 1 or won == 1:
        new_game()
        return
    # 点顶栏切模式
    # Tapping the top bar toggles the mode.
    if tx >= 8 and tx <= 8 + SW // 3 and ty >= 44 and ty <= 80:
        if flag_mode == 1:
            flag_mode = 0
        else:
            flag_mode = 1
        return
    x = (tx - OX) // CELL
    y = (ty - OY) // CELL
    if x < 0 or y < 0 or x >= GW or y >= GH:
        return
    if flag_mode == 1:
        if opn[at(x, y)] == 0:
            if flag[at(x, y)] == 1:
                flag[at(x, y)] = 0
            else:
                flag[at(x, y)] = 1
        return
    reveal(x, y)


def main():
    global LANG
    LANG = ui_scr_get_language()

    relayout()
    ui_win_open_ex("扫雷" if LANG == 0 else "Minesweeper (py)", 0, 0, 1, 0)
    relayout()
    new_game()
    draw()

    tid = ui_timer_set(80, 1)
    frames = 0
    done = 0
    while done == 0 and ui_win_is_closed() == 0:
        t = ui_msg_fetch()
        if t == 0:
            t = ui_msg_fetch_wait(80)
        if t == 0:
            continue

        if t == 6 or t == 4:
            tap(ui_msg_get_a(), ui_msg_get_b())
            draw()
            continue

        if t == 1:
            if ui_msg_get_a() == 27:
                new_game()
                draw()
            continue

        if t == 11:
            relayout()
            draw()
            continue

        if t == 9:
            frames = frames + 1
            if frames >= MAX_FRAMES:
                done = 1
            draw()
            continue

        if t == 10:
            break

    ui_timer_kill(tid)
    ui_win_close()
    return 0


main()
