Files
mayi_coco/tools/audit-release.mjs
T

272 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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(';') : '无'),
);
}