Skip to content

Instantly share code, notes, and snippets.

@phosphoer
Created May 13, 2021 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phosphoer/205cc23da747709e237db5468acfcc36 to your computer and use it in GitHub Desktop.
Save phosphoer/205cc23da747709e237db5468acfcc36 to your computer and use it in GitHub Desktop.
Simple C# AStar
// The MIT License (MIT)
// Copyright (c) 2021 David Evans @phosphoer
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
public interface IAStarNode
{
float Cost { get; }
float DistanceToNode(IAStarNode destination);
IReadOnlyList<IAStarNode> AdjacentNodes { get; }
}
public class AStar
{
public enum State
{
InProgress,
Complete,
Failed
}
public IReadOnlyList<IAStarNode> CalculatedPath => calculatedPath;
public State CurrentState => currentState;
private IAStarNode startNode;
private IAStarNode goalNode;
private IAStarNode currentNode;
private State currentState;
private List<IAStarNode> openSet = new List<IAStarNode>();
private List<IAStarNode> closedSet = new List<IAStarNode>();
private List<IAStarNode> calculatedPath = new List<IAStarNode>();
private Dictionary<IAStarNode, IAStarNode> nodeClosestMap = new Dictionary<IAStarNode, IAStarNode>();
private Dictionary<IAStarNode, float> nodeTravelToCosts = new Dictionary<IAStarNode, float>();
private Dictionary<IAStarNode, float> nodeTravelThroughCosts = new Dictionary<IAStarNode, float>();
public void Initialize(IAStarNode beginNode, IAStarNode endNode)
{
currentState = State.InProgress;
startNode = beginNode;
goalNode = endNode;
currentNode = null;
openSet.Clear();
openSet.Add(startNode);
nodeTravelToCosts.Clear();
nodeTravelToCosts[startNode] = 0;
nodeTravelThroughCosts.Clear();
nodeTravelThroughCosts[startNode] = startNode.DistanceToNode(goalNode);
closedSet.Clear();
calculatedPath.Clear();
nodeClosestMap.Clear();
}
public State Step()
{
if (openSet.Count > 0)
{
currentNode = FindLowestCostNode(openSet);
if (currentNode == goalNode)
{
ReconstructPath();
currentState = State.Complete;
return State.Complete;
}
openSet.Remove(currentNode);
closedSet.Add(currentNode);
for (int i = 0; i < currentNode.AdjacentNodes.Count; ++i)
{
IAStarNode neighborNode = currentNode.AdjacentNodes[i];
if (closedSet.Contains(neighborNode))
{
continue;
}
float tentativeCost = GetNodeTravelToCost(currentNode) + currentNode.DistanceToNode(neighborNode);
if (!openSet.Contains(neighborNode))
{
openSet.Add(neighborNode);
}
else if (tentativeCost >= GetNodeTravelToCost(neighborNode))
{
continue;
}
nodeClosestMap[neighborNode] = currentNode;
nodeTravelToCosts[neighborNode] = tentativeCost;
nodeTravelThroughCosts[neighborNode] = tentativeCost + neighborNode.DistanceToNode(goalNode);
}
return State.InProgress;
}
currentState = State.Failed;
return State.Failed;
}
private void ReconstructPath()
{
calculatedPath.Clear();
calculatedPath.Add(currentNode);
IAStarNode node = currentNode;
while (node != startNode)
{
IAStarNode closestNode = nodeClosestMap[node];
calculatedPath.Insert(0, closestNode);
node = closestNode;
}
}
private IAStarNode FindLowestCostNode(IReadOnlyList<IAStarNode> nodes)
{
float minCost = int.MaxValue;
IAStarNode minCostNode = null;
for (int i = 0; i < nodes.Count; ++i)
{
float travelThroughCost = GetNodeTravelThroughCost(nodes[i]);
if (travelThroughCost < minCost)
{
minCost = travelThroughCost;
minCostNode = nodes[i];
}
}
return minCostNode;
}
private float GetNodeTravelThroughCost(IAStarNode node)
{
float cost;
if (nodeTravelThroughCosts.TryGetValue(node, out cost))
{
return cost;
}
return float.MaxValue;
}
private float GetNodeTravelToCost(IAStarNode node)
{
float cost;
if (nodeTravelToCosts.TryGetValue(node, out cost))
{
return cost;
}
return float.MaxValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment