public Maze BuildMaze(MazeSize size) { Maze maze = new Maze(size); List <MazeWall> mazeWalls = new List <MazeWall>(); MazeCell current = new MazeCell() { X = 0, Y = Utlity.GetRandom(maze.Size - 1, DateTime.Now.Millisecond) }; maze.StartPoint = current; maze[current] = 1; mazeWalls.AddRange(GetCellWalls(current)); int i = 0; while (mazeWalls.Any()) { int count = mazeWalls.Count; int nextIndex = Utlity.GetRandom(count - 1, count * count + i * (i++));; //if (!mazeWalls.Exists(mw=>mw.Cell.X != current.X || mw.Cell.Y != current.Y)) //{ // nextIndex = Utlity.GetRandom(count - 1, count * count + i * (i++)); //}else //{ // nextIndex = mazeWalls.FindIndex(mw => mw.Cell.X != current.X || mw.Cell.Y != current.Y); //} var currentCell = mazeWalls[nextIndex].Cell; var neighborCell = GetNeighborCell(mazeWalls[nextIndex], maze.Size); if (neighborCell.HasValue) { var cell = neighborCell.Value; if (maze[cell] == 0) { mazeWalls.AddRange(GetCellWalls(cell, mazeWalls[nextIndex].Wall)); maze[cell] = 1; maze.AddPassage(currentCell, cell); //mazeWalls.RemoveAll(wall => { return wall.Cell.X == currentCell.X && wall.Cell.Y == currentCell.Y; }); } mazeWalls.RemoveAt(nextIndex); } else { mazeWalls.RemoveAt(nextIndex); } } //for (i = 0; i < maze.Size; i++) //{ // for (int j = 0; j < maze.Size; j++) // { // Console.Write(maze[i, j]); // Console.Write(" "); // } // Console.Write("\r\n"); //} return(maze); }
public Maze BuildMaze(MazeSize size) { Maze maze = new Maze(size); var mazeStack = new Stack <MazeCell>(); MazeCell current = new MazeCell() { X = 0, Y = Utlity.GetRandom(maze.Size - 1, DateTime.Now.Millisecond) }; maze.StartPoint = current; int step = 1; maze[current] = step++; mazeStack.Push(current); while (mazeStack.Count > 0) { var neighbors = maze.GetNeighbors(current); if (neighbors != null && neighbors.Count > 0) { mazeStack.Push(current); step = maze[current]; var start = current; current = neighbors[Utlity.GetRandom(neighbors.Count, current.X * current.X + current.Y * current.Y)]; maze[current] = 1; mazeStack.Push(current); maze.AddPassage(start, current); } else { current = mazeStack.Pop(); } } //for (int i = 0; i < maze.Size; i++) //{ // for (int j = 0; j < maze.Size; j++) // { // Console.Write(maze[i, j]); // Console.Write(" "); // } // Console.Write("\r\n"); //} return(maze); }