#!/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)均通过几何、压层、木夹与策略分叉审计!');