Files
mayi_coco/assets/scripts/core/RouteEngine.ts
T

731 lines
26 KiB
TypeScript

import { HOOP_CENTER, NEST, RIM_LIMIT, YARN_COLORS } from './LevelData';
import {
BallDef,
BlockReason,
ButtonAnchorDef,
ButtonEvent,
DeliveryEvent,
DyeEvent,
DyeVatDef,
GateDef,
GateEvent,
HintState,
LevelDef,
PickEvent,
Point2D,
PondDef,
RouteEvent,
RouteState,
SectionDef,
SpoolDef,
SpoolEvent,
TargetColor,
YarnColor,
} from './Types';
export const ANT_SPEED = 0.264;
export const STITCH_TIME = 710;
export function isPickEvent(event: RouteEvent): event is PickEvent {
return event.kind === 'pick';
}
export function isDeliveryEvent(event: RouteEvent): event is DeliveryEvent {
return event.kind === 'delivery';
}
export function isSpoolEvent(event: RouteEvent): event is SpoolEvent {
return event.kind === 'spool';
}
export function isButtonEvent(event: RouteEvent): event is ButtonEvent {
return event.kind === 'button';
}
export function isDyeEvent(event: RouteEvent): event is DyeEvent {
return event.kind === 'dye';
}
export function isGateEvent(event: RouteEvent): event is GateEvent {
return event.kind === 'gate';
}
export function distance(a: Point2D, b: Point2D): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}
export function interpolate(a: Point2D, b: Point2D, t: number): Point2D {
return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
}
export function closestFraction(start: Point2D, end: Point2D, point: Point2D, scaleX = 1, scaleY = 1): number {
const dx = (end.x - start.x) / scaleX;
const dy = (end.y - start.y) / scaleY;
const fx = (point.x - start.x) / scaleX;
const fy = (point.y - start.y) / scaleY;
const length = dx * dx + dy * dy;
return length ? Math.max(0, Math.min(1, (fx * dx + fy * dy) / length)) : 0;
}
export function intersectsPond(start: Point2D, end: Point2D, pond: PondDef): boolean {
const t = closestFraction(start, end, pond, pond.rx, pond.ry);
const point = interpolate(start, end, t);
return Math.hypot((point.x - pond.x) / pond.rx, (point.y - pond.y) / pond.ry) < 1;
}
export function hitSpan(from: Point2D, to: Point2D, center: Point2D, rx: number, ry: number): { enter: number; leave: number } | null {
const x = (from.x - center.x) / rx;
const y = (from.y - center.y) / ry;
const dx = (to.x - from.x) / rx;
const dy = (to.y - from.y) / ry;
const a = dx * dx + dy * dy;
if (a < 1e-8) {
return x * x + y * y <= 1 ? { enter: 0, leave: 1 } : null;
}
const b = x * dx + y * dy;
const d = b * b - a * (x * x + y * y - 1);
if (d < 0) return null;
const root = Math.sqrt(d);
const enter = Math.max(0, (-b - root) / a);
const leave = Math.min(1, (-b + root) / a);
return enter <= leave ? { enter, leave } : null;
}
function orient(a: Point2D, b: Point2D, c: Point2D): number {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
export function segmentsIntersect(a: Point2D, b: Point2D, c: Point2D, d: Point2D): boolean {
const minAx = Math.min(a.x, b.x) - 1;
const maxAx = Math.max(a.x, b.x) + 1;
const minAy = Math.min(a.y, b.y) - 1;
const maxAy = Math.max(a.y, b.y) + 1;
const minCx = Math.min(c.x, d.x) - 1;
const maxCx = Math.max(c.x, d.x) + 1;
const minCy = Math.min(c.y, d.y) - 1;
const maxCy = Math.max(c.y, d.y) + 1;
if (maxAx < minCx || maxCx < minAx || maxAy < minCy || maxCy < minAy) return false;
const o1 = orient(a, b, c);
const o2 = orient(a, b, d);
const o3 = orient(c, d, a);
const o4 = orient(c, d, b);
return (o1 * o2 < 0) && (o3 * o4 < 0);
}
export function segmentCost(level: LevelDef, from: Point2D, to: Point2D, segLen: number): number {
if (!level.roughZones.length || segLen <= 0) return segLen;
let extraFactor = 0;
for (const zone of level.roughZones) {
const span = hitSpan(from, to, zone, zone.rx, zone.ry);
if (span && span.leave > span.enter) {
const overlap = span.leave - span.enter;
const zoneExtra = Math.max(0, (zone.factor ?? 1.8) - 1) * overlap;
if (zoneExtra > extraFactor) extraFactor = zoneExtra;
}
}
return segLen * (1 + extraFactor);
}
export function createEmptyRoute(showTip = false, nest: Point2D = NEST): RouteState {
return {
nest: { ...nest },
points: [{ ...nest }],
cum: [0],
costCum: [0],
len: 0,
cost: 0,
picks: [],
deliveries: [],
spools: [],
buttons: [],
dyes: [],
gates: [],
events: [],
color: null,
blocked: null,
showTip,
startedAt: 0,
carry: [],
ant: { ...nest, angle: -Math.PI / 2, carry: [], walk: true },
finished: false,
arrivedAt: 0,
segment: 1,
nextEvent: 0,
duration: 0,
};
}
export function totalLength(lines: RouteState[]): number {
return lines.reduce((sum, line) => sum + line.cost, 0);
}
export function collectedSpoolBonus(lines: RouteState[], drawing?: RouteState | null): number {
let bonus = 0;
for (const line of lines) {
for (const sp of line.spools) bonus += sp.spool.bonus;
}
if (drawing) {
for (const sp of drawing.spools) bonus += sp.spool.bonus;
}
return bonus;
}
export function effectiveBudget(level: LevelDef, lines: RouteState[], drawing?: RouteState | null): number | undefined {
if (!level.budget) return undefined;
return level.budget + collectedSpoolBonus(lines, drawing);
}
export function isPondBridged(pond: PondDef, lines: RouteState[]): boolean {
if (!pond.bridgeSectionId) return false;
for (const line of lines) {
if (line.deliveries.some(d => d.target.id === pond.bridgeSectionId)) return true;
}
return false;
}
export function isTargetLocked(
level: LevelDef,
targetId: string,
lines: RouteState[],
drawing?: RouteState | null,
): boolean {
const reqId = level.locks?.[targetId];
if (!reqId) return false;
for (const line of lines) {
if (line.deliveries.some(d => d.target.id === reqId)) return false;
}
if (drawing && drawing.deliveries.some(d => d.target.id === reqId)) return false;
return true;
}
export function dyeUsedCount(dyeId: number, lines: RouteState[], drawing?: RouteState | null): number {
let count = 0;
for (const line of lines) {
for (const ev of line.dyes) if (ev.dye.id === dyeId) count++;
}
if (drawing) {
for (const ev of drawing.dyes) if (ev.dye.id === dyeId) count++;
}
return count;
}
export function dyeRemainingUses(dye: DyeVatDef, lines: RouteState[], drawing?: RouteState | null): number {
if (dye.uses === undefined) return Infinity;
return Math.max(0, dye.uses - dyeUsedCount(dye.id, lines, drawing));
}
export function availableTargets(level: LevelDef, lines: RouteState[], color?: YarnColor | null): SectionDef[] {
const used = new Set<string>();
for (const line of lines) {
for (const d of line.deliveries) used.add(d.target.id);
}
return level.targets.filter(target => (!color || target.color === color) && !used.has(target.id));
}
export function threadedButtonIds(lines: RouteState[], drawing?: RouteState | null): Set<number> {
const ids = new Set<number>();
for (const line of lines) for (const b of line.buttons) ids.add(b.button.id);
if (drawing) for (const b of drawing.buttons) ids.add(b.button.id);
return ids;
}
export function passedGateIds(lines: RouteState[], drawing?: RouteState | null): Set<number> {
const ids = new Set<number>();
for (const line of lines) for (const g of line.gates) ids.add(g.gate.id);
if (drawing) for (const g of drawing.gates) ids.add(g.gate.id);
return ids;
}
export function dispatchWarning(level: LevelDef, lines: RouteState[]): string {
if (!level.maxDispatches) return '';
const remaining = level.maxDispatches - lines.length;
const targets = availableTargets(level, lines);
const hasOverrideDye = level.dyes.some(d => d.override && dyeRemainingUses(d, lines) > 0);
const trips = hasOverrideDye
? Math.ceil(targets.length / 2)
: YARN_COLORS.reduce(
(sum, color) => sum + Math.ceil(targets.filter(t => t.color === color).length / 2),
0,
);
if (trips > remaining) {
return `剩 ${remaining} 笔、${targets.length} 个针位,撤销一笔把球串起来。`;
}
const missingButtons = level.buttons.filter(b => !threadedButtonIds(lines).has(b.id)).length;
const missingGates = level.gates.filter(g => !passedGateIds(lines).has(g.id)).length;
if (remaining === 0 && (missingButtons > 0 || missingGates > 0)) {
return missingButtons > 0
? `还有 ${missingButtons} 颗纽扣未穿过,请撤销重画。`
: `还有 ${missingGates} 处穿针眼未穿过,请撤销重画。`;
}
return '';
}
export function scoreForLength(level: LevelDef, used: number): number {
return used <= level.threeStar ? 3 : used <= level.twoStar ? 2 : 1;
}
export function rollbackToLength(route: RouteState, newLen: number, newCost: number): void {
route.len = newLen;
route.cost = newCost;
route.picks = route.picks.filter(e => e.at <= newLen);
route.deliveries = route.deliveries.filter(e => e.at <= newLen);
route.spools = route.spools.filter(e => e.at <= newLen);
route.buttons = route.buttons.filter(e => e.at <= newLen);
route.dyes = route.dyes.filter(e => e.at <= newLen);
route.gates = route.gates.filter(e => e.at <= newLen);
route.events = route.events.filter(e => e.at <= newLen);
// 根据保留的事件重算当前毛线颜色(支持白球染色后回退还原成白色)
let color: YarnColor | null = null;
for (const ev of route.events) {
if (isPickEvent(ev) && color === null) {
color = ev.ball.color;
} else if (isDyeEvent(ev) && color !== null) {
color = ev.dye.color;
}
}
route.color = color;
}
export function tryBacktrack(route: RouteState, point: Point2D): boolean {
let retracted = false;
while (route.points.length >= 2) {
const tip = route.points[route.points.length - 1];
const prev = route.points[route.points.length - 2];
const segLen = distance(prev, tip);
const dPrev = distance(point, prev);
const dTip = distance(point, tip);
if (dPrev + 1.5 < dTip && dPrev <= Math.max(segLen * 1.1, 14)) {
route.points.pop();
route.cum.pop();
route.costCum.pop();
rollbackToLength(route, route.cum[route.cum.length - 1], route.costCum[route.costCum.length - 1]);
retracted = true;
} else {
break;
}
}
return retracted;
}
export interface PlanCallbacks {
onPick?: (count: number) => void;
onMark?: (count: number) => void;
onLocked?: () => void;
onSpool?: (bonus: number) => void;
onButton?: () => void;
onDye?: (color: TargetColor) => void;
onGate?: () => void;
}
type HitCandidate =
| { kind: 'pick'; ball: BallDef; span: { enter: number; leave: number } }
| { kind: 'delivery'; target: SectionDef; span: { enter: number; leave: number } }
| { kind: 'spool'; spool: SpoolDef; span: { enter: number; leave: number } }
| { kind: 'button'; button: ButtonAnchorDef; span: { enter: number; leave: number } }
| { kind: 'dye'; dye: DyeVatDef; span: { enter: number; leave: number } }
| { kind: 'gate'; gate: GateDef; span: { enter: number; leave: number } };
export function planStops(
level: LevelDef,
lines: RouteState[],
route: RouteState,
from: Point2D,
to: Point2D,
startLength: number,
length: number,
cb?: PlanCallbacks,
): void {
const takenBalls = new Set<number>();
for (const line of lines) for (const p of line.picks) takenBalls.add(p.ball.id);
for (const p of route.picks) takenBalls.add(p.ball.id);
const takenSpools = new Set<number>();
for (const line of lines) for (const s of line.spools) takenSpools.add(s.spool.id);
for (const s of route.spools) takenSpools.add(s.spool.id);
const takenButtons = threadedButtonIds(lines, route);
const takenGates = passedGateIds(lines, route);
const candidates: HitCandidate[] = [];
for (const ball of level.balls) {
if (takenBalls.has(ball.id)) continue;
const span = hitSpan(from, to, ball, 28, 28);
if (span) candidates.push({ kind: 'pick', ball, span });
}
for (const spool of level.spools) {
if (takenSpools.has(spool.id)) continue;
const span = hitSpan(from, to, spool, 26, 26);
if (span) candidates.push({ kind: 'spool', spool, span });
}
for (const button of level.buttons) {
if (takenButtons.has(button.id)) continue;
const span = hitSpan(from, to, button, 26, 26);
if (span) candidates.push({ kind: 'button', button, span });
}
for (const dye of level.dyes) {
const span = hitSpan(from, to, dye, 28, 28);
if (span) candidates.push({ kind: 'dye', dye, span });
}
for (const gate of level.gates) {
if (takenGates.has(gate.id)) continue;
const r = gate.radius ?? 25;
const span = hitSpan(from, to, gate, r, r);
if (span) candidates.push({ kind: 'gate', gate, span });
}
const marked = new Set(route.deliveries.map(stop => stop.target.id));
const targetHits: { target: SectionDef; span: { enter: number; leave: number } }[] = [];
for (const target of availableTargets(level, lines)) {
if (marked.has(target.id)) continue;
const span = hitSpan(from, to, target, target.rx, target.ry);
if (span) {
targetHits.push({ target, span });
candidates.push({ kind: 'delivery', target, span });
}
}
candidates.sort((a, b) => a.span.enter - b.span.enter);
const markDelivery = (target: SectionDef, t: number) => {
if (!route.color || route.color === 'white') return;
if (target.color !== route.color || marked.has(target.id) || route.deliveries.length === route.picks.length) return;
if (isTargetLocked(level, target.id, lines, route)) {
cb?.onLocked?.();
return;
}
const stop: DeliveryEvent = { kind: 'delivery', target, at: startLength + length * t, origin: interpolate(from, to, t) };
marked.add(target.id);
route.deliveries.push(stop);
route.events.push(stop);
cb?.onMark?.(route.deliveries.length);
};
for (const entry of candidates) {
const enter = entry.span.enter;
if (entry.kind === 'delivery') {
markDelivery(entry.target, enter);
continue;
}
if (entry.kind === 'spool') {
if (takenSpools.has(entry.spool.id)) continue;
takenSpools.add(entry.spool.id);
const ev: SpoolEvent = { kind: 'spool', spool: entry.spool, at: startLength + length * enter };
route.spools.push(ev);
route.events.push(ev);
cb?.onSpool?.(entry.spool.bonus);
continue;
}
if (entry.kind === 'button') {
if (takenButtons.has(entry.button.id)) continue;
takenButtons.add(entry.button.id);
const ev: ButtonEvent = { kind: 'button', button: entry.button, at: startLength + length * enter };
route.buttons.push(ev);
route.events.push(ev);
cb?.onButton?.();
continue;
}
if (entry.kind === 'gate') {
if (takenGates.has(entry.gate.id)) continue;
takenGates.add(entry.gate.id);
const ev: GateEvent = { kind: 'gate', gate: entry.gate, at: startLength + length * enter };
route.gates.push(ev);
route.events.push(ev);
cb?.onGate?.();
continue;
}
if (entry.kind === 'dye') {
if (dyeRemainingUses(entry.dye, lines, route) <= 0) continue;
// 染缸:手上有球且未全部落针时染色;普通染缸只染白球,覆色染缸可强行改色
const canDye =
route.picks.length > 0 &&
route.deliveries.length < route.picks.length &&
route.color !== entry.dye.color &&
(route.color === 'white' || Boolean(entry.dye.override));
if (canDye) {
route.color = entry.dye.color;
const ev: DyeEvent = { kind: 'dye', dye: entry.dye, at: startLength + length * enter };
route.dyes.push(ev);
route.events.push(ev);
cb?.onDye?.(entry.dye.color);
for (const hit of targetHits) {
if (hit.span.enter <= enter && enter <= hit.span.leave) markDelivery(hit.target, enter);
}
}
continue;
}
// pick
const ball = entry.ball;
if (route.picks.length >= 2) continue;
if (route.color && route.color !== ball.color) continue;
if (!route.color) route.color = ball.color;
const pick: PickEvent = { kind: 'pick', ball, at: startLength + length * enter };
route.picks.push(pick);
route.events.push(pick);
cb?.onPick?.(route.picks.length);
for (const hit of targetHits) {
if (hit.span.enter <= enter && enter <= hit.span.leave) markDelivery(hit.target, enter);
}
}
}
export function checkSegmentBlock(
level: LevelDef,
lines: RouteState[],
route: RouteState,
from: Point2D,
to: Point2D,
segLen: number,
): BlockReason | null {
if (level.ponds.some(pond => !isPondBridged(pond, lines) && intersectsPond(from, to, pond))) return 'pond';
if (
Math.hypot(from.x - HOOP_CENTER.x, from.y - HOOP_CENTER.y) > RIM_LIMIT ||
Math.hypot(to.x - HOOP_CENTER.x, to.y - HOOP_CENTER.y) > RIM_LIMIT
) {
return 'rim';
}
// 实体毛线球阻挡:不可穿过异色或已满载时的未拾毛线球
if (level.solidBalls) {
const takenBalls = new Set<number>();
for (const line of lines) for (const p of line.picks) takenBalls.add(p.ball.id);
for (const p of route.picks) takenBalls.add(p.ball.id);
for (const ball of level.balls) {
if (takenBalls.has(ball.id)) continue;
const cannotPick = route.picks.length >= 2 || (route.color !== null && route.color !== ball.color);
if (cannotPick && hitSpan(from, to, ball, 22, 22)) return 'ball';
}
}
// 单向穿针眼校验:碰到未穿过的针眼时,行进方向必须与箭头夹角 < ~80°
if (level.gates.length > 0 && segLen > 0.5) {
const dirX = (to.x - from.x) / segLen;
const dirY = (to.y - from.y) / segLen;
const passed = passedGateIds(lines, route);
for (const gate of level.gates) {
if (passed.has(gate.id)) continue;
const r = gate.radius ?? 25;
if (hitSpan(from, to, gate, r, r)) {
const dot = dirX * Math.cos(gate.angle) + dirY * Math.sin(gate.angle);
if (dot < 0.15) return 'gate';
}
}
}
// 不可交叉校验:禁止压过任何已提交毛线的线段(共享蚁巢出口 24px 内豁免)
if (level.noCross && lines.length > 0) {
const nearAnyNest = level.nests.some(n => distance(from, n) < 24 && distance(to, n) < 24);
if (!nearAnyNest) {
for (const prevLine of lines) {
const pts = prevLine.points;
for (let i = 1; i < pts.length; i++) {
const a = pts[i - 1];
const b = pts[i];
if (level.nests.some(n => distance(a, n) < 24 && distance(b, n) < 24)) continue;
if (segmentsIntersect(from, to, a, b)) return 'cross';
}
}
}
}
const budget = effectiveBudget(level, lines, route);
if (budget !== undefined) {
const costAdd = segmentCost(level, from, to, segLen);
if (totalLength(lines) + route.cost + costAdd > budget) return 'budget';
}
return null;
}
export function trimRouteTail(route: RouteState): void {
const lastEvent = route.events[route.events.length - 1];
if (!lastEvent || lastEvent.at >= route.len - 0.5) return;
const cutAt = lastEvent.at;
let seg = 1;
while (seg < route.cum.length - 1 && route.cum[seg] < cutAt) seg++;
const prevLen = route.cum[seg - 1];
const nextLen = route.cum[seg];
const t = nextLen > prevLen ? Math.max(0, Math.min(1, (cutAt - prevLen) / (nextLen - prevLen))) : 0;
const endPoint = interpolate(route.points[seg - 1], route.points[seg], t);
const prevCost = route.costCum[seg - 1];
const nextCost = route.costCum[seg];
const endCost = prevCost + (nextCost - prevCost) * t;
route.points = [...route.points.slice(0, seg), endPoint];
route.cum = [...route.cum.slice(0, seg), cutAt];
route.costCum = [...route.costCum.slice(0, seg), endCost];
route.len = cutAt;
route.cost = endCost;
}
export function prepareRouteForRun(route: RouteState, startedAt: number): void {
route.blocked = null;
route.startedAt = startedAt;
route.carry = [];
route.ant = { ...route.nest, angle: -Math.PI / 2, carry: route.carry, walk: true };
route.finished = false;
route.arrivedAt = 0;
route.segment = 1;
route.nextEvent = 0;
let stopTime = 0;
for (const event of route.events) {
event.ms = event.at / ANT_SPEED + stopTime;
event.hold = isPickEvent(event) ? 135 : isDeliveryEvent(event) ? 160 : 75;
stopTime += event.hold;
}
route.duration = route.len / ANT_SPEED + stopTime;
}
export function findNextHint(level: LevelDef, lines: RouteState[], tier: 1 | 2 | 3 = 1): HintState {
const takenBalls = new Set<number>();
for (const line of lines) for (const p of line.picks) takenBalls.add(p.ball.id);
const remainingBalls = level.balls.filter(b => !takenBalls.has(b.id));
const remTargets = availableTargets(level, lines);
let chosen = level.demo[Math.min(lines.length, level.demo.length - 1)];
let firstBall: BallDef | null = null;
let firstBallIndex = 1;
for (const path of level.demo) {
let hit: BallDef | undefined;
let hitIdx = 1;
for (let i = 1; i < path.length; i++) {
const [x, y] = path[i];
hit = remainingBalls.find(ball => Math.hypot(x - ball.x, y - ball.y) < 34);
if (hit) {
hitIdx = i;
break;
}
const prev = { x: path[i - 1][0], y: path[i - 1][1] };
const cur = { x, y };
hit = remainingBalls.find(ball => hitSpan(prev, cur, ball, 28, 28) !== null);
if (hit) {
hitIdx = i;
break;
}
}
if (hit) {
chosen = path;
firstBall = hit;
firstBallIndex = hitIdx;
break;
}
}
const fullPts = (chosen ?? level.demo[0] ?? []).map(([x, y]) => ({ x, y }));
let firstTarget: SectionDef | null = null;
for (let i = 1; i < fullPts.length; i++) {
const pt = fullPts[i];
const hit = remTargets.find(t => Math.hypot((pt.x - t.x) / t.rx, (pt.y - t.y) / t.ry) <= 1.05);
if (hit) {
firstTarget = hit;
break;
}
}
let points = fullPts;
if (tier === 1) {
// 1 级提示:沿真实 demo 折线截取到第一颗球,保留绕开水洼的中间拐点(避免直线穿水洼)
points = fullPts.length >= 2 ? fullPts.slice(0, Math.min(fullPts.length, firstBallIndex + 1)) : fullPts;
} else if (tier === 2 && fullPts.length >= 2) {
// 2 级提示:截取该笔折线的前半程(按长度 52%)
let total = 0;
for (let i = 1; i < fullPts.length; i++) total += distance(fullPts[i - 1], fullPts[i]);
const halfLen = total * 0.52;
const sliced: Point2D[] = [fullPts[0]];
let acc = 0;
for (let i = 1; i < fullPts.length; i++) {
const seg = distance(fullPts[i - 1], fullPts[i]);
if (acc + seg >= halfLen) {
const t = seg > 0 ? (halfLen - acc) / seg : 0;
sliced.push(interpolate(fullPts[i - 1], fullPts[i], Math.max(0, Math.min(1, t))));
break;
}
sliced.push(fullPts[i]);
acc += seg;
}
points = sliced;
}
return { tier, points, ball: firstBall, target: firstTarget };
}
/** 自动化验关器:用真实引擎规则跑完整关 demo,返回是否通关、总耗线与失败原因 */
export function validateLevelDemo(level: LevelDef): { ok: boolean; cost: number; error?: string } {
const lines: RouteState[] = [];
for (let d = 0; d < level.demo.length; d++) {
const raw = level.demo[d];
if (!raw || raw.length < 2) {
return { ok: false, cost: 0, error: `demo[${d}] 点数不足` };
}
const startPt: Point2D = { x: raw[0][0], y: raw[0][1] };
const matchedNest = level.nests.find(n => distance(n, startPt) < 4);
if (!matchedNest) {
return { ok: false, cost: 0, error: `demo[${d}] 起点 (${startPt.x},${startPt.y}) 不在任何蚁巢上` };
}
const route = createEmptyRoute(false, matchedNest);
for (let i = 1; i < raw.length; i++) {
const fromPt = { x: raw[i - 1][0], y: raw[i - 1][1] };
const toPt = { x: raw[i][0], y: raw[i][1] };
const dist = distance(fromPt, toPt);
const steps = Math.max(1, Math.ceil(dist / 6));
for (let s = 1; s <= steps; s++) {
const pt = interpolate(fromPt, toPt, s / steps);
const prev = route.points[route.points.length - 1];
const segLen = distance(prev, pt);
if (segLen < 1.5) continue;
const blocked = checkSegmentBlock(level, lines, route, prev, pt, segLen);
if (blocked) {
return {
ok: false,
cost: totalLength(lines) + route.cost,
error: `demo[${d}] 第 ${i} 段在 (${pt.x.toFixed(1)},${pt.y.toFixed(1)}) 触发阻挡: ${blocked}`,
};
}
const costAdd = segmentCost(level, prev, pt, segLen);
route.points.push(pt);
const startLen = route.len;
route.len += segLen;
route.cost += costAdd;
route.cum.push(route.len);
route.costCum.push(route.cost);
planStops(level, lines, route, prev, pt, startLen, segLen);
}
}
if (!route.picks.length || route.picks.length !== route.deliveries.length) {
return {
ok: false,
cost: totalLength(lines) + route.cost,
error: `demo[${d}] 未完成配对: picks=${route.picks.length}, deliveries=${route.deliveries.length}, color=${route.color}`,
};
}
prepareRouteForRun(route, 0);
lines.push(route);
}
if (level.maxDispatches && lines.length > level.maxDispatches) {
return { ok: false, cost: totalLength(lines), error: `出发笔数 ${lines.length} 超过限笔 ${level.maxDispatches}` };
}
const remTargets = availableTargets(level, lines);
if (remTargets.length > 0) {
return { ok: false, cost: totalLength(lines), error: `尚有未绣针位: ${remTargets.map(t => t.id).join(',')}` };
}
const doneButtons = threadedButtonIds(lines);
if (level.buttons.some(b => !doneButtons.has(b.id))) {
return { ok: false, cost: totalLength(lines), error: `尚有纽扣未穿过` };
}
const doneGates = passedGateIds(lines);
if (level.gates.some(g => !doneGates.has(g.id))) {
return { ok: false, cost: totalLength(lines), error: `尚有单向针眼未穿过` };
}
const finalCost = totalLength(lines);
const maxBudget = effectiveBudget(level, lines);
if (maxBudget !== undefined && finalCost > maxBudget) {
return { ok: false, cost: finalCost, error: `总耗线 ${finalCost.toFixed(1)} 超出限额 ${maxBudget}` };
}
return { ok: true, cost: finalCost };
}