The AStar library implements the classic A* path-finding algorithm. It uses a min priority queue for managing potential paths, ordered by each
path's known and estimated cost. The AStar class delegates map-related functionality to a MapOracle
protocol to determine valid positions
as well as the cost of using a position. Example of a MapOracle
can be found in the AStarTests.swift
file.
The AStar API is very basic. There is just the static find
method. Here is an example of it being used:
let mapData = MapData(data: [
[.π, .π², .π², .π², .π², .π², .π², .π²],
[.π, .π², .π², .π², .π², .π², .π², .π²],
[.π², .π², .π², .π², .π», .π², .π², .π²],
[.π², .π², .π», .π», .π», .π», .π», .π²],
[.π², .π², .π», .π², .π², .π», .π, .π],
[.π², .π², .π», .π², .π», .π², .π², .π],
[.π, .π², .π», .π², .π², .π², .π», .π»],
[.π, .π², .π², .π², .π², .π², .π», .π²]
])
let start = Coord2D(x: 4, y: 0)
let end = Coord2D(x: 4, y: 4)
func distanceToEnd(position: Coord2D) -> Int { abs(position.x - end.x) + abs(position.y - end.y) }
let path = AStar.find(mapOracle: mapOracle, considerDiagonalPaths: true,
heuristicCostCalulator: distancToEnd,
start: start, end: end)
You supply something that implements the MapOracle
protocol like the MapData
above. You decide if diagonal paths are acceptable,
and provide a way to estimate the cost of moving from a given point on the map to the end point (the heuristic cost). The start and end
points complete the find
request.
You get back an optional array of Coord2D
values. If nil
then there was no path to be found. Otherwise, the array will have the map
coordinates of the path that was found, starting at start
and ending with end
.
Here is the visual representation of the map with the found path. The starting position appears as a red flag (π©) and the end position is a checkered flag (π). The path in between these two points contains an adventurer (π).
let image = mapData.asString(path: path!)
print(image)
ππ²π²π²π©π²π²π²
ππ²π²π²π²ππ²π²
π²π²π²π²π»π²ππ²
π²π²π»π»π»π»π»π
π²π²π»π²ππ»ππ
π²π²π»π²π»ππ²π
ππ²π»π²π²π²π»π»
ππ²π²π²π²π²π»π²
The map contains three different terrain elements, each with their own cost for travelling into their square:
- π² tree (1)
- π water (2)
- π» boulder (β)
The algorithm minimizes the cost of traveling over terrain elements while at the same time trying to keep to the shortest path to the goal. For comparison, here is what the algorithm found when constrained to not use diagonal moves:
ππ²π²π²π©π²π²π²
ππ²π²πππ²π²π²
π²ππππ»π²π²π²
π²ππ»π»π»π»π»π²
π²ππ»πππ»ππ
π²ππ»ππ»π²π²π
πππ»ππ²π²π»π»
πππππ²π²π»π²
There is another path to the right that is also 16 moves, but it goes over two π positions which increases the total cost of the trip by 2. Thus the algorithm chose the one shown above.