-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheightmap.ts
78 lines (67 loc) · 1.82 KB
/
heightmap.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
import { AStarNode } from "../helpers/astar.ts";
export class Pos extends AStarNode {
char: string;
height: number;
constructor(x: number, y: number, char: string) {
super(x, y);
this.char = char;
this.height = char.charCodeAt(0) - 97;
}
}
export interface HeightMap {
heights: Pos[][];
currentPos: Pos;
targetPos: Pos;
}
export function LoadHeightMap(i: string[]): HeightMap {
const heights: Pos[][] = [];
let currentPos!: Pos;
let targetPos!: Pos;
// Create Pos objects
for (let y = 0; y < i.length; y++) {
heights[y] = [];
for (let x = 0; x < i[y].length; x++) {
const char = i[y][x];
const pos = new Pos(x, y, char);
if (char === "S") {
pos.height = 0;
currentPos = pos;
} else if (char === "E") {
pos.height = 25;
targetPos = pos;
}
heights[y].push(pos);
}
}
// Link neighbours
for (let y = 0; y < i.length; y++) {
for (let x = 0; x < i[y].length; x++) {
const pos = heights[y][x];
if (y > 0) {
const nb = heights[y - 1][x];
if (Math.abs(nb.height - pos.height) <= 1 || nb.height < pos.height) {
pos.neighBours.push(nb);
}
}
if (y < i.length - 1) {
const nb = heights[y + 1][x];
if (Math.abs(nb.height - pos.height) <= 1 || nb.height < pos.height) {
pos.neighBours.push(nb);
}
}
if (x > 0) {
const nb = heights[y][x - 1];
if (Math.abs(nb.height - pos.height) <= 1 || nb.height < pos.height) {
pos.neighBours.push(nb);
}
}
if (x < i[y].length - 1) {
const nb = heights[y][x + 1];
if (Math.abs(nb.height - pos.height) <= 1 || nb.height < pos.height) {
pos.neighBours.push(nb);
}
}
}
}
return { heights, currentPos, targetPos };
}