xxxxxxxxxx
148
var cols, rows;
var w = 10;
var grid = [];
var stack = [];
var current;
function setup() {
var wid = round(window.innerWidth / w) * w;
var hei = round(window.innerHeight / w) * w;
createCanvas(wid, hei);
cols = floor(width / w); //i
rows = floor(height / w); //j
for(var j = 1; j < rows - 1; j++) {
var temp = [];
for(var i = 1; i < cols - 1; i++) {
var cell = new Cell(i, j);
temp.push(cell);
}
grid.push(temp);
}
current = grid[0][0];
}
function draw() {
background(51);
for(var j = 0; j < grid.length; j++) {
for(var i = 0; i < grid[0].length; i++) {
grid[j][i].display();
}
}
current.visited = true;
current.highlight();
//STEP 1
var next = current.checkNeighbors();
if (next) {
next.visited = true;
//STEP 2
stack.push(current)
//STEP 3
removeWalls(current, next);
current = next;
} else if (stack.length > 0) {
current = stack.pop();
}
}
function Cell(i, j) {
this.i = i - 1;
this.j = j - 1;
this.walls = [true, true, true, true];
this.visited = false;
this.highlight = function() {
var x = (this.i + 1) * w;
var y = (this.j + 1) * w;
noStroke();
fill(50, 255, 50);
rect(x, y, w, w);
}
this.checkNeighbors = function() {
var neighbors = [];
if (this.j > 0) {
var top = grid[this.j - 1][this.i];
if (!top.visited) {
neighbors.push(top);
}
}
if (this.i < cols - 3) {
var right = grid[this.j][this.i + 1];
if (!right.visited) {
neighbors.push(right);
}
}
if (this.j < rows - 3) {
var bottom = grid[this.j + 1][this.i];
if (!bottom.visited) {
neighbors.push(bottom);
}
}
if (this.i > 0) {
var left = grid[this.j][this.i - 1];
if (!left.visited) {
neighbors.push(left);
}
}
if (neighbors.length > 0) {
var r = floor(random(0, neighbors.length));
return neighbors[r];
} else {
return undefined;
}
}
this.display = function () {
var x = (this.i + 1) * w;
var y = (this.j + 1) * w;
var xw = x + w;
var yw = y + w;
stroke(255);
if (this.walls[0]) {
line(x, y, xw, y);
}
if (this.walls[1]) {
line(xw, y, xw, yw);
}
if (this.walls[2]) {
line(xw, yw, x, yw);
}
if (this.walls[3]) {
line(x, yw, x, y);
}
if (this.visited) {
noStroke();
fill(255, 0, 255, 100);
rect(x, y, w, w)
}
}
}
function removeWalls(a, b) {
var x = a.i - b.i;
if (x === 1) {
a.walls[3] = false;
b.walls[1] = false;
}
if (x === -1) {
a.walls[1] = false;
b.walls[3] = false;
}
var y = a.j - b.j
if (y === 1) {
a.walls[0] = false;
b.walls[2] = false;
}
if (y === -1) {
a.walls[2] = false;
b.walls[0] = false;
}
}