screeps_pathfinding/utils/
heuristics.rs

1use crate::common::traits::GetRangeTo;
2
3/// Helper function to create a heuristic cost function closure for a single goal node.
4///
5/// This heuristic cost is simply the range between the provided node and the goal node.
6///
7/// If using the convenience functions for common pathfinding use-cases,
8/// you will not normally need to use this function.
9///
10/// # Examples
11/// ```rust
12/// use screeps::RoomXY;
13/// use screeps_pathfinding::utils::goals::goal_exact_node;
14/// use screeps_pathfinding::utils::heuristics::heuristic_get_range_to;
15///
16/// let start = RoomXY::checked_new(24, 18).unwrap();
17/// let goal = RoomXY::checked_new(34, 40).unwrap();
18/// let cost_fn = |_| Some(1);
19/// screeps_pathfinding::algorithms::astar::shortest_path_roomxy(
20///     start,
21///     &goal_exact_node(goal),
22///     cost_fn,
23///     &heuristic_get_range_to(goal),
24/// );
25pub fn heuristic_get_range_to<T: GetRangeTo + Copy + 'static>(goal: T) -> impl Fn(T) -> u32 {
26    move |node: T| node.get_range_to(goal)
27}
28
29/// Helper function to create a heuristic cost function closure for multiple goal nodes.
30///
31/// This heuristic cost is simply the minimum range between the provided node and each of the goal nodes.
32///
33/// If using the convenience functions for common pathfinding use-cases,
34/// you will not normally need to use this function.
35///
36/// # Examples
37/// ```rust
38/// use screeps::RoomXY;
39/// use screeps_pathfinding::utils::goals::goal_exact_node_multigoal;
40/// use screeps_pathfinding::utils::heuristics::heuristic_get_range_to_multigoal;
41///
42/// let start = RoomXY::checked_new(24, 18).unwrap();
43/// let goal_a = RoomXY::checked_new(34, 40).unwrap();
44/// let goal_b = RoomXY::checked_new(34, 45).unwrap();
45/// let goals = &[goal_a, goal_b];
46/// let cost_fn = |_| Some(1);
47/// screeps_pathfinding::algorithms::astar::shortest_path_roomxy(
48///     start,
49///     &goal_exact_node_multigoal(goals),
50///     cost_fn,
51///     &heuristic_get_range_to_multigoal(goals),
52/// );
53pub fn heuristic_get_range_to_multigoal<T: GetRangeTo + Copy>(
54    goals: &[T],
55) -> impl Fn(T) -> u32 + '_ {
56    |node: T| {
57        goals
58            .iter()
59            .map(|g| node.get_range_to(*g))
60            .min()
61            .unwrap_or(0)
62    }
63}