Trying to port some of the code into objects to clean up the sketch.js file.

This commit is contained in:
2020-05-18 23:48:17 -05:00
commit 2fbcc0b345
4 changed files with 423 additions and 0 deletions
+88
View File
@@ -0,0 +1,88 @@
class Maze{
constructor(mazeWidth, mazeHeight, cellWidth){
this.columns = floor(mazeWidth / cellWidth);
this.rows = floor(mazeHeight / cellWidth);
this.width = mazeWidth;
this.height = mazeHeight;
this.cellWidth = cellWidth;
this.workingStack = [];
this.currentCell = {};
this.grid = [];
for (let y = 0; y < this.rows; y++) {
for (var x = 0; x < this.columns; x++) {
this.grid.push(new Cell(x, y, this.cellWidth));
}
}
this.grid[this.index(0,0)].visited = true;
this.grid[this.index(0,0)].selected = true;
this.workingStack.push(this.grid[this.index(0,0)]);
}
updateMazeDisplay(){
for (var i = 0; i < this.grid.length; i++) {
this.grid[i].show();
}
}
buildNextCell(){
//Build the maze
this.currentCell = this.workingStack.pop();
//currentCell.visited = true;
let nextCell = getNeighbors(this.currentCell);
if(nextCell){
this.workingStack.push(this.currentCell);
currentCell.Selected = false;
currentCell.visited = true;
nextCell.visited = true;
nextCell.selected = true;
removeWalls(currentCell, nextCell);
this.workingStack.push(nextCell);
}
else
this.workingStack.pop();
this.currentCell.selected = false;
}
get mazeGenDone() {
return this.workingStack.length == 0;
}
getNeighbors(cell){
var visited = [];
var top = this.grid[index(cell.x, cell.y - 1)];
var left = this.grid[index(cell.x - 1, cell.y)];
var bottom = this.grid[index(cell.x, cell.y + 1)];
var right = this.grid[index(cell.x + 1, cell.y)];
if (top && !top.visited) {
visited.push(top);
}
if (left && !left.visited) {
visited.push(left);
}
if (right && !right.visited) {
visited.push(right);
}
if (bottom && !bottom.visited) {
visited.push(bottom);
}
if(visited.length == 1)
return visited[0];
else if (visited.length > 1)
return visited[floor(random(0, visited.length))];
else
return undefined;
}
index(x, y) {
if (x < 0 || y < 0 || x > this.columns - 1 || y > this.rows - 1) return -1;
return x + y * this.columns;
}
}