-
Notifications
You must be signed in to change notification settings - Fork 0
/
a_star.js
70 lines (64 loc) · 1.85 KB
/
a_star.js
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
function Cell(y, x, obstacleChance = 0.4) {
this.y = y;
this.x = x;
this.isObstacle = Math.random() < obstacleChance;
this.gCost = 0;
this.hCost = 0;
this.fCost = () => {
return this.gCost + this.hCost;
}
this.parent = undefined;
this.findNeighbors = () => {
let neighbors = [];
const y = this.y;
const x = this.x;
if (y < gridRows - 1) {
neighbors.push(grid[y + 1][x]);
}
if (y > 0) {
neighbors.push(grid[y - 1][x]);
}
if (x < gridColumns - 1) {
neighbors.push(grid[y][x + 1]);
}
if (x > 0) {
neighbors.push(grid[y][x - 1]);
}
if (y > 0 && x > 0) {
neighbors.push(grid[y - 1][x - 1]);
}
if (y < gridRows - 1 && x > 0) {
neighbors.push(grid[y + 1][x - 1]);
}
if (y > 0 && x < gridColumns - 1) {
neighbors.push(grid[y - 1][x + 1]);
}
if (y < gridRows - 1 && x < gridColumns - 1) {
neighbors.push(grid[y + 1][x + 1]);
}
return neighbors;
}
this.calculateDistance = (to) => {
let distX = Math.abs(this.x - to.x);
let distY = Math.abs(this.y - to.y);
if (distX > distY) return 14 * distY + 10 * (distX - distY);
else return 14 * distX + 10 * (distY - distX);
}
this.draw = () => {
strokeWeight(1);
fill(255, 255, 255, 200);
if (this.isObstacle) {
fill(0);
}
if (openSet.includes(this)) {
fill(0, 100, 0);
}
if (closedSet.includes(this)) {
fill(100, 0, 0);
}
if (startCell === this || targetCell === this) {
fill(128, 128, 128);
}
rect(this.y * cellWidth, this.x * cellHeight, cellWidth, cellHeight);
};
}