Files
BABA_YAGA/Assets/Scripts/GameSetup/Maze/RecursiveAlgorithm.cs

70 lines
2.2 KiB
C#
Raw Normal View History

2026-04-21 23:28:49 +07:00
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);
}
}
}
}
}