将节点添加到成本排序字典时,A * Pathfinding AI会冻结

时间:2014-09-01 02:35:34

标签: c# dictionary artificial-intelligence a-star

我尝试在简单的四向移动网格上构建基于A Star Pathfinding的AI,但每当我尝试将节点添加到比较字典中并对其进行排序时,它就会崩溃Dictionary.add。我不完全确定为什么会有人发现这个漏洞?

    void DirectionFinder()
{
    // Find Target Point //
    GetBoardPosition();
    BuildOrReBuildPawnRefBoard();
    bool IsTrue = false;
    int Serial = lastSquare.Location.Serial;
    // Get the Serial Keys of the nodes that are neighboring this node //
    bool TestNode = NodesClosed.ContainsKey(Serial);
    Dictionary<int, Node> SortArray = new Dictionary<int, Node>();
    SortArray.Clear();
    if (TestNode) 
    {
        Node ScanNode = NodesClosed[Serial];
        // Get the Number of Neighbors I have //
        int TestNumNeighbors = ScanNode.NeighborNodes.Count;
        // Set up a Loop that will go through these nodes and get the lowest-scored movement node //
        for (int loop = 0; loop < TestNumNeighbors; loop++)
        {
            int ScanNodePointX = ScanNode.NeighborNodes[loop].X;
            int ScanNodePointY = ScanNode.NeighborNodes[loop].Y;
            int ScanTestSerial = System_GameController.Instance.NodeArray[ScanNodePointX, ScanNodePointY].Location.Serial;
            bool IsNodeOpen = NodesOpen.ContainsKey(ScanTestSerial);
            if (IsNodeOpen)
            {
                Debug.Log("This Node is Open:" + ScanTestSerial);
                Node CompareNode = NodesOpen[ScanTestSerial];
                int CostOfNode = CompareNode.TotalCost;
                SortArray.Add(CostOfNode, CompareNode);
            }
        }
    }
}

它一直到#34; CostOfNode&#34;。这有效....然后当它试图添加到SortArray时会中断。

1 个答案:

答案 0 :(得分:0)

  

它在Dictionary.add上崩溃了。我不完全确定为什么会有人发现这个漏洞?

int CostOfNode = CompareNode.TotalCost;
SortArray.Add(CostOfNode, CompareNode);

如果CostOfNode对于添加到字典中的两个不同节点是相同的,则第二个节点会导致崩溃。

请参阅Dictionary.Add

  

<强>的ArgumentException

     

字典中已存在具有相同键的元素。