Implementation of a maze generation algorithm and maze walking with pathfinding in JavaScript, using p5.js lib for drawing.
The choosen algorithm for maze generation is iterative depth-first search (DFS) and it is composed of the following steps:
- Choose the initial cell, mark it as visited and push it to the stack
- While the stack is not empty
- Pop a cell from the stack and make it a current cell
- If the current cell has any neighbours which have not been visited
- Push the current cell to the stack
- Choose one of the unvisited neighbours
- Remove the wall between the current cell and the chosen cell
- Mark the chosen cell as visited and push it to the stack
Pathfinding is done using simplified A* algorithm, with breadth-first search (BFS) and simple heuristics based on path length:
- Set the cost for all cells as '+Infinity'
- Create a queue for cells to process
- Set target cell cost to 0 (zero)
- Add target cell to queue
- While the queue is not empty
- Pop the first cell from the queue and make it the current cell
- For each neighbouring cell (top, right, left and bottom)
- If there is a wall between the current cell and the current neighbour, skip to next neighbour
- If the neighbour is already in the queue
- If it has a cost less then or equal to the current cell, skip to next neighbour
- Remove current neighbour from queue
- Set current neighbour cost to current cell cost + 1
- If current neigbour is the target cell, end the while loop
- If queue is empty, no path was found, return
- Empty the queue
- Make the starting cell the current cell
- While the current cell is not the target cell
- Add the current cell to the queue
- For each neighbouring cell (top, right, left and bottom)
- If there is a wall between the current cell and the current neighbour, skip to next neighbour
- If the current neighbour cost is less than the current cell cost
- Make the current neighbour the current cell
- End the neighbours loop
After running this algorithm, the queue will contain the cells for the shortest path.
This project only depends on p5.js 1.0+.
To install dependencies, navigate to the root of the repository and run:
npm install
# OR
yarn
Open index.html
file and the generation will start.