Files
javascript-search-tests/maze-solver.js
T

58 lines
1.3 KiB
JavaScript

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();
}
}