-1

我试图构建一个 Pathfinding A* 代码,但不断收到数组索引错误。我试过用 x 和 y 进行调整,但到目前为止还没有运气。这是代码。

public int columns = 9;                                                      //Columns and rows to set up the board
public int rows = 9;                                                //This number are the usable tiles, the complete board is 11 by 11
                                                                    //With a border of 1 tile

public Node[,] graph;

//Class Node
public class Node
{
    public List<Node> neighbours;                                                   //List of all the neighbours nodes (4Directions)

    public Node()
    {
        neighbours = new List<Node>();
    }
}

//Sets up the outer walls and floor (background) of the game board.
void BoardSetup()
{
    for (int x = -1; x < columns + 1; x++)
    {
        for (int y = -1; y < rows + 1; y++)
        {
            Edited out Code, don't think has anything to do with my problem.
        }
    }
}

//Creates the graph to use Pathfinding
void GeneratePathfindingGraph()
{
    //Create graph
    graph = new Node[columns, rows];

    for (int x = -1; x < columns + 1; x++)
    {
        for (int y = -1; y < rows + 1; y++)
        {

            graph[x, y] = new Node();

            Add the 4 cardinal adjacent tiles
            if (x != - 1)
                graph[x, y].neighbours.Add(graph[x - 1, y]);      
            if (x != columns - 1)
                graph[x, y].neighbours.Add(graph[x + 1, y]);       //Where I am getting the error
            if (y != - 1)
                graph[x, y].neighbours.Add(graph[x, y - 1]);
            if (y != rows - 1)
                graph[x, y].neighbours.Add(graph[x, y + 1]);
        }
    }
}

//SetupScene initializes our level and calls the previous functions to lay out the game board
public void SetupScene(int level)
{
    //Creates the outer walls and floor.
    BoardSetup();

    //Creates the Node map to use Pathfinding
    GeneratePathfindingGraph();
}

}

我已经编辑掉了这个类的大部分代码,我认为它与问题没有太大关系。

4

1 回答 1

1

您能否将循环中的所有初始化更改x = -1;x = 0; 数组总是以零开头。

于 2017-05-31T06:20:22.893 回答