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

79 lines
1.9 KiB
JavaScript

class MazeSolver {
constructor(startingCell, targetCell, searchedColor = [210, 180, 140], finalPathColor = [173, 216, 230]){
this.frontier = [];
this.explored = [];
this.finalPathColor = finalPathColor;
this.targetCell = targetCell;
this.startingCell = startingCell;
this.searchedColor = searchedColor;
this.currentCell = startingCell;
this.frontier.push(startingCell);
this.statesExplored = 0;
}
clearState(){
this.frontier = [];
this.explored = [];
this.statesExplored = 0;
}
highlightFinalPath(maze){
let tmp = this.explored.pop();
while(tmp != undefined){
tmp.color = this.finalPathColor;
tmp = tmp.parent;
}
maze.updateMazeDisplay();
}
}
class DepthFirstSolver extends MazeSolver {
solve(maze) {
this.currentCell.color = this.searchedColor;
this.currentCell = this.frontier.pop();
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);
this.statesExplored++;
if(this.currentCell.x == this.targetCell.x && this.currentCell.y == this.targetCell.y)
this.frontier = [];
this.currentCell.color = this.searchedColor;
}
}
class BreadthFirstSolver extends MazeSolver {
solve(maze) {
this.currentCell.color = this.searchedColor;
this.currentCell = this.frontier.shift();
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);
this.statesExplored++;
if(this.currentCell.x == this.targetCell.x && this.currentCell.y == this.targetCell.y)
this.frontier = [];
this.currentCell.color = this.searchedColor;
}
}