So I'm implementing a maze generator using prim's algorithm. the maze itself generates pretty much fine, however two (touching) walls would always be missing.
the mazes I'm generating (the right and bottom walls are missing):
Maze 1
here the left and top walls are missing:
Maze 2
The code I use to generate the maze:
int _height = 50;
int _width = 50;
private bool[,] maze = new bool[_height, _width];
private void generateMaze()
{
//_height = 50
//_width = 50
List<MazeCell> walls = new List<MazeCell>();
int randX = genRand(1, _height-1);
int randY = genRand(1, _width-1);
maze[randX, randY] = true;
MazeCell start = new MazeCell(randX, randY, null);
for (int i = -1; i <= 1; i++)
{
for(int j = -1; j <= 1; j++)
{
if ((i == 0 && j == 0) || (i != 0 && j != 0))
continue;
try
{
if (maze[randX + i, randY + j])
continue;
}
catch(Exception e)
{
continue;
}
walls.Add(new MazeCell(randX + i, randY + j, start));
}
}
while (walls.Count > 0)
{
int index = genRand(0, walls.Count - 1);
MazeCell cur = walls[index];
MazeCell op = cur.opposite();
walls.RemoveAt(index);
try
{
if(!maze[cur.x, cur.y])
{
if(!maze[op.x, op.y])
{
maze[cur.x, cur.y] = true;
maze[op.x, op.y] = true;
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0 || i != 0 && j != 0)
continue;
try
{
if (maze[op.x + i, op.y + j])
continue;
}
catch (Exception e)
{
continue;
}
walls.Add(new MazeCell(op.x + i, op.y + j, op));
}
}
}
}
}
catch (Exception e) { }
}
}
private int genRand(int min, int max)
{
Random rnd = new Random();
return rnd.Next(min, max);
}
And the mazeCell class:
public class MazeCell
{
public int x;
public int y;
public bool passage = false;
MazeCell parent;
public MazeCell(int x, int y, MazeCell parent)
{
this.x = x;
this.y = y;
this.parent = parent;
}
public MazeCell opposite()
{
if (x.CompareTo(parent.x) != 0)
return new MazeCell(x + x.CompareTo(parent.x), y, this);
if (y.CompareTo(parent.y) != 0)
return new MazeCell(x, y + y.CompareTo(parent.y), this);
return null;
}
}
the code is an adaptation of java code I found here: http://jonathanzong.com/blog/2012/11/06/maze-generation-with-prims-algorithm
I can't find where it suddenly decides to remove walls. Any help is greatly appreciated!
Randomclass. Do it once and then use that instance over and over. That way you can also create it with a seed value when you want to test in a repeatable manner. - Ian Mercer