Added a maze solver object to handle the search algorithms that will be used to solve the maze. Updated the sketch code to use said object.
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
class MazeSolver {
|
||||
constructor(startingCell, targetCell, searchedColor = [210, 180, 140]){
|
||||
this.frontier = [];
|
||||
this.explored = [];
|
||||
this.targetCell = targetCell;
|
||||
this.searchedColor = searchedColor;
|
||||
this.selectedColor = [50, 175, 50];
|
||||
this.currentCell = startingCell;
|
||||
this.frontier.push(startingCell);
|
||||
}
|
||||
|
||||
clearState(){
|
||||
this.frontier = [];
|
||||
this.explored = [];
|
||||
}
|
||||
|
||||
depthFirstNextCell(maze){
|
||||
breadthFirstNextCell(maze, true);
|
||||
}
|
||||
|
||||
breadthFirstNextCell(maze, depthFirst = false){
|
||||
this.currentCell.color = this.searchedColor;
|
||||
|
||||
if(!depthFirst)
|
||||
this.currentCell = this.frontier.shift();
|
||||
else
|
||||
this.currentCell = this.frontier.pop();
|
||||
|
||||
this.currentCell.color = this.selectedColor;
|
||||
|
||||
this.currentCell.visited = true;
|
||||
|
||||
let moves = maze.getLegalMoves(this.currentCell);
|
||||
|
||||
for (let i = 0; i < moves.length; i++){
|
||||
this.frontier.push(moves[i]);
|
||||
moves[i].parent = this.currentCell;
|
||||
}
|
||||
|
||||
this.explored.push(this.currentCell);
|
||||
|
||||
if(this.currentCell.x == this.targetCell.x && this.currentCell.y == this.targetCell.y)
|
||||
this.frontier = [];
|
||||
this.currentCell.color = this.searchedColor;
|
||||
}
|
||||
|
||||
highlightFinalPath(maze, finalPathColor = [173, 216, 230]){
|
||||
let tmp = this.explored.pop();
|
||||
|
||||
while(tmp != undefined){
|
||||
tmp.color = finalPathColor;
|
||||
tmp = tmp.parent;
|
||||
}
|
||||
|
||||
maze.updateMazeDisplay();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user