# gwg_pathfinding
[](https://hex.pm/packages/gwg_pathfinding)
[](https://hexdocs.pm/gwg_pathfinding/)
This is a generic searching/pathfinding algorithm library for the [Gleam programming language](https://gleam.run).
## Installation
```sh
gleam add gwg_pathfinding
```
```gleam
import gleam/bool
import gleam/dict
import gleam/float
import gleam/list
import gwg/pathfinding.{Action}
import vec/dict/vec2i_dict
import vec/vec2.{Vec2}
import vec/vec2i.{type Vec2i}
pub fn main() {
let actions = [
Vec2(-1, 0),
Vec2(1, 0),
Vec2(0, -1),
Vec2(0, 1),
Vec2(-1, -1),
Vec2(-1, 1),
Vec2(1, -1),
Vec2(1, 1),
]
let world =
vec2i_dict.from_string(
""
<> "###########\n"
<> "# # #\n"
<> "# # #\n"
<> "# # #\n"
<> "# ## ####\n"
<> "# # #\n"
<> "# # #\n"
<> "## ##### ##\n"
<> "# # # #\n"
<> "# #\n"
<> "###########\n",
)
let init = Vec2(2, 2)
let target = Vec2(7, 2)
pathfinding.astar(
init:,
successor: fn(state, g_score) {
actions
|> list.filter_map(fn(action) {
let weight = action |> vec2i.length
use <- bool.guard(g_score +. weight >. 32.0, Error(Nil))
let state = state |> vec2i.add(action)
case world |> dict.has_key(state) {
True -> Error(Nil)
False -> Ok(Action(action:, state:, weight:))
}
})
},
heuristic: fn(state: Vec2i) -> Float { vec2i.distance(state, target) },
)
// ###########
// # # #
// # @ # * #
// # ↓ # ↗ #
// # ↓ ##↑####
// # ↓ # ↖ #
// # ↓ # ↖ #
// ##↘#####↑##
// # ↘# #↗ #
// # →→↗ #
// ###########
}
```
Further documentation can be found at <https://hexdocs.pm/gwg_pathfinding>.