← 都来码 / Dolaima← 例程索引ruby/app/maze.rb▶ 在浏览器里试玩 原文

ruby/app/maze.rb · 12059 字节 · 下载原文

▶ 在浏览器里试玩

# 迷宫 —— 用 **Ruby** 写的手机小游戏(探索 / 每局现生成)
# Maze — a small phone game written in **Ruby** (exploration / generated every round)
#
# 玩法(与 Examples/c/app/maze.c / Examples/python/app/maze.py 同一套):
# Gameplay (same rules as the C / Python versions):
#   · 每局**现生成**一张新迷宫(深度优先挖洞,一定连通、一定有路);
#   · every round **generates** a fresh maze (depth-first carving; always connected, always solvable);
#   · 方向键 / 点屏幕四边移动,走到右下角红格即通关;ESC / 通关后点一下换一张。
#   · arrow keys / tapping a screen edge move; reaching the bottom-right red cell wins;
#     ESC or a tap after winning gives a new maze.
#
# ## 生成用**显式栈**,不用递归
# ## Generation uses an **explicit stack**, not recursion
#
# 递归在这种规模上容易把固定额度的栈吃掉,症状是"跑到一半没了",很难查。
# Recursion at this size can eat the fixed stack budget and the symptom is "it just vanished
# halfway", which is hard to diagnose.
#
# ## 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** (the other order
#     makes the function read garbage);
#   · 状态一律 g_ 前缀;数组用 [] + push 填充;
#   · state is g_-prefixed; arrays are built with [] + push;
#   · 数字转字符串用 .to_s,拼接用 +;
#   · numbers to strings use .to_s; concatenation uses +;
#   · 颜色写负数十进制;
#   · colours are negative decimals;
#   · **"只写不读"的名字在函数里写的是该函数自己的局部** ⇒ 用 mz_touch_state 先把状态名各读一遍。
#   · **a name that is only written and never read gets written to the function's own local**
#     ⇒ mz_touch_state reads every state name once first.
#
# 跑法 —— 手机:vml run examples/ruby/maze.rb
# How to run — on the phone: vml run examples/ruby/maze.rb
# 跑法 —— 桌面:vmlcli Examples/ruby/maze.rb --screen 480x640 --frames /tmp/fr
# How to run — on the desktop: vmlcli Examples/ruby/maze.rb --screen 480x640 --frames /tmp/fr

# UI 库的显式引用(用户 2026-10-01 定的口径),声明文件 Lib/ruby/vml_ui.rb 由 GenLib 生成。
# The explicit reference to the UI library (user convention of 2026-10-01); Lib/ruby/vml_ui.rb is generated by GenLib.
require 'vml_ui'

# ══════════════════════════════════════════════════════════════════════════
# 第一段:全部函数(⚠ 必须排在"给全局赋值"之前,理由见文件头那条)
# Section 1: all the functions (⚠ must come before any assignment to a global; see the header)
# ══════════════════════════════════════════════════════════════════════════

# ⚠ 编译期保险(见 minesweeper.rb 同名函数):让各状态的全局槽在任何函数生成之前就存在。
# ⚠ Compile-time safeguard (see the same function in minesweeper.rb): make every state slot exist
#   before any function is generated.
def mz_touch_state()
  return g_cells.length + g_stx.length + g_sty.length + g_dirs.length + g_seed + g_px + g_py + g_won + g_steps + g_sw + g_sh + g_cell + g_ox + g_oy + g_lang + g_top + g_m + g_fs + g_fs_lbl + g_fs_hint + g_hint_y
end

def mz_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 ⇒ 格子 3px)。
  # 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 => 3 px cells).
  g_m = g_sw
  if g_sh < g_m
    g_m = g_sh
  end
  g_fs = g_m / 24
  if g_fs < 9
    g_fs = 9
  end
  if g_fs > 16
    g_fs = 16
  end
  g_fs_lbl = g_m / 48
  if g_fs_lbl < 8
    g_fs_lbl = 8
  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 > 11
    g_fs_hint = 11
  end
  g_oy = 60
  g_side = g_sw - 16
  avail = g_sh - g_oy - g_fs_hint - 22
  if avail < g_side
    g_side = avail
  end
  g_cell = g_side / 21
  if g_cell < 3
    g_cell = 3
  end
  g_ox = (g_sw - 21 * g_cell) / 2
  g_hint_y = g_oy + 21 * g_cell + 16
  if g_hint_y > g_sh - g_fs_hint - 6
    g_hint_y = g_sh - g_fs_hint - 6
  end
end

# ── 开一局:DFS 挖洞(显式栈),每局现生成 ──
# ── New maze: DFS carving with an explicit stack, generated fresh every round ──
def mz_new_maze()
  i = 0
  while i < 441
    g_cells[i] = 1
    i = i + 1
  end
  g_seed = 20268
  g_top = 0
  g_cells[1 * 21 + 1] = 0
  g_stx[g_top] = 1
  g_sty[g_top] = 1
  g_top = g_top + 1
  while g_top > 0
    cx = g_stx[g_top - 1]
    cy = g_sty[g_top - 1]
    n = 0
    # 四个方向里"目标格还是墙"的那些(那种才没挖过)
    # Of the four directions, keep the ones whose two-cells-away target is still a wall
    if cx + 2 < 20
      if g_cells[(cx + 2) * 21 + cy] == 1
        g_dirs[n] = 0
        n = n + 1
      end
    end
    if cx - 2 > 0
      if g_cells[(cx - 2) * 21 + cy] == 1
        g_dirs[n] = 1
        n = n + 1
      end
    end
    if cy + 2 < 20
      if g_cells[cx * 21 + cy + 2] == 1
        g_dirs[n] = 2
        n = n + 1
      end
    end
    if cy - 2 > 0
      if g_cells[cx * 21 + cy - 2] == 1
        g_dirs[n] = 3
        n = n + 1
      end
    end
    if n == 0
      # 死路:回退 / dead end: backtrack
      g_top = g_top - 1
    else
      g_seed = (g_seed * 1103 + 12345) % 32768
      k = g_dirs[(g_seed / 256) % n]
      if k == 0
        g_cells[(cx + 1) * 21 + cy] = 0
        cx = cx + 2
      else
        if k == 1
          g_cells[(cx - 1) * 21 + cy] = 0
          cx = cx - 2
        else
          if k == 2
            g_cells[cx * 21 + cy + 1] = 0
            cy = cy + 2
          else
            g_cells[cx * 21 + cy - 1] = 0
            cy = cy - 2
          end
        end
      end
      g_cells[cx * 21 + cy] = 0
      if g_top < 512
        g_stx[g_top] = cx
        g_sty[g_top] = cy
        g_top = g_top + 1
      end
    end
  end
  # 右下角出口强制打通(保证一定到得了)
  # Force the bottom-right exit open (so it is always reachable)
  i = 0
  while i < 3
    if 21 - 2 - i >= 0
      g_cells[(21 - 2 - i) * 21 + 21 - 2] = 0
    end
    if 21 - 2 - i >= 0
      g_cells[(21 - 2) * 21 + 21 - 2 - i] = 0
    end
    i = i + 1
  end
  g_px = 1
  g_py = 1
  g_won = 0
  g_steps = 0
end

def mz_draw()
  ui_2d_clear(g_c_bg)
  x = 0
  while x < 21
    y = 0
    while y < 21
      if g_cells[x * 21 + y] == 1
        ui_2d_rect(g_ox + x * g_cell, g_oy + y * g_cell, g_cell, g_cell, g_c_wall, 1, 0, 0)
      else
        ui_2d_rect(g_ox + x * g_cell, g_oy + y * g_cell, g_cell, g_cell, g_c_path, 1, 0, 0)
      end
      y = y + 1
    end
    x = x + 1
  end
  ui_2d_rect(g_ox + 19 * g_cell + 1, g_oy + 19 * g_cell + 1, g_cell - 2, g_cell - 2, g_c_goal, 1, 0, 2)
  ui_2d_rect(g_ox + g_px * g_cell + 1, g_oy + g_py * g_cell + 1, g_cell - 2, g_cell - 2, g_c_player, 1, 0, g_cell / 2)

  ui_2d_text(10, 6 + g_fs, g_steps.to_s, g_c_text, g_fs, VML_ANCHOR_LEFT)
  if g_lang == 0
    ui_2d_text(10, 6 + g_fs + 2 + g_fs_lbl, "步数", g_c_dim, g_fs_lbl, VML_ANCHOR_LEFT)
  else
    ui_2d_text(10, 6 + g_fs + 2 + g_fs_lbl, "steps", 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, "走出来了!点一下/ESC 换一张", g_c_text, g_fs_hint, VML_ANCHOR_CENTER)
    else
      ui_2d_text(g_sw / 2, g_hint_y, "Out! Tap / ESC for a new maze", g_c_text, g_fs_hint, 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, "Arrows / tap a screen edge; reach the red cell", g_c_dim, g_fs_hint, VML_ANCHOR_CENTER)
    end
  end
end

# ══════════════════════════════════════════════════════════════════════════
# 第二段:全局布局与状态(⚠ 必须在所有 def 之后;文件头那条)
# Section 2: layout and state (⚠ must come after every def; see the header)
# ══════════════════════════════════════════════════════════════════════════

g_c_bg = -15724520        # 0xFF101018
g_c_wall = -14013898      # 0xFF2A2A36
g_c_path = -15066588      # 0xFF1A1A24
g_c_player = -11409298    # 0xFF51E86E
g_c_goal = -2069424       # 0xFFE06C50
g_c_text = -1513232       # 0xFFE8E8F0
g_c_dim = -6643536        # 0xFF9AA0B0

g_lang = ui_scr_get_language()
g_sw = 360
g_sh = 620
g_cell = 16
g_ox = 0
g_oy = 110
g_side = 0
g_m = 360
g_fs = 15
g_fs_lbl = 10
g_fs_hint = 11
g_hint_y = 0

# 迷宫状态:21×21 的格子图 + 512 格的显式栈
# Maze state: a 21x21 cell map plus a 512-slot explicit stack
g_cells = []
g_stx = []
g_sty = []
g_dirs = []
i = 0
while i < 441
  g_cells.push(0)
  i = i + 1
end
i = 0
while i < 512
  g_stx.push(0)
  g_sty.push(0)
  i = i + 1
end
i = 0
while i < 4
  g_dirs.push(0)
  i = i + 1
end
g_px = 1
g_py = 1
g_won = 0
g_steps = 0
g_seed = 20268
g_top = 0
g_alive = 1
g_frames = 0

ui_win_open("迷宫", 0, 0)
mz_relayout()
mz_new_maze()

g_tid = ui_timer_set(120, 1)

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

  if t == 1
    k = ui_msg_get_a()
    if k == 27
      mz_new_maze()
    else
      nx = g_px
      ny = g_py
      if k == 37
        nx = g_px - 1
      end
      if k == 39
        nx = g_px + 1
      end
      if k == 38
        ny = g_py - 1
      end
      if k == 40
        ny = g_py + 1
      end
      if g_won == 0
        if nx != g_px || ny != g_py
          if nx >= 0 && ny >= 0 && nx < 21 && ny < 21
            if g_cells[nx * 21 + ny] == 0
              g_px = nx
              g_py = ny
              g_steps = g_steps + 1
              if g_px == 19 && g_py == 19
                g_won = 1
              end
            end
          end
        end
      end
    end
  end

  if t == 6 || t == 4
    tx = ui_msg_get_a()
    ty = ui_msg_get_b()
    if g_won == 1
      mz_new_maze()
    else
      # 点屏幕四边:离哪边最近就往那边走
      # A screen edge decides the direction (whichever side is nearest)
      dl = tx
      dr = g_sw - tx
      dt = ty
      db = g_sh - ty
      nx = g_px
      ny = g_py
      if dl <= dr && dl <= dt && dl <= db
        nx = g_px - 1
      else
        if dr <= dt && dr <= db
          nx = g_px + 1
        else
          if dt <= db
            ny = g_py - 1
          else
            ny = g_py + 1
          end
        end
      end
      if g_won == 0
        if nx >= 0 && ny >= 0 && nx < 21 && ny < 21
          if g_cells[nx * 21 + ny] == 0
            g_px = nx
            g_py = ny
            g_steps = g_steps + 1
            if g_px == 19 && g_py == 19
              g_won = 1
            end
          end
        end
      end
    end
  end

  if t == 11
    mz_relayout()
  end

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

  mz_draw()
  ui_2d_present()
end

ui_timer_kill(g_tid)
ui_win_close()