Skip to content

Commit d218e7f

Browse files
committed
Added options to use the closest position to find a path when the end can't be reached.
1 parent 186d565 commit d218e7f

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

AStar/Options/PathFinderOptions.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ public class PathFinderOptions
1212

1313
public int SearchLimit { get; set; }
1414

15+
public bool ClosestNodeWhenCantReach { get; set; }
16+
1517
public PathFinderOptions()
1618
{
1719
HeuristicFormula = HeuristicFormula.Manhattan;

AStar/PathFinder.cs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ public Position[] FindPath(Position start, Position end)
3636
{
3737
var nodesVisited = 0;
3838
IModelAGraph<PathFinderNode> graph = new PathFinderGraph(_world.Height, _world.Width, _options.UseDiagonals);
39+
var lowestNode = start;
40+
var lowestNodeDist = int.MaxValue;
3941

4042
var startNode = new PathFinderNode(position: start, g: 0, h: 2, parentNodePosition: start);
4143
graph.OpenNode(startNode);
@@ -62,6 +64,13 @@ public Position[] FindPath(Position start, Position end)
6264
}
6365

6466
var newG = q.G + DistanceBetweenNodes;
67+
var distanceBetweenSuccessorAndEnd = this.CalculateDistance(q.Position, end);
68+
69+
if (distanceBetweenSuccessorAndEnd < lowestNodeDist)
70+
{
71+
lowestNode = q.Position;
72+
lowestNodeDist = distanceBetweenSuccessorAndEnd;
73+
}
6574

6675
if (_options.PunishChangeDirection)
6776
{
@@ -72,7 +81,7 @@ public Position[] FindPath(Position start, Position end)
7281
{
7382
if (qIsHorizontallyAdjacent)
7483
{
75-
newG += Math.Abs(successor.Position.Row - end.Row) + Math.Abs(successor.Position.Column - end.Column);
84+
newG += this.CalculateDistance(successor.Position, end);
7685
}
7786
}
7887

@@ -81,7 +90,7 @@ public Position[] FindPath(Position start, Position end)
8190
{
8291
if (!qIsHorizontallyAdjacent)
8392
{
84-
newG += Math.Abs(successor.Position.Row - end.Row) + Math.Abs(successor.Position.Column - end.Column);
93+
newG += this.CalculateDistance(successor.Position, end);
8594
}
8695
}
8796
}
@@ -101,9 +110,19 @@ public Position[] FindPath(Position start, Position end)
101110
nodesVisited++;
102111
}
103112

113+
if (_options.ClosestNodeWhenCantReach && lowestNode != start)
114+
{
115+
return this.FindPath(start, lowestNode);
116+
}
117+
104118
return new Position[0];
105119
}
106120

121+
private int CalculateDistance(Position currentNode, Position endNode)
122+
{
123+
return Math.Abs(currentNode.Row - endNode.Row) + Math.Abs(currentNode.Column - endNode.Column);
124+
}
125+
107126
private bool BetterPathToSuccessorFound(PathFinderNode updateSuccessor, PathFinderNode currentSuccessor)
108127
{
109128
return !currentSuccessor.HasBeenVisited ||

0 commit comments

Comments
 (0)