# 十五格拼图（Puzzle 15）—— 用 **Ruby** 写的手机小游戏
# Puzzle 15 — a small phone game written in **Ruby**
#
# 玩法（与 Examples/c/app/puzzle15.c / Examples/python/app/puzzle15.py 同一套）：
# Gameplay (same rules as the C / Python versions):
#   · 4×4 共 15 个数字加一个空格；点空格旁边的格子（或按方向键）把格子滑进空格；
#   · 4x4 with fifteen numbered tiles and one blank; tap a tile next to the blank (or press an arrow)
#     to slide it into the blank;
#   · 把 1..15 按顺序排好、空格落在右下角即通关；
#   · put 1..15 in order with the blank in the bottom-right corner to win;
#   · 打乱靠**随机走步**（从解决态出发随机走 200 步），所以一定可解。
#   · shuffling is done by **random legal moves** (200 steps from the solved state), so it is always solvable.
#
# ## Ruby 这一路的写法约束（见 Examples/ruby/app/minesweeper.rb 文件头）
# ## Style constraints on this Ruby path (see the header of Examples/ruby/app/minesweeper.rb)
#
#   · **所有 def 放在文件最前面，全局变量赋值在它们之后**；
#   · **every def sits at the very top, and global assignments come after them**;
#   · 状态一律 g_ 前缀；数组用 [] + push 填充；数字转字符串用 .to_s；颜色写负数十进制；
#   · state is g_-prefixed; arrays are built with [] + push; numbers to strings use .to_s;
#     colours are negative decimals;
#   · **"只写不读"的名字在函数里写的是该函数自己的局部** ⇒ 用 pz_touch_state 先把状态名各读一遍。
#   · **a name that is only written and never read gets written to the function's own local**
#     ⇒ pz_touch_state reads every state name once first.
#
# 跑法 —— 手机：vml run examples/ruby/puzzle15.rb
# How to run — on the phone: vml run examples/ruby/puzzle15.rb
# 跑法 —— 桌面：vmlcli Examples/ruby/puzzle15.rb --screen 480x640 --frames /tmp/fr
# How to run — on the desktop: vmlcli Examples/ruby/puzzle15.rb --screen 480x640 --frames /tmp/fr

# UI 库的显式引用（用户 2026-10-01 定的口径），声明文件 Lib/ruby/vml_ui.rb 由 GenLib 生成。
require 'vml_ui'

# ══════════════════════════════════════════════════════════════════════════
# 第一段：全部函数（⚠ 必须排在"给全局赋值"之前，理由见文件头那条）
# ══════════════════════════════════════════════════════════════════════════

def pz_touch_state()
  return g_board.length + g_seed + g_moves + g_blank + g_won + g_frames + g_cell + g_ox + g_oy + g_sw + g_sh + g_lang + g_m + g_fs_score + g_fs_lbl + g_fs_hint + g_fs_num + g_hint_y
end

def pz_relayout()
  g_sw = ui_scr_get_w()
  g_sh = ui_scr_get_h()
  if g_sw <= 0
    g_sw = 360
  end
  if g_sh <= 0
    g_sh = 620
  end
  # 字号随 min(W,H) 缩放；棋盘同时受宽和高约束（240x240 上旧写法只给 70px ⇒ 格子 17px）。
  # Font sizes scale with min(W,H); the board is bounded by both width and height (the
  # old layout left only 70 px on 240x240 => 17 px cells).
  g_m = g_sw
  if g_sh < g_m
    g_m = g_sh
  end
  g_fs_score = g_m / 26
  if g_fs_score < 12
    g_fs_score = 12
  end
  if g_fs_score > 18
    g_fs_score = 18
  end
  g_fs_lbl = g_m / 48
  if g_fs_lbl < 9
    g_fs_lbl = 9
  end
  if g_fs_lbl > 12
    g_fs_lbl = 12
  end
  g_fs_hint = g_m / 30
  if g_fs_hint < 8
    g_fs_hint = 8
  end
  if g_fs_hint > 12
    g_fs_hint = 12
  end
  g_oy = 6 + g_fs_score + 2 + g_fs_lbl + 8
  side = g_sw - 16
  avail = g_sh - g_oy - g_fs_hint - 22
  if avail < side
    side = avail
  end
  g_cell = side / 4
  if g_cell < 6
    g_cell = 6
  end
  g_ox = (g_sw - 4 * g_cell) / 2
  g_fs_num = g_cell / 2
  if g_fs_num < 10
    g_fs_num = 10
  end
  if g_fs_num > 56
    g_fs_num = 56
  end
  g_hint_y = g_oy + 4 * g_cell + 16
  if g_hint_y > g_sh - g_fs_hint - 6
    g_hint_y = g_sh - g_fs_hint - 6
  end
end

def pz_new_game()
  i = 0
  while i < 16
    g_board[i] = i + 1
    i = i + 1
  end
  g_board[15] = 0
  g_blank = 15
  g_moves = 0
  g_won = 0
  n = 0
  while n < 200
    g_seed = (g_seed * 1103 + 12345) % 32768
    r = (g_seed / 256) % 4
    bx = g_blank % 4
    by = g_blank / 4
    j = g_blank
    if r == 0 && bx > 0
      j = g_blank - 1
    end
    if r == 1 && bx < 3
      j = g_blank + 1
    end
    if r == 2 && by > 0
      j = g_blank - 4
    end
    if r == 3 && by < 3
      j = g_blank + 4
    end
    if j != g_blank
      g_board[g_blank] = g_board[j]
      g_board[j] = 0
      g_blank = j
    end
    n = n + 1
  end
