Exemplo n.º 1
0
    public IEnumerator SolveCoroutine(Graph graph, NodeComponent start, NodeComponent goal)
    {
        var unvisited = new List <NodeComponent>(graph.Nodes);

        if (unvisited.Count == 0)
        {
            yield break;
        }
        //Initializing open data structure
        //Using a proerty of nodeInfo we don't need a close list, avoiding searching
        var open = new List <NodeComponent>();

        //Every node will start with an infinity cost except the start node
        foreach (var node in unvisited)
        {
            bool isStart = node == start;
            node.NodeInfo = new HeuristicNodeInfo(null,
                                                  isStart ? heuristicFuncDict[heuristicType](start, goal) : Mathf.Infinity,
                                                  isStart ? 0 : Mathf.Infinity);
        }
        //The iteration begins
        NodeComponent currentNode = null;

        start.NodeInfo.category = Category.Open;
        open.Add(start);
        while (open.Count > 0)
        {
            currentNode = GetMinNode(open);
            currentNode.MarkAsCurrent();
            yield return(new WaitForSeconds(timeToWait));

            //If it is the goal node, then terminate - following the book algorithm
            if (currentNode == goal)
            {
                break;
            }
            //Otherwise, gets its ungoing connection
            foreach (var connection in graph.GetConnections(currentNode))
            {
                ProcessConnection(goal, open, currentNode, connection);
            }
            yield return(new WaitForSeconds(timeToWait));

            //We've finished looking at the connections for the current node, so add it to the closed list
            //and remove it from the open list
            var currNodeInfo = currentNode.NodeInfo;
            currNodeInfo.category = Category.Closed;
            currentNode.NodeInfo  = currNodeInfo;
            open.Remove(currentNode);
            yield return(new WaitForSeconds(timeToWait));
        }
        //We've here if we've either found a goal, or if we've no more nodes to search, find which
        if (currentNode == goal)
        {
            CalculatePath(start, currentNode);
        }
    }