Example #1
0
    /// <summary>
    /// Generate the maze by randomly creating paths with cells.
    /// </summary>
    /// <returns></returns>
    public IEnumerator Generate(int seed)
    {
        randomGenerator = new System.Random(seed);
        cells           = new MazeCell[Size.x, Size.z];
        // Will contain the added cells in order
        List <MazeCell> activeCells = new List <MazeCell>();

        DoFirstGenerationStep(activeCells);
        while (activeCells.Count > 0)
        {
            if (GenerationStepDelay > 0)
            {
                yield return(new WaitForSeconds(GenerationStepDelay));
            }
            DoNextGenerationStep(activeCells);
        }
        // Add fractals
        int             count          = randomGenerator.Next(0, NumberFractals);
        List <MazeCell> freeEdgesCells = new List <MazeCell>();

        for (int x = 0; x < Size.x; x++)
        {
            for (int y = 0; y < Size.z; y++)
            {
                IntVector2 coordinates = new IntVector2(x, y);
                MazeCell   cell        = GetCell(coordinates);
                if (cell != null && cell.HasFreeCellEdges())
                {
                    freeEdgesCells.Add(cell);
                }
            }
        }
        for (int i = 0; i < count; i++)
        {
            if (freeEdgesCells.Count == 0)
            {
                break;
            }
            int      index   = randomGenerator.Next(0, freeEdgesCells.Count);
            MazeCell newCell = Instantiate(FractalPrefabs[randomGenerator.Next(0, FractalPrefabs.Length)]) as MazeCell;
            newCell.transform.position      = freeEdgesCells[index].transform.position;
            newCell.transform.parent        = transform;
            newCell.transform.localRotation = Quaternion.identity;
            freeEdgesCells.RemoveAt(index);
        }
    }