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

ruby/app/snake.rb · 10295 字节 · 下载原文

▶ 在浏览器里试玩

# 贪吃蛇 —— 用 **Ruby** 写的手机小游戏
# Snake — a small phone game written in **Ruby**
#
# 玩法(与 Examples/c/app/snake.c / Examples/go/app/snake.go 同一套):
# Gameplay (same rules as the C / Go versions):
#   · 20×18 格,蛇每 150 毫秒前进一格;吃到食物长一节、加 1 分并提速;
#   · a 20x18 grid, the snake advances one cell every 150 ms; eating food grows it by one, +1 point, faster;
#   · 撞墙或咬到自己结束;方向键 / 点屏幕四边也能转向;回车 / ESC 重开。
#   · hitting a wall or biting yourself ends the run; arrows / tapping a screen edge also turns;
#     Enter / ESC restarts.
#
# ## 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;
#   · **"只写不读"的名字在函数里写的是该函数自己的局部** ⇒ 用 sn_touch_state 先把状态名各读一遍。
#   · **a name that is only written and never read gets written to the function's own local**
#     ⇒ sn_touch_state reads every state name once first.
#
# 跑法 —— 手机:vml run examples/ruby/snake.rb
# How to run — on the phone: vml run examples/ruby/snake.rb
# 跑法 —— 桌面:vmlcli Examples/ruby/snake.rb --screen 480x640 --frames /tmp/fr
# How to run — on the desktop: vmlcli Examples/ruby/snake.rb --screen 480x640 --frames /tmp/fr

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

# ══════════════════════════════════════════════════════════════════════════
# 第一段:全部函数(⚠ 必须排在"给全局赋值"之前,理由见文件头那条)
# ══════════════════════════════════════════════════════════════════════════

def sn_touch_state()
  return g_body.length + g_sw + g_sh + g_cell + g_ox + g_oy + g_len + g_dx + g_dy + g_fx + g_fy + g_score + g_alive_flag + g_step_ms + g_seed + g_frames + g_head_x + g_head_y + g_lang + g_timer_ms + g_alive + g_m + g_fs_score + g_fs_lbl + g_fs_hint + g_hint_y
end

def sn_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
  g_m = g_sw
  if g_sh < g_m
    g_m = g_sh
  end
  # 字号随 min(W,H) 缩放;顶栏(分数 + “得分”)与底部提示都先量出高度,
  # 剩下的才给棋盘 —— 240x240 上旧写法把提示行画在 g_oy+18*cell+26(=246,出画布)。
  # Font sizes scale with min(W,H); the top bar (score + label) and the footer hint
  # are measured first and only the rest goes to the board -- the old 240x240 layout
  # put the hint at oy+18*cell+26 (=246), past the bottom edge.
  g_fs_score = g_m / 24
  if g_fs_score < 11
    g_fs_score = 11
  end
  if g_fs_score > 22
    g_fs_score = 22
  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 / 26
  if g_fs_hint < 9
    g_fs_hint = 9
  end
  if g_fs_hint > 12
    g_fs_hint = 12
  end
  hud = 6 + g_fs_score + 2 + g_fs_lbl + 6
  byw = g_sw - 8
  byh = g_sh - hud - g_fs_hint - 22
  g_cell = byw / 20
  if byh / 18 < g_cell
    g_cell = byh / 18
  end
  if g_cell < 4
    g_cell = 4
  end
  g_ox = (g_sw - g_cell * 20) / 2
  g_oy = hud
  g_hint_y = g_oy + g_cell * 18 + 16
  if g_hint_y > g_sh - g_fs_hint - 6
    g_hint_y = g_sh - g_fs_hint - 6
  end
end

def sn_place_food()
  tries = 0
  g_seed = (g_seed * 1103 + 12345) % 32768
  fx = (g_seed / 256) % 20
  g_seed = (g_seed * 1103 + 12345) % 32768
  fy = (g_seed / 256) % 18
  while tries < 300
    hit = 0
    k = 0
    while k < g_len
      if g_body[k * 2] == fx && g_body[k * 2 + 1] == fy
        hit = 1
      end
      k = k + 1
    end
    if hit == 0
      g_fx = fx
      g_fy = fy
      tries = 300
    else
      g_seed = (g_seed * 1103 + 12345) % 32768
      fx = (g_seed / 256) % 20
      g_seed = (g_seed * 1103 + 12345) % 32768
      fy = (g_seed / 256) % 18
    end
    tries = tries + 1
  end
end

def sn_new_game()
  g_len = 3
  g_dx = 1
  g_dy = 0
  g_score = 0
  g_alive_flag = 1
  g_step_ms = 150
  g_timer_ms = 150
  g_frames = 0
  g_head_x = 10
  g_head_y = 9
  g_body[0] = 10
  g_body[1] = 9
  g_body[2] = 9
  g_body[3] = 9
  g_body[4] = 8
  g_body[5] = 9
  sn_place_food()
end

