/
pathfinding.test.ts
137 lines (122 loc) · 2.68 KB
/
pathfinding.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import { Pathfinder } from "./pathfinding";
type Node = {
x: number;
y: number;
};
function distance(start: Node, end: Node): number {
return Math.abs(start.x - end.x) + Math.abs(start.y - end.y);
}
function cost(start: Node, end: Node): number {
return 1;
}
function neighbors(node: Node): Node[] {
const results = [];
if (node.x > 0) {
results.push({
x: node.x - 1,
y: node.y,
});
}
if (node.y > 0) {
results.push({
y: node.y - 1,
x: node.x,
});
}
results.push({
y: node.y + 1,
x: node.x,
});
results.push({
x: node.x + 1,
y: node.y,
});
return results;
}
function hash(node: Node): string {
return `${node.x}/${node.y}`;
}
describe("pathfinding", () => {
it("can find paths", async () => {
const pf = new Pathfinder<Node>({
distance,
cost,
neighbors,
hash,
});
expect(
(await pf.findPath({ x: 1, y: 1 }, { x: 10, y: 1 })).path.length,
).toBe(10);
});
it("can find long paths", async () => {
const pf = new Pathfinder<Node>({
distance,
cost,
neighbors,
hash,
});
expect(
(await pf.findPath({ x: 1, y: 50 }, { x: 22, y: 13 })).path.length,
).toBe(71);
});
it("can find paths around walls", async () => {
const pf = new Pathfinder<Node>({
distance,
cost,
neighbors: (node: Node) =>
neighbors(node).filter((n) => !(n.x < 12 && n.y < 5 && n.y > 3)),
hash,
});
expect(
(await pf.findPath({ x: 1, y: 1 }, { x: 5, y: 5 })).path.length,
).toBe(23);
});
it("will fail to find path outside limit", async () => {
const pf = new Pathfinder<Node>({
distance,
cost,
neighbors,
hash,
maxLength: 5,
});
expect((await pf.findPath({ x: 1, y: 1 }, { x: 10, y: 1 })).success).toBe(
false,
);
});
it("will find path within limit", async () => {
const pf = new Pathfinder<Node>({
distance,
cost,
neighbors,
hash,
maxLength: 15,
});
expect(
(await pf.findPath({ x: 1, y: 1 }, { x: 10, y: 1 })).path.length,
).toBe(10);
});
it("will find path of exact limit", async () => {
const pf = new Pathfinder<Node>({
distance,
cost,
neighbors,
hash,
maxLength: 10,
});
expect(
(await pf.findPath({ x: 1, y: 1 }, { x: 10, y: 1 })).path.length,
).toBe(10);
});
it("will not find path of length - 1", async () => {
const pf = new Pathfinder<Node>({
distance,
cost,
neighbors,
hash,
maxLength: 9,
});
expect((await pf.findPath({ x: 1, y: 1 }, { x: 10, y: 1 })).success).toBe(
false,
);
});
});