I'm working on writing a Maze generator. I have a "Cell" class which is as follows:
public class Cell {
public boolean northWall;
public boolean southWall;
public boolean eastWall;
public boolean westWall;
public Cell north;
public Cell south;
public Cell east;
public Cell west;
public boolean visited;
public Cell() {
northWall = true;
southWall = true;
eastWall = true;
westWall = true;
visited = false;
}
public boolean hasUnvisitedNeighbors() {
return ((north != null && !north.Visited)
|| (south != null && !south.Visited)
|| (east != null && !east.Visited) || (west != null && !west.Visited));
}
public Cell removeRandomWall() {
List<Cell> unvisitedNeighbors = new ArrayList<Cell>();
if (north != null && !north.Visited)
unvisitedNeighbors.add(north);
if (south != null && !south.Visited)
unvisitedNeighbors.add(south);
if (west != null && !west.Visited)
unvisitedNeighbors.add(west);
if (east != null && !east.Visited)
unvisitedNeighbors.add(east);
if (unvisitedNeighbors.size() == 0) {
return null;
} else {
Random randGen = new Random();
Cell neighbor = unvisitedNeighbors.get(randGen
.nextInt((unvisitedNeighbors.size())));
if (neighbor == north) {
northWall = false;
north.southWall = false;
return north;
} else if (neighbor == south) {
southWall = false;
south.northWall = false;
return south;
} else if (neighbor == west) {
westWall = false;
west.eastWall = false;
return west;
} else if (neighbor == east) {
eastWall = false;
east.westWall = false;
return east;
}
return null;
}
}
}
A maze in my program is simply a 2d dimensional array of Cells. After I create the array I manually go in and set all the references to the adjancent cells (North, South, East, West).
What I'm trying to clean up is removeRandomWall(). It is suppose to randomly choose an adjacent Cell which has its visited flag set to false, and remove the wall in both this cell and the adjacent cell that connects them.
So, it needs to consider all adjacent cells who haven't been visited, randomly choose one, then set the wall in this cell and the adjacent one to false so there is a path between them now. I've attempted it above but it seems very cludgey.
Can anyone help me out?