/// <summary> /// Initializes a new instance of the <see cref="AStarNode"/> class. /// </summary> /// <param name="graph">The <see cref="AStarGraph"/> to which this node belongs.</param> /// <param name="x">The x tile coordinate.</param> /// <param name="y">The y tile coordinate.</param> public AStarNode(AStarGraph graph, int x, int y) { this.graph = graph; this.X = x; this.Y = y; }
/// <summary> /// Initializes a new instance of the <see cref="AStarNode" /> class. /// </summary> /// <param name="graph"> /// The <see cref="AStarGraph" /> to which this node belongs. /// </param> /// <param name="x"> /// The x tile coordinate. /// </param> /// <param name="y"> /// The y tile coordinate. /// </param> public AStarNode(AStarGraph graph, int x, int y) { this.graph = graph; this.X = x; this.Y = y; this.GCost = int.MaxValue; }
/// <summary> /// Computes a path between the two specified nodes. /// </summary> /// <param name="startNode">The start node.</param> /// <param name="endNode">The end node.</param> /// <returns>A path from the start node to the end node.</returns> public AStarPath FindPath(AStarNode startNode, AStarNode endNode) { if (startNode is null || endNode is null) { return(null); } startNode.GCost = 0; startNode.HCost = AStarGraph.Heuristic(startNode, endNode); startNode.PreviousNode = null; // The set of discovered nodes that may need to be expanded. Initially, only the start // node is known. FastBinaryHeap <AStarNode> openSet = new FastBinaryHeap <AStarNode>(); openSet.Push(startNode); // The set of nodes already expanded. HashSet <AStarNode> closedSet = new HashSet <AStarNode>(); while (!openSet.IsEmpty()) { AStarNode currentNode = openSet.Pop(); if (currentNode == endNode) { return(new AStarPath(startNode, endNode)); } closedSet.Add(currentNode); foreach (AStarNode neighbour in currentNode.GetNeighbours()) { if (closedSet.Contains(neighbour)) { continue; } int gCost = currentNode.GCost + 1; bool visited = openSet.Contains(neighbour); if (gCost < neighbour.GCost || !visited) { // This path to neighbour is better than any previous one. Record it! neighbour.GCost = gCost; neighbour.HCost = AStarGraph.Heuristic(neighbour, endNode); neighbour.PreviousNode = currentNode; if (visited) { openSet.Heapify(neighbour); } else { openSet.Push(neighbour); } } } } // Open set is empty but goal was never reached. return(null); }