Exemple #1
0
        private List <Node> AStar(Node start, Node target)
        {
            List <Node> path = new List <Node>();

            List <Node>    openSet   = new List <Node>();
            HashSet <Node> closedSet = new HashSet <Node>();

            openSet.Add(start);

            while (openSet.Count > 0)
            {
                Node current = openSet[0];

                for (int i = 0; i < openSet.Count; i++)
                {
                    if (openSet[i].fCost < current.fCost ||
                        (openSet[i].fCost == current.fCost &&
                         openSet[i].hCost < current.hCost))
                    {
                        if (!current.Equals(openSet[i]))
                        {
                            current = openSet[i];
                        }
                    }
                }

                openSet.Remove(current);
                closedSet.Add(current);

                if (current.Equals(target))
                {
                    return(Backtrace(start, current));
                }

                foreach (Node neighbour in _gridGenerator.GetNeighbours(current))
                {
                    if (neighbour.obstructed || closedSet.Contains(neighbour))
                    {
                        continue;
                    }

                    float moveCost = current.gCost + GetDistance(current, neighbour);
                    if (moveCost < neighbour.gCost || !openSet.Contains(neighbour))
                    {
                        neighbour.gCost  = moveCost;
                        neighbour.hCost  = GetDistance(neighbour, target);
                        neighbour.parent = current;

                        if (!openSet.Contains(neighbour))
                        {
                            openSet.Add(neighbour);
                        }
                    }
                }
            }

            return(null);
        }