Browse Source

fix(chase): handle invalid path endpoints and optimize bfs queue

Made-with: Cursor
master
npmrun 2 weeks ago
parent
commit
0e85b657de
  1. 20
      src/game/chase/hexGraph.ts
  2. 21
      tests/chase/hexGraph.test.ts

20
src/game/chase/hexGraph.ts

@ -16,19 +16,21 @@ export function shortestPathLength(
from: NodeId,
to: NodeId,
): number {
if (from === to) {
return 0;
}
if (!graph.nodes[from] || !graph.nodes[to]) {
return Infinity;
}
if (from === to) {
return 0;
}
const queue: Array<[NodeId, number]> = [[from, 0]];
let head = 0;
const visited = new Set<NodeId>([from]);
while (queue.length > 0) {
const [current, distance] = queue.shift()!;
while (head < queue.length) {
const [current, distance] = queue[head];
head += 1;
const node = graph.nodes[current];
for (const neighbor of node.neighbors) {
@ -54,9 +56,11 @@ export function isConnected(graph: GameGraph): boolean {
const start = nodeIds[0];
const visited = new Set<NodeId>([start]);
const queue: NodeId[] = [start];
let head = 0;
while (queue.length > 0) {
const current = queue.shift()!;
while (head < queue.length) {
const current = queue[head];
head += 1;
const node = graph.nodes[current];
for (const neighbor of node.neighbors) {

21
tests/chase/hexGraph.test.ts

@ -48,6 +48,17 @@ describe("hex graph utilities", () => {
expect(shortestPathLength(graph, "A", "C")).toBe(Infinity);
});
it("returns Infinity for invalid from/to nodes", () => {
const graph = buildGraph({
A: { id: "A", q: 0, r: 0, neighbors: ["B"] },
B: { id: "B", q: 1, r: 0, neighbors: ["A"] },
});
expect(shortestPathLength(graph, "X", "X")).toBe(Infinity);
expect(shortestPathLength(graph, "X", "A")).toBe(Infinity);
expect(shortestPathLength(graph, "A", "X")).toBe(Infinity);
});
it("checks graph connectivity", () => {
const connectedGraph = buildGraph({
A: { id: "A", q: 0, r: 0, neighbors: ["B"] },
@ -64,4 +75,14 @@ describe("hex graph utilities", () => {
expect(isConnected(connectedGraph)).toBe(true);
expect(isConnected(disconnectedGraph)).toBe(false);
});
it("treats empty and single-node graph as connected", () => {
const emptyGraph = buildGraph({});
const singleNodeGraph = buildGraph({
A: { id: "A", q: 0, r: 0, neighbors: [] },
});
expect(isConnected(emptyGraph)).toBe(true);
expect(isConnected(singleNodeGraph)).toBe(true);
});
});

Loading…
Cancel
Save