100 lines
2.3 KiB
JavaScript
100 lines
2.3 KiB
JavaScript
class MazeSolver {
|
|
constructor(startingCell, targetCell, searchedColor = [210, 180, 140], finalPathColor = [173, 216, 230]){
|
|
this.frontier = [];
|
|
this.explored = [];
|
|
|
|
this.startingCellColor = [255, 0, 0];
|
|
this.endingCellColor = [0, 0, 255];
|
|
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();
|
|
|
|
tmp.color = this.endingCellColor;
|
|
|
|
tmp = tmp.parent;
|
|
|
|
while(tmp != undefined){
|
|
tmp.color = this.finalPathColor;
|
|
|
|
if(tmp.parent == undefined)
|
|
tmp.color = this.startingCellColor;
|
|
|
|
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;
|
|
}
|
|
}
|
|
/*
|
|
class AStarSolver extends MazeSolver {
|
|
constructor(startingCell, targetCell, searchedColor = [210, 180, 140], finalPathColor = [173, 216, 230]) {
|
|
super(staringCell, targetCell, searchedColor, finalPathColor);
|
|
|
|
this.
|
|
}
|
|
}*/
|