Пример #1
0
    /*
     * //  Add a function to generate path which creates a list of nodes reachable within alloted moves for the selected piece
     * //
     */
    public void GeneratePathToPosition(int x, int y)
    {
        movePath          = null;
        selectedUnit.path = null;

        if (selectedUnit == null)
        {
            Debug.Log("Selected Unit was null");
            return;
        }
        if (selectedUnit.currentSpace == null)
        {
            Debug.Log("current space was null");
            return;
        }

        Dictionary <Spaces, float>  dist = new Dictionary <Spaces, float>();
        Dictionary <Spaces, Spaces> prev = new Dictionary <Spaces, Spaces>();
        List <Spaces> unvisited          = new List <Spaces>();

        Spaces source = selectedUnit.currentSpace;
        Spaces target = spacesGrid[x, y];


        dist[source] = 0;
        prev[source] = null;

        // Step 1 - Create a set of all nodes and mark them as unvisited and set the origin position to a dist cost of 0
        foreach (Spaces v in spacesGrid)
        {
            if (v != source)
            {
                dist[v] = Mathf.Infinity;
                prev[v] = null;
            }
            unvisited.Add(v);
        }


        while (unvisited.Count > 0)
        {
            // Sort the unvisited nodes by distance
            Spaces u = unvisited.OrderBy(n => dist[n]).First();

            if (u == target)
            {
                break;
            }

            unvisited.Remove(u);
            // Step 2 - Compare all unvisited nodes and calculate their costs and assign the smaller value
            foreach (Spaces v in u.edges)
            {
                float alt = dist[u] + u.DistanceToSpace(v);
                if (alt < dist[v])
                {
                    dist[v] = alt;
                    prev[v] = u;
                }
            }
        }

        if (prev[target] == null)
        {
            // no route found
            Debug.Log("No route Found");
            return;
        }
        movePath = new List <Spaces>();
        Spaces curr = target;

        while (curr != null)
        {
            movePath.Add(curr);
            curr = prev[curr];
        }

        movePath.Reverse();
        movePath.RemoveAt(0);
        selectedUnit.path = movePath;
        // Clean up
        dist.Clear();
        prev.Clear();
        unvisited.Clear();
    }