! 扫雷 —— 用 **Fortran** 写的手机小游戏（网格推理）
! Minesweeper -- a small phone game written in **Fortran** (grid deduction)
!
! 玩法（与 Examples/c/app/minesweeper.c / Examples/python/app/minesweeper.py 同一套的目标）：
!   9×9 共 10 颗雷；点格子翻开，周围 8 格的雷数用**格内小圆点数量**表示（0 个点 = 安全）；
!   翻到 0 会连锁展开；顶部按钮切到「插旗」模式再点就是标雷；踩到雷就结束。
!
! ◆ 写法要求（见 Examples/fortran/app/sokoban.f90 文件头）
!   · `k = ui_2d_rect(...)` 函数调用表达式；数组 1 基：扁平下标 = (行-1)*9 + 列 + 1
!   · `!=` 写 `/=`
!
! 跑法 —— 手机：vml run examples/fortran/minesweeper.f90
! 跑法 —— 桌面：vmlcli Examples/fortran/minesweeper.f90 --screen 480x640 --frames /tmp/fr

program minesweeper
  implicit none
  integer :: mine(81)
  integer :: openc(81)
  integer :: flag(81)
  integer :: qx(81)
  integer :: qy(81)
  integer :: w
  integer :: h
  integer :: cell
  integer :: ox
  integer :: oy
  integer :: opened
  integer :: dead
  integer :: won
  integer :: flagmode
  integer :: frames
  integer :: seed
  integer :: i
  integer :: j
  integer :: k
  integer :: x
  integer :: y
  integer :: n
  integer :: nb
  integer :: dx
  integer :: dy
  integer :: nx
  integer :: ny
  integer :: head
  integer :: tail
  integer :: cx
  integer :: cy
  integer :: t
  integer :: tid
  integer :: lang
  integer :: tx
  integer :: ty
  integer :: idx
  integer :: px
  integer :: py
  integer :: side

  lang = ui_scr_get_language()
  if (lang == 0) k = ui_win_open('扫雷', 0, 0)
  if (lang /= 0) k = ui_win_open('Minesweeper', 0, 0)

  w = ui_scr_get_w()
  h = ui_scr_get_h()
  if (w <= 0) w = 360
  if (h <= 0) h = 620
  ! 9×9 棋盘：放在顶部按钮（44..74）下面，宽度与高度各算一次取小
  oy = 84
  cell = (w - 16) / 9
  k = (h - oy - 8) / 9
  if (k < cell) cell = k
  if (cell < 6) cell = 6
  ox = (w - 9 * cell) / 2

  ! 起一局
  do i = 1, 81
    mine(i) = 0
    openc(i) = 0
    flag(i) = 0
  end do
  seed = 20261117
  i = 0
  do while (i < 10)
    seed = mod(seed * 1103 + 12345, 32768)
    x = mod(seed / 256, 9) + 1
    seed = mod(seed * 1103 + 12345, 32768)
    y = mod(seed / 256, 9) + 1
    idx = (x - 1) * 9 + y
    if (mine(idx) == 0) then
      mine(idx) = 1
      i = i + 1
    end if
  end do
  opened = 0
  dead = 0
  won = 0
  flagmode = 0
  frames = 0

  k = ui_scr_set_keep_on(1)
  tid = ui_timer_set(80, 0)

  do while (ui_win_is_closed() == 0)

    ! ── draw ──
    ! 布局随画布现算（含 resize）
    oy = 84
    cell = (w - 16) / 9
    k = (h - oy - 8) / 9
    if (k < cell) cell = k
    if (cell < 6) cell = 6
    ox = (w - 9 * cell) / 2

    k = ui_2d_clear(-15724520)

    if (flagmode == 0) then
      k = ui_2d_rect(8, 44, w / 3, 30, -14013898, 1, 0, 8)
      if (lang == 0) k = ui_2d_text(12, 52, '翻开模式', -1513232, 12, 0)
      if (lang /= 0) k = ui_2d_text(12, 52, 'Reveal mode', -1513232, 12, 0)
    else
      k = ui_2d_rect(8, 44, w / 3, 30, -2069424, 1, 0, 8)
      if (lang == 0) k = ui_2d_text(12, 52, '插旗模式', -15724520, 12, 0)
      if (lang /= 0) k = ui_2d_text(12, 52, 'Flag mode', -15724520, 12, 0)
    end if

    x = 1
    do while (x <= 9)
      y = 1
      do while (y <= 9)
        idx = (x - 1) * 9 + y
        px = ox + (x - 1) * cell
        py = oy + (y - 1) * cell
        if (openc(idx) /= 0) then
          if (mine(idx) == 1) then
            k = ui_2d_rect(px + 1, py + 1, cell - 2, cell - 2, -2069424, 1, 0, 2)
          else
            k = ui_2d_rect(px + 1, py + 1, cell - 2, cell - 2, -15066588, 1, 0, 2)
            ! 周围雷数 → 格内画 n 个小圆点（最多 8 个，两行四列）
            nb = 0
            dx = -1
            do while (dx <= 1)
              dy = -1
              do while (dy <= 1)
                if (.not. (dx == 0 .and. dy == 0)) then
                  nx = x + dx
                  ny = y + dy
                  if (nx >= 1 .and. ny >= 1 .and. nx <= 9 .and. ny <= 9) then
                    if (mine((nx - 1) * 9 + ny) == 1) nb = nb + 1
                  end if
                end if
                dy = dy + 1
              end do
              dx = dx + 1
            end do
            n = 0
            do while (n < nb)
              k = ui_2d_circle(px + cell / 4 + mod(n, 4) * (cell / 5), py + cell / 3 + (n / 4) * (cell / 5), cell / 12, -1513232, 1, 0)
              n = n + 1
            end do
          end if
        else
          k = ui_2d_rect(px + 1, py + 1, cell - 2, cell - 2, -14013898, 1, 0, 3)
          if (flag(idx) /= 0) then
            k = ui_2d_circle(px + cell / 2, py + cell / 2, cell / 4, -2069424, 1, 0)
          end if
        end if
        y = y + 1
      end do
      x = x + 1
    end do

    if (dead /= 0) then
      if (lang == 0) k = ui_2d_text(8, 14, '踩雷了，ESC 重来', -2069424, 14, 0)
      if (lang /= 0) k = ui_2d_text(8, 14, 'Boom - ESC to restart', -2069424, 14, 0)
    else
      if (won /= 0) then
        if (lang == 0) k = ui_2d_text(8, 14, '扫清了！ESC 再来', -11409298, 14, 0)
        if (lang /= 0) k = ui_2d_text(8, 14, 'Cleared! ESC for a new board', -11409298, 14, 0)
      else
        if (lang == 0) k = ui_2d_text(8, 14, '点格子翻开 / 点顶部按钮插旗', -6643536, 11, 0)
        if (lang /= 0) k = ui_2d_text(8, 14, 'Tap a cell / tap the top button to flag', -6643536, 11, 0)
      end if
    end if
    k = ui_2d_present()

    t = ui_msg_fetch_wait(0)
    if (t == 10) exit

    if (t == 6 .or. t == 4) then
      tx = ui_msg_get_a()
      ty = ui_msg_get_b()
      if (tx >= 8 .and. tx <= 8 + w / 3 .and. ty >= 44 .and. ty <= 74) then
        if (flagmode == 0) then
          flagmode = 1
        else
          flagmode = 0
        end if
      else
        if (tx >= ox .and. ty >= oy) then
          x = (tx - ox) / cell + 1
          y = (ty - oy) / cell + 1
          if (x <= 9 .and. y <= 9) then
            if (dead == 0 .and. won == 0) then
              idx = (x - 1) * 9 + y
              if (flagmode == 1) then
                if (openc(idx) == 0) then
                  if (flag(idx) == 0) then
                    flag(idx) = 1
                  else
                    flag(idx) = 0
                  end if
                end if
              else
                ! 连锁展开（显式队列）
                if (openc(idx) == 0 .and. flag(idx) == 0) then
                  qx(1) = x
                  qy(1) = y
                  head = 1
                  tail = 1
                  do while (head <= tail)
                    cx = qx(head)
                    cy = qy(head)
                    head = head + 1
                    idx = (cx - 1) * 9 + cy
                    if (openc(idx) == 0 .and. flag(idx) == 0) then
                      openc(idx) = 1
                      opened = opened + 1
                      if (mine(idx) == 1) then
                        dead = 1
                        head = tail + 1
                      else
                        nb = 0
                        dx = -1
                        do while (dx <= 1)
                          dy = -1
                          do while (dy <= 1)
                            if (.not. (dx == 0 .and. dy == 0)) then
                              nx = cx + dx
                              ny = cy + dy
                              if (nx >= 1 .and. ny >= 1 .and. nx <= 9 .and. ny <= 9) then
                                if (mine((nx - 1) * 9 + ny) == 1) nb = nb + 1
                              end if
                            end if
                            dy = dy + 1
                          end do
                          dx = dx + 1
                        end do
                        if (nb == 0 .and. dead == 0) then
                          dx = -1
                          do while (dx <= 1)
                            dy = -1
                            do while (dy <= 1)
                              if (.not. (dx == 0 .and. dy == 0)) then
                                nx = cx + dx
                                ny = cy + dy
                                if (nx >= 1 .and. ny >= 1 .and. nx <= 9 .and. ny <= 9) then
                                  if (tail < 81) then
                                    tail = tail + 1
                                    qx(tail) = nx
                                    qy(tail) = ny
                                  end if
                                end if
                              end if
                              dy = dy + 1
                            end do
                            dx = dx + 1
                          end do
                        end if
                      end if
                    end if
                  end do
                  if (dead == 0 .and. opened >= 81 - 10) won = 1
                end if
              end if
            end if
          end if
        end if
      end if
    end if

    if (t == 1) then
      k = ui_msg_get_a()
      if (k == 27 .or. k == 82) then
        ! 重开
        do i = 1, 81
          mine(i) = 0
          openc(i) = 0
          flag(i) = 0
        end do
        seed = 20261117
        i = 0
        do while (i < 10)
          seed = mod(seed * 1103 + 12345, 32768)
          x = mod(seed / 256, 9) + 1
          seed = mod(seed * 1103 + 12345, 32768)
          y = mod(seed / 256, 9) + 1
          idx = (x - 1) * 9 + y
          if (mine(idx) == 0) then
            mine(idx) = 1
            i = i + 1
          end if
        end do
        opened = 0
        dead = 0
        won = 0
        flagmode = 0
        frames = 0
      end if
    end if

    if (t == 11) then
      w = ui_scr_get_w()
      h = ui_scr_get_h()
      if (w <= 0) w = 360
      if (h <= 0) h = 620
    end if

    if (t == 9) then
      frames = frames + 1
      if (frames >= 4000) exit
    end if
  end do

  k = ui_timer_kill(tid)
  k = ui_scr_set_keep_on(0)
  k = ui_win_close()
end program minesweeper
