コード例 #1
0
    //prims maze generation algorithm
    public maze generate()
    {
        maze dungeon = new maze(mazeLength);
        //Prim's maze generator algorithm
        List <cell>  toBeVisited = new List <cell>();
        List <short> choices     = new List <short>();

        toBeVisited.Add(dungeon.getCells()[0][0]);
        while (toBeVisited.Count != 0)
        {
            //select randomly
            cell selected = toBeVisited[Random.Range(0, toBeVisited.Count)];
            selected.visited = true;
            //find choices
            if (selected.getC_x() != 0 && selected.getNeighbours()[directions.north].visited)
            {
                choices.Add(directions.north);
            }
            if (selected.getC_y() != dungeon.getMaze_length() - 1 && selected.getNeighbours()[directions.east].visited)
            {
                choices.Add(directions.east);
            }
            if (selected.getC_x() != dungeon.getMaze_length() - 1 && selected.getNeighbours()[directions.south].visited)
            {
                choices.Add(directions.south);
            }
            if (selected.getC_y() != 0 && selected.getNeighbours()[directions.west].visited)
            {
                choices.Add(directions.west);
            }
            //choose where selected will be connected
            if (choices.Count > 0)
            {
                cell toWhere = selected.getNeighbours()[choices[Random.Range(0, choices.Count)]];
                dungeon.createPassage(selected.getC_x(), selected.getC_y(), toWhere.getC_x(), toWhere.getC_y());
            }
            //add unvisited nodes
            if (selected.getC_x() != 0 && !selected.getNeighbours()[directions.north].visited)
            {
                toBeVisited.Add(selected.getNeighbours()[directions.north]);
            }
            if (selected.getC_y() != dungeon.getMaze_length() - 1 && !selected.getNeighbours()[directions.east].visited)
            {
                toBeVisited.Add(selected.getNeighbours()[directions.east]);
            }
            if (selected.getC_x() != dungeon.getMaze_length() - 1 && !selected.getNeighbours()[directions.south].visited)
            {
                toBeVisited.Add(selected.getNeighbours()[directions.south]);
            }
            ;
            if (selected.getC_y() != 0 && !selected.getNeighbours()[directions.west].visited)
            {
                toBeVisited.Add(selected.getNeighbours()[directions.west]);
            }
            choices.Clear();
            toBeVisited.Remove(selected);
        }
        //Remove unreachable neighbours
        for (int i = 0; i < mazeLength; i++)
        {
            for (int j = 0; j < mazeLength; j++)
            {
                dungeon.getCells()[i][j].fix_neighbours();
            }
        }

        return(dungeon);
    }