import test from "node:test"; import assert from "node:assert/strict"; import { findPath, orderedCardinals } from "../src/navigation/astar.js"; test("A* walks around an impassable tile", () => { const blocked = new Set(["1,0"]); const path = findPath(0, 0, 2, 0, (x, y) => !blocked.has(`${x},${y}`), -4, -4, 4, 4); assert.ok(path.length > 0); assert.deepEqual(path.at(-1), { x: 2, y: 0 }); assert.ok(!path.some((step) => step.x === 1 && step.y === 0)); }); test("A* returns empty when the goal is blocked", () => { const path = findPath(0, 0, 1, 0, (x, y) => x === 0 && y === 0, -2, -2, 2, 2); assert.deepEqual(path, []); }); test("ordered cardinals prefer longer remaining axis over axis-tie flag", () => { // |dy|=3 > |dx|=1 → vertical first even when axis-tie prefers horizontal. const tallGoal = orderedCardinals(0, 0, -1, -3, false); assert.deepEqual(tallGoal[0], { x: 0, y: -1 }); assert.deepEqual(tallGoal[1], { x: -1, y: 0 }); // |dx|=3 > |dy|=1 → horizontal first even when axis-tie prefers vertical. const wideGoal = orderedCardinals(0, 0, -3, -1, true); assert.deepEqual(wideGoal[0], { x: -1, y: 0 }); assert.deepEqual(wideGoal[1], { x: 0, y: -1 }); const horizontalOnly = orderedCardinals(0, 0, 3, 0, false); assert.deepEqual(horizontalOnly[0], { x: 1, y: 0 }); }); test("axis-tie preference diverges only when |dx| equals |dy|", () => { const open = () => true; const mobPath = findPath(0, 0, -2, -2, open, -8, -8, 8, 8, { preferVertical: false }); const playerPath = findPath(0, 0, -2, -2, open, -8, -8, 8, 8, { preferVertical: true }); assert.equal(mobPath.length, 4); assert.equal(playerPath.length, 4); assert.deepEqual(mobPath[0], { x: -1, y: 0 }); assert.deepEqual(playerPath[0], { x: 0, y: -1 }); // Tall goal: both close the larger vertical gap first (no mob/player swap dance). const tallMob = findPath(0, 0, -1, -3, open, -8, -8, 8, 8, { preferVertical: false }); const tallPlayer = findPath(0, 0, -1, -3, open, -8, -8, 8, 8, { preferVertical: true }); assert.deepEqual(tallMob[0], { x: 0, y: -1 }); assert.deepEqual(tallPlayer[0], { x: 0, y: -1 }); }); test("A* stepCost prefers the cheaper route around an expensive corridor", () => { // Two routes from (0,0) to (2,0): through (1,0) cost 10, or via (0,1)-(1,1)-(2,1) cost 1 each. const expensive = new Set(["1,0"]); const path = findPath( 0, 0, 2, 0, () => true, -2, -2, 4, 4, { stepCost: (x, y) => (expensive.has(`${x},${y}`) ? 10 : 1) } ); assert.ok(path.length > 0); assert.deepEqual(path.at(-1), { x: 2, y: 0 }); assert.ok(!path.some((step) => step.x === 1 && step.y === 0)); });