mazeGenerator.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var MazeGenerator = function(rows, cols) {
  2. this.graph = new Graph(rows, cols);
  3. this.cellStack = [];
  4. var self = this;
  5. var recurse = function(cell) {
  6. cell.visit();
  7. var neighbors = self.graph.cellUnvisitedNeighbors(cell);
  8. if(neighbors.length > 0) {
  9. var randomNeighbor = neighbors[Math.floor(Math.random() * neighbors.length)];
  10. self.cellStack.push(cell);
  11. self.graph.removeEdgeBetween(cell, randomNeighbor);
  12. recurse(randomNeighbor);
  13. }
  14. else {
  15. var waitingCell = self.cellStack.pop();
  16. if(waitingCell) {
  17. recurse(waitingCell);
  18. }
  19. }
  20. };
  21. this.solve = function() {
  22. var closedSet = [];
  23. var startCell = this.graph.getCellAt(0, 0); // top left cell
  24. var targetCell = this.graph.getCellAt(this.graph.width - 1, this.graph.height - 1); // bottom right cell
  25. var openSet = [startCell];
  26. var searchCell = startCell;
  27. while(openSet.length > 0) {
  28. var neighbors = this.graph.cellDisconnectedNeighbors(searchCell);
  29. for(var i = 0; i < neighbors.length; i ++) {
  30. var neighbor = neighbors[i];
  31. if(neighbor == targetCell) {
  32. neighbor.parent = searchCell;
  33. this.path = neighbor.pathToOrigin();
  34. openSet = [];
  35. return;
  36. }
  37. if(!_.include(closedSet, neighbor)) {
  38. if(!_.include(openSet, neighbor)) {
  39. openSet.push(neighbor);
  40. neighbor.parent = searchCell;
  41. neighbor.heuristic = neighbor.score() + this.graph.getCellDistance(neighbor, targetCell);
  42. }
  43. }
  44. }
  45. closedSet.push(searchCell);
  46. openSet.remove(_.indexOf(openSet, searchCell));
  47. searchCell = null;
  48. _.each(openSet, function(cell) {
  49. if(!searchCell) {
  50. searchCell = cell;
  51. }
  52. else if(searchCell.heuristic > cell.heuristic) {
  53. searchCell = cell;
  54. }
  55. });
  56. }
  57. };
  58. this.generate = function() {
  59. var initialCell = this.graph.getCellAt(0, 0);
  60. recurse(initialCell);
  61. };
  62. };