Update
This commit is contained in:
69
Assets/Scripts/GameSetup/Maze/RecursiveAlgorithm.cs
Normal file
69
Assets/Scripts/GameSetup/Maze/RecursiveAlgorithm.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using Hallucinate.GameSetup.Maze.Extensions;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Hallucinate.GameSetup.Maze
|
||||
{
|
||||
public class RecursiveAlgorithm : IMazeAlgorithm
|
||||
{
|
||||
private const int StartX = 5;
|
||||
private const int StartZ = 5;
|
||||
private const int DeadEndNeighbourThreshold = 2;
|
||||
|
||||
private readonly List<MapLocation> _directions = MapLocation.Directions;
|
||||
|
||||
public void Generate(MazeGrid grid)
|
||||
{
|
||||
GenerateRecursive(grid, StartX, StartZ);
|
||||
}
|
||||
|
||||
public IEnumerator GenerateStepByStep(MazeGrid grid, float interval)
|
||||
{
|
||||
yield return GenerateRecursiveStepByStep(grid, StartX, StartZ, interval);
|
||||
}
|
||||
|
||||
private void GenerateRecursive(MazeGrid grid, int x, int z)
|
||||
{
|
||||
if (grid.CountSquareNeighbours(x, z, MazeCellType.Corridor) >= DeadEndNeighbourThreshold) return;
|
||||
|
||||
grid.SetCell(x, z, MazeCellType.Corridor);
|
||||
|
||||
List<MapLocation> shuffledDirs = new List<MapLocation>(_directions);
|
||||
shuffledDirs.Shuffle();
|
||||
|
||||
foreach (var dir in shuffledDirs)
|
||||
{
|
||||
int nx = x + dir.x;
|
||||
int nz = z + dir.z;
|
||||
if (grid.IsInBounds(nx, nz))
|
||||
{
|
||||
GenerateRecursive(grid, nx, nz);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerator GenerateRecursiveStepByStep(MazeGrid grid, int x, int z, float interval)
|
||||
{
|
||||
if (grid.CountSquareNeighbours(x, z, MazeCellType.Corridor) >= DeadEndNeighbourThreshold) yield break;
|
||||
|
||||
grid.SetCell(x, z, MazeCellType.Processing);
|
||||
if (interval > 0) yield return new WaitForSeconds(interval);
|
||||
|
||||
grid.SetCell(x, z, MazeCellType.Corridor);
|
||||
|
||||
List<MapLocation> shuffledDirs = new List<MapLocation>(_directions);
|
||||
shuffledDirs.Shuffle();
|
||||
|
||||
foreach (var dir in shuffledDirs)
|
||||
{
|
||||
int nx = x + dir.x;
|
||||
int nz = z + dir.z;
|
||||
if (grid.IsInBounds(nx, nz))
|
||||
{
|
||||
yield return GenerateRecursiveStepByStep(grid, nx, nz, interval);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user