end

def pz_draw()
  ui_2d_clear(g_c_bg)
  i = 0
  while i < 16
    px = g_ox + (i % 4) * g_cell
    py = g_oy + (i / 4) * g_cell
    if g_board[i] == 0
      ui_2d_rect(px + 2, py + 2, g_cell - 4, g_cell - 4, g_c_hole, 1, 0, 4)
    else
      if i == g_board[i] - 1
        ui_2d_rect(px + 2, py + 2, g_cell - 4, g_cell - 4, g_c_tile2, 1, 0, 4)
      else
        ui_2d_rect(px + 2, py + 2, g_cell - 4, g_cell - 4, g_c_tile, 1, 0, 4)
      end
      ui_2d_text(px + g_cell / 2, py + (g_cell + g_fs_num) / 2, g_board[i].to_s, g_c_text, g_fs_num, VML_ANCHOR_CENTER)
    end
    i = i + 1
  end

  ui_2d_text(10, 6 + g_fs_score, g_moves.to_s, g_c_text, g_fs_score, VML_ANCHOR_LEFT)
  if g_lang == 0
    ui_2d_text(10, 6 + g_fs_score + 2 + g_fs_lbl, "步数", g_c_dim, g_fs_lbl, VML_ANCHOR_LEFT)
  else
    ui_2d_text(10, 6 + g_fs_score + 2 + g_fs_lbl, "moves", g_c_dim, g_fs_lbl, VML_ANCHOR_LEFT)
  end

  if g_won == 1
    if g_lang == 0
      ui_2d_text(g_sw / 2, g_hint_y, "排好了！", g_c_win, g_fs_score, VML_ANCHOR_CENTER)
    else
      ui_2d_text(g_sw / 2, g_hint_y, "Solved!", g_c_win, g_fs_score, VML_ANCHOR_CENTER)
    end
  else
    if g_lang == 0
      ui_2d_text(g_sw / 2, g_hint_y, "点空格旁的数字 / 方向键滑动", g_c_dim, g_fs_hint, VML_ANCHOR_CENTER)
    else
      ui_2d_text(g_sw / 2, g_hint_y, "Tap a tile beside the blank / arrows", g_c_dim, g_fs_hint, VML_ANCHOR_CENTER)
    end
  end
end

# ══════════════════════════════════════════════════════════════════════════
# 第二段：全局布局与状态（⚠ 必须在所有 def 之后；文件头那条）
# ══════════════════════════════════════════════════════════════════════════

g_c_bg = -15724520        # 0xFF101018
g_c_tile = -14013898      # 0xFF2A2A36
g_c_tile2 = -12960184     # 0xFF3A3A48
g_c_hole = -15066588      # 0xFF1A1A24
g_c_text = -1513232       # 0xFFE8E8F0
g_c_dim = -6643536        # 0xFF9AA0B0
g_c_win = -11409298       # 0xFF51E86E

g_lang = ui_scr_get_language()
g_sw = 360
g_sh = 620
g_cell = 80
g_ox = 20
g_oy = 110
g_m = 360
g_fs_score = 15
g_fs_lbl = 10
g_fs_hint = 11
g_fs_num = 40
g_hint_y = 0
g_seed = 20264
g_moves = 0
g_blank = 15
g_won = 0
g_frames = 0
g_alive = 1

g_board = []
i = 0
while i < 16
  g_board.push(0)
  i = i + 1
end

ui_win_open("十五格拼图", 0, 0)
pz_relayout()
pz_new_game()

g_tid = ui_timer_set(60, 1)

while g_alive == 1
  t = ui_msg_fetch_wait(60)
  if t == 10
    g_alive = 0
  end

  if t == 1
    k = ui_msg_get_a()
    if k == 27
      g_alive = 0
    end
    bx = g_blank % 4
    by = g_blank / 4
    j = g_blank
    if k == 37 && bx < 3
      j = g_blank + 1
    end
    if k == 39 && bx > 0
      j = g_blank - 1
    end
    if k == 38 && by < 3
      j = g_blank + 4
    end
    if k == 40 && by > 0
      j = g_blank - 4
    end
    if j != g_blank
      g_board[g_blank] = g_board[j]
      g_board[j] = 0
      g_blank = j
      g_moves = g_moves + 1
    end
  end

  if t == 6 || t == 4
    tx = ui_msg_get_a()
    ty = ui_msg_get_b()
    if tx >= g_ox && ty >= g_oy
      cx = (tx - g_ox) / g_cell
      cy = (ty - g_oy) / g_cell
      if cx >= 0 && cy >= 0 && cx < 4 && cy < 4
        j = cy * 4 + cx
        bx = g_blank % 4
        by = g_blank / 4
        if (cx == bx && (cy == by + 1 || cy == by - 1)) || (cy == by && (cx == bx + 1 || cx == bx - 1))
          g_board[g_blank] = g_board[j]
          g_board[j] = 0
          g_blank = j
          g_moves = g_moves + 1
        end
      end
    end
  end

  if t == 11
    pz_relayout()
  end

  if t == 9
    g_frames = g_frames + 1
    if g_frames >= 20000
      g_alive = 0
    end
  end

  # 判胜
  won = 1
  i = 0
  while i < 15
    if g_board[i] != i + 1
      won = 0
    end
    i = i + 1
  end
  if g_board[15] != 0
    won = 0
  end
  g_won = won

  pz_draw()
  ui_2d_present()
end

ui_timer_kill(g_tid)
ui_win_close()
