xxxxxxxxxx
121
class Cell {
constructor(i, j) {
// point
this.i = i;
this.j = j;
// walls
this.walls = [true, true, true, true];
// direction
this.TOP = 0;
this.RIGHT = 1;
this.BOTTOM = 2;
this.LEFT = 3;
// visited
this.visited = false;
// color
this.color = [255, 0, 255, 100];
}
getAllNeighbors() {
// undefined or Cell instance in array
let neighbors = [];
neighbors[this.TOP] = grid[this.index(this.i, this.j - 1)];
neighbors[this.RIGHT] = grid[this.index(this.i + 1, this.j)];
neighbors[this.BOTTOM] = grid[this.index(this.i, this.j + 1)];
neighbors[this.LEFT] = grid[this.index(this.i - 1, this.j)];
return neighbors;
}
getVisitedNeighborCount() {
let cnt = 0;
let neighbors = this.getAllNeighbors();
for (let n of neighbors) {
if(n != undefined && n.visited) {
cnt++;
}
}
return cnt;
}
highlight() {
noStroke();
fill(0, 255, 0);
rect(this.i * w, this.j * w, w, w);
}
removeWalls(other) {
let di = this.i - other.i;
let dj = this.j - other.j;
if (di === -1) {
this.walls[this.RIGHT] = false;
other.walls[other.LEFT] = false;
} else if (di === 1) {
this.walls[this.LEFT] = false;
other.walls[other.RIGHT] = false;
}
if (dj === -1) {
this.walls[this.BOTTOM] = false;
other.walls[other.TOP] = false;
} else if (dj === 1) {
this.walls[this.TOP] = false;
other.walls[other.BOTTOM] = false;
}
}
index(i, j) {
if (i < 0 || j < 0 || i > cols - 1 || j > rows - 1)
return -1;
else
return i + (j * cols);
}
checkNeighbors() {
let neighbors = this.getAllNeighbors();
let able = []
for (let n of neighbors) {
if ((n != undefined) && (!n.visited) && (n.getVisitedNeighborCount() < 2)) {
able.push(n);
}
}
return random(able);
}
show() {
let x = this.i * w;
let y = this.j * w;
stroke(255);
noFill();
// rect(x, y, w, w);
if (this.walls[this.TOP])
line(x, y, x + w, y); // top
if (this.walls[this.RIGHT])
line(x + w, y, x + w, y + w); // right
if (this.walls[this.BOTTOM])
line(x, y + w, x + w, y + w); // bottom
if (this.walls[this.LEFT])
line(x, y, x, y + w); // left
// paint color
if (this.visited) {
noStroke();
fill(this.color);
rect(x, y, w, w);
}
}
}