零构建打造《华容道》小游戏:网格滑块建模、BFS 求最短解与布局可解性验证

举报
yd_229606956 发表于 2026/11/10 10:40:15 2026/11/10
【摘要】 导读:华容道看起来是个"拼图游戏",本质上却是一个标准的搜索问题:在一个 4×5 的网格里,十几个尺寸不同的矩形块只能整体平移,目标是把 2×2 的"曹操"挪到底部中央。本文用纯单文件 HTML(CSS/JS 全内联,零依赖、零构建)实现一个完整的华容道,重点讲清三件事:移动判定为什么要先"清空自己"、BFS 怎么把 2.4 万个状态跑出最短解、以及怎么验证一个自定义布局到底能不能通关(这一...

导读:华容道看起来是个"拼图游戏",本质上却是一个标准的搜索问题:在一个 4×5 的网格里,十几个尺寸不同的矩形块只能整体平移,目标是把 2×2 的"曹操"挪到底部中央。

本文用纯单文件 HTML(CSS/JS 全内联,零依赖、零构建)实现一个完整的华容道,重点讲清三件事:移动判定为什么要先"清空自己"、BFS 怎么把 2.4 万个状态跑出最短解、以及怎么验证一个自定义布局到底能不能通关(这一条是我实际踩坑后加的)。


一、把游戏抽象成网格滑块问题

1.1 棋盘与棋子

棋盘固定为 4 列 × 5 行,共 20 个格子。所有棋子都是矩形,用四个属性描述:

{ id: 'cao', name: '曹操', w: 2, h: 2, r: 0, c: 1, type: 'cao' }
//  w/h 是宽高(以格为单位),r/c 是左上角的行列坐标

经典"横刀立马"布局:

列 0    1    2    3
┌────┬────┬────┬────┐
│ 张 │ 曹 │ 曹 │ 赵 │  行 0
│ 飞 │ 曹 │ 曹 │ 云 │  行 1
├────┼────┼────┼────┤
│ 马 │ 关 │ 关 │ 黄 │  行 2
│ 超 ├────┼────┤ 忠 │  行 3
│ 超 │ 卒 │ 卒 │ 忠 │
├────┼────┼────┼────┤
│ 卒 │ 空 │ 空 │ 卒 │  行 4
└────┴────┴────┴────┘
              ↑
          底部中央是出口

数一下:曹操 4 格 + 四名竖将各 2 格(8 格)+ 关羽 2 格 + 四个卒 4 格 = 18 格,剩下 2 格是空格。

这 2 个空格是整个游戏的关键。 华容道所有移动都依赖"把空格挪到需要的位置",一旦空格数为 0,棋盘就彻底卡死——后面第四节会看到,我正是因为没有检查这一点,写出过一个完全无解的布局。

1.2 胜利条件

曹操左上角到达 (r=3, c=1),也就是它的 2×2 方阵正好压在底部中央的两个出口格上:

const GOAL_R = 3;
const GOAL_C = 1;

if (cao.r === GOAL_R && cao.c === GOAL_C) {
  /* 通关 */
}

注意判定用的是左上角坐标,不是"中心点"。用左上角写起来最简单,也最容易和渲染逻辑对齐。


二、移动判定:一个必须"先清空自己"的坑

2.1 直觉写法为什么是错的

最直觉的实现是:把整个棋盘铺成一张占用表,然后检查目标格是否为空。

function buildGrid() {
  const grid = new Array(ROWS * COLS).fill(-1);   // -1 表示空
  for (let i = 0; i < pieces.length; i++) {
    const p = pieces[i];
    for (let dr = 0; dr < p.h; dr++) {
      for (let dc = 0; dc < p.w; dc++) {
        grid[(p.r + dr) * COLS + (p.c + dc)] = i;
      }
    }
  }
  return grid;
}

问题来了:棋子自己要占的格子也在表里。假设一个 2×2 的曹操要向右移动一格,目标区域的左半边刚好是它自己当前占的位置——检查时会发现"被占用",于是判定为不可移动。

所有棋子都会永远动不了。

2.2 正确做法:先把"自己"从占用表里抹掉

function canMove(pieceIndex, dr, dc) {
  const p = pieces[pieceIndex];
  const grid = buildGrid();

  /* 关键一步:把自己占的格子置空,否则自己会挡住自己 */
  for (let r = 0; r < p.h; r++) {
    for (let c = 0; c < p.w; c++) {
      grid[(p.r + r) * COLS + (p.c + c)] = -1;
    }
  }

  /* 再检查目标区域是否越界或被别人占用 */
  for (let r = 0; r < p.h; r++) {
    for (let c = 0; c < p.w; c++) {
      const nr = p.r + r + dr;
      const nc = p.c + c + dc;
      if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) return false;
      if (grid[nr * COLS + nc] !== -1) return false;
    }
  }
  return true;
}

这个"先清空自己"的步骤,和数独里"先算翻转再落子"属于同一类问题:判断时用的应该是"变化前"的状态,而不是"变化后"的状态。这类顺序错误不会报错,只会让游戏安静地失灵。

2.3 边界检查不能省

nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS 这一行看起来理所当然,但如果漏掉,grid[] 会读到 undefined,undefined !== -1 为 true,于是越界移动会被误判为"被占用"——表面上像是"被挡住了",实际后果是棋子会莫名其妙地卡在边界上,而且很难定位原因。

测试里我专门验证了这一条:让曹操向上(越界)移动,必须返回 false。


三、BFS 求最短解:2.4 万个状态怎么跑

3.1 为什么是 BFS 而不是 DFS

华容道要求的是最少步数。BFS(广度优先)按层扩展,第一次搜到目标状态时的深度就是最短步数——这是 BFS 的天然优势。

如果用 DFS,第一次找到的解可能是一百多步的绕路方案,完全不能作为"参考步数"。

3.2 状态编码:卒可以互换,所以可以规范化

如果直接把"每个棋子的 (r,c) 拼成字符串"作为状态键,会遇到一个严重的组合爆炸:

四个卒是完全相同的。卒 A 在 (3,1)、卒 B 在 (3,2),与"卒 B 在 (3,1)、卒 A 在 (3,2)"在视觉和玩法上完全等价,但如果按棋子 id 编码,它们会被当成两个不同的状态,状态数直接乘以 4!=244! = 24。

解决办法是按形状分组后排序:

