Search code examples
c#dictionaryartificial-intelligencea-star

A* Pathfinding AI is freezing when adding nodes to a cost-sorted dictionary


I'm trying to build an AI based around A Star Pathfinding on a simple four-direction movement grid, however whenever I try to add nodes into a comparison dictionary and sort them, it's crashing on the Dictionary.add. I'm not entirely sure why on this, can anyone spot the flaw?

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

It gets all the way down to "CostOfNode". That works.... and then it breaks when it tries to add to SortArray.


Solution

  • it's crashing on the Dictionary.add. I'm not entirely sure why on this, can anyone spot the flaw?

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

    If CostOfNode is the same for two different nodes which are being added to the dictionary, the second one causes a crash.

    See Dictionary.Add:

    ArgumentException

    An element with the same key already exists in the Dictionary.