def sn_step()
  if g_alive_flag == 0
    return 0
  end
  nx = g_head_x + g_dx
  ny = g_head_y + g_dy
  if nx < 0 || ny < 0 || nx >= 20 || ny >= 18
    g_alive_flag = 0
    return 0
  end

  body = 0
  k = 0
  while k < g_len - 1
    if g_body[k * 2] == nx && g_body[k * 2 + 1] == ny
      body = 1
    end
    k = k + 1
  end
  if body != 0
    g_alive_flag = 0
    return 0
  end

  # 整体后移一节,头插在最前
  k = g_len - 1
  while k > 0
    g_body[k * 2] = g_body[(k - 1) * 2]
    g_body[k * 2 + 1] = g_body[(k - 1) * 2 + 1]
    k = k - 1
  end
  g_body[0] = nx
  g_body[1] = ny
  g_head_x = nx
  g_head_y = ny

  if nx == g_fx && ny == g_fy
    if g_len < 62
      g_len = g_len + 1
    end
    g_score = g_score + 1
    if g_step_ms > 70
      g_step_ms = g_step_ms - 10
    end
    sn_place_food()
  end
  return 0
end

def sn_draw()
  ui_2d_clear(g_c_bg)

  x = 0
  while x < 20
    y = 0
    while y < 18
      ui_2d_rect(g_ox + x * g_cell, g_oy + y * g_cell, g_cell - 1, g_cell - 1, g_c_cell, 1, 0, 0)
      y = y + 1
    end
    x = x + 1
  end

  ui_2d_rect(g_ox + g_fx * g_cell, g_oy + g_fy * g_cell, g_cell - 1, g_cell - 1, g_c_food, 1, 0, 3)

  k = 0
  while k < g_len
    if k == 0
      ui_2d_rect(g_ox + g_body[0] * g_cell, g_oy + g_body[1] * g_cell, g_cell - 1, g_cell - 1, g_c_head, 1, 0, 3)
    else
      ui_2d_rect(g_ox + g_body[k * 2] * g_cell, g_oy + g_body[k * 2 + 1] * g_cell, g_cell - 1, g_cell - 1, g_c_body, 1, 0, 3)
    end
    k = k + 1
  end

  ui_2d_text(10, 6 + g_fs_score, g_score.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, "score", g_c_dim, g_fs_lbl, VML_ANCHOR_LEFT)
  end

  if g_alive_flag == 0
    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, "Crash - Enter / ESC to restart", 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 to steer", g_c_dim, g_fs_hint, VML_ANCHOR_CENTER)
    end
  end
end

# ══════════════════════════════════════════════════════════════════════════
# 第二段:全局布局与状态(⚠ 必须在所有 def 之后;文件头那条)
# ══════════════════════════════════════════════════════════════════════════

g_c_bg = -15724520        # 0xFF101018
g_c_cell = -15066588      # 0xFF1A1A24
g_c_head = -11409298      # 0xFF51E86E
g_c_body = -11890471      # 0xFF4A90D9
g_c_food = -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 = 10
g_ox = 10
g_oy = 40
g_m = 360
g_fs_score = 15
g_fs_lbl = 10
g_fs_hint = 11
g_hint_y = 0
g_len = 3
g_dx = 1
g_dy = 0
g_fx = 5
g_fy = 5
g_score = 0
g_alive_flag = 1
g_alive = 1
g_step_ms = 150
g_timer_ms = 150
g_seed = 20263
g_frames = 0
g_head_x = 10
g_head_y = 9

g_body = []
i = 0
while i < 128
  g_body.push(0)
  i = i + 1
end

ui_win_open("贪吃蛇", 0, 0)
sn_relayout()
sn_new_game()

g_tid = ui_timer_set(g_step_ms, 1)

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

  if t == 9
    g_frames = g_frames + 1
    if g_frames >= 20000
      g_alive = 0
    end
    sn_step()
    if g_step_ms != g_timer_ms
      ui_timer_kill(g_tid)
      g_timer_ms = g_step_ms
      g_tid = ui_timer_set(g_timer_ms, 1)
    end
  end

  if t == 1
    k = ui_msg_get_a()
    if k == 27
      g_alive = 0
    end
    if k == 37 && g_dx != 1
      g_dx = -1
      g_dy = 0
    end
    if k == 39 && g_dx != -1
      g_dx = 1
      g_dy = 0
    end
    if k == 38 && g_dy != 1
      g_dx = 0
      g_dy = -1
    end
    if k == 40 && g_dy != -1
      g_dx = 0
      g_dy = 1
    end
    if k == 13
      sn_new_game()
    end
  end

  if t == 6 || t == 4
    tx = ui_msg_get_a()
    ty = ui_msg_get_b()
    if g_alive_flag == 0
      sn_new_game()
    else
      dl = tx
      dr = g_sw - tx
      dt = ty
      db = g_sh - ty
      if dl <= dr && dl <= dt && dl <= db
        if g_dx != 1
          g_dx = -1
          g_dy = 0
        end
      else
        if dr <= dt && dr <= db
          if g_dx != -1
            g_dx = 1
            g_dy = 0
          end
        else
          if dt <= db
            if g_dy != 1
              g_dx = 0
              g_dy = -1
            end
          else
            if g_dy != -1
              g_dx = 0
              g_dy = 1
            end
          end
        end
      end
    end
  end

  if t == 11
    sn_relayout()
  end

  sn_draw()
  ui_2d_present()
end

ui_timer_kill(g_tid)
ui_win_close()