2014-09-01 37 views
0

我试图在简单的四向移动网格上围绕A Star Pathfinding构建AI,但每当我尝试将节点添加到比较中字典和排序它们在Dictionary.add上崩溃。我不完全确定为什么在这方面,任何人都可以发现缺陷?A *寻路AI在向节点排序的字典添加节点时冻结

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); 
      } 
     } 
    } 
} 

它一直下降到“CostOfNode”。这是有效的....然后当它试图添加到SortArray时它会中断。

+0

查看Eric Lippert的C#A-star here:http://blogs.msdn.com/b/ericlippert/archive/2007/10/10/path-finding-using-a-in-c-3 -0-part-four.aspx – 2014-09-01 03:04:53

回答

0

它在Dictionary.add上崩溃。我不完全确定为什么在这方面,任何人都可以发现缺陷?

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

如果CostOfNode为正被添加到词典中的两个不同节点的相同,第二个导致系统崩溃。

Dictionary.Add

的ArgumentException

具有相同键的元素已经存在于词典。

+0

这实际上可以解释它。什么是解决这个问题的最佳方法?我“认为”我可以通过使用节点序列号来避免这种情况 - 因为它们都是不同的 - 作为密钥,并以Cost为Value的值排序值。如果它们一样,我也可以消除一个键。 – Merlin 2014-09-01 03:12:05