xxxxxxxxxx
133
let cols, rows;
let gap = 100;
let grid = [];
let current;
function setup() {
createCanvas(600, 600);
cols = floor(width / gap);
rows = floor(height / gap);
for (let x = 0; x < rows; x++) {
for (let y = 0; y < cols; y++) {
let cell = new Cell(y, x);
grid.push(cell);
}
}
current = grid[0];
// frameRate(5);
}
function draw() {
background(0);
for (let i = 0; i < grid.length; i++) {
grid[i].show();
}
current.visited = true;
current.highlight();
let nextCell = current.checkNeighbors();
if(nextCell){
nextCell.visited = true;
removeWalls(current, nextCell);
current = nextCell;
}
}
function index(x, y) {
if (x < 0 || y < 0 || x > cols - 1 || y > rows - 1) {
return -1;
}
return x + y * cols; // algorithm to get the index in an array (grid)
}
function removeWalls(current, nextCell){
let posX = current.x - nextCell.x;
let posY = current.y - nextCell.y;
if(posX === 1){
current.walls[3] = false;
nextCell.walls[1] = false;
}
if(posX === -1){
current.walls[1] = false;
nextCell.walls[3] = false;
}
if(posY === 1){
current.walls[0] = false;
nextCell.walls[2] = false;
}
if(posY === -1){
current.walls[2] = false;
nextCell.walls[0] = false;
}
}
class Cell {
constructor(x, y) {
this.x = x;
this.y = y;
this.walls = [true, true, true, true];
this.visited = false;
}
show() {
stroke(255);
let x = this.x * gap;
let y = this.y * gap;
if (this.walls[0]) {
line(x, y, x + gap, y);
}
if (this.walls[1]) {
line(x + gap, y, x + gap, y + gap);
}
if (this.walls[2]) {
line(x + gap, y + gap, x, y + gap);
}
if (this.walls[3]) {
line(x, y + gap, x, y);
}
if (this.visited) {
noStroke();
fill(random(255), random(255), random(255), 25);
rect(x, y, gap, gap);
}
}
checkNeighbors() {
let neighbors = [];
let top = grid[index(this.x, this.y - 1)];
let right = grid[index(this.x + 1, this.y)];
let bottom = grid[index(this.x, this.y + 1)];
let left = grid[index(this.x - 1, this.y)];
if (top && !top.visited) {
neighbors.push(top);
}
if (right && !right.visited) {
neighbors.push(right);
}
if (bottom && !bottom.visited) {
neighbors.push(bottom);
}
if (left && !left.visited) {
neighbors.push(left);
}
if(neighbors.length > 0){
let randy = floor(random(0,neighbors.length));
return neighbors[randy];
} else {
return undefined;
}
}
highlight(){
fill(100,100,250);
rect(this.x*gap, this.y*gap, gap);
}
}