Download source my files here
First of all, I created a class that contains the details for each "cell" of the maze (GridCell.java). This contains the details required for each maze cell (which walls are up/down, and whether that cell has been visited yet).
Now on to the main code, my (MazeGrid.java). Hopefully, there's enough commenting on here to make it clear what it's doing, but just in case, here is the pseudo-code for the generateMaze() method:
- Reset all cells in the grid ( resetGridCells() ).
- Work out how many cells there are (width*height) and also create a last-in-first-out stack of visited cells.
- Start at the top-left (y=0,x=0)
- While there are still cells left unvisited (cellsVisited < width*height):
- See if there are any cells that can be visited from the current cell that we have not yet visited ( unvisitedCellCanBeReached(...) ).
- If there are cells we can visit, pick one at random ( getRandomUnvisitedCell(...) ), set the wall on the current side as down and move to the next cell. Add this next cell to the top of the stack, set it to "visited" and increase the visited count.
- If there are no cells we can visit from our current location, then "pop" the previous location off the stack and move back there.
- Once we've visited all the cells, I need to do a "cleanup". A slight flaw in my design means that if (say) a cells east wall is flagged as down (intact = false), then the cell next to it (on the east side) should have its west wall down (basically I've created double-strength walls). So the cleanup method knocks down any of these walls as well.