feat(levels): D5 three-rotation prototype

The shipped 1000 levels have a hole: 568 of them need no rotation at all, and
none needs more than two — the mechanic the game is built on is mostly
decoration. This fills the empty band with levels that need at least three.

createDeepLock builds a four-piece chain where each link only releases at a
later orientation, and growDeepLevel packs the rest of the board around it
without opening a shortcut. Candidate pools are built per orientation and left
untruncated; ranking by bend count first starved the packer and capped levels
at four to six pieces instead of twelve.

deadTurnAudit enumerates every reachable (orientation, remaining-set) state to
prove no dead ends exist, and counts how long a player can be left with
nothing to do — solvable and feeling solvable are different things, which is
what "level 2 is impossible" turned out to be about.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
cabinw
2026-09-14 14:00:33 +08:00
co-authored by Claude Opus 5
parent f3e91e3597
commit 643cba0ed9
8 changed files with 27443 additions and 0 deletions
+40
View File
@@ -0,0 +1,40 @@
# D5 · 三转链式锁构造原型
目的:验证在现行规则(消除单调、旋转免费可逆)下,能否稳定构造出**最少需要三次旋转**、且**开局大部分棋子被锁住**的关卡。这是 v0.6 难度曲线里 D5 档的内容来源;v0.5 千关里该档为 0,`createStageSeed` 只能产出两转锁。
打开:`npm run dev` 后访问 `/labs/d5/index.html`。只读 `levels/prototypes/d5.json`,不写入主线存档。
## 构造方法
`src/deep-lock.js`
1. **`createDeepLock(base)`** — 四子链式锁 A/B/C/D。朝向 0 全部被锁;+1 只有 B 能走;+2(B 走后)只有 C 能走,A 与 D 互锁;转回 +1 放 A,再放 D。网格路线只用来提议,每一阶段都用主游戏的扫掠碰撞 `trace()` 逐条认证,最后由 `solveRotations()` 证明不存在一转或两转的清盘方案。
2. **`growDeepLevel(base, lock, { target, layerShares })`** — 反向插入更多棋子,按朝向 0 / 1 / 2 分层配额;优先选「在更早的朝向都被挡」的棋子,使它们真正等旋转;每插一枚重新求解,最少旋转数跌破 3 即拒绝。
3. **`deepLevelStats(level)`** — 锁住占比(首转时剩余)、每次旋转释放数、首转是否只有一侧能开路、波次。
## 一次扫描的产出(6 形态 × r3/r4 × 8 种子)
```
找到锁 55/96 · 长成 R≥3 关 55 · 旋转次数 {3:47, 4:1, 5:7}
锁住占比中位 78%(v0.5 现状 22%)· 每转释放 ≥2 枚 38/55 · 首转单向 9/55
随机玩家 动作÷棋子 中位 7.5(v0.5 全库 1.67,v0.4 手作 3.42)
switchback r3、crossing r3 产出 0:小盘上这两种形态找不到满足四子约束的候选
```
重新生成:`node scripts/prototype-d5.mjs --seeds=8 --keep=18`(`--radii=3,4,5` 可含 91 格;默认不含)。
## 「无解」问题与可玩性门槛
第一批里的第 02 关(orbits r3 s3)被试玩者判为无解。穷举全部 324 个可达状态:0 个死局,参考解在真实界面里也能清盘。问题出在体感:**开局 100% 锁死 + 首转只有右边有效 + 最后一步要转回来**。先往左转的人连看 3 个空朝向,右右之后继续右转的人连看 4 个——两条路都读作"无解"。
对策分两层,都已落地:
1. **结构门槛**(`scripts/prototype-d5.mjs`):`deadTurnAudit()` 穷举玩家可达的全部状态(任意点击顺序、任意旋转序列),证明没有死局,并统计「双向死转态」(卡住时左右各转一次都打不开的状态数)与「最长盲转」。入选关必须:首转两侧都能开路、开局锁住 ≤90%、无不可解可达态;按双向死转态升序排。现在前 4 关这两项都是 0,随机玩家动作÷棋子回到 3.6–6.5。
2. **反馈**(`labs/d5/app.js`):卡住后闲置 3 秒,正确的旋转按钮开始脉冲并提示方向——即 §07 第 1 条的做法,方向永远不即时给出。任何输入都会清掉提示。
## 尚未解决
- 随机玩家的动作数仍高于手作版(v0.4 为 3.42);D5 放在第 501 关后是否合适,要真人试玩。
- 现在的参考解是求解器给出的最短解,不是作者解;正式接入生产时应保留作者见证(同 `createStageSeed`)。
- 「首转释放 ≥2 枚」只在扫描时排序,未在生长时强制。
- 「双向死转态 = 0」目前只是排序偏好,不是硬门槛;D5 后段若需要单向关,应配合闲置提示一起上线,不能单独放。
+159
View File
@@ -0,0 +1,159 @@
import { Game, available, trace, solveRotations } from '../../src/core.js';
import { TapQueue } from '../../src/tap-queue.js';
import { layout, hitCell } from '../../src/geometry.js';
import { CanvasPainter, drawScene } from '../../src/renderer.js';
import { TILE_ATLAS } from '../../src/sprites.js';
import { exitTiming } from '../../src/exit-animation.js';
import { MOTION } from '../../src/design-tokens.js';
import { unlockAudio, playSound } from '../../src/audio.js';
const $ = id => document.getElementById(id);
const canvas = $('board'), context = canvas.getContext('2d'), painter = new CanvasPainter(context);
const taps = new TapQueue();
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
let levels = [], current = null, game = null, view, width, height, animation = null, turning = null, hint = null, path = null, frame = 0;
const pct = value => `${Math.round(value * 100)}%`;
function describeWitness(actions, tiles) {
// Compress the solver reference into "+1 · 3 枚 · +1 · 2 枚 · −1 · 4 枚".
const parts = []; let taps = 0;
for (const action of actions) {
if (action.type === 'rotate') { if (taps) parts.push(`${taps} 枚`); taps = 0; parts.push(action.direction === 1 ? '右转' : '左转'); }
else taps++;
}
if (taps) parts.push(`${taps} 枚`);
return `参考解:${parts.join(' · ')}(共 ${tiles.length} 枚)`;
}
function showEvidence() {
const p = current.prototype, s = p.stats;
const rows = [
['底盘 / 棋子', `${current.cells.length} 格 · ${s.pieces} 枚 · ${p.family} r${p.radius} · seed ${p.seed}`],
['最少旋转', `${s.rotations} 次`],
['开局被锁住', `${s.lockedAtStart} / ${s.pieces} 枚(${pct(s.lockedShare)})`],
['每次旋转释放', s.releasePerTurn.join(' / ') + ' 枚'],
['首转方向', s.firstTurnDirections === 1 ? '只有一侧能开路' : '两侧都能开路'],
['主角路线', `${p.lock.heroBends} 弯`],
['随机玩家 动作 ÷ 棋子', p.monkeyActionsPerPiece.toFixed(2) + '(v0.5 全库 1.67)'],
];
$('evidence').innerHTML = rows.map(([k, v]) => `<div><dt>${k}</dt><dd>${v}</dd></div>`).join('');
$('witness').textContent = describeWitness(current.experience.actions, current.tiles);
}
// Stuck-state idle hint: when nothing can leave, wait, then point at the turn
// that opens something. This is the §07 rule — the direction is never shown
// instantly, so "which way" stays the player's move first.
let idleTimer = null;
function clearIdleHint() { clearTimeout(idleTimer); idleTimer = null; for (const id of ['left', 'right']) $(id).classList.remove('hinted'); }
function scheduleIdleHint() {
clearIdleHint();
if (!game || game.won || animation || turning || available(game.level, game.tiles).length) return;
idleTimer = setTimeout(() => {
const action = solveRotations({ ...game.level, tiles: game.tiles, moveLimit: game.moves }).actions[0];
if (!action || action.type !== 'rotate') return;
$(action.direction === 1 ? 'right' : 'left').classList.add('hinted');
$('message').textContent = `这个朝向没有出口。试试向${action.direction === 1 ? '右' : '左'}转。`;
}, 3000);
}
function stats() {
const busy = !!(animation || turning);
if (!busy) scheduleIdleHint();
$('remaining').textContent = game.tiles.length;
$('progress').textContent = game.won ? '清盘 · 三转到位' : `已放行 ${current.tiles.length - game.tiles.length} / ${current.tiles.length} · 旋转 ${game.rotations}${taps.ids.length ? ` · 待出发 ${taps.ids.length}` : ''}`;
for (const id of ['left', 'right', 'hint']) $(id).disabled = busy || game.won;
$('undo').disabled = busy || !game.history.length;
if (game.won && !busy) $('message').textContent = `清盘。用了 ${game.rotations} 次旋转,参考解 ${current.prototype.stats.rotations} 次。`;
}
function draw(now = performance.now()) {
cancelAnimationFrame(frame);
if (!view || !game) return;
context.clearRect(0, 0, width, height);
const state = { hint, path, reduced, queued: taps.ids };
if (animation) {
const progress = Math.min(1, (now - animation.start) / animation.duration);
state.animation = { route: animation.route, progress };
if (progress >= 1) animation = null;
}
if (turning) {
const progress = Math.min(1, (now - turning.start) / turning.duration);
state.boardAngle = -turning.direction * Math.PI / 3 * Math.pow(1 - progress, 3);
if (progress >= 1) turning = null;
}
drawScene(painter, game.level, game.tiles, view, state);
if (!animation && !turning) {
const next = taps.take(game.tiles);
if (next) { tap(next); return; }
}
stats();
if (animation || turning) frame = requestAnimationFrame(draw);
}
function resize() {
if (!game) return;
const rect = canvas.getBoundingClientRect(), dpr = Math.min(devicePixelRatio || 1, 3);
width = rect.width; height = rect.height;
canvas.width = Math.round(width * dpr); canvas.height = Math.round(height * dpr);
context.setTransform(dpr, 0, 0, dpr, 0, 0);
view = layout(game.level.cells, width, height); draw();
}
function clearEffects() { taps.clear(); cancelAnimationFrame(frame); animation = null; turning = null; hint = null; path = null; clearIdleHint(); }
canvas.addEventListener('pointerdown', clearIdleHint, { passive: true });
for (const id of ['left', 'right', 'undo', 'reset', 'hint']) $(id).addEventListener('pointerdown', clearIdleHint, { passive: true });
function load(index) {
current = levels[index]; clearEffects(); game = new Game(current);
const free = available(game.level, game.tiles).length;
$('message').textContent = free ? `开局有 ${free} 枚能走,其余都在等旋转。` : '开局没有任何棋子能走。转一下,看哪一层松开了。';
$('meta').textContent = `${current.cells.length} 格 · ${current.tiles.length} 枚 · 最少 ${current.prototype.stats.rotations} 转`;
showEvidence(); resize();
}
function tap(tile) {
if (game.won) return;
if (animation || turning) { if (taps.add(tile.id, animation?.route.tile.id)) draw(); return; }
hint = null; path = null;
const before = new Set(available(game.level, game.tiles).map(t => t.id));
const result = game.tap(tile.id);
if (result.status === 'exit') {
animation = { route: result, start: performance.now(), duration: reduced ? 100 : exitTiming(result).duration };
const opened = available(game.level, game.tiles).filter(t => !before.has(t.id)).length;
$('message').textContent = opened ? `移开这一枚,${opened} 枚棋子的路通了。` : result.steps.length > 3 ? '沿着轨道绕出去了。' : '出去了。';
playSound('exit');
} else {
taps.clear();
if (result.travelPoints) animation = { route: result, start: performance.now(), duration: reduced ? 150 : MOTION.collisionMs };
$('message').textContent = result.status === 'loop' ? '这条路线绕回原处。转一下底盘换条路。' : '前方有棋子挡住。它在等另一个朝向。';
playSound('hit');
}
draw();
}
function rotate(direction) {
if (animation || turning || game.won) return;
taps.clear();
const before = new Set(available(game.level, game.tiles).map(t => t.id));
game.rotate(direction); hint = null; path = null;
const opened = available(game.level, game.tiles).filter(t => !before.has(t.id)).length;
turning = { direction, start: performance.now(), duration: reduced ? 100 : MOTION.rotationMs };
$('message').textContent = opened ? `这一转松开了 ${opened} 枚。` : '这个朝向什么都没松开。再转,或转回去。';
playSound('rotate'); draw();
}
canvas.addEventListener('pointerup', event => {
const rect = canvas.getBoundingClientRect(), cell = hitCell(game.level.cells, view, event.clientX - rect.left, event.clientY - rect.top);
const tile = cell && game.tiles.find(t => t.q === cell.q && t.r === cell.r);
if (tile) tap(tile);
});
$('left').onclick = () => rotate(-1);
$('right').onclick = () => rotate(1);
$('undo').onclick = () => { if (!animation && !turning && game.undo()) { clearEffects(); $('message').textContent = '回到上一步。'; draw(); } };
$('reset').onclick = () => load(Number($('level').value));
$('hint').onclick = () => {
const action = solveRotations({ ...game.level, tiles: game.tiles, moveLimit: game.moves }).actions[0];
if (!action) return;
if (action.type === 'rotate') { $('message').textContent = `向${action.direction === 1 ? '右' : '左'}转一次。`; }
else { hint = action.id; path = trace(game.level, game.tiles.find(t => t.id === hint), game.tiles); $('message').textContent = '这一枚现在可以走。'; }
draw();
};
$('level').onchange = () => load(Number($('level').value));
document.addEventListener('pointerdown', unlockAudio, { passive: true });
const atlas = new Image(); atlas.onload = () => { painter.atlas = atlas; draw(); }; atlas.src = '../../' + TILE_ATLAS;
new ResizeObserver(resize).observe(canvas);
const response = await fetch('../../levels/prototypes/d5.json');
levels = (await response.json()).levels;
$('level').innerHTML = levels.map((level, i) => `<option value="${i}">${String(i + 1).padStart(2, '0')} · ${level.prototype.family} r${level.prototype.radius} · ${level.tiles.length} 枚 · 锁住 ${pct(level.prototype.stats.lockedShare)} · 释放 ${level.prototype.stats.releasePerTurn.join('/')}</option>`).join('');
load(0);
+46
View File
@@ -0,0 +1,46 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>三转锁 · D5 构造原型</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main>
<header>
<a class="back" href="../../">← 返回主线</a>
<span class="badge">D5 · 三转链式锁 · 原型</span>
</header>
<section class="intro">
<p class="eyebrow">THREE TURNS TO CLEAR</p>
<h1>三转锁 <small>深旋转</small></h1>
<p>开局几乎全锁。转一次放一层,转两次放一层,转回来放主角。</p>
</section>
<div class="picker">
<label for="level">关卡</label>
<select id="level" aria-label="选择原型关卡"></select>
<span class="meta" id="meta"></span>
</div>
<div class="status"><span>待离场 <strong id="remaining">0</strong></span><span id="progress">已放行 0 / 0 · 旋转 0</span></div>
<div class="board-wrap"><canvas id="board" aria-label="三转锁原型棋盘,点击箭头棋子离场"></canvas></div>
<p class="message" id="message" role="status">先找找有没有能直接走的棋子——多半没有。转一下。</p>
<nav class="controls" aria-label="棋盘操作">
<button id="left" type="button">↶ <span>左转</span></button>
<button id="undo" type="button">↩ <span>撤销</span></button>
<button id="hint" type="button">✧ <span>提示</span></button>
<button id="reset" type="button">↻ <span>重来</span></button>
<button id="right" type="button">↷ <span>右转</span></button>
</nav>
<section class="evidence">
<h2>结构证据</h2>
<dl id="evidence"></dl>
<p class="witness" id="witness"></p>
</section>
<footer>
<p>数据来自 <code>levels/prototypes/d5.json</code>,由 <code>scripts/prototype-d5.mjs</code> 生成;规则、碰撞与求解与主游戏共用。此页只用于验证构造,不写入主线存档。</p>
</footer>
</main>
<script type="module" src="./app.js"></script>
</body>
</html>
+41
View File
@@ -0,0 +1,41 @@
:root{font-family:system-ui,-apple-system,"PingFang SC",sans-serif;color:#33414d;background:#e9edf0;font-synthesis:none}
*{box-sizing:border-box}
body{margin:0}
main{max-width:900px;margin:auto;padding:16px 28px 24px}
header{display:flex;align-items:center;justify-content:space-between;gap:12px}
.back{color:#526575;text-decoration:none;font-size:13px}
.badge{font-size:11px;letter-spacing:.08em;color:#4d6478;border:1px solid #b9c7d2;border-radius:20px;padding:7px 12px}
.intro{text-align:center;margin:10px 0 12px}
.eyebrow{font-size:10px;letter-spacing:.24em;color:#6b7f90}
h1{font-size:28px;letter-spacing:.15em;margin:7px 0 10px;font-weight:650}
h1 small{font-size:13px;letter-spacing:.1em;font-weight:500;vertical-align:middle;border-left:1px solid #b9c7d2;margin-left:5px;padding-left:12px;color:#6b7f90}
.intro>p:last-child{font-size:13px;margin:0;color:#65717b}
.picker{display:flex;align-items:center;justify-content:center;gap:10px;flex-wrap:wrap;margin:6px auto 10px;font-size:12px;color:#526575}
.picker select{font:13px system-ui;padding:7px 10px;border:1px solid #b9c7d2;border-radius:10px;background:#fff;color:#33414d;max-width:100%}
.picker .meta{font-variant-numeric:tabular-nums;color:#6b7f90}
.status{display:flex;align-items:center;justify-content:space-between;gap:12px;max-width:620px;margin:auto;font-size:12px;color:#65717b}
.status strong{font-size:24px;color:#33414d;margin-left:6px}
#progress{font-size:11px;font-variant-numeric:tabular-nums}
.board-wrap{width:100%;height:clamp(400px,calc(100svh - 360px),700px);min-height:380px}
canvas{width:100%;height:100%;display:block;touch-action:manipulation}
.message{margin:4px 0 16px;text-align:center;font-size:13px;min-height:36px;line-height:1.6}
.controls{display:flex;justify-content:center;gap:14px}
button{font:24px system-ui;color:#526575;background:#f9fbfc;border:1px solid #cfd9e1;border-radius:18px;min-width:74px;min-height:66px;padding:6px 12px;cursor:pointer;box-shadow:0 3px 0 #c5d1da}
button span{display:block;font-size:11px}
button:hover{background:#fff}
button:active{transform:translateY(2px);box-shadow:0 1px 0 #c5d1da}
button:disabled{opacity:.4;cursor:default}
button.hinted{border-color:#5b7a94;box-shadow:0 3px 0 #5b7a94,0 0 0 4px rgba(91,122,148,.25);animation:hint-pulse .7s ease-in-out infinite alternate}
@keyframes hint-pulse{from{transform:translateY(0)}to{transform:translateY(-4px)}}
button:focus-visible,a:focus-visible,select:focus-visible{outline:3px solid #5b7a94;outline-offset:4px}
.evidence{max-width:620px;margin:22px auto 0;border-top:1px solid #cfd9e1;padding-top:14px}
.evidence h2{font-size:11px;letter-spacing:.18em;color:#6b7f90;margin:0 0 10px;font-weight:600}
.evidence dl{display:grid;grid-template-columns:1fr 1fr;gap:8px 18px;margin:0;font-size:12.5px}
.evidence dl>div{display:flex;justify-content:space-between;gap:10px;border-bottom:1px dashed #d8e0e6;padding-bottom:6px}
.evidence dt{color:#6b7f90}
.evidence dd{margin:0;font-variant-numeric:tabular-nums;text-align:right;color:#33414d}
.witness{margin:12px 0 0;font-size:12px;color:#526575;font-variant-numeric:tabular-nums;text-align:center}
footer{text-align:center;margin:18px auto 0;max-width:560px;font-size:11px;color:#6b757e;line-height:1.7}
footer code{font-family:ui-monospace,Menlo,monospace;font-size:10.5px;background:#dfe6ec;padding:1px 4px;border-radius:3px}
@media(max-width:540px){main{padding:16px 14px 20px}.board-wrap{height:380px;min-height:0}.controls{gap:9px}button{min-width:57px;min-height:60px;padding:5px 9px}.message{font-size:12px;margin-bottom:12px}.evidence dl{grid-template-columns:1fr}}
@media(prefers-reduced-motion:reduce){button:active{transform:none}}
File diff suppressed because it is too large Load Diff
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env node
// D5 (three-turn) construction prototype. Sweeps route families and seeds,
// grows each chain lock into a full level, and writes a small playable set.
// Usage: node scripts/prototype-d5.mjs [--seeds=8] [--target=12] [--keep=18] [--out=levels/prototypes/d5.json]
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { Game, random } from '../src/core.js';
import { createRouteBoard, ROUTE_FAMILIES } from '../src/route-grammar.js';
import { createDeepLock, growDeepLevel, deepLevelStats, deepLevelKey, deadTurnAudit } from '../src/deep-lock.js';
const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));
const SEEDS = Number(args.seeds ?? 8), TARGET = Number(args.target ?? 12), KEEP = Number(args.keep ?? 18);
const OUT = resolve(args.out ?? 'levels/prototypes/d5.json');
// 91-cell boards stay out by default: they are a readability problem, not a difficulty band.
const RADII = String(args.radii ?? '3,4').split(',').map(Number);
const MIN_PIECES = Number(args.minPieces ?? 8);
// Random player: taps a random piece; after three blocked taps in a row, turns randomly.
function monkeyActionsPerPiece(level, runs = 8) {
let total = 0;
for (let run = 0; run < runs; run++) {
const rng = random(4242 + run * 31), game = new Game(level);
let actions = 0, streak = 0;
while (!game.won && !game.lost && actions < 800) {
if (streak >= 3) { game.rotate(rng() < .5 ? 1 : -1); actions++; streak = 0; continue; }
const tile = game.tiles[Math.floor(rng() * game.tiles.length)];
const result = game.tap(tile.id); actions++;
if (result.status === 'exit') streak = 0; else streak++;
}
total += game.won ? actions / level.tiles.length : 999;
}
return total / runs;
}
const started = Date.now();
const rows = [], seen = new Set();
const yieldTable = {};
for (const { id: family } of ROUTE_FAMILIES) for (const radius of RADII) {
const cellKey = `${family}/r${radius}`;
yieldTable[cellKey] = { locks: 0, grown: 0, seeds: SEEDS };
for (let seed = 0; seed < SEEDS; seed++) {
const base = createRouteBoard(seed, { family, radius });
const lock = createDeepLock(base, { seed, maxChecks: 600000 });
if (!lock) continue;
yieldTable[cellKey].locks++;
const target = Math.min(TARGET, { 3: 9, 4: 12, 5: 14 }[radius]);
const grown = growDeepLevel(base, lock, { seed, target });
const level = grown.level;
if (grown.solution.rotations < 3) continue;
const signature = deepLevelKey(level);
if (seen.has(signature)) continue;
seen.add(signature);
yieldTable[cellKey].grown++;
const stats = deepLevelStats(level);
const audit = deadTurnAudit(level);
const apt = monkeyActionsPerPiece(level);
level.id = `proto-d5-${family}-r${radius}-s${seed}`;
level.prototype = { family, radius, seed, target, lock: { hero: lock.hero.id, heroBends: lock.heroRoute.bends, search: lock.search }, placements: grown.placements, rejected: grown.rejected, stats, audit, monkeyActionsPerPiece: apt };
rows.push({ level, stats, audit, apt, family, radius, seed });
}
}
// A bare four-piece lock is 100% locked by definition; only fully grown levels
// count. The playable set also refuses what reads as "unsolvable": a fully
// locked opening, a first turn that only works one way, or any stuck state
// where neither adjacent orientation opens anything.
const grownEnough = rows.filter(r => r.stats.pieces >= MIN_PIECES);
const playable = grownEnough.filter(r => r.audit.unsolvable === 0 && r.stats.firstTurnDirections === 2 && r.stats.lockedShare <= .9);
playable.sort((a, b) => (a.audit.doubleDead - b.audit.doubleDead) || (b.stats.minRelease - a.stats.minRelease) || (b.stats.lockedShare - a.stats.lockedShare) || (a.apt - b.apt));
console.log(`\n【可玩性门槛】长成 ${grownEnough.length} 关 → 首转双向 ${grownEnough.filter(r => r.stats.firstTurnDirections === 2).length} → 开局锁住 ≤90% ${grownEnough.filter(r => r.stats.firstTurnDirections === 2 && r.stats.lockedShare <= .9).length} → 无不可解可达态 ${playable.length}`);
const kept = [];
const perFamily = {};
for (const row of playable) {
perFamily[row.family] = (perFamily[row.family] || 0);
if (perFamily[row.family] >= Math.ceil(KEEP / ROUTE_FAMILIES.length) + 1) continue;
perFamily[row.family]++;
kept.push(row);
if (kept.length >= KEEP) break;
}
const pad = (v, w) => String(v).padStart(w);
console.log(`D5 三转构造原型 · ${ROUTE_FAMILIES.length} 形态 × ${RADII.length} 尺寸 × ${SEEDS} 种子 · ${((Date.now() - started) / 1000).toFixed(1)} s`);
console.log('\n【产出率】形态/尺寸 找到锁 长成 R=3 关');
for (const [k, v] of Object.entries(yieldTable)) console.log(' ' + k.padEnd(18) + pad(v.locks, 5) + '/' + v.seeds + pad(v.grown, 9) + '/' + v.seeds);
const all = rows.map(r => r.stats);
const med = arr => { const s = [...arr].sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : NaN; };
console.log(`\n【全部 ${rows.length} 个 R≥3 关卡】`);
console.log(` 旋转次数分布: ${JSON.stringify(all.reduce((m, s) => (m[s.rotations] = (m[s.rotations] || 0) + 1, m), {}))}`);
console.log(` 锁住占比(首转时剩余)中位 ${(med(all.map(s => s.lockedShare)) * 100).toFixed(0)}% (v0.5 现状中位 22%)`);
console.log(` 每次旋转最少释放 ≥2 枚的关: ${all.filter(s => s.minRelease >= 2).length}/${all.length}`);
console.log(` 首转只有一侧能开路的关: ${all.filter(s => s.firstTurnDirections === 1).length}/${all.length}`);
console.log(` 猴子 动作/棋子 中位 ${med(rows.map(r => r.apt)).toFixed(2)} (v0.5 全库 1.67 · v0.4 手作 3.42)`);
console.log(`\n【写入 ${kept.length} 关】`);
console.log(' id 格 枚 R 锁住% 每转释放 首转方向 双向死转态 最长盲转 猴子APT hero弯');
for (const { level, stats, audit, apt } of kept) console.log(' ' + level.id.padEnd(36) + pad(level.cells.length, 3) + pad(stats.pieces, 4) + pad(stats.rotations, 3) + pad((stats.lockedShare * 100).toFixed(0) + '%', 7) + ' ' + stats.releasePerTurn.join('/').padEnd(12) + pad(stats.firstTurnDirections === 1 ? '单向' : '双向', 6) + pad(audit.doubleDead, 10) + pad(audit.maxDeadTurns, 9) + pad(apt.toFixed(2), 9) + pad(level.prototype.lock.heroBends, 7));
console.log('\n 「双向死转态」= 可达的卡住状态里,左右各转一次都打不开任何棋子的状态数;「最长盲转」= 从某个可达卡住态朝错误方向连转、遇到第一个有效朝向前经过的空朝向数。');
mkdirSync(dirname(OUT), { recursive: true });
writeFileSync(OUT, JSON.stringify({ generated: 'prototype-d5', version: 1, options: { seeds: SEEDS, target: TARGET, radii: RADII }, summary: { candidates: rows.length, kept: kept.length, yieldTable }, levels: kept.map(r => r.level) }, null, 1));
console.log(`\n已写入 ${OUT}`);
+213
View File
@@ -0,0 +1,213 @@
import { available, key, opposite, random, rotateBoard, solveRotations, trace, validateLevel } from './core.js';
const positionKey = tile => `${tile.q},${tile.r}`;
const countBends = route => route.steps.filter(step => step.enter !== null && opposite(step.enter) !== step.exit).length;
function shuffled(items, rng) {
const result = [...items];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
// Every candidate carries its independent route at orientations 0, 1 and 2.
// Grid membership only proposes a lock; the swept tracer certifies it below.
function candidatePool(base, boards, maxBends) {
const pool = [];
for (const cell of base.cells) for (let dir = 0; dir < 6; dir++) {
const tile = { q: cell.q, r: cell.r, dir };
const routes = [0, 1, 2].map(turn => trace(boards[turn], tile, [], true));
if (routes.some(route => route.status !== 'exit')) continue;
const bends = routes.map(countBends);
if (bends[1] > maxBends) continue;
pool.push({
tile, position: positionKey(tile), bends, cells: routes.map(route => route.steps.length),
at: routes.map(route => new Set(route.steps.slice(1).map(positionKey))),
});
}
return pool;
}
// A/B/C/D is a three-turn chain, not three independent long routes.
// At 0 all four are locked. At +1 only B can leave. At +2 only C can leave;
// A and D still hold each other. Turning back to +1 frees A, then D.
// The solver certifies that no one- or two-turn plan clears the board.
export function createDeepLock(base, {
seed = 0, minHeroBends = 6, maxHeroBends = 70, maxChecks = 2000000,
} = {}) {
const rng = random(seed);
const boards = [0, 1, 2].map(turn => rotateBoard(base, turn));
const pool = candidatePool(base, boards, maxHeroBends);
const candidates = shuffled(pool, rng);
const heroes = candidates.filter(c => c.bends[1] >= minHeroBends);
let checks = 0, formalChecks = 0;
for (const a of heroes) {
// D holds A at 0 and at +2, and never stands on A's +1 departure.
const tails = candidates.filter(d => d.position !== a.position
&& a.at[0].has(d.position) && d.at[0].has(a.position)
&& a.at[2].has(d.position) && d.at[2].has(a.position)
&& !a.at[1].has(d.position));
for (const d of tails) {
// C holds A at +1 and leaves alone at +2 once B is gone.
const seconds = candidates.filter(c => c.position !== a.position && c.position !== d.position
&& a.at[1].has(c.position) && !c.at[2].has(a.position) && !c.at[2].has(d.position));
for (const c of seconds) {
// B is A's blocker at 0 and is the only piece that leaves at +1.
const gates = candidates.filter(b => b.position !== a.position && b.position !== c.position && b.position !== d.position
&& a.at[0].has(b.position) && !b.at[1].has(a.position) && !b.at[1].has(c.position) && !b.at[1].has(d.position)
&& (c.at[1].has(a.position) || c.at[1].has(d.position) || c.at[1].has(b.position)));
for (const b of gates) {
if (++checks > maxChecks) return null;
const tiles = [a, b, c, d].map((candidate, i) => ({ ...candidate.tile, id: `t${i}`, color: i }));
const [hero, gate, second, tail] = tiles;
formalChecks++;
// Formal certification of every stage with the production swept tracer.
if (tiles.some(tile => trace(boards[0], tile, tiles).status === 'exit')) continue;
if (trace(boards[1], gate, tiles).status !== 'exit') continue;
const afterGate = [hero, second, tail];
if (afterGate.some(tile => trace(boards[1], tile, afterGate).status === 'exit')) continue;
if (trace(boards[2], second, afterGate).status !== 'exit') continue;
const afterSecond = [hero, tail];
if (afterSecond.some(tile => trace(boards[2], tile, afterSecond).status === 'exit')) continue;
if (trace(boards[1], hero, afterSecond).status !== 'exit') continue;
if (trace(boards[1], tail, [tail]).status !== 'exit') continue;
const level = { ...base, tiles, moveLimit: tiles.length };
const solution = solveRotations(level);
if (!solution.solvable || solution.exhausted || solution.rotations !== 3) continue;
return {
tiles, placements: [1, 1, 2, 1], hero,
heroRoute: { bends: a.bends[1], cells: a.cells[1] },
actions: [
{ type: 'rotate', direction: 1 }, { type: 'tap', id: gate.id },
{ type: 'rotate', direction: 1 }, { type: 'tap', id: second.id },
{ type: 'rotate', direction: -1 }, { type: 'tap', id: hero.id }, { type: 'tap', id: tail.id },
],
minimumRotations: solution.rotations, solution,
search: { checks, formalChecks, heroCandidates: heroes.length, poolSize: pool.length },
};
}
}
}
}
return null;
}
// Reverse insertion keeps the chain intact while raising how much of the
// board depends on turning. Each inserted piece must leave at its scheduled
// orientation, and the solver must still need exactly three turns afterwards.
export function growDeepLevel(base, lock, {
seed = 0, target = 12, layerShares = { 0: .35, 1: .35, 2: .3 }, maxHeroBends = 70, minRotations = 3,
} = {}) {
const rng = random(seed + 7919);
const boards = [0, 1, 2].map(turn => rotateBoard(base, turn));
// A layer piece only needs a departure at its own orientation. Requiring
// exits at every orientation would leave almost nothing to insert.
const layerPool = boards.map(board => {
const pool = [];
for (const cell of base.cells) for (let dir = 0; dir < 6; dir++) {
const tile = { q: cell.q, r: cell.r, dir }, route = trace(board, tile, [], true);
if (route.status === 'exit' && countBends(route) <= maxHeroBends) pool.push({ tile, position: positionKey(tile), bends: countBends(route) });
}
return pool;
});
const tiles = [...lock.tiles], placements = [...lock.placements];
const extras = Math.max(0, target - tiles.length);
const schedule = [];
for (const [turn, share] of Object.entries(layerShares)) for (let i = 0; i < Math.round(extras * share); i++) schedule.push(Number(turn));
while (schedule.length < extras) schedule.push(0);
schedule.length = extras;
let rejected = { orientationless: 0, shortcut: 0 };
for (const orientation of shuffled(schedule, rng)) {
const occupied = new Set(tiles.map(positionKey));
const choices = shuffled(layerPool[orientation].filter(c => !occupied.has(c.position)), rng);
let chosen = null, fallback = null;
for (const c of choices) {
const tile = { ...c.tile, id: `t${tiles.length}`, color: tiles.length % 7 }, proposed = [...tiles, tile];
if (trace(boards[orientation], tile, proposed).status !== 'exit') { rejected.orientationless++; continue; }
// Prefer pieces that genuinely wait for this turn: blocked at every earlier orientation.
const waits = [...Array(orientation).keys()].every(earlier => trace(boards[earlier], tile, proposed).status !== 'exit');
if (!waits && fallback) continue;
const solution = solveRotations({ ...base, tiles: proposed, moveLimit: proposed.length });
if (!solution.solvable || solution.exhausted || solution.rotations < minRotations) { rejected.shortcut++; continue; }
if (waits) { chosen = tile; break; }
fallback = tile;
}
chosen = chosen || fallback;
if (!chosen) break;
tiles.push(chosen); placements.push(orientation);
}
const level = {
...base, tiles, moveLimit: tiles.length,
name: `${(base.name || 'route').replace(' · 路线草图', '')} · 深旋转`,
experience: { kind: 'deep', feature: { id: lock.hero.id } },
};
const solution = solveRotations(level);
level.experience.actions = solution.actions;
const errors = validateLevel(level);
if (errors.length) throw new Error(errors.join('; '));
return { level, placements, solution, rejected };
}
// Structural evidence for the difficulty bands: how much of the board waits
// for a turn, how many pieces each turn releases, and whether the direction
// of the first turn is a real choice.
export function deepLevelStats(level) {
const n = level.tiles.length, solution = solveRotations(level);
let board = level, remaining = [...level.tiles];
const drain = () => { for (;;) { const free = available(board, remaining); if (!free.length) return; const ids = new Set(free.map(t => t.id)); remaining = remaining.filter(t => !ids.has(t.id)); } };
drain();
const lockedAtStart = remaining.length;
const openings = [1, -1].filter(direction => available(rotateBoard(board, direction), remaining).length > 0).length;
const releases = [];
for (const action of solution.actions) {
if (action.type !== 'rotate') continue;
const before = remaining.length;
board = rotateBoard(board, action.direction);
drain();
releases.push(before - remaining.length);
}
return {
pieces: n, rotations: solution.rotations, lockedShare: lockedAtStart / n, lockedAtStart,
firstTurnDirections: openings, releasePerTurn: releases, minRelease: releases.length ? Math.min(...releases) : 0,
waves: solution.waves.map(wave => wave.length), states: solution.states,
};
}
// Player-side audit over every reachable state (any tap order, any turn
// sequence). Removal only reduces occupancy and turns are reversible, so no
// reachable state can be unsolvable — the audit proves it rather than assuming
// it — and it measures how many blind turns a player can run into.
export function deadTurnAudit(level, maxStates = 20000) {
const boards = Array.from({ length: 6 }, (_, i) => rotateBoard(level, i));
const keyOf = (o, rem) => o + ':' + [...rem].sort().join(',');
const start = { o: 0, rem: new Set(level.tiles.map(t => t.id)) };
const seen = new Map([[keyOf(0, start.rem), start]]), queue = [start];
let stuckStates = 0, doubleDead = 0, maxDeadTurns = 0, unsolvable = 0;
while (queue.length && seen.size < maxStates) {
const state = queue.shift();
if (!state.rem.size) continue;
const tiles = level.tiles.filter(t => state.rem.has(t.id)), free = available(boards[state.o], tiles);
if (!free.length) {
stuckStates++;
if (![1, -1].some(d => available(boards[(state.o + d + 6) % 6], tiles).length)) doubleDead++;
let nearest = 6;
for (const d of [1, -1]) for (let k = 1; k < 6; k++) if (available(boards[(state.o + d * k + 6) % 6], tiles).length) { nearest = Math.min(nearest, k); break; }
if (nearest === 6) unsolvable++; else maxDeadTurns = Math.max(maxDeadTurns, nearest - 1);
}
for (const t of free) {
const rem = new Set(state.rem); rem.delete(t.id);
const k = keyOf(state.o, rem);
if (!seen.has(k)) { const next = { o: state.o, rem }; seen.set(k, next); queue.push(next); }
}
for (const d of [1, -1]) {
const o = (state.o + d + 6) % 6, k = keyOf(o, state.rem);
if (!seen.has(k)) { const next = { o, rem: state.rem }; seen.set(k, next); queue.push(next); }
}
}
return { states: seen.size, stuckStates, doubleDead, maxDeadTurns, unsolvable, exhausted: seen.size >= maxStates };
}
export const deepLevelKey = level => level.tiles.map(t => `${t.q},${t.r},${t.dir}`).sort().join('|');
export { key as cellKey };
+78
View File
@@ -0,0 +1,78 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Game, rotateBoard, solveRotations, trace, validateLevel } from '../src/core.js';
import { createRouteBoard } from '../src/route-grammar.js';
import { createDeepLock, growDeepLevel, deepLevelStats, deadTurnAudit } from '../src/deep-lock.js';
// Seeds known to yield a chain lock; the sweep script records the full yield table.
const WITNESSES = [
{ family: 'orbits', radius: 3, seed: 0 },
{ family: 'weave', radius: 4, seed: 0 },
{ family: 'spiral', radius: 4, seed: 1 },
{ family: 'switchback', radius: 4, seed: 0 },
];
for (const { family, radius, seed } of WITNESSES) {
test(`${family} r${radius}: three-turn chain is certified stage by stage and by the solver`, () => {
const base = createRouteBoard(seed, { family, radius });
const snapshot = JSON.stringify(base);
const lock = createDeepLock(base, { seed });
assert.ok(lock, `${family}, radius ${radius}, seed ${seed}`);
assert.equal(JSON.stringify(base), snapshot, 'The helper must not alter its input route');
assert.equal(lock.minimumRotations, 3);
assert.ok(lock.heroRoute.bends >= 6);
const level = { ...base, tiles: lock.tiles, moveLimit: lock.tiles.length };
assert.deepEqual(validateLevel(level), []);
assert.equal(solveRotations(level).rotations, 3, 'No one- or two-turn plan may clear the chain');
const [hero, gate, second, tail] = lock.tiles;
const at = turn => rotateBoard(level, turn);
assert.ok(lock.tiles.every(tile => trace(level, tile).status === 'blocked'), 'Everything is locked at the opening');
assert.equal(trace(at(1), gate).status, 'exit', 'Only the gate leaves at +1');
assert.ok([hero, second, tail].every(tile => trace(at(1), tile, [hero, second, tail]).status === 'blocked'));
assert.equal(trace(at(2), second, [hero, second, tail]).status, 'exit', 'The second gate leaves at +2');
assert.equal(trace(at(2), hero, [hero, tail]).status, 'blocked', 'Hero and tail hold each other at +2');
assert.equal(trace(at(2), tail, [hero, tail]).status, 'blocked');
assert.equal(trace(at(1), hero, [hero, tail]).status, 'exit', 'Turning back frees the hero');
const game = new Game(level);
for (const action of lock.actions) {
if (action.type === 'rotate') game.rotate(action.direction);
else assert.equal(game.tap(action.id).status, 'exit');
}
assert.equal(game.tiles.length, 0, 'The authored three-turn witness must fully clear the board');
assert.equal(game.rotations, 3);
});
test(`${family} r${radius}: growth keeps three turns and locks most of the board`, () => {
const base = createRouteBoard(seed, { family, radius });
const lock = createDeepLock(base, { seed });
const target = radius === 3 ? 9 : 12;
const { level, solution, placements } = growDeepLevel(base, lock, { seed, target });
assert.deepEqual(validateLevel(level), []);
assert.ok(level.tiles.length >= target - 2, `grew to ${level.tiles.length} of ${target}`);
assert.equal(placements.length, level.tiles.length);
assert.ok(solution.solvable && !solution.exhausted);
assert.ok(solution.rotations >= 3, 'Inserted pieces must not open a shorter plan');
const stats = deepLevelStats(level);
assert.ok(stats.lockedShare >= .5, `locked share ${stats.lockedShare}`);
assert.equal(stats.releasePerTurn.length, stats.rotations);
// Every state a player can reach — any tap order, any turn sequence — must still clear.
const audit = deadTurnAudit(level);
assert.ok(!audit.exhausted, 'audit must enumerate every reachable state');
assert.equal(audit.unsolvable, 0, 'no reachable state may be a dead end');
const game = new Game(level);
for (const action of level.experience.actions) {
if (action.type === 'rotate') game.rotate(action.direction);
else assert.equal(game.tap(action.id).status, 'exit');
}
assert.ok(game.won, 'The solver reference must clear the grown level');
});
}
test('deep lock search is deterministic and an unmet constraint returns no lock', () => {
const base = createRouteBoard(0, { family: 'orbits', radius: 3 });
assert.deepEqual(createDeepLock(base, { seed: 5 }), createDeepLock(base, { seed: 5 }));
assert.equal(createDeepLock(base, { minHeroBends: 999 }), null);
assert.equal(createDeepLock(base, { maxChecks: 0 }), null);
});