2014-09-01 60 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