feat: consolidate unspool gameplay, 30 release levels, and 5 validation samples (026A/B, 038A, 039, 051)

This commit is contained in:
fannyxl committed 2026-11-26 09:45:05 +08:00
1 parent 96c19dca82
commit f02f9b085e
18 files changed
+2922 -39

No files matched your search

+271
View File
@@ -0,0 +1,271 @@
#!/usr/bin/env node
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { registerHooks } from 'node:module';
import { fileURLToPath } from 'node:url';
registerHooks({
resolve(specifier, context, nextResolve) {
return nextResolve(/^\.\.?\//.test(specifier) && !/\.[a-z]+$/i.test(specifier) ? specifier + '.ts' : specifier, context);
},
load(url, context, nextLoad) {
if (!url.endsWith('.ts')) return nextLoad(url, context);
const source = readFileSync(fileURLToPath(url), 'utf8').replace(
/import\s*\{[^}]*\}\s*from\s*['"]\.\/Types['"];?/g, '',
);
return { format: 'module-typescript', source, shortCircuit: true };
},
});
const { RELEASE_CHAPTERS, RELEASE_LEVELS, isReleaseStageOpen } = await import('../assets/scripts/core/ReleaseLevels.ts');
const {
availableTargets, checkSegmentBlock, createEmptyRoute, distance, interpolate,
isTargetLocked, planStops, prepareRouteForRun, segmentCost, totalLength,
} = await import('../assets/scripts/core/RouteEngine.ts');
function traceRoute(level, lines, points, ballIds, targetIds) {
const route = createEmptyRoute(false, points[0]);
for (let i = 1; i < points.length; i++) {
const parts = Math.max(1, Math.ceil(distance(points[i - 1], points[i]) / 6));
for (let j = 1; j <= parts; j++) {
const from = route.points.at(-1);
const to = interpolate(points[i - 1], points[i], j / parts);
const length = distance(from, to);
if (length < 1.5) continue;
if (checkSegmentBlock(level, lines, route, from, to, length)) return null;
const start = route.len;
route.len += length;
route.cost += segmentCost(level, from, to, length);
route.points.push(to);
route.cum.push(route.len);
route.costCum.push(route.cost);
planStops(level, lines, route, from, to, start, length);
}
}
if (
route.picks.length !== ballIds.length ||
route.deliveries.length !== targetIds.length ||
ballIds.some((id, idx) => route.picks[idx]?.ball.id !== id) ||
targetIds.some((id, idx) => route.deliveries[idx]?.target.id !== id)
) {
return null;
}
prepareRouteForRun(route, 0);
for (const stop of route.deliveries) stop.arrivedAt = 1;
route.finished = true;
return route;
}
function findRoute(level, lines, ball, target) {
const nest = level.nests[0];
const prefix = [nest, ball];
const candidates = [[...prefix, target]];
if (level.ponds.length) {
const near = Math.max(...level.ponds.map(pond => pond.y + pond.ry)) + 12;
const far = Math.min(...level.ponds.map(pond => pond.y - pond.ry)) - 12;
for (const x of [124, 155, 176, 295, 310, 425, 451, 480]) {
candidates.push([...prefix, { x, y: near }, { x, y: far }, target]);
}
}
let best = null;
for (const points of candidates) {
const route = traceRoute(level, lines, points, [ball.id], [target.id]);
if (route && (!best || route.cost < best.route.cost)) {
best = { route, points: points.map(p => [p.x, p.y]) };
}
}
return best;
}
function findChainedRoute(level, lines, ball1, ball2, target1, target2) {
const nest = level.nests[0];
const candidates = [[nest, ball1, ball2, target1, target2]];
if (level.ponds.length) {
const near = Math.max(...level.ponds.map(pond => pond.y + pond.ry)) + 12;
const far = Math.min(...level.ponds.map(pond => pond.y - pond.ry)) - 12;
for (const x of [124, 155, 176, 295, 310, 425, 451, 480]) {
candidates.push([nest, ball1, ball2, { x, y: near }, { x, y: far }, target1, target2]);
}
}
let best = null;
for (const points of candidates) {
const route = traceRoute(level, lines, points, [ball1.id, ball2.id], [target1.id, target2.id]);
if (route && (!best || route.cost < best.route.cost)) {
best = { route, points: points.map(p => [p.x, p.y]) };
}
}
return best;
}
function solve(blueprint, forcedFirst, allowChain = false) {
const { strands, slots } = blueprint.unspool;
const strandById = new Map(strands.map((strand, i) => [strand.id, { ...strand, ballId: i + 100 }]));
const bestByState = new Map();
let best = null;
function visit(removed, occupancy, lines, actions) {
const cost = totalLength(lines);
if (best && cost >= best.cost) return;
const pending = availableTargets(blueprint, lines);
if (!pending.length) {
best = { actions, cost, strokes: lines.length };
return;
}
const key = JSON.stringify([Array.from(removed).sort(), occupancy, pending.map(t => t.id)]);
if (cost >= (bestByState.get(key) ?? Infinity)) return;
bestByState.set(key, cost);
const balls = occupancy.map((id, slot) => {
if (!id) return null;
const strand = strandById.get(id);
return { id: strand.ballId, color: strand.color, ...slots[slot] };
});
const level = { ...blueprint, balls: balls.filter(Boolean) };
if (allowChain) {
for (let s1 = 0; s1 < balls.length; s1++) {
const b1 = balls[s1];
if (!b1) continue;
for (let s2 = 0; s2 < balls.length; s2++) {
if (s1 === s2) continue;
const b2 = balls[s2];
if (!b2 || b2.color !== b1.color) continue;
const sameColorOpen = pending.filter(t => t.color === b1.color && !isTargetLocked(level, t.id, lines));
if (sameColorOpen.length < 2) continue;
for (let i = 0; i < sameColorOpen.length; i++) {
for (let j = 0; j < sameColorOpen.length; j++) {
if (i === j) continue;
const t1 = sameColorOpen[i];
const t2 = sameColorOpen[j];
const traced = findChainedRoute(level, lines, b1, b2, t1, t2);
if (!traced) continue;
const next = [...occupancy];
next[s1] = null;
next[s2] = null;
visit(
removed,
next,
[...lines, traced.route],
[...actions, { stitch: [t1.id, t2.id], points: traced.points }],
);
}
}
}
}
}
for (let slot = 0; slot < balls.length; slot++) {
const ball = balls[slot];
if (!ball) continue;
for (const target of pending) {
if (ball.color !== target.color || isTargetLocked(level, target.id, lines)) continue;
const traced = findRoute(level, lines, ball, target);
if (!traced) continue;
const next = [...occupancy];
next[slot] = null;
visit(removed, next, [...lines, traced.route], [...actions, { stitch: target.id, points: traced.points }]);
}
}
const free = occupancy.indexOf(null);
if (free === -1) return;
for (const strand of strands) {
if (removed.has(strand.id) || strand.coveredBy.some(id => !removed.has(id))) continue;
if (forcedFirst && actions.length === 0 && strand.id !== forcedFirst) continue;
const next = [...occupancy];
next[free] = strand.id;
visit(new Set([...removed, strand.id]), next, lines, [...actions, { pull: strand.id }]);
}
}
visit(new Set(), slots.map(() => null), [], []);
return best;
}
function measureOpeningFillDeadlocks(blueprint) {
const { strands, slots } = blueprint.unspool;
const k = slots.length;
const openTargetColors = new Set(
blueprint.targets.filter(t => !isTargetLocked(blueprint, t.id, [])).map(t => t.color),
);
let total = 0;
let dead = 0;
function dfs(removed, pulledColors) {
if (pulledColors.length === k) {
total++;
if (!pulledColors.some(c => openTargetColors.has(c))) dead++;
return;
}
const exposed = strands.filter(s => !removed.has(s.id) && s.coveredBy.every(cid => removed.has(cid)));
for (const s of exposed) {
const next = new Set(removed);
next.add(s.id);
dfs(next, [...pulledColors, s.color]);
}
}
dfs(new Set(), []);
return { k, total, dead };
}
assert.equal(RELEASE_LEVELS.length, 30);
assert.deepEqual(RELEASE_CHAPTERS.map(chapter => chapter.count), [10, 10, 10]);
assert.equal(isReleaseStageOpen(0, () => false), true);
assert.equal(isReleaseStageOpen(1, () => false), false);
assert.equal(isReleaseStageOpen(10, level => level.id === RELEASE_LEVELS[9].id), true);
assert.equal(isReleaseStageOpen(30, () => true), false);
const cm = v => (v / 100).toFixed(2);
const reportRows = [];
const solutions = RELEASE_LEVELS.map((level, index) => {
const { strands, slots } = level.unspool;
assert.equal(slots.length, index < 10 ? 3 : 2);
assert.equal(strands.length, level.targets.length);
const visible = strands.filter(strand => strand.coveredBy.length === 0);
const starts = visible.map(strand => ({ id: strand.id, solution: solve(level, strand.id, false) })).filter(entry => entry.solution);
assert(starts.length, `关卡 ${index + 1} ${level.name} 无参考通路`);
if (level.difficulty === 'D4') assert(starts.length >= 2, `关卡 ${index + 1} 缺少第二种起手`);
const reference = starts.map(entry => entry.solution).sort((a, b) => a.cost - b.cost)[0];
assert(reference.cost <= level.threeStar, `关卡 ${index + 1} 缺少三星参考走法`);
const chained = solve(level, null, true);
const margin = level.threeStar - reference.cost;
const perStroke = margin / Math.max(1, reference.strokes);
const chainSave = chained ? reference.cost - chained.cost : 0;
const opening = measureOpeningFillDeadlocks(level);
const tightFlag = perStroke < 40 ? ' ⚠过紧' : '';
const chainText = chainSave > 5 ? ` · 串双球省 ${cm(chainSave)}cm(${chained.strokes}笔)` : '';
const deadText = opening.dead > 0 ? ` · 满${opening.k}抽死锁 ${opening.dead}/${opening.total}` : '';
console.error(
`${String(index + 1).padStart(3, '0')} ${level.name} ${level.difficulty} · ${strands.length}缕/${slots.length}碗 · ${starts.length}起手 · ` +
`1球 ${cm(reference.cost)}cm / 3★ ${cm(level.threeStar)}cm (余 +${cm(margin)}cm, +${cm(perStroke)}cm/笔${tightFlag})${chainText}${deadText}`,
);
reportRows.push({
stage: index + 1,
name: level.name,
difficulty: level.difficulty,
strands: strands.length,
slots: slots.length,
starts: starts.length,
singleCost: reference.cost,
singleStrokes: reference.strokes,
chainedCost: chained?.cost ?? reference.cost,
chainedStrokes: chained?.strokes ?? reference.strokes,
threeStar: level.threeStar,
margin,
perStroke,
openingDead: opening.dead,
openingTotal: opening.total,
});
return reference;
});
if (process.argv.includes('--json')) {
console.log(JSON.stringify(solutions));
} else if (process.argv.includes('--report-json')) {
console.log(JSON.stringify(reportRows, null, 2));
} else {
const tight = reportRows.filter(r => r.perStroke < 45).sort((a, b) => a.perStroke - b.perStroke);
const chainUseful = reportRows.filter(r => r.singleCost - r.chainedCost > 5);
console.log('首期 30 关均通过抽线层级、线碗容量、三星路线和解锁验证。');
console.log(`串双球可省线关卡:${chainUseful.length}/30 关(${chainUseful.map(r => String(r.stage).padStart(3, '0')).join(', ')})`);
console.log(
`单笔三星余量 < 0.45cm 预警(共 ${tight.length} 关):` +
(tight.length ? tight.map(r => `${String(r.stage).padStart(3, '0')} ${r.name}(+${cm(r.margin)}cm / +${cm(r.perStroke)}cm每笔)`).join(';') : '无'),
);
}
+301
View File
@@ -0,0 +1,301 @@
#!/usr/bin/env node
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { registerHooks } from 'node:module';
import { fileURLToPath } from 'node:url';
registerHooks({
resolve(specifier, context, nextResolve) {
return nextResolve(/^\.\.?\//.test(specifier) && !/\.[a-z]+$/i.test(specifier) ? specifier + '.ts' : specifier, context);
},
load(url, context, nextLoad) {
if (!url.endsWith('.ts')) return nextLoad(url, context);
const source = readFileSync(fileURLToPath(url), 'utf8').replace(
/import\s+(?:type\s+)?\{[^}]*\}\s*from\s*['"]\.\/Types['"];?/g,
'',
);
return { format: 'module-typescript', source, shortCircuit: true };
},
});
const { VALIDATION_SAMPLES } = await import('../assets/scripts/core/ValidationSamples.ts');
const {
availableTargets,
checkSegmentBlock,
createEmptyRoute,
distance,
interpolate,
isClipUnlocked,
isStrandExposed,
isTargetLocked,
planStops,
prepareRouteForRun,
segmentCost,
totalLength,
} = await import('../assets/scripts/core/RouteEngine.ts');
function traceRoute(level, lines, points, ballIds, targetIds) {
const route = createEmptyRoute(false, points[0]);
for (let i = 1; i < points.length; i++) {
const parts = Math.max(1, Math.ceil(distance(points[i - 1], points[i]) / 6));
for (let j = 1; j <= parts; j++) {
const from = route.points.at(-1);
const to = interpolate(points[i - 1], points[i], j / parts);
const length = distance(from, to);
if (length < 1.5) continue;
if (checkSegmentBlock(level, lines, route, from, to, length)) return null;
const start = route.len;
route.len += length;
route.cost += segmentCost(level, from, to, length);
route.points.push(to);
route.cum.push(route.len);
route.costCum.push(route.cost);
planStops(level, lines, route, from, to, start, length);
}
}
if (
route.picks.length !== ballIds.length ||
route.deliveries.length !== targetIds.length ||
ballIds.some((id, idx) => route.picks[idx]?.ball.id !== id) ||
targetIds.some((id, idx) => route.deliveries[idx]?.target.id !== id)
) {
return null;
}
prepareRouteForRun(route, 0);
for (const stop of route.deliveries) stop.arrivedAt = 1;
route.finished = true;
return route;
}
function candidateDetours(level) {
const pts = [];
if (level.ponds.length) {
const near = Math.max(...level.ponds.map(p => p.y + p.ry)) + 12;
const far = Math.min(...level.ponds.map(p => p.y - p.ry)) - 12;
for (const x of [124, 155, 176, 295, 310, 425, 451, 480]) {
pts.push([{ x, y: near }, { x, y: far }]);
}
}
if (level.noCross) {
// 两侧与顶部外绕走廊,用于验证不交叉让路路径
pts.push(
[{ x: 112, y: 458 }, { x: 84, y: 318 }, { x: 132, y: 186 }],
[{ x: 488, y: 458 }, { x: 516, y: 318 }, { x: 468, y: 186 }],
[{ x: 108, y: 340 }, { x: 146, y: 158 }, { x: 244, y: 118 }],
[{ x: 492, y: 340 }, { x: 454, y: 158 }, { x: 356, y: 118 }],
[{ x: 472, y: 298 }, { x: 422, y: 132 }, { x: 266, y: 134 }],
[{ x: 128, y: 298 }, { x: 178, y: 132 }, { x: 334, y: 134 }],
);
}
return pts;
}
function findSingleRoute(level, lines, ball, target) {
const detours = candidateDetours(level);
let best = null;
for (const nest of level.nests) {
const candidates = [[nest, ball, target]];
for (const mid of detours) {
candidates.push([nest, ball, ...mid, target]);
}
for (const points of candidates) {
const route = traceRoute(level, lines, points, [ball.id], [target.id]);
if (route && (!best || route.cost < best.route.cost)) {
best = { route, points: points.map(p => [p.x, p.y]) };
}
}
}
return best;
}
function findChainRoute(level, lines, b1, b2, t1, t2) {
const detours = candidateDetours(level);
let best = null;
for (const nest of level.nests) {
const candidates = [[nest, b1, b2, t1, t2]];
for (const mid of detours) {
candidates.push([nest, b1, b2, ...mid, t1, t2]);
}
for (const points of candidates) {
const route = traceRoute(level, lines, points, [b1.id, b2.id], [t1.id, t2.id]);
if (route && (!best || route.cost < best.route.cost)) {
best = { route, points: points.map(p => [p.x, p.y]) };
}
}
}
return best;
}
function solveSample(blueprint, { allowChain = true, forcedFirst = null, maxStrokes = null } = {}) {
const unspool = blueprint.unspool;
const { strands, slots } = unspool;
const capacity = unspool.capacity ?? slots.length;
const strandById = new Map(strands.map((s, i) => [s.id, { ...s, ballId: i + 100 }]));
const bestByState = new Map();
let best = null;
function visit(removed, occupancy, lines, actions) {
const cost = totalLength(lines);
if (best && cost >= best.cost) return;
if (maxStrokes !== null && lines.length > maxStrokes) return;
if (blueprint.maxDispatches && lines.length > blueprint.maxDispatches) return;
const pending = availableTargets(blueprint, lines);
if (!pending.length) {
best = { actions, cost, strokes: lines.length };
return;
}
const key = JSON.stringify([Array.from(removed).sort(), occupancy, pending.map(t => t.id), lines.length]);
if (cost >= (bestByState.get(key) ?? Infinity)) return;
bestByState.set(key, cost);
const balls = occupancy.map((id, slot) => {
if (!id) return null;
const strand = strandById.get(id);
return { id: strand.ballId, color: strand.color, ...slots[slot] };
});
const level = { ...blueprint, balls: balls.filter(Boolean) };
if (allowChain) {
for (let s1 = 0; s1 < balls.length; s1++) {
const b1 = balls[s1];
if (!b1) continue;
for (let s2 = 0; s2 < balls.length; s2++) {
if (s1 === s2) continue;
const b2 = balls[s2];
if (!b2 || b2.color !== b1.color) continue;
const openSame = pending.filter(t => t.color === b1.color && !isTargetLocked(level, t.id, lines));
if (openSame.length < 2) continue;
for (let i = 0; i < openSame.length; i++) {
for (let j = 0; j < openSame.length; j++) {
if (i === j) continue;
const t1 = openSame[i];
const t2 = openSame[j];
const traced = findChainRoute(level, lines, b1, b2, t1, t2);
if (!traced) continue;
const next = [...occupancy];
next[s1] = null;
next[s2] = null;
visit(removed, next, [...lines, traced.route], [...actions, { stitch: [t1.id, t2.id] }]);
}
}
}
}
}
for (let slot = 0; slot < balls.length; slot++) {
const ball = balls[slot];
if (!ball) continue;
for (const target of pending) {
if (ball.color !== target.color || isTargetLocked(level, target.id, lines)) continue;
const traced = findSingleRoute(level, lines, ball, target);
if (!traced) continue;
const next = [...occupancy];
next[slot] = null;
visit(removed, next, [...lines, traced.route], [...actions, { stitch: target.id }]);
}
}
const occupiedCount = occupancy.filter(Boolean).length;
if (occupiedCount >= capacity) return;
for (const strand of strands) {
if (!isStrandExposed(unspool, strand, removed, lines)) continue;
if (forcedFirst && actions.length === 0 && strand.id !== forcedFirst) continue;
const targetSlot = strand.slotIndex !== undefined && occupancy[strand.slotIndex] === null
? strand.slotIndex
: occupancy.indexOf(null);
if (targetSlot === -1) continue;
const next = [...occupancy];
next[targetSlot] = strand.id;
const nextRem = new Set(removed);
nextRem.add(strand.id);
visit(nextRem, next, lines, [...actions, { pull: strand.id }]);
}
}
visit(new Set(), slots.map(() => null), [], []);
return best;
}
function measureOpeningFillDeadlocks(blueprint) {
const unspool = blueprint.unspool;
const k = unspool.capacity ?? unspool.slots.length;
const openColors = new Set(blueprint.targets.filter(t => !isTargetLocked(blueprint, t.id, [])).map(t => t.color));
let total = 0;
let dead = 0;
function dfs(removed, pulledColors) {
if (pulledColors.length === k) {
total++;
if (!pulledColors.some(c => openColors.has(c))) dead++;
return;
}
for (const s of unspool.strands) {
if (!isStrandExposed(unspool, s, removed, [])) continue;
const next = new Set(removed);
next.add(s.id);
dfs(next, [...pulledColors, s.color]);
}
}
dfs(new Set(), []);
return { k, total, dead };
}
const cm = v => (v / 100).toFixed(2);
for (const entry of VALIDATION_SAMPLES) {
const lv = entry.level;
const unspool = lv.unspool;
const exposed = unspool.strands.filter(s => isStrandExposed(unspool, s, new Set(), []));
const single = solveSample(lv, { allowChain: false });
const optimal = solveSample(lv, { allowChain: true });
assert(optimal, `样板 ${entry.key} 无解`);
const opening = measureOpeningFillDeadlocks(lv);
console.log(
`[${entry.key}] ${entry.headerTitle} · 容量 ${unspool.capacity ?? unspool.slots.length} · ` +
`最优 ${cm(optimal.cost)}cm(${optimal.strokes}笔)` +
(single ? ` | 单球 ${cm(single.cost)}cm(${single.strokes}笔)` : '') +
` | 3★ ${cm(lv.threeStar)}cm` +
(opening.total ? ` | 满${opening.k}抽死锁 ${opening.dead}/${opening.total}` : ''),
);
// 针对每张样板的核心假设跑专项断言
if (entry.key === '026b') {
const startE = solveSample(lv, { forcedFirst: 'unspool-release-26-e' });
const startA = solveSample(lv, { forcedFirst: 'unspool-release-26-a' });
const startC = solveSample(lv, { forcedFirst: 'unspool-release-26-c' });
assert(startE && startA && startC, '026B 应支持先拆中拱 e 或配中拱的左右起手');
assert(opening.dead > 0 && opening.dead < opening.total, '026B 3 碗交叉压层应既保留死锁张力又不过度卡死');
console.log(` ↳ 026B 交叉压层核验:先抽e=${cm(startE.cost)}cm, 先抽a=${cm(startA.cost)}cm, 先抽c=${cm(startC.cost)}cm, 满3抽死锁=${opening.dead}/${opening.total}`);
}
if (entry.key === '039') {
const threeStroke = solveSample(lv, { allowChain: false, maxStrokes: 3 });
const twoStroke = solveSample(lv, { allowChain: true, maxStrokes: 2 });
assert(threeStroke, '039 缺少 3 笔分送解');
assert(twoStroke, '039 缺少 2 笔串双金外绕解');
assert(twoStroke.cost <= lv.threeStar, `039 两笔外绕解 (${cm(twoStroke.cost)}cm) 超出三星线 (${cm(lv.threeStar)}cm)`);
console.log(
` ↳ 039 双解核验:3笔分送=${cm(threeStroke.cost)}cm vs 2笔串双金让路=${cm(twoStroke.cost)}cm ` +
`(差值 +${cm(twoStroke.cost - threeStroke.cost)}cm, 均 ≤ 三星 ${cm(lv.threeStar)}cm)`,
);
}
if (entry.key === '051') {
const clipFirst = solveSample(lv, { allowChain: true, forcedFirst: 's51-green' });
const naiveGoldFirst = solveSample(lv, { allowChain: false, forcedFirst: 's51-gold-a' });
assert(clipFirst, '051 先绣绿叶开夹路径无解');
assert(naiveGoldFirst, '051 先拆左片金甲朴素路径也应可通关');
assert(clipFirst.strokes <= 3, `051 先开夹应可 3 笔成画,当前 ${clipFirst.strokes} 笔`);
assert(clipFirst.cost <= lv.threeStar, `051 先开夹 (${cm(clipFirst.cost)}cm) 应稳拿三星 (${cm(lv.threeStar)}cm)`);
assert(naiveGoldFirst.cost > lv.threeStar, `051 朴素分送 (${cm(naiveGoldFirst.cost)}cm) 应高于三星线以凸显改序收益`);
const clipDef = unspool.clips[0];
assert.equal(isClipUnlocked(clipDef, []), false);
console.log(
` ↳ 051 开夹改序核验:先开夹=${cm(clipFirst.cost)}cm(${clipFirst.strokes}笔, 3★) vs 朴素分送=${cm(naiveGoldFirst.cost)}cm(${naiveGoldFirst.strokes}笔), ` +
`改序省线 ${cm(naiveGoldFirst.cost - clipFirst.cost)}cm!`,
);
}
}
console.log('全部 5 张验证样板(026A / 026B / 038A / 039 / 051)均通过几何、压层、木夹与策略分叉审计!');