function encode(pieces) {
  const cao = pieces.find(p => p.id === 'cao');

  /* 除曹操外,按"形状"分组收集位置 */
  const groups = {};
  for (const p of pieces) {
    if (p.id === 'cao') continue;
    const key = p.w + 'x' + p.h;
    (groups[key] = groups[key] || []).push(p.r * COLS + p.c);
  }

  /* 每组内部排序,消除同形状棋子的排列差异 */
  let s = cao.r * COLS + cao.c + '|';
  Object.keys(groups).sort().forEach(k => {
    s += k + ':' + groups[k].sort((a, b) => a - b).join(',') + '|';
  });
  return s;
}

排序这一步把"24 种排列"折叠成"1 种",状态数从可能的几十万降到两万多。

3.3 搜索框架

function search(pieces) {
  const caoIndex = pieces.findIndex(p => p.id === 'cao');
  const queue = [pieces];
  const dist = new Map([[encode(pieces), 0]]);
  const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  let head = 0;

  while (head < queue.length) {
    const cur = queue[head++];
    const d = dist.get(encode(cur));

    /* 到达目标,返回步数 */
    if (cur[caoIndex].r === 3 && cur[caoIndex].c === 1) {
      return { ok: true, steps: d };
    }

    /* 依次尝试每个棋子的四个方向 */
    for (let i = 0; i < cur.length; i++) {
      // ...
      const key = encode(next);
      if (dist.has(key)) continue;   // 已访问过
      dist.set(key, d + 1);
      queue.push(next);
    }
  }
  return { ok: false };              // 队列耗尽仍未到达 → 不可解
}

用数组 + head 指针模拟队列,比 shift() 快得多(shift() 每次都要移动整个数组)。

3.4 实测结果

我在 Node.js 里跑了四个布局(encode 用上面的规范化方案):

布局 最短步数 探索状态数 耗时
横刀立马 116 24,098 约 460 ms
指挥若定 100 23,620 约 490 ms
围而不歼 114 23,950 约 420 ms
兵临城下 87 19,811 约 320 ms

关于"81 步"的说明:网上流传的"横刀立马最少 81 步",采用的是**“同一个棋子连续移动只算一步"的计法。本文统计的是"每移动一格算一步”**,所以是 116 步。两种口径都对,只是标准不同——游戏里用的是后者(每次位移 +1),因此界面上显示的"参考步数"也是 116。写文档时如果把两种口径混用,读者会以为程序算错了。


四、拖拽交互:把像素位移翻译成"格"

4.1 为什么不能直接用 mousemove 事件改坐标

如果按"手指移动多少像素,棋子就移动多少像素"来做,会出现两个问题:

  1. 松手时棋子的位置往往不在整格上,视觉上歪歪扭扭;
  2. 棋子会脱离网格,下一次移动的判定基准全乱了。

正确的模型是:棋子的位置永远由 (r, c) 整数坐标决定,拖拽只负责"识别出用户想往哪个方向走一格"。

4.2 阈值 + 基准点重置

el.addEventListener('pointermove', function (e) {
  if (!drag || drag.index !== index) return;

  const dx = e.clientX - drag.startX;
  const dy = e.clientY - drag.startY;

  /* 位移更大的方向作为主轴 */
  if (Math.abs(dx) >= Math.abs(dy)) {
    if (Math.abs(dx) > drag.cellW * 0.42) {          // 超过 0.42 格触发
      const dir = dx > 0 ? 1 : -1;
      if (doMove(index, 0, dir, true)) {
        drag.startX += dir * drag.cellW;             // 基准点重置
        drag.moved = true;
      }
    }
  } else {
    /* 垂直方向同理 */
  }
});

两个细节值得说明:

① 0.42 这个阈值。 取值太小(比如 0.2)会让手指轻微抖动就触发移动,棋子"乱跑";太大(比如 0.8)则要拖很远才有反应,手感很沉。0.42 略小于半格,实测最接近直觉。

② 基准点重置是连续拖拽的关键。 移动成功后执行 drag.startX += dir * cellW,相当于把"起点"往前推了一格。这样用户一直按住不放、继续往同一方向拖,就能连续走多格——而不是"拖一格就得松手重来"。

4.3 主轴判断

Math.abs(dx) >= Math.abs(dy) 决定这次是横向还是纵向移动。斜着拖的时候,取位移更大的那个轴,避免"又想横又想竖"导致来回横跳。


五、布局可解性验证:我踩过的坑

这一节值得单独拿出来说,因为它是实际开发中真正踩到的坑。

5.1 一个看起来很合理的布局,其实完全无解

我最初设计第四档"层层设防"时,想当然地把它排成:

张 曹 曹 赵
张 曹 曹 赵
马 关 关 黄
马 卒 卒 黄
卒 卒 卒 卒

数一下:曹操 4 格 + 四名竖将 8 格 + 关羽 2 格 + 六个卒 6 格 = 20 格。

正好填满整个 4×5 棋盘,一个空格都没有。

放进 BFS 求解器一跑,结果是:

层层设防: 不可解 · 探索 1 状态 · 0ms

"探索 1 状态"意味着——从初始局面出发,连一步都走不了。因为没有任何空格,所有棋子都被锁死。

5.2 教训:每个布局都必须过一遍求解器

如果没做这一步验证,这个布局会堂而皇之地出现在 UI 里。玩家点进去,发现怎么拖都纹丝不动,只会以为是"程序坏了",而不是"这个关卡设计错了"。

所以现在的流程是:

  1. 写布局数据;
  2. 先跑 BFS,确认 可解 且拿到最短步数;
  3. 把步数写进 PAR_MOVES,作为界面上的"参考步数";
  4. 才放进 UI。

最终替换成了"围而不歼"(底行中间两卒、两侧留空),BFS 验证 114 步可解。

5.3 一个顺手得到的质检工具

BFS 还顺便帮我验证了另外三件事:

  • 初始可动棋子数量:横刀立马应该是 4 个卒能动,其余全被挡住——如果数字不对,说明某个棋子的坐标写错了;
  • 空格数:必须恰好 2 个;
  • 越界拒绝:曹操向上移动必须返回 false。

这三条现在都是自动化检查项。



完整源码(保存为 index.html 即可运行)

