-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboard.js
63 lines (59 loc) · 1.82 KB
/
board.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
class Board {
constructor (width, height) {
this.width = width;
this.height = height;
this.data = this.createSquareArray();
this.populateNeighbors();
}
fetchSquare(x, y) {
return this.data[y][x];
}
getSquareNeighbors(square) {
let squareNeighbors = [];
let x = square.x;
let y = square.y;
if (x + 1 < this.width) {
squareNeighbors.push(this.fetchSquare(x + 1, y));
if (y + 1 < this.height) {
squareNeighbors.push(this.fetchSquare(x + 1, y + 1));
}
if (y !== 0) {
squareNeighbors.push(this.fetchSquare(x + 1, y - 1));
}
}
if (x !== 0) {
squareNeighbors.push(this.fetchSquare(x - 1, y));
if (y + 1 < this.height) {
squareNeighbors.push(this.fetchSquare(x - 1, y + 1));
}
if (y !== 0) {
squareNeighbors.push(this.fetchSquare(x - 1, y - 1));
}
}
if (y !== 0) {
squareNeighbors.push(this.fetchSquare(x, y - 1));
}
if (y + 1 < this.height) {
squareNeighbors.push(this.fetchSquare(x, y + 1));
}
return squareNeighbors;
}
populateNeighbors() {
for (let row of this.data) {
for (let square of row) {
square.neighbors = this.getSquareNeighbors(square);
}
}
}
createSquareArray () {
var board = [];
while (board.length < this.height) {
var row = [];
while (row.length < this.width) {
row.push(new Square(row.length, board.length));
}
board.push(row);
}
return board;
}
}