public void GenerateMaze(int xCells, int yCells) { Stack <MazeCell> oldCells = new Stack <MazeCell>(); MazeCell currentCell = MazeGrid[0, 0]; MazeCell nextCell; while (true) { Direction[] directions = (Direction[])Enum.GetValues(typeof(Direction)); while (directions.Length > 0) { Direction move = GetRandomDirection(directions); nextCell = null; switch (move) { case Direction.Down: if (currentCell.Y + 1 < yCells) { nextCell = MazeGrid[currentCell.X, currentCell.Y + 1]; } break; case Direction.Left: if (currentCell.X - 1 >= 0) { nextCell = MazeGrid[currentCell.X - 1, currentCell.Y]; } break; case Direction.Right: if (currentCell.X + 1 < xCells) { nextCell = MazeGrid[currentCell.X + 1, currentCell.Y]; } break; case Direction.Up: if (currentCell.Y - 1 >= 0) { nextCell = MazeGrid[currentCell.X, currentCell.Y - 1]; } break; } if (nextCell != null && !nextCell.Touched) { currentCell.OpenWall(move); nextCell.OpenWall(OpositeDirection(move)); oldCells.Push(currentCell); currentCell = nextCell; break; } else { List <Direction> tmpDirections = directions.ToList(); tmpDirections.Remove(move); directions = tmpDirections.ToArray(); } } if (directions.Length == 0) { if (oldCells.Count == 0) { break; } currentCell = oldCells.Pop(); } } }
public string SolveMaze() { MazeStack = new Stack <MazeCell>(); MazeCell exitCell = new MazeCell(); MazeCell entryCell = new MazeCell(); MazeCell currentCell = new MazeCell(); for (int y = 0; y < Maze.GetLength(0); y++) { for (int x = 0; x < Maze.GetLength(1); x++) { if (Maze[y, x] == 'm') { entryCell.Y = y; entryCell.X = x; currentCell.Y = y; currentCell.X = x; } else if (Maze[y, x] == 'e') { exitCell.Y = y; exitCell.X = x; } } } while (exitCell.X != currentCell.X || exitCell.Y != currentCell.Y) { if (Maze[currentCell.Y, currentCell.X] == '0') { Maze[currentCell.Y, currentCell.X] = '.'; } if (Maze[currentCell.Y - 1, currentCell.X] == '0' || Maze[currentCell.Y - 1, currentCell.X] == 'e') { MazeStack.Push(new MazeCell(currentCell.X, currentCell.Y - 1)); } if (Maze[currentCell.Y + 1, currentCell.X] == '0' || Maze[currentCell.Y + 1, currentCell.X] == 'e') { MazeStack.Push(new MazeCell(currentCell.X, currentCell.Y + 1)); } if (Maze[currentCell.Y, currentCell.X - 1] == '0' || Maze[currentCell.Y, currentCell.X - 1] == 'e') { MazeStack.Push(new MazeCell(currentCell.X - 1, currentCell.Y)); } if (Maze[currentCell.Y, currentCell.X + 1] == '0' || Maze[currentCell.Y, currentCell.X + 1] == 'e') { MazeStack.Push(new MazeCell(currentCell.X + 1, currentCell.Y)); } if (MazeStack.Count == 0) { return("The exit can't be reached!"); } else { currentCell = MazeStack.Pop(); } } return("The exit has been reached!"); }