public void Reset()
 {
     _grid.Initialize();
 }
Ejemplo n.º 2
0
    public void GenerateMaze()
    {
        grid = new Cell[width, height];
        grid.Initialize();
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                grid[x, y] = new Cell();
                grid[x, y].gridPosition = new Vector2Int(x, y);
                grid[x, y].walls        = Wall.DOWN | Wall.LEFT | Wall.RIGHT | Wall.UP;
            }
        }

        Stack <Cell> cellStack    = new Stack <Cell>();
        List <Cell>  visitedCells = new List <Cell>();

        cellStack.Push(grid[0, 0]);
        Cell currentCell;

        while (cellStack.Count > 0)
        {
            currentCell = cellStack.Pop();
            List <Cell> neighbours = GetUnvisitedNeighbours(currentCell, visitedCells, cellStack);
            if (neighbours.Count > 1)
            {
                cellStack.Push(currentCell);
            }

            if (neighbours.Count != 0)
            {
                Cell randomUnvisitedNeighbour = neighbours[Random.Range(0, neighbours.Count)];
                RemoveWallBetweenCells(currentCell, randomUnvisitedNeighbour);
                visitedCells.Add(randomUnvisitedNeighbour);
                cellStack.Push(randomUnvisitedNeighbour);
            }
        }

        //Remove a couple random walls to make the maze more 'open'
        int   totalWallsInMaze         = GetWallCount(grid);
        int   totalPossibleWallsInmaze = 4 * width * height;
        float wallPercentage           = totalWallsInMaze / (float)totalPossibleWallsInmaze;

        //Debug.Log("Wall Percentage: " + wallPercentage);
        while (wallPercentage > desiredWallpercentage)
        {
            int         randomX    = Random.Range(0, width);
            int         randomY    = Random.Range(0, height);
            Cell        randomCell = grid[randomX, randomY];
            List <Cell> neighbours = GetNeighbours(randomCell);
            if (neighbours.Count > 0)
            {
                Cell randomNeighbour = neighbours[Random.Range(0, neighbours.Count)];
                bool wallsRemoved    = RemoveWallBetweenCells(randomCell, randomNeighbour);
                if (wallsRemoved)
                {
                    totalWallsInMaze -= 2;
                    wallPercentage    = totalWallsInMaze / (float)totalPossibleWallsInmaze;
                }
            }
        }

        //Generate Objects
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                CellPrefab cellObject = Instantiate(cellPrefab, new Vector3(x * scaleFactor, 0, y * scaleFactor), Quaternion.identity, transform);
                cellObject.transform.localScale = new Vector3(scaleFactor, scaleFactor, scaleFactor);
                cellObject.SpawnWalls(grid[x, y]);
                allCellObjects.Add(cellObject.gameObject);
            }
        }
    }