Files
BABA_YAGA/Assets/Scripts/GameSetup/Maze/CrawlerAlgorithm.cs
2026-04-22 00:29:09 +07:00

78 lines
2.5 KiB
C#

using System.Collections;
using UnityEngine;
namespace Hallucinate.GameSetup.Maze
{
public class CrawlerAlgorithm : IMazeAlgorithm
{
private const int CrawlChance = 50;
private const int MinBoundary = 1;
private const int VerticalCrawlerCount = 3;
private const int HorizontalCrawlerCount = 3;
public void Generate(MazeGrid grid)
{
for (int i = 0; i < VerticalCrawlerCount; i++) CrawlV(grid, 0);
for (int i = 0; i < HorizontalCrawlerCount; i++) CrawlH(grid, 0);
}
public IEnumerator GenerateStepByStep(MazeGrid grid, float interval)
{
for (int i = 0; i < VerticalCrawlerCount; i++) yield return CrawlV(grid, interval);
for (int i = 0; i < HorizontalCrawlerCount; i++) yield return CrawlH(grid, interval);
}
private IEnumerator CrawlV(MazeGrid grid, float interval)
{
bool done = false;
int x = Random.Range(MinBoundary, grid.Width - MinBoundary);
int z = MinBoundary;
while (!done)
{
grid.SetCell(x, z, MazeCellType.Processing);
if (interval > 0) yield return new WaitForSeconds(interval);
grid.SetCell(x, z, MazeCellType.Corridor);
if (Random.Range(0, 100) < CrawlChance)
{
x += Random.Range(-1, 2);
}
else
{
z += Random.Range(0, 2);
}
done |= (x < MinBoundary || x >= grid.Width - MinBoundary || z < MinBoundary || z >= grid.Depth - MinBoundary);
}
}
private IEnumerator CrawlH(MazeGrid grid, float interval)
{
bool done = false;
int x = MinBoundary;
int z = Random.Range(MinBoundary, grid.Depth - MinBoundary);
while (!done)
{
grid.SetCell(x, z, MazeCellType.Processing);
if (interval > 0) yield return new WaitForSeconds(interval);
grid.SetCell(x, z, MazeCellType.Corridor);
if (Random.Range(0, 100) < CrawlChance)
{
x += Random.Range(0, 2);
}
else
{
z += Random.Range(-1, 2);
}
done |= (x < MinBoundary || x >= grid.Width - MinBoundary || z < MinBoundary || z >= grid.Depth - MinBoundary);
}
}
}
}