-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcell.js
148 lines (122 loc) Β· 2.85 KB
/
cell.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
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
138
139
140
141
142
143
144
145
146
147
148
function randomArrayValue(arr) {
const index = floor(random(0, arr.length));
return arr[index];
}
class Cell {
constructor(col = 0, row = 0) {
this.col = col;
this.row = row;
this.walls = [true, true, true, true];
this.visited = false;
}
getSize() {
return [width / GRID_SIZE, height / GRID_SIZE];
}
getPosition() {
const [w, h] = this.getSize();
return [this.row * w, this.col * h];
}
isValid() {
const col = this.col + 1;
const row = this.row + 1;
if (col > GRID_SIZE || col <= 0) {
return false;
}
if (row > GRID_SIZE || row <= 0) {
return false;
}
return true;
}
checkNeighbors() {
let neighbors = [
new Cell(this.col - 1, this.row),
new Cell(this.col + 1, this.row),
new Cell(this.col, this.row - 1),
new Cell(this.col, this.row + 1)
]
neighbors = neighbors
.filter(cell => cell.isValid())
.map(cell => {
return grid.find(c => cell.col === c.col && cell.row === c.row);
})
.filter(cell => !cell.visited);
if (neighbors.length > 0) {
return randomArrayValue(neighbors);
}
}
removeWalls(cell) {
const diffCols = this.col - cell.col;
if (diffCols === 1) {
this.walls[0] = false;
cell.walls[2] = false;
} else if (diffCols === -1) {
this.walls[2] = false;
cell.walls[0] = false;
}
const diffRows = this.row - cell.row;
if (diffRows === 1) {
this.walls[3] = false;
cell.walls[1] = false;
} else if (diffRows === -1) {
this.walls[1] = false;
cell.walls[3] = false;
}
}
highlight(color = [156, 136, 255]) {
const [x, y] = this.getPosition();
const [w, h] = this.getSize();
noStroke();
fill(...color);
rect(x, y, w, h);
}
draw() {
const [x, y] = this.getPosition();
const [w, h] = this.getSize();
stroke(255, 255, 255);
strokeWeight(2);
if (this.walls[0]) {
line(x, y, x + w, y);
}
if (this.walls[1]) {
line(x + w, y, x + w, y + h);
}
if (this.walls[2]) {
line(x + w, y + h, x, y + h);
}
if (this.walls[3]) {
line(x, y + w, x, y);
}
if (this.visited) {
noStroke();
fill(53, 59, 72);
rect(x, y, w + 1, w + 1);
}
}
static serialize(cell) {
return {
column: cell.col + 1,
row: cell.row + 1,
visited: cell.visited,
walls: {
top: cell.walls[0],
right: cell.walls[1],
bottom: cell.walls[2],
left: cell.walls[3]
}
}
}
static deserialize(data) {
const cell = new Cell(data.column - 1, data.row - 1);
cell.visited = data.visited;
cell.walls = [
data.walls.top,
data.walls.right,
data.walls.bottom,
data.walls.left
];
return cell;
}
static isCell(cell) {
return cell instanceof Cell;
}
}