以下为 klotski/index.html 的完整内容,双击即可在浏览器中运行,无需安装依赖、无需构建命令。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>华容道 · 滑块解谜 Klotski</title>
<style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
  }

  :root {
    --bg-deep: #100a0a;
    --panel: rgba(38, 26, 26, 0.82);
    --line: rgba(180, 140, 120, 0.22);
    --text: #f7f2ec;
    --muted: #b3a095;
    --gold: #e8b44a;
    --gold-soft: #f6d68a;
    --wood: #4a2f24;
    --wood-dark: #2b1a13;
    --jade: #5fa88a;
    --rose: #d97070;
    --indigo: #6d78b8;
  }

  html, body { height: 100%; }

  body {
    background:
      radial-gradient(900px 460px at 50% -10%, #3a2420 0%, transparent 62%),
      radial-gradient(760px 420px at 88% 108%, #241416 0%, transparent 58%),
      linear-gradient(180deg, var(--bg-deep), #060405 85%);
    color: var(--text);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif;
    min-height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 12px 10px 20px;
    overflow-x: hidden;
    user-select: none;
    -webkit-user-select: none;
  }

  .container {
    width: 100%;
    max-width: 420px;
    display: flex;
    flex-direction: column;
    gap: 9px;
  }

  header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    padding: 0 4px;
  }

  header h1 {
    font-size: 23px;
    font-weight: 900;
    letter-spacing: 3px;
    background: linear-gradient(108deg, var(--gold-soft), var(--gold) 45%, #c98a3c);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  header .sub {
    font-size: 11px;
    color: var(--muted);
    letter-spacing: 1px;
  }

  /* ============ 统计 ============ */
  .stats {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 6px;
  }

  .stat {
    background: var(--panel);
    border: 1px solid var(--line);
    border-radius: 10px;
    padding: 6px 3px;
    text-align: center;
    backdrop-filter: blur(8px);
  }

  .stat .k {
    font-size: 10px;
    color: var(--muted);
    letter-spacing: 0.5px;
  }

  .stat .v {
    font-size: 16px;
    font-weight: 800;
    font-variant-numeric: tabular-nums;
    margin-top: 1px;
  }

  .stat.moves .v { color: var(--gold); }
  .stat.best .v { color: var(--jade); }
  .stat.par .v { color: var(--indigo); }
  .stat.time .v { color: var(--rose); }

  /* ============ 棋盘 ============ */
  .board-wrap {
    position: relative;
    width: 100%;
    aspect-ratio: 4 / 5;
    padding: 8px;
    border-radius: 16px;
    background:
      repeating-linear-gradient(90deg, rgba(255, 255, 255, 0.02) 0 2px, transparent 2px 7px),
      linear-gradient(155deg, #6b4534, #4a2f24 45%, #2b1a13);
    box-shadow:
      0 20px 44px rgba(0, 0, 0, 0.7),
      inset 0 1px 0 rgba(255, 255, 255, 0.12),
      inset 0 0 26px rgba(0, 0, 0, 0.55);
    border: 1px solid rgba(120, 80, 60, 0.5);
  }

  .board {
    position: relative;
    width: 100%;
    height: 100%;
    background: #23150f;
    border-radius: 9px;
    box-shadow: inset 0 0 22px rgba(0, 0, 0, 0.75);
    overflow: visible;
  }

  /* 出口虚线框 */
  .exit-zone {
    position: absolute;
    left: 25%;
    top: 80%;
    width: 50%;
    height: 20%;
    border: 2px dashed rgba(232, 180, 74, 0.42);
    border-radius: 6px;
    pointer-events: none;
    z-index: 0;
  }

  .exit-zone::after {
    content: "出口";
    position: absolute;
    left: 50%;
    bottom: 4px;
    transform: translateX(-50%);
    font-size: 9px;
    letter-spacing: 3px;
    color: rgba(232, 180, 74, 0.55);
  }

  /* ============ 棋子 ============ */
  .piece {
    position: absolute;
    z-index: 2;
    transition: left 0.16s cubic-bezier(0.3, 0.9, 0.4, 1),
                top 0.16s cubic-bezier(0.3, 0.9, 0.4, 1);
    touch-action: none;
    cursor: grab;
  }

  .piece.selected { z-index: 6; }
  .piece.dragging { z-index: 8; transition: none; cursor: grabbing; }

  .piece-inner {
    position: absolute;
    inset: 3px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    letter-spacing: 1px;
    color: #fff8e8;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
    box-shadow:
      inset 0 1px 0 rgba(255, 255, 255, 0.28),
      inset 0 -2px 6px rgba(0, 0, 0, 0.35),
      0 3px 8px rgba(0, 0, 0, 0.5);
    transition: transform 0.14s ease, box-shadow 0.14s ease;
    overflow: hidden;
  }

  /* 棋子木纹纹理 */
  .piece-inner::before {
    content: "";
    position: absolute;
    inset: 0;
    background:
      repeating-linear-gradient(115deg, rgba(255, 255, 255, 0.05) 0 3px, transparent 3px 9px);
    pointer-events: none;
  }

  /* 曹操 */
  .piece.cao .piece-inner {
    background: linear-gradient(150deg, #c0392b 0%, #96251b 48%, #6e140d 100%);
    border: 1.5px solid rgba(246, 214, 138, 0.7);
    font-size: 21px;
    letter-spacing: 4px;
    box-shadow:
      inset 0 1px 0 rgba(255, 220, 160, 0.5),
      inset 0 -3px 10px rgba(0, 0, 0, 0.45),
      0 4px 14px rgba(192, 57, 43, 0.45);
  }

  /* 五虎将 */
  .piece.general .piece-inner {
    background: linear-gradient(150deg, #4a5aa8 0%, #35407e 50%, #222a56 100%);
    border: 1px solid rgba(160, 175, 230, 0.55);
    font-size: 15px;
  }

  /* 卒 */
  .piece.soldier .piece-inner {
    background: linear-gradient(150deg, #4e7a63 0%, #365a48 52%, #223a2e 100%);
    border: 1px solid rgba(150, 200, 175, 0.45);
    font-size: 15px;
  }

  .piece.selected .piece-inner {
    transform: scale(0.965);
    box-shadow:
      0 0 0 2.5px var(--gold-soft),
      0 0 18px rgba(232, 180, 74, 0.75),
      inset 0 1px 0 rgba(255, 255, 255, 0.3);
  }

  .piece.dragging .piece-inner {
    transform: scale(0.97);
    box-shadow:
      0 0 0 2.5px var(--gold-soft),
      0 10px 22px rgba(0, 0, 0, 0.7);
  }

  /* 可移动提示:轻微闪烁的角标 */
  .piece.can-move::after {
    content: "";
    position: absolute;
    top: 5px;
    right: 5px;
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background: var(--gold-soft);
    box-shadow: 0 0 8px var(--gold);
    animation: dotBlink 1.5s ease-in-out infinite;
    z-index: 3;
  }

  @keyframes dotBlink {
    0%, 100% { opacity: 0.35; transform: scale(0.8); }
    50%      { opacity: 1; transform: scale(1); }
  }

  /* 曹操脱出动画 */
  .piece.escaping {
    transition: top 0.75s cubic-bezier(0.4, 0, 0.6, 1), opacity 0.75s ease 0.35s;
    opacity: 0;
  }

  /* ============ 遮罩 ============ */
  .overlay {
    position: absolute;
    inset: 0;
    border-radius: 16px;
    background: rgba(10, 6, 5, 0.95);
    backdrop-filter: blur(7px);
    display: none;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 12px;
    padding: 24px 20px;
    text-align: center;
    z-index: 30;
  }

  .overlay.show { display: flex; animation: fadeUp 0.36s ease-out; }

  @keyframes fadeUp {
    from { opacity: 0; transform: translateY(12px); }
    to   { opacity: 1; transform: translateY(0); }
  }

  .overlay h2 {
    font-size: 25px;
    font-weight: 900;
    letter-spacing: 3px;
    background: linear-gradient(100deg, var(--gold-soft), var(--jade));
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .overlay .detail {
    font-size: 13px;
    color: #d8c9bd;
    line-height: 1.9;
  }

  .overlay .detail b { color: var(--gold); font-size: 17px; }

  /* ============ 按钮 ============ */
  .btn {
    border: 1px solid var(--line);
    background: linear-gradient(180deg, #3a2720, #221410);
    color: var(--text);
    border-radius: 10px;
    padding: 11px 8px;
    font-size: 13px;
    font-weight: 700;
    letter-spacing: 1px;
    cursor: pointer;
    transition: transform 0.12s ease, filter 0.15s ease;
  }

  .btn:active { transform: translateY(1px); filter: brightness(1.2); }

  .btn.primary {
    background: linear-gradient(135deg, #b8862f, #e8b44a);
    border-color: rgba(232, 180, 74, 0.5);
    color: #2a1a08;
    box-shadow: 0 6px 16px rgba(232, 180, 74, 0.3);
  }

  .btn:disabled { opacity: 0.42; cursor: not-allowed; }

  .btn.wide { width: 100%; max-width: 190px; }

  .layout-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 5px;
  }

  .lay {
    padding: 8px 2px;
    border-radius: 9px;
    font-size: 10.5px;
    font-weight: 700;
    color: var(--muted);
    background: rgba(58, 39, 32, 0.8);
    border: 1px solid var(--line);
    cursor: pointer;
    line-height: 1.35;
    transition: all 0.16s ease;
  }

  .lay span {
    display: block;
    font-size: 8.5px;
    font-weight: 500;
    opacity: 0.7;
  }

  .lay.active {
    color: #2a1a08;
    background: linear-gradient(135deg, #e8b44a, #f6d68a);
    border-color: transparent;
    box-shadow: 0 4px 14px rgba(232, 180, 74, 0.35);
  }

  .lay.active span { opacity: 0.75; }

  .actions {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 7px;
  }

  .footer-tip {
    font-size: 11px;
    color: #7d6a60;
    text-align: center;
    line-height: 1.7;
  }

  .footer-tip b { color: #a89184; font-weight: 600; }

  /* 通关彩带 */
  .confetti {
    position: absolute;
    width: 7px;
    height: 11px;
    border-radius: 1px;
    pointer-events: none;
    z-index: 40;
  }
</style>
</head>
<body>
<div class="container">
  <header>
    <h1>KLOTSKI</h1>
    <div class="sub">华容道 · 助曹操脱险</div>
  </header>

  <div class="stats">
    <div class="stat moves"><div class="k">步数</div><div class="v" id="statMoves">0</div></div>
    <div class="stat best"><div class="k">最佳</div><div class="v" id="statBest">—</div></div>
    <div class="stat par"><div class="k">参考步数</div><div class="v" id="statPar">—</div></div>
    <div class="stat time"><div class="k">用时</div><div class="v" id="statTime">00:00</div></div>
  </div>

  <div class="board-wrap">
    <div class="board" id="board">
      <div class="exit-zone"></div>
    </div>

    <div class="overlay" id="overlay">
      <h2>曹操已脱险</h2>
      <div class="detail" id="ovDetail">共用 0 步</div>
      <button class="btn primary wide" id="ovBtn">再挑战一次</button>
    </div>
  </div>

  <div class="layout-row" id="layoutRow">
    <button class="lay active" data-layout="classic">横刀立马<span>经典</span></button>
    <button class="lay" data-layout="command">指挥若定<span>进阶</span></button>
    <button class="lay" data-layout="layers">围而不歼<span>挑战</span></button>
    <button class="lay" data-layout="besiege">兵临城下<span>高手</span></button>
  </div>

  <div class="actions">
    <button class="btn" id="btnUndo">撤销</button>
    <button class="btn" id="btnHint">提示一步</button>
    <button class="btn primary" id="btnReset">重新开始</button>
  </div>

  <div class="footer-tip">
    拖动棋子沿空格移动,或点击选中后用 <b>方向键</b> 移动;<br>
    把红色的<b>曹操</b>移到棋盘底部中央的出口即胜利。
  </div>
</div>

<script>
(function () {
  'use strict';

  /* =========================================================
   * 棋盘规格:4 列 × 5 行
   * ======================================================= */
  const COLS = 4;
  const ROWS = 5;

  /* 曹操脱出位置(底部中央) */
  const GOAL_R = 3;
  const GOAL_C = 1;

  /* =========================================================
   * 布局定义
   * 每个棋子:{ id, name, w, h, r, c, type }
   * type: cao(曹操) / general(五虎将) / soldier(卒)
   * ======================================================= */
  const LAYOUTS = {
    /* 横刀立马:最经典的入门布局 */
    classic: {
      name: '横刀立马',
      pieces: [
        { id: 'cao',  name: '曹操', w: 2, h: 2, r: 0, c: 1, type: 'cao' },
        { id: 'zf',   name: '张飞', w: 1, h: 2, r: 0, c: 0, type: 'general' },
        { id: 'zy',   name: '赵云', w: 1, h: 2, r: 0, c: 3, type: 'general' },
        { id: 'mc',   name: '马超', w: 1, h: 2, r: 2, c: 0, type: 'general' },
        { id: 'hz',   name: '黄忠', w: 1, h: 2, r: 2, c: 3, type: 'general' },
        { id: 'gy',   name: '关羽', w: 2, h: 1, r: 2, c: 1, type: 'general' },
        { id: 's1',   name: '卒', w: 1, h: 1, r: 3, c: 1, type: 'soldier' },
        { id: 's2',   name: '卒', w: 1, h: 1, r: 3, c: 2, type: 'soldier' },
        { id: 's3',   name: '卒', w: 1, h: 1, r: 4, c: 0, type: 'soldier' },
        { id: 's4',   name: '卒', w: 1, h: 1, r: 4, c: 3, type: 'soldier' }
      ]
    },

    /* 指挥若定:两名卒移到中部两侧,马超黄忠整体下移 */
    command: {
      name: '指挥若定',
      pieces: [
        { id: 'cao',  name: '曹操', w: 2, h: 2, r: 0, c: 1, type: 'cao' },
        { id: 'zf',   name: '张飞', w: 1, h: 2, r: 0, c: 0, type: 'general' },
        { id: 'zy',   name: '赵云', w: 1, h: 2, r: 0, c: 3, type: 'general' },
        { id: 'mc',   name: '马超', w: 1, h: 2, r: 3, c: 0, type: 'general' },
        { id: 'hz',   name: '黄忠', w: 1, h: 2, r: 3, c: 3, type: 'general' },
        { id: 'gy',   name: '关羽', w: 2, h: 1, r: 2, c: 1, type: 'general' },
        { id: 's1',   name: '卒', w: 1, h: 1, r: 2, c: 0, type: 'soldier' },
        { id: 's2',   name: '卒', w: 1, h: 1, r: 2, c: 3, type: 'soldier' },
        { id: 's3',   name: '卒', w: 1, h: 1, r: 3, c: 1, type: 'soldier' },
        { id: 's4',   name: '卒', w: 1, h: 1, r: 3, c: 2, type: 'soldier' }
      ]
    },

    /* 围而不歼:两名卒下移至底行中央,两侧留出通行空隙 */
    layers: {
      name: '围而不歼',
      pieces: [
        { id: 'cao',  name: '曹操', w: 2, h: 2, r: 0, c: 1, type: 'cao' },
        { id: 'zf',   name: '张飞', w: 1, h: 2, r: 0, c: 0, type: 'general' },
        { id: 'zy',   name: '赵云', w: 1, h: 2, r: 0, c: 3, type: 'general' },
        { id: 'mc',   name: '马超', w: 1, h: 2, r: 2, c: 0, type: 'general' },
        { id: 'hz',   name: '黄忠', w: 1, h: 2, r: 2, c: 3, type: 'general' },
        { id: 'gy',   name: '关羽', w: 2, h: 1, r: 2, c: 1, type: 'general' },
        { id: 's1',   name: '卒', w: 1, h: 1, r: 3, c: 1, type: 'soldier' },
        { id: 's2',   name: '卒', w: 1, h: 1, r: 3, c: 2, type: 'soldier' },
        { id: 's3',   name: '卒', w: 1, h: 1, r: 4, c: 1, type: 'soldier' },
        { id: 's4',   name: '卒', w: 1, h: 1, r: 4, c: 2, type: 'soldier' }
      ]
    },

    /* 兵临城下:曹操偏居一侧,卒群封锁中路 */
    besiege: {
      name: '兵临城下',
      pieces: [
        { id: 'cao',  name: '曹操', w: 2, h: 2, r: 0, c: 0, type: 'cao' },
        { id: 'zf',   name: '张飞', w: 1, h: 2, r: 0, c: 2, type: 'general' },
        { id: 'zy',   name: '赵云', w: 1, h: 2, r: 0, c: 3, type: 'general' },
        { id: 'mc',   name: '马超', w: 1, h: 2, r: 2, c: 0, type: 'general' },
        { id: 'hz',   name: '黄忠', w: 1, h: 2, r: 2, c: 3, type: 'general' },
        { id: 'gy',   name: '关羽', w: 2, h: 1, r: 2, c: 1, type: 'general' },
        { id: 's1',   name: '卒', w: 1, h: 1, r: 3, c: 1, type: 'soldier' },
        { id: 's2',   name: '卒', w: 1, h: 1, r: 3, c: 2, type: 'soldier' },
        { id: 's3',   name: '卒', w: 1, h: 1, r: 4, c: 1, type: 'soldier' },
        { id: 's4',   name: '卒', w: 1, h: 1, r: 4, c: 2, type: 'soldier' }
      ]
    }
  };

  /* =========================================================
   * 运行时状态
   * ======================================================= */
  let layoutKey = 'classic';
  let pieces = [];              // 当前棋子列表(含 r/c)
  let pieceEls = [];            // 与 pieces 一一对应的 DOM
  let selectedId = null;
  let moves = 0;
  let elapsed = 0;
  let timerId = null;
  let started = false;
  let solved = false;
  let history = [];             // 撤销栈

  const boardEl = document.getElementById('board');
  const statMoves = document.getElementById('statMoves');
  const statBest = document.getElementById('statBest');
  const statPar = document.getElementById('statPar');
  const statTime = document.getElementById('statTime');
  const overlay = document.getElementById('overlay');
  const ovDetail = document.getElementById('ovDetail');
  const ovBtn = document.getElementById('ovBtn');
  const btnUndo = document.getElementById('btnUndo');
  const btnHint = document.getElementById('btnHint');
  const btnReset = document.getElementById('btnReset');

  /* =========================================================
   * 网格占用表:把棋子铺到 5×4 的格子上
   * 0 表示空,其它值为棋子 id 的索引
   * ======================================================= */
  function buildGrid() {
    const grid = new Array(ROWS * COLS).fill(-1);
    for (let i = 0; i < pieces.length; i++) {
      const p = pieces[i];
      for (let dr = 0; dr < p.h; dr++) {
        for (let dc = 0; dc < p.w; dc++) {
          const r = p.r + dr;
          const c = p.c + dc;
          if (r >= 0 && r < ROWS && c >= 0 && c < COLS) {
            grid[r * COLS + c] = i;
          }
        }
      }
    }
    return grid;
  }

  /* =========================================================
   * 移动判定:整体平移 1 格,目标区域必须全部为空
   * ======================================================= */
  function canMove(pieceIndex, dr, dc) {
    const p = pieces[pieceIndex];
    const grid = buildGrid();

    /* 先清掉自己占的格子,否则自己会挡住自己 */
    for (let r = 0; r < p.h; r++) {
      for (let c = 0; c < p.w; c++) {
        grid[(p.r + r) * COLS + (p.c + c)] = -1;
      }
    }

    for (let r = 0; r < p.h; r++) {
      for (let c = 0; c < p.w; c++) {
        const nr = p.r + r + dr;
        const nc = p.c + c + dc;
        if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) return false;
        if (grid[nr * COLS + nc] !== -1) return false;
      }
    }
    return true;
  }

  /* 执行移动 */
  function doMove(pieceIndex, dr, dc, silent) {
    const p = pieces[pieceIndex];
    if (!canMove(pieceIndex, dr, dc)) return false;

    history.push({
      id: p.id,
      r: p.r,
      c: p.c
    });

    p.r += dr;
    p.c += dc;
    moves++;
    statMoves.textContent = moves;
    updateUndoBtn();

    const el = pieceEls[pieceIndex];
    el.style.left = (p.c / COLS * 100) + '%';
    el.style.top = (p.r / ROWS * 100) + '%';

    if (!silent) SFX.slide();

    if (!started) startTimer();
    refreshMovable();
    checkWin();
    return true;
  }

  /* =========================================================
   * 胜利判定:曹操左上角到达底部中央
   * ======================================================= */
  function checkWin() {
    const cao = pieces.find(function (p) { return p.id === 'cao'; });
    if (!cao) return;
    if (cao.r === GOAL_R && cao.c === GOAL_C && !solved) {
      solved = true;
      stopTimer();
      SFX.win();

      /* 脱出动画:向下滑出棋盘 */
      const idx = pieces.indexOf(cao);
      const el = pieceEls[idx];
      el.classList.add('escaping');
      el.style.top = ((ROWS) / ROWS * 100) + '%';

      setTimeout(function () {
        burstConfetti();
        showResult();
      }, 620);
    }
  }

  function showResult() {
    const best = getBest();
    const isNewBest = best === null || moves < best;

    if (isNewBest) saveBest(moves);

    ovDetail.innerHTML =
      '共用 <b>' + moves + '</b> 步 · 耗时 <b>' + fmtTime(elapsed) + '</b>' +
      (isNewBest ? '<br>刷新了该布局的最佳纪录' : '<br>该布局最佳成绩 ' + best + ' 步');
    overlay.classList.add('show');
    statBest.textContent = getBest();
  }

  function burstConfetti() {
    const colors = ['#e8b44a', '#f6d68a', '#5fa88a', '#d97070', '#6d78b8'];
    const rect = boardEl.getBoundingClientRect();
    for (let i = 0; i < 26; i++) {
      const el = document.createElement('div');
      el.className = 'confetti';
      el.style.background = colors[i % colors.length];
      el.style.left = (rect.width / 2) + 'px';
      el.style.top = '40%';
      boardEl.appendChild(el);

      const dx = (Math.random() - 0.5) * rect.width * 1.1;
      const dy = -(Math.random() * rect.height * 0.55 + 40);
      const rot = Math.random() * 720 - 360;

      el.animate(
        [
          { transform: 'translate(0, 0) rotate(0deg)', opacity: 1 },
          { transform: 'translate(' + dx + 'px, ' + dy + 'px) rotate(' + rot + 'deg)', opacity: 0.9, offset: 0.55 },
          { transform: 'translate(' + (dx * 1.25) + 'px, ' + (rect.height * 0.6) + 'px) rotate(' + (rot * 1.6) + 'deg)', opacity: 0 }
        ],
        { duration: 1300 + Math.random() * 500, easing: 'cubic-bezier(0.2, 0.7, 0.4, 1)' }
      ).onfinish = function () { el.remove(); };
    }
  }

  /* =========================================================
   * 提示:找出当前可移动的棋子中"更靠近目标"的一步
   * 采用简单启发式:优先让曹操靠近出口,其次移动挡路的棋子
   * ======================================================= */
  function hintMove() {
    if (solved) return;

    const cao = pieces.find(function (p) { return p.id === 'cao'; });
    const caoIdx = pieces.indexOf(cao);

    /* 1) 曹操能直接朝目标方向移动就优先 */
    const towardR = GOAL_R - cao.r;
    const towardC = GOAL_C - cao.c;
    const dirs = [];
    if (towardR > 0) dirs.push([1, 0]);
    if (towardR < 0) dirs.push([-1, 0]);
    if (towardC > 0) dirs.push([0, 1]);
    if (towardC < 0) dirs.push([0, -1]);

    for (let i = 0; i < dirs.length; i++) {
      if (canMove(caoIdx, dirs[i][0], dirs[i][1])) {
        flashHint(caoIdx);
        return;
      }
    }

    /* 2) 否则找一个能移动、且离曹操较近的棋子 */
    let bestIdx = -1;
    let bestDist = Infinity;
    for (let i = 0; i < pieces.length; i++) {
      if (pieces[i].id === 'cao') continue;
      if (!anyMove(i)) continue;
      const d = Math.abs(pieces[i].r - cao.r) + Math.abs(pieces[i].c - cao.c);
      if (d < bestDist) { bestDist = d; bestIdx = i; }
    }

    if (bestIdx >= 0) flashHint(bestIdx);
    else flashHint(caoIdx);
  }

  function anyMove(index) {
    return canMove(index, 1, 0) || canMove(index, -1, 0) ||
           canMove(index, 0, 1) || canMove(index, 0, -1);
  }

  let hintTimer = null;
  function flashHint(index) {
    const el = pieceEls[index];
    el.classList.add('can-move');
    clearTimeout(hintTimer);
    hintTimer = setTimeout(function () {
      el.classList.remove('can-move');
    }, 2200);
  }

  /* 刷新"可移动"角标 */
  function refreshMovable() {
    for (let i = 0; i < pieces.length; i++) {
      pieceEls[i].classList.toggle('can-move', !solved && anyMove(i));
    }
  }

  /* =========================================================
   * 渲染
   * ======================================================= */
  function createPiecesDOM() {
    /* 清除旧棋子(保留出口标记) */
    pieceEls.forEach(function (el) { el.remove(); });
    pieceEls = [];

    pieces.forEach(function (p, i) {
      const el = document.createElement('div');
      el.className = 'piece ' + p.type;
      el.style.left = (p.c / COLS * 100) + '%';
      el.style.top = (p.r / ROWS * 100) + '%';
      el.style.width = (p.w / COLS * 100) + '%';
      el.style.height = (p.h / ROWS * 100) + '%';

      const inner = document.createElement('div');
      inner.className = 'piece-inner';
      inner.textContent = p.name;
      if (p.w === 2 && p.h === 2) inner.style.fontSize = '21px';
      else if (p.w === 2) inner.style.fontSize = '15px';
      else if (p.h === 2) inner.style.fontSize = '15px';
      else inner.style.fontSize = '15px';

      el.appendChild(inner);
      boardEl.appendChild(el);
      pieceEls.push(el);
    });
  }

  function updatePositions() {
    pieces.forEach(function (p, i) {
      pieceEls[i].style.left = (p.c / COLS * 100) + '%';
      pieceEls[i].style.top = (p.r / ROWS * 100) + '%';
    });
  }

  /* =========================================================
   * 交互:拖拽 + 点击选中 + 键盘
   * ======================================================= */
  let drag = null;

  function attachDrag(index) {
    const el = pieceEls[index];

    el.addEventListener('pointerdown', function (e) {
      if (solved) return;
      e.preventDefault();
      selectPiece(pieces[index].id);

      const rect = boardEl.getBoundingClientRect();
      drag = {
        index: index,
        startX: e.clientX,
        startY: e.clientY,
        cellW: rect.width / COLS,
        cellH: rect.height / ROWS,
        moved: false
      };
      el.classList.add('dragging');
      el.setPointerCapture(e.pointerId);
    });

    el.addEventListener('pointermove', function (e) {
      if (!drag || drag.index !== index) return;

      const dx = e.clientX - drag.startX;
      const dy = e.clientY - drag.startY;

      /* 主轴判断:位移更大的方向优先 */
      if (Math.abs(dx) >= Math.abs(dy)) {
        if (Math.abs(dx) > drag.cellW * 0.42) {
          const dir = dx > 0 ? 1 : -1;
          if (doMove(index, 0, dir, true)) {
            drag.startX += dir * drag.cellW;
            drag.moved = true;
          }
        }
      } else {
        if (Math.abs(dy) > drag.cellH * 0.42) {
          const dir = dy > 0 ? 1 : -1;
          if (doMove(index, dir, 0, true)) {
            drag.startY += dir * drag.cellH;
            drag.moved = true;
          }
        }
      }
    });

    el.addEventListener('pointerup', function (e) {
      if (!drag || drag.index !== index) return;
      el.classList.remove('dragging');
      drag = null;
      refreshMovable();
    });

    el.addEventListener('pointercancel', function () {
      if (el) el.classList.remove('dragging');
      drag = null;
    });
  }

  function selectPiece(id) {
    selectedId = id;
    const idx = pieces.findIndex(function (p) { return p.id === id; });
    pieceEls.forEach(function (el, i) {
      el.classList.toggle('selected', i === idx);
    });
  }

  function moveSelected(dr, dc) {
    if (solved || !selectedId) return;
    const idx = pieces.findIndex(function (p) { return p.id === selectedId; });
    if (idx < 0) return;
    doMove(idx, dr, dc);
  }

  /* =========================================================
   * 计时与最佳成绩
   * ======================================================= */
  function startTimer() {
    started = true;
    stopTimer();
    timerId = setInterval(function () {
      elapsed++;
      statTime.textContent = fmtTime(elapsed);
    }, 1000);
  }

  function stopTimer() {
    if (timerId) { clearInterval(timerId); timerId = null; }
  }

  function fmtTime(s) {
    const m = String(Math.floor(s / 60)).padStart(2, '0');
    const ss = String(s % 60).padStart(2, '0');
    return m + ':' + ss;
  }

  function bestKey() {
    return 'klotski_best_' + layoutKey;
  }

  function getBest() {
    try {
      const v = localStorage.getItem(bestKey());
      return v ? parseInt(v, 10) : null;
    } catch (e) { return null; }
  }

  function saveBest(v) {
    try { localStorage.setItem(bestKey(), String(v)); } catch (e) { /* 忽略 */ }
  }

  /* =========================================================
   * 音效
   * ======================================================= */
  let audioCtx = null;
  function beep(freq, dur, type, vol) {
    try {
      if (!audioCtx) {
        const AC = window.AudioContext || window.webkitAudioContext;
        if (!AC) return;
        audioCtx = new AC();
      }
      if (audioCtx.state === 'suspended') audioCtx.resume();
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      osc.type = type || 'sine';
      osc.frequency.setValueAtTime(freq, audioCtx.currentTime);
      gain.gain.setValueAtTime(0.0001, audioCtx.currentTime);
      gain.gain.exponentialRampToValueAtTime(vol || 0.05, audioCtx.currentTime + 0.01);
      gain.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + dur);
      osc.connect(gain); gain.connect(audioCtx.destination);
      osc.start(); osc.stop(audioCtx.currentTime + dur + 0.02);
    } catch (e) { /* 静默降级 */ }
  }

  const SFX = {
    slide: function () { beep(340, 0.06, 'triangle', 0.04); },
    win:   function () {
      [523, 659, 784, 1047].forEach(function (f, i) {
        setTimeout(function () { beep(f, 0.2, 'sine', 0.06); }, i * 120);
      });
    }
  };

  /* =========================================================
   * 开局 / 重置 / 撤销
   * ======================================================= */
  function loadLayout(key) {
    layoutKey = key;
    const cfg = LAYOUTS[key];

    /* 深拷贝,避免修改布局模板 */
    pieces = cfg.pieces.map(function (p) {
      return { id: p.id, name: p.name, w: p.w, h: p.h, r: p.r, c: p.c, type: p.type };
    });

    moves = 0;
    elapsed = 0;
    started = false;
    solved = false;
    history = [];
    selectedId = null;
    drag = null;

    stopTimer();
    overlay.classList.remove('show');

    statMoves.textContent = '0';
    statTime.textContent = '00:00';
    statPar.textContent = PAR_MOVES[key] || '—';
    statBest.textContent = getBest() === null ? '—' : getBest();

    createPiecesDOM();
    pieceEls.forEach(function (_, i) { attachDrag(i); });
    refreshMovable();
    updateUndoBtn();
  }

  /* 各布局的参考步数(由 BFS 求解器算出的最短步数,按"移动一格算一步"计) */
  const PAR_MOVES = {
    classic: 116,
    command: 100,
    layers: 114,
    besiege: 87
  };

  function undo() {
    if (solved || history.length === 0) return;
    const last = history.pop();
    const idx = pieces.findIndex(function (p) { return p.id === last.id; });
    if (idx < 0) return;

    pieces[idx].r = last.r;
    pieces[idx].c = last.c;
    moves = Math.max(0, moves - 1);
    statMoves.textContent = moves;

    updatePositions();
    refreshMovable();
    updateUndoBtn();
  }

  function updateUndoBtn() {
    btnUndo.disabled = history.length === 0 || solved;
  }

  /* =========================================================
   * 事件绑定
   * ======================================================= */
  document.querySelectorAll('#layoutRow .lay').forEach(function (btn) {
    btn.addEventListener('click', function () {
      const key = btn.getAttribute('data-layout');
      if (key === layoutKey) return;
      document.querySelectorAll('#layoutRow .lay').forEach(function (b) {
        b.classList.toggle('active', b === btn);
      });
      loadLayout(key);
    });
  });

  btnUndo.addEventListener('click', undo);
  btnHint.addEventListener('click', hintMove);
  btnReset.addEventListener('click', function () { loadLayout(layoutKey); });
  ovBtn.addEventListener('click', function () { loadLayout(layoutKey); });

  window.addEventListener('keydown', function (e) {
    const map = {
      arrowup: [-1, 0], arrowdown: [1, 0],
      arrowleft: [0, -1], arrowright: [0, 1],
      w: [-1, 0], s: [1, 0], a: [0, -1], d: [0, 1]
    };
    const k = e.key.toLowerCase();
    if (map[k]) {
      e.preventDefault();
      moveSelected(map[k][0], map[k][1]);
    } else if (k === 'z') {
      undo();
    } else if (k === 'r') {
      loadLayout(layoutKey);
    }
  });

  /* =========================================================
   * 启动
   * ======================================================= */
  loadLayout('classic');
})();
</script>
</body>
</html>

六、基于华为云 DevKit 临时沙箱的部署与分享

华容道是纯前端应用——布局数据、移动判定、动画全部在浏览器里完成,没有后端依赖。这种形态用临时沙箱分享最划算。

6.1 连接沙箱

hcloud DevKit sandbox-connect

成功后会返回工作区标识。容量暂不可用时稍等重试即可。

6.2 上传单文件

hcloud DevKit sandbox-upload-file \
  --local-path="./klotski/index.html" \
  --remote-path="/workspace/klotski/index.html"

整个项目就一个文件,几秒钟传完,也不存在"漏传资源导致 404"的问题。

6.3 用 Nginx 托管

hcloud DevKit sandbox-deploy-nginx \
  --project="klotski" \
  --output_dir="." \
  --nginx_type="spa" \
  --port=8092

命令会自动生成独立的 conf.d 配置、修正目录权限、nginx -t 校验后热重载。端口选 8092 是为了避开常被占用的 8080/8081。

6.4 暴露公网隧道

hcloud DevKit sandbox-expose-tunnel --port=8092 --expiry_hours=72

返回形如 https://sandbox-8092.devbridge-s2.hwtunnel.com 的地址。

6.5 验证清单

检查项 命令 期望
Nginx 配置合法 nginx -t syntax is ok
本地端口可访问 curl -sI http://127.0.0.1:8092 HTTP/1.1 200 OK
公网隧道通畅 curl -sI https://sandbox-8092.devbridge-s2.hwtunnel.com HTTP/1.1 200 OK
手机端实测 扫码或直接访问 棋子可拖动、曹操能移动、布局切换正常

需要说明的是:隧道有效期与沙箱实例的生命周期是两件事。临时沙箱在长时间空闲后会被回收,届时即使隧道仍在有效期内,地址也会因为后端无响应而打不开。因此这个地址适合一两天的评审或演示;若要长期公开,应把静态文件迁到对象存储的静态网站托管或正式服务器。


七、可持续迭代的方向

方向一:把 BFS 求解器搬进页面,做"一键演示解法"

现在求解器只在构建阶段用来验证布局。其实它可以成为一个很棒的功能:点"看解法"按钮,让程序演示最优走法,一步一步动画播放出来。

需要注意两点:

  1. BFS 在浏览器里有代价:单次求解约 2.4 万状态、几百毫秒,会阻塞主线程。建议放到 Web Worker 里跑,或者每次只算一步(用迭代加深,每次只找"下一步该走哪个方向");
  2. 求解结果要缓存:同一布局的最短路径是固定的,第一次算完可以存进 localStorage,之后直接播放。

有了这个功能,"参考步数"就不再是写死的常量,而是实时算出来的。

方向二:手势与操作手感打磨

当前的拖拽是"超过 0.42 格触发一次移动"。可以进一步优化:

  • 实时跟手预览:拖动过程中让棋子跟随手指偏移(但仍限制在合法方向),松手时吸附到最近的合法格;
  • 移动轨迹提示:拖动某个棋子时,把它可滑动的空格用半透明轮廓标出来,新玩家会更容易理解"空格是通道"这个核心机制;
  • 长按查看该棋子的活动范围。

这些改动都在视图层,不涉及状态逻辑。

方向三:加入"步数评级"与本地排行榜

有了 BFS 给出的最优步数 PAR,就可以给成绩分档:

评级 条件
完美 步数 = PAR
优秀 步数 ≤ PAR × 1.15
合格 步数 ≤ PAR × 1.5
待提高 超过 PAR × 1.5

配合 localStorage 保存每个布局的最佳记录,通关结算页就能显示"该布局最佳 128 步 / 最优 116 步",让玩家知道还有多少提升空间。

方向四:接入华为云服务,做自定义布局分享

华容道玩家群体里有一类需求:自己设计布局,然后分享给别人挑战。可以这样实现:

  1. 华为云对象存储 OBS:把布局 JSON(棋子坐标数组)以短 ID 为键存成对象,天然支持匿名只读分享;
  2. 华为云函数工作流 FunctionGraph:提供一个"提交布局"接口,函数端先跑一遍 BFS,确认可解且有解,再落库——不可解的布局直接拒绝。

这正好把本文第五节的经验固化成了服务端校验:让人工设计的关卡也必须通过机器验证才能上线。


八、总结

层次 关键点
数据建模 4×5 网格 + 矩形棋子(w/h/r/c 四元组),空格是唯一的移动资源
移动判定 先把"自己"从占用表里清空,再检查目标区域;越界检查必须显式写出
状态编码 同形状棋子(卒、竖将)排序后规范化,把状态数压缩约一个数量级
最短解 BFS 按层扩展,首次到达目标即最短;数组 + 指针模拟队列避免 shift() 开销
交互 位移阈值 0.42 格触发移动,成功后重置基准点实现连续拖拽
质量保障 每个自定义布局都必须过一遍求解器,否则可能做出"一步都走不了"的死局

华容道最有趣的地方在于:它的规则简单到一句话就能说完,但"能不能解"这件事却需要穷举两万多个状态才能确定。人工设计一个布局,凭直觉往往判断不出它是否有解——这也是为什么我把求解器从"开发工具"提升到了"上线前的必要检查"。先验证,再呈现,这个习惯比代码本身更值得带走。

【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0)

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。