From 5811e5385554c7f9dfbd5570d4038f3bc1e9a7d9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 16:59:29 -0800 Subject: [PATCH 1/2] Pokemon Navigation: robust leg planner and route scorer The robust leg planner (a24eaee8e) and the route scorer (8b3a21ee6), with their tests, as bdsp/rebuild-base carries them. Both are game-agnostic and only need the tile grid; the BDSP rebuild chain uses them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 4 + .../Navigation/Pokemon_RobustLegPlanner.h | 571 ++++++++++++++++++ .../Pokemon_RobustLegPlanner_Tests.cpp | 370 ++++++++++++ .../Pokemon_RobustLegPlanner_Tests.h | 23 + .../Navigation/Pokemon_RouteScorer.cpp | 504 ++++++++++++++++ .../Pokemon/Navigation/Pokemon_RouteScorer.h | 150 +++++ .../Navigation/Pokemon_RouteScorer_Tests.cpp | 382 ++++++++++++ .../Navigation/Pokemon_RouteScorer_Tests.h | 23 + SerialPrograms/cmake/SourceFiles.cmake | 7 + 9 files changed, 2034 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index c3e8fdc685..34dc9f9643 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -36,9 +36,11 @@ #include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" #include "Pokemon/Navigation/Pokemon_LegPlanner_Tests.h" +#include "Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h" #include "Pokemon/Navigation/Pokemon_LegWalker_Tests.h" #include "Pokemon/Navigation/Pokemon_MapData_Tests.h" #include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" +#include "Pokemon/Navigation/Pokemon_RouteScorer_Tests.h" #include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" #include "Pokemon/Navigation/Pokemon_WallRecovery_Tests.h" #include "VideoGames/PokemonHome/PokemonHome_Tests.h" @@ -80,11 +82,13 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ OCR::add_tests(ret); Kernels::add_tests(ret); Pokemon::add_tests_LegPlanner(ret); + Pokemon::add_tests_RobustLegPlanner(ret); Pokemon::add_tests_LegWalker(ret); Pokemon::add_tests_WallRecovery(ret); Pokemon::add_tests_MapData(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); + Pokemon::add_tests_RouteScorer(ret); Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h new file mode 100644 index 0000000000..0f36ff63fe --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h @@ -0,0 +1,571 @@ +/* Robust Leg Planner + * + * From: https://github.com/PokemonAutomation/ + * + * Plans walks whose open legs may go a tile short or long. A leg to a wall + * is walked until the player stops; an open leg is walked for its tiles' + * worth of time and may end a few tiles either way. The planner searches + * over the sets of places the player may stand on after each leg, and + * later walls bring them back together, so the plan reaches the goal from + * every place the player may be. + * + * A step model is a class with: + * + * using State = ...; // where the player is: comparable with == + * using StateLess = ...; // a strict order of State, for sets of them: + * // std::less for TilePos and MapPlace + * std::optional step(const State& state, Direction direction) const; + * size_t step_tiles(const State& from, const State& to) const; + * bool held_at(const State& state, Direction direction) const; + * bool wild(const State& state) const; + * bool wander(const State& state) const; + * + * step() is where one step `direction` lands, or nothing if the player is + * stopped. step_tiles() is how many tiles that step counts (a ledge hop + * counts 2). held_at() is whether the player, stopped, stays put however + * long the button is held (a wall); a stop that isn't held (a door, an exit + * off the maps) makes a leg the planner can't tell the end of, and it is + * not used. wild() is a place where a wild battle may stop the walk (tall + * grass); wander() one where someone wanders. + * + * Warps and game actions (doors, Surf, spin tiles) are not legs: a stop + * that isn't held is never used, so a plan never crosses a warp. Callers + * plan each stretch between warps on its own. The step model here and the + * one of Pokemon_LegPlanner.h (press(), Step) describe the same + * world rules for two planners; a game writes one adapter for each. + * + */ + +#ifndef PokemonAutomation_Pokemon_RobustLegPlanner_H +#define PokemonAutomation_Pokemon_RobustLegPlanner_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A leg of a robust plan: walk `direction` for `tiles` tiles, or until +// stopped if `to_wall`. `after` lists every place the player may stand on +// once the leg is done. +template +struct RobustLeg{ + Direction direction = Direction::NORTH; + size_t tiles = 0; // tiles travelled; a ledge hop counts 2 + bool to_wall = false; + std::vector after; + // An open leg held for its tiles' time instead of tapped a tile at a + // time (RobustLegCosts::hold_open_legs). A held leg is never joined + // with the next one the same way: each is its own hold. + bool held = false; +}; + + +// The weights of a robust plan and the limits of its search. +struct RobustLegCosts{ + int per_tile = 1; + int per_wild_tile = 4; // extra for each wild tile entered + int per_wander_tile = 3; // extra for each tile entered where someone wanders + int per_leg = 8; + int leg_not_at_wall = 50; // extra for a leg that stops in the open + // An open leg of n tiles may end open_error + n / open_error_per tiles + // short or long. open_error_per 0 adds no growth: every open leg is + // off by open_error at most, and by nothing if open_error is 0 too. + int open_error = 1; + int open_error_per = 5; + // Open legs this many tiles or shorter land exactly. 0 keeps every + // open leg uncertain. + int exact_open_tiles = 0; + // Extra per tile of an open leg: its timing error grows with its length. + int per_open_tile = 0; + // Open legs that may end off (longer than exact_open_tiles) are held + // for their time (RobustLeg::held), not tapped, and pay no + // per_open_tile: no such leg is planned whose possible ends past its + // shortest enter a wild or wander place or hop a ledge, so a long or + // short hold meets nothing a tap would not have. + bool hold_open_legs = false; + // Extra per wild place an open leg enters, on top of per_wild_tile: a + // wild battle loses an open leg's count, while a leg to a wall just + // walks to the wall again. + int per_open_wild_tile = 0; + int max_open_tiles = 12; // longest open leg to consider + size_t max_spread = 5; // most places the player may be on after a leg + // Most sets of places to search before giving up. The search is over + // sets, not places, so it grows far faster than the map. + size_t max_searched = 20000; +}; + + +// The cheapest legs that take the player from any of `from` to places that +// all satisfy `goal`, even if every open leg ends up to its error off. +// Legs that run along where someone wanders (two such places in a row, the +// leg's start among them) are not used. Nothing if no such plan exists, or +// none is found within `costs.max_searched` sets. +template +std::optional>> plan_robust_legs( + const Model& model, + std::vector from, + const std::function& goal, + const RobustLegCosts& costs +); + +// What plan_robust_legs() charges for walking `legs` from any of `from`, +// each leg from the places the one before may end on. A leg it would not +// plan costs its tiles and legs without wild or wander tiles. +template +long long robust_legs_cost( + const Model& model, + std::vector from, + const std::vector>& legs, + const RobustLegCosts& costs +); + + + +namespace RobustLegPlannerInternal{ + +// Most steps a leg to a wall may take. No map is this long; a model whose +// steps loop (edge connections that come back round, or a model bug) +// would otherwise slide forever. +inline constexpr size_t MAX_STEPS_TO_WALL = 1024; + +// Where the player stops walking `direction` until stopped. +template +struct WallHit{ + State stop; + size_t tiles = 0; + bool held = false; +}; +// Walks `direction` from `from` until the player is stopped. A walk that +// is not stopped within MAX_STEPS_TO_WALL steps is not held. +template +WallHit slide_to_wall(const Model& model, const typename Model::State& from, Direction direction){ + WallHit hit{from}; + for (size_t steps = 0; steps < MAX_STEPS_TO_WALL; steps++){ + const auto next = model.step(hit.stop, direction); + if (!next){ + hit.held = model.held_at(hit.stop, direction); + return hit; + } + hit.tiles += model.step_tiles(hit.stop, *next); + hit.stop = *next; + } + return hit; +} + +// How many tiles an open leg of `tiles` tiles may end short or long. +inline int open_leg_error(int tiles, const RobustLegCosts& costs){ + if (tiles <= costs.exact_open_tiles){ + return 0; + } + if (costs.open_error_per <= 0){ + return costs.open_error; + } + return costs.open_error + tiles / costs.open_error_per; +} + +// Where `from` ends up after `tiles` tiles `direction`, stopping early +// where it is held, and the wild and wander tiles it enters. Nothing if a +// step is stopped where the player is not held. +template +struct Stepped{ + State end; + int wild = 0; + int wander = 0; + bool along_wander = false; +}; +// Steps `from` up to `tiles` tiles `direction` (see Stepped). +template +std::optional> step_tiles(const Model& model, typename Model::State from, Direction direction, int tiles){ + Stepped stepped{from}; + int travelled = 0; + bool in_wander = model.wander(from); + while (travelled < tiles){ + const auto next = model.step(from, direction); + if (!next){ + if (!model.held_at(from, direction)){ + return std::nullopt; + } + break; + } + travelled += (int)model.step_tiles(from, *next); + stepped.wild += model.wild(*next) ? 1 : 0; + const bool next_wander = model.wander(*next); + if (next_wander){ + stepped.wander++; + stepped.along_wander |= in_wander; + } + in_wander = next_wander; + from = *next; + } + stepped.end = from; + return stepped; +} + +// step_tiles() for each count from 1 to `most`, in one walk: [n - 1] is +// step_tiles(model, from, direction, n). +template +std::vector>> step_prefixes( + const Model& model, typename Model::State from, Direction direction, int most +){ + std::vector>> out; + Stepped stepped{from}; + int travelled = 0; + bool in_wander = model.wander(from); + while ((int)out.size() < most){ + const auto next = model.step(from, direction); + if (!next){ + stepped.end = from; + std::optional> last; + if (model.held_at(from, direction)){ + last = stepped; + } + out.resize((size_t)most, last); + break; + } + travelled += (int)model.step_tiles(from, *next); + stepped.wild += model.wild(*next) ? 1 : 0; + const bool next_wander = model.wander(*next); + if (next_wander){ + stepped.wander++; + stepped.along_wander |= in_wander; + } + in_wander = next_wander; + from = *next; + stepped.end = from; + while ((int)out.size() < std::min(travelled, most)){ + out.push_back(stepped); + } + } + return out; +} + +// Whether a held leg's possible ends, `ends` in order from the shortest, +// meet nothing past the shortest that a tap would not: no wild or wander +// place, no ledge hop. +template +bool held_ends_safe(const Model& model, const std::vector& ends){ + for (size_t i = 1; i < ends.size(); i++){ + if (model.step_tiles(ends[i - 1], ends[i]) > 1 || model.wild(ends[i]) || model.wander(ends[i])){ + return false; + } + } + return true; +} + +// Sorts a spread and drops repeated places, so equal sets compare equal. +template +void normalize(std::vector& spread){ + using State = typename Model::State; + std::sort(spread.begin(), spread.end(), typename Model::StateLess()); + spread.erase(std::unique(spread.begin(), spread.end(), [](const State& a, const State& b){ return a == b; }), spread.end()); +} +// Orders spreads, for keeping them in a map. +template +struct SpreadLess{ + bool operator()(const std::vector& a, const std::vector& b) const{ + return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), typename Model::StateLess()); + } +}; + +// A leg out of a spread: where every place of it ends, and its cost. +template +struct Expansion{ + long long cost = 0; + RobustLeg leg; + // A held leg that may end somewhere unsafe (held_ends_safe()): not to + // be used, though a longer one may be. + bool unsafe = false; +}; + +// To the wall: every place walks until stopped. Nothing unless each is +// held, and one moves. +template +std::optional> to_wall_leg( + const Model& model, const std::vector& spread, Direction direction, const RobustLegCosts& costs +){ + Expansion expansion; + size_t longest = 0; + int wild = 0; + int wander = 0; + for (const auto& place : spread){ + const auto hit = slide_to_wall(model, place, direction); + if (!hit.held){ + return std::nullopt; + } + if (const auto stepped = step_tiles(model, place, direction, (int)hit.tiles)){ + if (stepped->along_wander){ + return std::nullopt; + } + wild = std::max(wild, stepped->wild); + wander = std::max(wander, stepped->wander); + } + longest = std::max(longest, hit.tiles); + expansion.leg.after.push_back(hit.stop); + } + if (longest == 0){ + return std::nullopt; + } + expansion.cost = (long long)costs.per_leg + (long long)costs.per_tile * longest + + (long long)costs.per_wild_tile * wild + (long long)costs.per_wander_tile * wander; + expansion.leg.direction = direction; + expansion.leg.tiles = longest; + expansion.leg.to_wall = true; + return expansion; +} + +// Open: about `tiles` tiles, give or take the error. Nothing if any +// possible end is stopped where the player is not held. A held leg whose +// ends may be unsafe is marked so (Expansion::unsafe). +template +std::optional> open_leg( + const Model& model, const std::vector& spread, Direction direction, int tiles, const RobustLegCosts& costs +){ + using State = typename Model::State; + Expansion expansion; + int wild = 0; + int wander = 0; + const int error = open_leg_error(tiles, costs); + const bool held = costs.hold_open_legs && error > 0; + for (const auto& place : spread){ + std::vector ends; + const auto prefixes = step_prefixes(model, place, direction, tiles + error); + for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ + const auto& stepped = prefixes[(size_t)n - 1]; + if (!stepped || stepped->along_wander){ + return std::nullopt; + } + wild = std::max(wild, stepped->wild); + wander = std::max(wander, stepped->wander); + ends.push_back(stepped->end); + } + if (held && !held_ends_safe(model, ends)){ + expansion.unsafe = true; + } + expansion.leg.after.insert(expansion.leg.after.end(), ends.begin(), ends.end()); + } + const int per_open_tile = held ? 0 : costs.per_open_tile; + expansion.cost = (long long)costs.per_leg + costs.leg_not_at_wall + + (long long)(costs.per_tile + per_open_tile) * tiles + + (long long)(costs.per_wild_tile + costs.per_open_wild_tile) * wild + (long long)costs.per_wander_tile * wander; + expansion.leg.direction = direction; + expansion.leg.tiles = (size_t)tiles; + expansion.leg.held = held; + return expansion; +} + +// Whether `next` walks on as one hold with `prev`: both open and tapped, +// the same way. +template +bool joins(const RobustLeg& prev, const RobustLeg& next){ + return prev.direction == next.direction && !prev.to_wall && !prev.held && !next.held; +} + +// Joins an open leg with the next one the same way: they are one hold. +template +std::vector> consolidate(const std::vector>& legs){ + std::vector> consolidated; + for (const RobustLeg& leg : legs){ + if (!consolidated.empty() && joins(consolidated.back(), leg)){ + consolidated.back().tiles += leg.tiles; + consolidated.back().to_wall = leg.to_wall; + consolidated.back().after = leg.after; + }else{ + consolidated.push_back(leg); + } + } + return consolidated; +} + +// The way back: the direction opposite `direction`. +inline Direction opposite(Direction direction){ + return Direction(((int)direction + 2) % 4); +} + +// Dijkstra over sets of places the player may stand on. +template +class Search{ +public: + using State = typename Model::State; + using Spread = std::vector; + + Search(const Model& model, const RobustLegCosts& costs) + : m_model(model) + , m_costs(costs) + {} + + std::optional>> run(Spread start, const std::function& goal){ + normalize(start); + m_start = start; + m_nodes[start] = Node{}; + m_queue.emplace(0, start); + size_t searched = 0; + while (!m_queue.empty()){ + const auto [cost, spread] = m_queue.top(); + m_queue.pop(); + Node& node = m_nodes[spread]; + if (node.done || node.cost != cost){ + continue; + } + node.done = true; + if (++searched > m_costs.max_searched){ + return std::nullopt; + } + if (std::all_of(spread.begin(), spread.end(), goal)){ + return consolidate(legs_to(spread)); + } + expand(spread, cost); + } + return std::nullopt; + } + +private: + struct Node{ + long long cost = 0; + Spread parent; + RobustLeg leg; + bool done = false; + }; + using Entry = std::pair; + struct EntryGreater{ + bool operator()(const Entry& a, const Entry& b) const{ + return a.first > b.first; + } + }; + + void expand(const Spread& spread, long long cost){ + for (Direction direction : ALL_DIRECTIONS){ + const auto wall = to_wall_leg(m_model, spread, direction, m_costs); + if (wall){ + relax(spread, cost, Expansion(*wall)); + } + // A held leg unsafe at one length may be safe at a longer one. + for (int tiles = 1; tiles <= m_costs.max_open_tiles; tiles++){ + auto open = open_leg(m_model, spread, direction, tiles, m_costs); + if (!open){ + break; + } + // An open leg that ends where the leg to the wall does is + // that leg: it is held until the wall stops the player. + if (wall && wall->leg.tiles == open->leg.tiles && wall->leg.after == open->leg.after){ + continue; + } + if (!open->unsafe){ + relax(spread, cost, std::move(*open)); + } + } + } + } + + // Only the start may be wider than costs.max_spread: every leg must + // bring the player within it. + void relax(const Spread& spread, long long cost, Expansion expansion){ + Spread& next = expansion.leg.after; + normalize(next); + if (next.size() > m_costs.max_spread || next == spread){ + return; + } + if (spread != m_start){ + const Node& arrived = m_nodes.at(spread); + const RobustLeg& prev = arrived.leg; + // A run to a wall and back after a tapped leg: the taps left the + // player on a known tile, so the run past it and back adds a + // turn for nothing. From the start or after a leg to a wall it + // is how a long leg is made fast and exact. + if (prev.to_wall && arrived.parent != m_start && expansion.leg.direction == opposite(prev.direction)){ + if (!m_nodes.at(arrived.parent).leg.to_wall){ + return; + } + } + if (joins(prev, expansion.leg)){ + expansion.cost -= m_costs.per_leg; + } + } + const long long total = cost + expansion.cost; + auto iter = m_nodes.find(next); + if (iter != m_nodes.end() && iter->second.cost <= total){ + return; + } + m_nodes[next] = Node{total, spread, expansion.leg}; + m_queue.emplace(total, std::move(next)); + } + + std::vector> legs_to(const Spread& end) const{ + std::vector> legs; + for (Spread at = end; at != m_start; ){ + const Node& step = m_nodes.at(at); + legs.push_back(step.leg); + at = step.parent; + } + std::reverse(legs.begin(), legs.end()); + return legs; + } + + const Model& m_model; + const RobustLegCosts& m_costs; + Spread m_start; + std::map> m_nodes; + std::priority_queue, EntryGreater> m_queue; +}; + +} // namespace RobustLegPlannerInternal + + + +template +std::optional>> plan_robust_legs( + const Model& model, + std::vector from, + const std::function& goal, + const RobustLegCosts& costs +){ + return RobustLegPlannerInternal::Search(model, costs).run(std::move(from), goal); +} + +template +long long robust_legs_cost( + const Model& model, + std::vector from, + const std::vector>& legs, + const RobustLegCosts& costs +){ + using State = typename Model::State; + long long total = 0; + std::vector spread = std::move(from); + RobustLegPlannerInternal::normalize(spread); + const RobustLeg* previous = nullptr; + for (const RobustLeg& leg : legs){ + const auto expansion = leg.to_wall + ? RobustLegPlannerInternal::to_wall_leg(model, spread, leg.direction, costs) + : RobustLegPlannerInternal::open_leg(model, spread, leg.direction, (int)leg.tiles, costs); + long long cost = (long long)costs.per_leg + (long long)costs.per_tile * (long long)leg.tiles; + if (!leg.to_wall){ + cost += costs.leg_not_at_wall + (long long)costs.per_open_tile * (long long)leg.tiles; + } + if (expansion){ + cost = expansion->cost; + } + if (previous != nullptr && RobustLegPlannerInternal::joins(*previous, leg)){ + cost -= costs.per_leg; + } + total += cost; + spread = leg.after; + RobustLegPlannerInternal::normalize(spread); + previous = ⋚ + } + return total; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp new file mode 100644 index 0000000000..b9866592b5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp @@ -0,0 +1,370 @@ +/* Robust Leg Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The robust planner on a small made-up game: walls hold the player, a + * door stops them without holding them, a ledge hops them south, and open + * legs may end a tile off. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_RobustLegPlanner.h" +#include "Pokemon_RobustLegPlanner_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// '#' wall (and everything outside the rows), '.' floor, '"' tall grass, +// 'w' where someone wanders, 'D' a door: the player is stopped there but +// not held, since walking on enters the building. 'v' a ledge: a step south +// onto it hops to the tile past it and counts 2; it holds the player any +// other way. Rows that wrap join their east end to their west end, so a +// walk along them is never stopped. +class ToyGame{ +public: + using State = TilePos; + using StateLess = std::less; + + ToyGame(const std::vector& rows, bool wraps) + : m_rows(rows.begin(), rows.end()) + , m_wraps(wraps) + {} + + std::optional step(const State& state, Direction direction) const{ + TilePos next = wrapped(state.next(direction)); + const char tile = at(next); + if (tile == 'v' && direction == Direction::SOUTH){ + next = next.next(Direction::SOUTH); + return at(next) == '#' ? std::nullopt : std::optional(next); + } + if (tile == '#' || tile == 'D' || tile == 'v'){ + return std::nullopt; + } + return next; + } + size_t step_tiles(const State& from, const State& to) const{ + return to.y - from.y == 2 ? 2 : 1; + } + bool held_at(const State& state, Direction direction) const{ + return at(wrapped(state.next(direction))) != 'D'; + } + bool wild(const State& state) const{ + return at(state) == '"'; + } + bool wander(const State& state) const{ + return at(state) == 'w'; + } + +private: + TilePos wrapped(TilePos pos) const{ + if (m_wraps && pos.y >= 0 && pos.y < (int)m_rows.size()){ + const int width = (int)m_rows[pos.y].size(); + pos.x = (pos.x % width + width) % width; + } + return pos; + } + char at(const TilePos& pos) const{ + if (pos.y < 0 || pos.y >= (int)m_rows.size() || pos.x < 0 || pos.x >= (int)m_rows[pos.y].size()){ + return '#'; + } + return m_rows[pos.y][pos.x]; + } + + std::vector m_rows; + bool m_wraps = false; +}; + +using Legs = std::vector>; + +// Legs as "east 2 to wall: (2, 0); south 1 open: (2, 1) (2, 2)", or "none". +std::string describe(const std::optional& legs){ + if (!legs){ + return "none"; + } + std::string text; + for (const RobustLeg& leg : *legs){ + text += std::format("{}{} {} {}:", text.empty() ? "" : "; ", direction_name(leg.direction), leg.tiles, + leg.to_wall ? "to wall" : leg.held ? "held" : "open"); + for (const TilePos& pos : leg.after){ + text += " " + to_string(pos); + } + } + return text; +} + +constexpr RobustLegCosts EXACT{.exact_open_tiles = 12}; +// Open legs held for their time, a tile short or long at any length. +constexpr RobustLegCosts HELD{.open_error = 1, .open_error_per = 0, .hold_open_legs = true}; + + +struct PlanInput{ + std::string_view name; + std::vector rows; + bool wraps = false; + std::vector from; + TilePos goal; + RobustLegCosts costs; +}; +struct PlanExpectation{ + std::string_view legs; // as describe() writes them +}; +struct PlanCase{ + PlanInput input; + PlanExpectation expectation; +}; + +class Test_RobustLegPlanner_Plan : public UnitTest{ +public: + explicit Test_RobustLegPlanner_Plan(PlanCase scenario) + : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const PlanInput& input = m_scenario.input; + const ToyGame game(input.rows, input.wraps); + const TilePos goal = input.goal; + const std::optional legs = plan_robust_legs(game, input.from, + std::function([goal](const TilePos& pos){ return pos == goal; }), input.costs); + const std::string actual = describe(legs); + if (actual != m_scenario.expectation.legs){ + return std::format("Planned \"{}\", expected \"{}\".", actual, m_scenario.expectation.legs); + } + return true; + } +private: + PlanCase m_scenario; +}; + +// Open legs on default costs may end a tile either way (two up to 5 tiles). +const PlanCase PLAN_CASES[] = { + { + .input = {.name = "a wall gathers the possible tiles", .rows = {"...#"}, .from = {{0, 0}, {1, 0}}, .goal = {2, 0}}, + .expectation = {.legs = "east 2 to wall: (2, 0)"}, + }, + { + .input = {.name = "no plan ends in the open while open legs may be off", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}}, + .expectation = {.legs = "none"}, + }, + { + .input = {.name = "an exact open leg ends in the open", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, .costs = EXACT}, + .expectation = {.legs = "east 3 open: (3, 0)"}, + }, + { + .input = { + .name = "open_error_per 0 with no open_error is exact", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, + .costs = {.open_error = 0, .open_error_per = 0}, + }, + .expectation = {.legs = "east 3 open: (3, 0)"}, + }, + { + .input = { + .name = "open_error_per 0 keeps open_error", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, + .costs = {.open_error = 1, .open_error_per = 0}, + }, + .expectation = {.legs = "none"}, + }, + { + .input = {.name = "a door is not a wall", .rows = {"#..D"}, .from = {{1, 0}}, .goal = {2, 0}, .costs = EXACT}, + .expectation = {.legs = "east 1 open: (2, 0)"}, + }, + { + .input = {.name = "no leg along a wander zone", .rows = {".www.", "....."}, .from = {{1, 0}}, .goal = {4, 0}, .costs = EXACT}, + .expectation = {.legs = "south 1 to wall: (1, 1); east 3 to wall: (4, 1); north 1 to wall: (4, 0)"}, + }, + { + .input = {.name = "a ledge hop counts 2 tiles", .rows = {".", "v", "."}, .from = {{0, 0}}, .goal = {0, 2}}, + .expectation = {.legs = "south 2 to wall: (0, 2)"}, + }, + { + .input = {.name = "a ledge cannot be climbed", .rows = {".", "v", "."}, .from = {{0, 2}}, .goal = {0, 0}}, + .expectation = {.legs = "none"}, + }, + { + .input = {.name = "tall grass costs less than a detour", .rows = {".\"\"..", "....."}, .from = {{0, 0}}, .goal = {4, 0}}, + .expectation = {.legs = "east 4 to wall: (4, 0)"}, + }, + { + .input = { + .name = "costly tall grass is walked round", .rows = {".\"\"..", "....."}, .from = {{0, 0}}, .goal = {4, 0}, + .costs = {.per_wild_tile = 20}, + }, + .expectation = {.legs = "south 1 to wall: (0, 1); east 4 to wall: (4, 1); north 1 to wall: (4, 0)"}, + }, + { + // Only an open leg reaches the second row; a wall then gathers. + .input = {.name = "an open leg spreads, a wall gathers", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}}, + .expectation = {.legs = "east 1 open: (1, 0) (2, 0); south 1 to wall: (1, 1) (2, 1); east 2 to wall: (3, 1)"}, + }, + { + .input = { + .name = "a spread wider than max_spread is not planned", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, + .costs = {.max_spread = 1}, + }, + .expectation = {.legs = "none"}, + }, + { + .input = { + .name = "the search gives up past max_searched", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, + .costs = {.max_searched = 1}, + }, + .expectation = {.legs = "none"}, + }, + { + .input = { + .name = "two open legs the same way are one", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, + .costs = {.exact_open_tiles = 12, .max_open_tiles = 2}, + }, + .expectation = {.legs = "east 3 open: (3, 0)"}, + }, + { + .input = {.name = "a walk that is never stopped is not a wall", .rows = {"...."}, .wraps = true, .from = {{0, 0}}, .goal = {2, 0}, .costs = EXACT}, + .expectation = {.legs = "east 2 open: (2, 0)"}, + }, + { + .input = {.name = "an open leg that may end off is held", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = HELD}, + .expectation = {.legs = "east 1 held: (1, 0) (2, 0); south 1 to wall: (1, 1) (2, 1); east 2 to wall: (3, 1)"}, + }, + { + .input = {.name = "a held leg is refused when its long end lands in tall grass", .rows = {"..\"..", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = HELD}, + .expectation = {.legs = "none"}, + }, + { + .input = {.name = "a held leg is refused when its long end lands where someone wanders", .rows = {"..w..", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = HELD}, + .expectation = {.legs = "none"}, + }, + { + .input = {.name = "a held leg south lines up a wall leg", .rows = {".##", "...", "...", ".##", ".##"}, .from = {{0, 0}}, .goal = {2, 2}, .costs = HELD}, + .expectation = {.legs = "south 1 held: (0, 1) (0, 2); east 2 to wall: (2, 1) (2, 2); south 1 to wall: (2, 2)"}, + }, + { + .input = {.name = "a held leg is refused when its long end hops a ledge", .rows = {".##", "...", "v..", ".##", ".##"}, .from = {{0, 0}}, .goal = {2, 2}, .costs = HELD}, + .expectation = {.legs = "none"}, + }, + { + .input = {.name = "open legs are tapped while hold_open_legs is off", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = {.open_error = 1, .open_error_per = 0}}, + .expectation = {.legs = "east 1 open: (1, 0) (2, 0); south 1 to wall: (1, 1) (2, 1); east 2 to wall: (3, 1)"}, + }, +}; + + +struct CostInput{ + std::string_view name; + std::vector rows; + TilePos from; + Legs legs; + RobustLegCosts costs; +}; +struct CostExpectation{ + long long cost = 0; +}; +struct CostCase{ + CostInput input; + CostExpectation expectation; +}; + +class Test_RobustLegPlanner_Cost : public UnitTest{ +public: + explicit Test_RobustLegPlanner_Cost(CostCase scenario) + : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const CostInput& input = m_scenario.input; + const ToyGame game(input.rows, false); + const long long actual = robust_legs_cost(game, {input.from}, input.legs, input.costs); + if (actual != m_scenario.expectation.cost){ + return std::format("Cost {} for \"{}\", expected {}.", actual, describe(input.legs), m_scenario.expectation.cost); + } + return true; + } +private: + CostCase m_scenario; +}; + +// Default costs: 8 a leg, 1 a tile, 4 more a grass tile, 50 more for a +// leg that stops in the open. +const CostCase COST_CASES[] = { + { + .input = {.name = "a wall leg costs a leg and its tiles", .rows = {"...#"}, .from = {0, 0}, .legs = {{Direction::EAST, 2, true, {{2, 0}}}}}, + .expectation = {.cost = 8 + 2}, + }, + { + .input = { + .name = "an open leg costs its stop and open tiles on top", .rows = {"...#"}, .from = {0, 0}, + .legs = {{Direction::EAST, 1, false, {{1, 0}}}}, .costs = {.exact_open_tiles = 12, .per_open_tile = 2}, + }, + .expectation = {.cost = 8 + 50 + 3}, + }, + { + .input = {.name = "each grass tile entered costs extra", .rows = {".\"\"#"}, .from = {0, 0}, .legs = {{Direction::EAST, 2, true, {{2, 0}}}}}, + .expectation = {.cost = 8 + 2 + 2 * 4}, + }, + { + .input = { + .name = "a cost with open_error_per 0", .rows = {"........"}, .from = {0, 0}, + .legs = {{Direction::EAST, 3, false, {{3, 0}}}}, .costs = {.open_error_per = 0}, + }, + .expectation = {.cost = 8 + 50 + 3}, + }, + { + .input = { + .name = "a held leg pays no per_open_tile", .rows = {"........"}, .from = {0, 0}, + .legs = {{Direction::EAST, 3, false, {{2, 0}, {3, 0}, {4, 0}}, true}}, + .costs = {.open_error = 1, .open_error_per = 0, .per_open_tile = 2, .hold_open_legs = true}, + }, + .expectation = {.cost = 8 + 50 + 3}, + }, + { + .input = { + .name = "held legs the same way are not joined", .rows = {"........"}, .from = {0, 0}, + .legs = { + {Direction::EAST, 2, false, {{1, 0}, {2, 0}, {3, 0}}, true}, + {Direction::EAST, 2, false, {{2, 0}, {3, 0}, {4, 0}, {5, 0}}, true}, + }, + .costs = HELD, + }, + .expectation = {.cost = 2 * (8 + 50 + 2)}, + }, + { + .input = { + .name = "each grass tile of an open leg costs per_open_wild_tile more", .rows = {".\"\"...."}, .from = {0, 0}, + .legs = {{Direction::EAST, 3, false, {{3, 0}}}}, .costs = {.exact_open_tiles = 12, .per_open_wild_tile = 10}, + }, + .expectation = {.cost = 8 + 50 + 3 + 2 * (4 + 10)}, + }, + { + .input = { + .name = "per_open_wild_tile leaves a wall leg's grass alone", .rows = {".\"\"#"}, .from = {0, 0}, + .legs = {{Direction::EAST, 2, true, {{2, 0}}}}, .costs = {.per_open_wild_tile = 10}, + }, + .expectation = {.cost = 8 + 2 + 2 * 4}, + }, +}; + +} // namespace + + +void add_tests_RobustLegPlanner(UnitTestDatabase& database){ + for (const PlanCase& scenario : PLAN_CASES){ + database.add(scenario); + } + for (const CostCase& scenario : COST_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h new file mode 100644 index 0000000000..fec9e8a2e0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h @@ -0,0 +1,23 @@ +/* Robust Leg Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_RobustLegPlanner_Tests_H +#define PokemonAutomation_Pokemon_RobustLegPlanner_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers robust leg planner unit tests. +void add_tests_RobustLegPlanner(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp new file mode 100644 index 0000000000..9e216d8791 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp @@ -0,0 +1,504 @@ +/* Route Scorer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Pokemon_RouteScorer.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string to_string(const ScoredLeg& leg){ + std::string_view how = "taps"; + switch (leg.kind){ + case ScoredLegKind::TO_WALL: + how = leg.run ? "run to wall" : "walk to wall"; + break; + case ScoredLegKind::OPEN_HOLD: + how = leg.run ? "run, open" : "walk, open"; + break; + case ScoredLegKind::TAPS: + break; + } + return std::format("{} {} ({})", direction_name(leg.direction), leg.tiles, how); +} + +size_t tiles_walked_back(const std::vector& legs){ + size_t tiles = 0; + for (size_t i = 0; i < legs.size(); i++){ + const Direction back = Direction(((int)legs[i].direction + 2) % 4); + if (i > 0 && legs[i - 1].kind == ScoredLegKind::TO_WALL && legs[i - 1].direction == back){ + continue; + } + for (size_t j = 0; j < i; j++){ + if (legs[j].direction == back){ + tiles += legs[i].tiles; + break; + } + } + } + return tiles; +} + +std::string_view verdict_name(RouteVerdict verdict){ + switch (verdict){ + case RouteVerdict::PASS: + return "PASS"; + case RouteVerdict::FAIL: + return "FAIL"; + case RouteVerdict::STRAND: + return "STRAND"; + case RouteVerdict::RETRIES: + return "RETRIES"; + } + return "?"; +} + + +namespace{ + +size_t distance(const TilePos& a, const TilePos& b){ + return (size_t)(std::abs(a.x - b.x) + std::abs(a.y - b.y)); +} + +bool stops_on(TileRisk risk){ + return risk == TileRisk::WARP || risk == TileRisk::TRIGGER; +} + +// One leg walked from one tile, nothing interrupting. +struct LegWalk{ + std::vector path; // tiles surely walked, in order, the first after the start + std::vector ends; // where the leg may end + long long ms = 0; + bool stop = false; // ended at a wall (a re-localization) + size_t taps = 0; + std::string unsafe; // why the leg may end somewhere it must not +}; + +// Steps from `from` until stopped, at most `most` steps; stops on a warp +// or a trigger. +std::vector walk_steps(const ScoreMap& map, const TilePos& from, Direction direction, size_t most){ + std::vector path; + TilePos at = from; + while (path.size() < most){ + const std::optional next = map.step(at, direction); + if (!next){ + break; + } + path.push_back(*next); + at = *next; + if (stops_on(map.risk(at))){ + break; + } + } + return path; +} + +size_t path_tiles(const TilePos& from, const std::vector& path){ + size_t tiles = 0; + TilePos at = from; + for (const TilePos& pos : path){ + tiles += distance(at, pos); + at = pos; + } + return tiles; +} + +LegWalk walk_to_wall(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, const RoutePaces& paces){ + LegWalk walk; + walk.path = walk_steps(map, from, leg.direction, (size_t)-1); + walk.ends = {walk.path.empty() ? from : walk.path.back()}; + walk.stop = walk.path.empty() || !stops_on(map.risk(walk.path.back())); + walk.ms = paces.start_ms + (long long)path_tiles(from, walk.path) * paces.ms_per_tile(leg.direction, leg.run) + + (walk.stop ? paces.stop_ms : 0); + return walk; +} + +LegWalk walk_taps(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, const RoutePaces& paces){ + LegWalk walk; + walk.path = walk_steps(map, from, leg.direction, leg.tiles); + walk.ends = {walk.path.empty() ? from : walk.path.back()}; + const bool blocked = walk.path.size() < leg.tiles && (walk.path.empty() || !stops_on(map.risk(walk.path.back()))); + // A blocked walk of taps ends after two taps that move nothing. + walk.taps = walk.path.size() + (blocked ? 2 : 0); + walk.ms = (long long)walk.taps * paces.tap_ms; + return walk; +} + +// Why a tile in a held leg's uncertain end must not be reached, or "". +std::string unsafe_overshoot(const ScoreMap& map, const TilePos& before, const TilePos& pos, + const std::function& goal +){ + if (distance(before, pos) > 1){ + return "a ledge hop at " + to_string(pos); + } + switch (map.risk(pos)){ + case TileRisk::NONE: + return ""; + case TileRisk::TRIGGER: + return goal(pos) ? "" : "a trigger at " + to_string(pos); + case TileRisk::WARP: + return goal(pos) ? "" : "a warp at " + to_string(pos); + case TileRisk::ENCOUNTER: + return "grass at " + to_string(pos); + case TileRisk::WANDERER: + return "a wanderer's tile at " + to_string(pos); + case TileRisk::SIGHT: + return "a trainer's sight at " + to_string(pos); + } + return ""; +} + +LegWalk walk_open_hold(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, + const RoutePaces& paces, const std::function& goal +){ + const size_t error = paces.open_hold_error ? paces.open_hold_error(leg.tiles) : 0; + const size_t fewest = leg.tiles > error ? leg.tiles - error : 0; + const std::vector all = walk_steps(map, from, leg.direction, leg.tiles + error); + LegWalk walk; + walk.path.assign(all.begin(), all.begin() + std::min(fewest, all.size())); + for (size_t k = fewest; k <= all.size(); k++){ + walk.ends.push_back(k == 0 ? from : all[k - 1]); + if (k > fewest && walk.unsafe.empty()){ + walk.unsafe = unsafe_overshoot(map, k == 1 ? from : all[k - 2], all[k - 1], goal); + } + } + walk.ms = paces.start_ms + (long long)leg.tiles * paces.ms_per_tile(leg.direction, leg.run); + return walk; +} + +LegWalk walk_leg(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, + const RoutePaces& paces, const std::function& goal +){ + LegWalk walk; + switch (leg.kind){ + case ScoredLegKind::TO_WALL: + walk = walk_to_wall(map, from, leg, paces); + break; + case ScoredLegKind::TAPS: + walk = walk_taps(map, from, leg, paces); + break; + case ScoredLegKind::OPEN_HOLD: + walk = walk_open_hold(map, from, leg, paces, goal); + break; + } + walk.ms += paces.press_ms; + return walk; +} + + +// One way the walk may have gone so far, from one start tile. +struct Branch{ + TilePos pos; + long long ms = 0; + double weight = 0; // chance of this branch, the starts equally likely + bool sighted = false; // a trainer has seen us (and been fought) +}; + +// Where an interruption may happen, and what it costs. +struct Interruption{ + size_t leg; + size_t steps; // steps of the leg walked when it happens + TilePos from; // where the leg started + TilePos at; + double chance; + long long cost_ms; + double weight; +}; + +// The plan from where an interruption leaves the player on: the rest of +// the interrupted leg, then the legs after it. +std::vector rest_of_plan(const std::vector& legs, const Interruption& stop){ + const ScoredLeg& leg = legs[stop.leg]; + std::vector rest; + if (leg.kind == ScoredLegKind::TO_WALL || stop.steps < leg.tiles){ + ScoredLeg left = leg; + left.tiles = leg.kind == ScoredLegKind::TO_WALL ? leg.tiles : leg.tiles - stop.steps; + rest.push_back(left); + } + rest.insert(rest.end(), legs.begin() + stop.leg + 1, legs.end()); + return rest; +} + +// The tiles an interruption on a leg without a wall may leave us on: a +// tap lost or one too many either way. +std::vector unsure_tiles(const ScoreMap& map, const ScoredLeg& leg, const Interruption& stop){ + std::vector tiles{stop.at}; + if (leg.kind == ScoredLegKind::TO_WALL){ + return tiles; + } + const std::vector back = walk_steps(map, stop.at, Direction((int(leg.direction) + 2) % 4), 1); + const std::vector ahead = walk_steps(map, stop.at, leg.direction, 1); + tiles.insert(tiles.end(), back.begin(), back.end()); + tiles.insert(tiles.end(), ahead.begin(), ahead.end()); + return tiles; +} + +std::string key_of(std::vector tiles){ + std::sort(tiles.begin(), tiles.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + std::string key; + for (const TilePos& pos : tiles){ + key += to_string(pos); + } + return key; +} + + +// What a nominal walk of a plan gives: the branches at its end, the +// interruptions it may meet, and how it may fail. +struct PlanWalk{ + std::vector branches; + std::vector interruptions; + size_t stops = 0; + size_t presses = 0; + std::string fail; +}; + +class Scorer{ +public: + Scorer(const ScoreMap& map, const std::function& goal, + const RoutePaces& paces, const InterruptModel& model, const RouteReplanner& replan + ) + : m_map(map), m_goal(goal), m_paces(paces), m_model(model), m_replan(replan) + {} + + RouteScore score(const std::vector& from, const std::vector& legs, size_t depth); + +private: + PlanWalk walk_plan(const std::vector& from, const std::vector& legs) const; + void walk_branch(PlanWalk& out, const Branch& branch, size_t index, const ScoredLeg& leg, + bool last, std::map& next) const; + void add_interruptions(PlanWalk& out, Branch& branch, size_t index, const TilePos& from, const LegWalk& walk) const; + void recover(RouteScore& score, const std::vector& legs, const Interruption& stop, size_t depth); + RouteScore recovery_score(const std::vector& unsure, size_t depth); + bool relocalizes(const std::vector& unsure, const std::vector& legs) const; + static void fail(RouteScore& score, RouteVerdict verdict, const std::string& why); + + const ScoreMap& m_map; + const std::function& m_goal; + const RoutePaces& m_paces; + const InterruptModel& m_model; + const RouteReplanner& m_replan; + std::map m_done; + std::set m_open; + // Recoveries in progress whose plan first stops every tile at one wall + // out of harm's way (relocalizes()). + std::set m_relocalizing; +}; + +// Whether `legs` from `unsure` first walk every tile to one wall tile +// where nothing interrupts. A recovery that does is a retry from a known +// place: if it is interrupted where it was before, the walk does the same +// again, each time with the interruption's chance, so it ends. +bool Scorer::relocalizes(const std::vector& unsure, const std::vector& legs) const{ + if (legs.empty() || legs.front().kind != ScoredLegKind::TO_WALL){ + return false; + } + std::optional end; + for (const TilePos& pos : unsure){ + const LegWalk walk = walk_to_wall(m_map, pos, legs.front(), m_paces); + if (!walk.stop || (end && *end != walk.ends.front())){ + return false; + } + end = walk.ends.front(); + } + return end && m_map.risk(*end) == TileRisk::NONE; +} + +void Scorer::fail(RouteScore& score, RouteVerdict verdict, const std::string& why){ + if (score.verdict == RouteVerdict::PASS){ + score.verdict = verdict; + score.why = why; + } +} + +void Scorer::add_interruptions(PlanWalk& out, Branch& branch, size_t index, const TilePos& from, const LegWalk& walk) const{ + for (size_t k = 0; k < walk.path.size(); k++){ + const TilePos& at = walk.path[k]; + Interruption stop{.leg = index, .steps = k + 1, .from = from, .at = at, .chance = 0, .cost_ms = 0, .weight = branch.weight}; + switch (m_map.risk(at)){ + case TileRisk::ENCOUNTER: + stop.chance = m_model.encounter_per_tile; + stop.cost_ms = m_model.encounter_ms; + break; + case TileRisk::WANDERER: + stop.chance = m_model.wanderer_per_tile; + stop.cost_ms = m_model.wanderer_ms; + break; + case TileRisk::SIGHT: + stop.chance = branch.sighted ? 0 : 1; + stop.cost_ms = m_model.trainer_ms; + branch.sighted = true; + break; + default: + break; + } + if (stop.chance > 0){ + out.interruptions.push_back(stop); + } + } +} + +void Scorer::walk_branch(PlanWalk& out, const Branch& branch, size_t index, const ScoredLeg& leg, + bool last, std::map& next +) const{ + const LegWalk walk = walk_leg(m_map, branch.pos, leg, m_paces, m_goal); + if (!walk.unsafe.empty() && out.fail.empty()){ + out.fail = std::format("leg {} ({}) from {} may overshoot onto {}", index + 1, to_string(leg), to_string(branch.pos), walk.unsafe); + } + for (const TilePos& pos : walk.path){ + if (m_map.risk(pos) == TileRisk::WARP && !(last && pos == walk.path.back() && m_goal(pos)) && out.fail.empty()){ + out.fail = std::format("leg {} ({}) from {} walks into the warp at {}", index + 1, to_string(leg), to_string(branch.pos), to_string(pos)); + } + } + Branch walked = branch; + walked.ms += walk.ms; + add_interruptions(out, walked, index, branch.pos, walk); + for (const TilePos& end : walk.ends){ + Branch b = walked; + b.pos = end; + b.weight = walked.weight / (double)walk.ends.size(); + auto [it, added] = next.try_emplace(key_of({end}), b); + if (!added){ + it->second.weight += b.weight; + it->second.ms = std::max(it->second.ms, b.ms); + } + } +} + +PlanWalk Scorer::walk_plan(const std::vector& from, const std::vector& legs) const{ + PlanWalk out; + for (const TilePos& pos : from){ + out.branches.push_back({.pos = pos, .ms = 0, .weight = 1.0 / (double)from.size(), .sighted = false}); + } + for (size_t i = 0; i < legs.size(); i++){ + std::map next; + for (const Branch& branch : out.branches){ + walk_branch(out, branch, i, legs[i], i + 1 == legs.size(), next); + } + out.branches.clear(); + for (auto& item : next){ + out.branches.push_back(item.second); + } + if (out.branches.size() > m_model.max_spread && out.fail.empty()){ + out.fail = std::format("after leg {} the player may be on {} tiles", i + 1, out.branches.size()); + } + out.presses += legs[i].kind == ScoredLegKind::TAPS ? legs[i].tiles : 1; + out.stops += legs[i].kind == ScoredLegKind::TO_WALL ? 1 : 0; + } + for (const Branch& branch : out.branches){ + if (!m_goal(branch.pos) && out.fail.empty()){ + out.fail = "may end on " + to_string(branch.pos) + ", off the goal"; + } + } + return out; +} + +RouteScore Scorer::recovery_score(const std::vector& unsure, size_t depth){ + RouteScore score; + const std::string key = key_of(unsure); + if (m_open.contains(key)){ + // A retry from a wall: charged its replan alone (recover()). + if (!m_relocalizing.contains(key)){ + fail(score, RouteVerdict::STRAND, "the recovery from " + key + " leads back to itself"); + } + return score; + } + const auto done = m_done.find(key); + if (done != m_done.end()){ + return done->second; + } + if (depth > m_model.max_recoveries){ + fail(score, RouteVerdict::RETRIES, std::format("more than {} recoveries in a row, at {}", m_model.max_recoveries, key)); + return score; + } + const std::optional> legs = m_replan ? m_replan(unsure) : std::nullopt; + if (!legs){ + fail(score, RouteVerdict::FAIL, "no recovery from " + key); + return score; + } + m_open.insert(key); + if (relocalizes(unsure, *legs)){ + m_relocalizing.insert(key); + } + score = this->score(unsure, *legs, depth); + m_open.erase(key); + m_relocalizing.erase(key); + if (score.verdict != RouteVerdict::PASS){ + score.why = "recovery from " + key + ": " + score.why; + } + m_done[key] = score; + return score; +} + +void Scorer::recover(RouteScore& score, const std::vector& legs, const Interruption& stop, size_t depth){ + score.recoveries++; + const ScoredLeg& leg = legs[stop.leg]; + const std::vector rest = rest_of_plan(legs, stop); + const PlanWalk resumed_exact = walk_plan({stop.at}, rest); + const long long rest_ms = resumed_exact.branches.empty() ? 0 : resumed_exact.branches.front().ms; + const std::vector unsure = unsure_tiles(m_map, leg, stop); + const PlanWalk resumed = walk_plan(unsure, rest); + long long extra_ms = m_paces.start_ms + m_paces.press_ms; + long long extra_worst = extra_ms; + if (!resumed.fail.empty()){ + score.replans++; + const RouteScore again = recovery_score(unsure, depth + 1); + if (again.verdict != RouteVerdict::PASS){ + fail(score, again.verdict, std::format("leg {} interrupted at {}: {}", stop.leg + 1, to_string(stop.at), again.why)); + return; + } + extra_ms = std::max(0, m_model.replan_ms + (long long)again.expected_ms - rest_ms); + extra_worst = std::max(0, m_model.replan_ms + again.worst_ms - rest_ms); + } + score.expected_ms += stop.weight * stop.chance * (double)(stop.cost_ms + extra_ms); + score.worst_ms = std::max(score.worst_ms, score.nominal_ms + stop.cost_ms + extra_worst); +} + +RouteScore Scorer::score(const std::vector& from, const std::vector& legs, size_t depth){ + RouteScore score; + const PlanWalk walk = walk_plan(from, legs); + score.stops = walk.stops; + score.presses = walk.presses; + for (const Branch& branch : walk.branches){ + score.nominal_ms = std::max(score.nominal_ms, branch.ms); + score.expected_ms += branch.weight * (double)branch.ms; + } + score.worst_ms = score.nominal_ms; + if (!walk.fail.empty()){ + fail(score, RouteVerdict::FAIL, walk.fail); + return score; + } + for (const Interruption& stop : walk.interruptions){ + recover(score, legs, stop, depth); + } + return score; +} + +} // namespace + + +RouteScore score_route( + const ScoreMap& map, const std::vector& from, + const std::function& goal, + const std::vector& legs, + const RoutePaces& paces, const InterruptModel& model, + const RouteReplanner& replan +){ + Scorer scorer(map, goal, paces, model, replan); + return scorer.score(from, legs, 0); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h new file mode 100644 index 0000000000..4c844da83b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h @@ -0,0 +1,150 @@ +/* Route Scorer + * +// code-health: allow header_symbols -- route scoring profile definitions and path evaluation criteria + * + * From: https://github.com/PokemonAutomation/ + * + * Scores a walk plan on a tile grid: how long it takes on the game's + * measured paces, from every tile the player may start on, and whether it + * can go wrong. A leg held to a wall ends where the wall stops it; a leg of + * taps moves exactly its taps; a held open leg may end a few tiles short or + * long, and those tiles must be safe. Interruptions on the way (a wild + * battle in grass, someone walking about, a trainer's sight) are charged by + * their chance times the recovery they need, and a recovery that can lead + * back into itself strands the player: the plan fails. + * + * Game-neutral: the game supplies the step rules, the tile risks, its + * paces and hold error (RoutePaces), how often and how dearly it is + * interrupted (InterruptModel) and, for recoveries, its replanner. Nothing + * here defaults to one game's numbers: BDSP's profile is in + * PokemonBDSP_AutoStory_RouteChoice. FRLG, to use it, must supply its own + * paces (walk, run and the bike's, as RoutePaces::ms_per_tile's "run" is + * one faster pace), its hold error, its encounter rates, and later the + * tiles that move the player on their own (spinners, currents), which + * ScoreMap::step does not model yet. + * + */ + +#ifndef PokemonAutomation_Pokemon_RouteScorer_H +#define PokemonAutomation_Pokemon_RouteScorer_H + +#include +#include +#include +#include +#include +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What walking onto a tile risks. +enum class TileRisk{ + NONE, + ENCOUNTER, // tall grass: a wild battle may start + WANDERER, // someone walking about may stand in the way + SIGHT, // a trainer sees the player and walks over + WARP, // a door or warp: walking onto it leaves the map + TRIGGER, // a scene starts here and stops the player +}; + +// The grid a plan is scored on. +struct ScoreMap{ + // Where one step from a tile lands (a ledge hop lands two tiles on), or + // nothing if the player is stopped. A warp's tile is landed on. + std::function(const TilePos&, Direction)> step; + std::function risk; +}; + +// How a leg is walked. +enum class ScoredLegKind{ + TO_WALL, // held until the player stops: lands exactly + TAPS, // one D-pad tap per tile: lands exactly + OPEN_HOLD, // held for its tiles' time: may land a few tiles off +}; +// One leg of a plan. +struct ScoredLeg{ + Direction direction = Direction::NORTH; + size_t tiles = 0; + ScoredLegKind kind = ScoredLegKind::TAPS; + bool run = false; // held at a run (B), not a walk +}; +// "west 16 (taps)", "south 33 (run to wall)". +std::string to_string(const ScoredLeg& leg); + +// Tiles `legs` walk back: each leg opposite to a leg before it. A planned +// stop at a wall re-localizes and is not counted, nor are the taps back +// from it right after (running past the goal to a wall and tapping back, +// as the user walks into Twinleaf). +size_t tiles_walked_back(const std::vector& legs); + +// The game's measured times. The game sets every field. +struct RoutePaces{ + // Time per tile held in a direction, walking or running. + std::function ms_per_tile; + long long start_ms = 0; // from pressing to the first step + long long tap_ms = 0; // one tap and its release + long long press_ms = 0; // a leg's overhead: the turn, the watch + long long stop_ms = 0; // confirming a stop at a wall (a re-localization) + // How many tiles short or long a held open leg of so many tiles may + // end. Null: a hold ends exactly. + std::function open_hold_error; +}; + +// How interruptions are charged. The game sets the chances and costs; +// none charges nothing. +struct InterruptModel{ + double encounter_per_tile = 0; + long long encounter_ms = 0; // a wild battle run from + double wanderer_per_tile = 0; + long long wanderer_ms = 0; // waiting for them to move on + long long trainer_ms = 0; // a trainer battle + long long replan_ms = 0; // a stop and a new plan + // Most recoveries in a row before the plan counts as stuck. + size_t max_recoveries = 3; + // Most tiles the player may be on at once, before a plan is too loose. + size_t max_spread = 32; +}; + +// A new plan from where an interruption left the player, or nothing if +// none exists. Null: a recovery that needs a new plan fails. +using RouteReplanner = std::function>(const std::vector& from)>; + +// Whether a plan gets there, from every start and through every recovery. +enum class RouteVerdict{ + PASS, + FAIL, // may end off the goal, overshoot onto a hazard, or never arrive + STRAND, // a recovery can lead back into itself without first stopping at a wall out of harm's way + RETRIES, // more recoveries in a row than InterruptModel::max_recoveries +}; +// "PASS", "FAIL", "STRAND", "RETRIES". +std::string_view verdict_name(RouteVerdict verdict); + +// A plan's score. +struct RouteScore{ + RouteVerdict verdict = RouteVerdict::PASS; + std::string why; // for a verdict other than PASS + long long nominal_ms = 0; // slowest start, nothing interrupting + double expected_ms = 0; // average start, interruptions by their chance + long long worst_ms = 0; // slowest start and the costliest single interruption + size_t stops = 0; // legs that end on a wall: each re-localizes + size_t presses = 0; // legs plus taps + size_t recoveries = 0; // places an interruption may happen + size_t replans = 0; // of those, the ones the plan's own legs cannot absorb +}; + +// Scores `legs` walked from any of `from` toward tiles `goal` accepts. +RouteScore score_route( + const ScoreMap& map, const std::vector& from, + const std::function& goal, + const std::vector& legs, + const RoutePaces& paces, const InterruptModel& model, + const RouteReplanner& replan = nullptr +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp new file mode 100644 index 0000000000..a80bb7f59d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp @@ -0,0 +1,382 @@ +/* Route Scorer Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The scorer on small made-up grids. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_RouteScorer_Tests.h" +#include "Pokemon_RouteScorer.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// '#' wall, '.' floor, '"' tall grass, 'D' a warp, 'T' a scene's trigger, +// 'w' a wanderer's tile, 's' a trainer's sight, 'v' a ledge hopped south. +class ToyMap{ +public: + explicit ToyMap(std::vector rows) + : m_rows(std::move(rows)) + {} + + char at(const TilePos& pos) const{ + if (pos.y < 0 || pos.y >= (int)m_rows.size() || pos.x < 0 || pos.x >= (int)m_rows[pos.y].size()){ + return '#'; + } + return m_rows[pos.y][pos.x]; + } + ScoreMap score_map() const{ + return { + .step = [this](const TilePos& from, Direction direction) -> std::optional{ + const TilePos next = from.next(direction); + if (at(next) == 'v'){ + return direction == Direction::SOUTH ? std::optional(next.next(direction)) : std::nullopt; + } + return at(next) == '#' ? std::nullopt : std::optional(next); + }, + .risk = [this](const TilePos& pos){ + switch (at(pos)){ + case '"': + return TileRisk::ENCOUNTER; + case 'D': + return TileRisk::WARP; + case 'T': + return TileRisk::TRIGGER; + case 'w': + return TileRisk::WANDERER; + case 's': + return TileRisk::SIGHT; + default: + return TileRisk::NONE; + } + }, + }; + } + +private: + std::vector m_rows; +}; + +RoutePaces toy_paces(){ + return { + .ms_per_tile = [](Direction, bool run){ return run ? 100LL : 250LL; }, + .start_ms = 250, .tap_ms = 800, .press_ms = 100, .stop_ms = 1000, + .open_hold_error = [](size_t tiles){ return 1 + tiles / 5; }, + }; +} + +InterruptModel toy_model(){ + InterruptModel model; + model.encounter_per_tile = 0.1; + model.encounter_ms = 12000; + model.wanderer_per_tile = 0.25; + model.wanderer_ms = 2500; + model.trainer_ms = 45000; + model.replan_ms = 2000; + return model; +} + +std::function exactly(const TilePos& goal){ + return [goal](const TilePos& pos){ return pos == goal; }; +} + +RouteScore score(const ToyMap& toy, const std::vector& from, const TilePos& goal, + const std::vector& legs, const RouteReplanner& replan = nullptr, const InterruptModel& model = toy_model() +){ + return score_route(toy.score_map(), from, exactly(goal), legs, toy_paces(), model, replan); +} + +// "" if `got` has `verdict`, else why not. +std::string expect(const RouteScore& got, RouteVerdict verdict, const std::string& what){ + if (got.verdict != verdict){ + return std::format("{}: expected {}, got {} ({})", what, verdict_name(verdict), verdict_name(got.verdict), got.why); + } + return ""; +} + +// Passes if every check is "". +UnitTestResult all_of(std::initializer_list checks){ + for (const std::string& check : checks){ + if (!check.empty()){ + return check; + } + } + return true; +} + +UnitTestResult test_taps_time(){ + const ToyMap toy({"......"}); + const RouteScore got = score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 4, .kind = ScoredLegKind::TAPS}}); + if (got.verdict != RouteVerdict::PASS || got.nominal_ms != 4 * 800 + 100 || got.presses != 4 || got.stops != 0){ + return std::format("4 taps: {} {} ms, {} presses, {} stops", verdict_name(got.verdict), got.nominal_ms, got.presses, got.stops); + } + return true; +} + +UnitTestResult test_run_to_wall_beats_taps(){ + const ToyMap toy({"......#"}); + const RouteScore taps = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}); + const RouteScore run = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL, .run = true}}); + if (run.verdict != RouteVerdict::PASS || run.nominal_ms != 250 + 500 + 1000 + 100 || run.stops != 1){ + return std::format("run: {} {} ms ({})", verdict_name(run.verdict), run.nominal_ms, run.why); + } + return run.expected_ms < taps.expected_ms ? UnitTestResult(true) : UnitTestResult("the run is not faster than the taps"); +} + +UnitTestResult test_wall_collapses_a_set(){ + // Three columns, all stopped by row 2's wall, then taps west. + const ToyMap toy({".....", ".....", "#####"}); + const RouteScore got = score(toy, {{2, 0}}, {0, 1}, { + {.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::OPEN_HOLD, .run = true}, + {.direction = Direction::SOUTH, .tiles = 1, .kind = ScoredLegKind::TO_WALL}, + {.direction = Direction::WEST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}, + }); + return all_of({expect(got, RouteVerdict::PASS, "open run east, then walls south and west")}); +} + +UnitTestResult test_open_hold_off_the_goal(){ + const ToyMap toy({"........"}); + const RouteScore got = score(toy, {{0, 0}}, {3, 0}, {{.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::OPEN_HOLD}}); + return all_of({expect(got, RouteVerdict::FAIL, "an open hold with nothing to stop it")}); +} + +UnitTestResult test_open_hold_into_grass(){ + const ToyMap toy({"....\"\"\"#"}); + const RouteScore got = score(toy, {{0, 0}}, {6, 0}, { + {.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::OPEN_HOLD}, + {.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::TO_WALL}, + }); + return all_of({expect(got, RouteVerdict::FAIL, "an open hold whose overshoot reaches grass")}); +} + +UnitTestResult test_open_hold_onto_a_ledge(){ + const ToyMap toy({".", ".", ".", "v", ".", "#"}); + const RouteScore got = score(toy, {{0, 0}}, {0, 4}, { + {.direction = Direction::SOUTH, .tiles = 2, .kind = ScoredLegKind::OPEN_HOLD}, + {.direction = Direction::SOUTH, .tiles = 2, .kind = ScoredLegKind::TO_WALL}, + }); + return all_of({expect(got, RouteVerdict::FAIL, "an open hold whose overshoot hops a ledge")}); +} + +UnitTestResult test_open_hold_before_a_wall(){ + const ToyMap toy({".....#"}); + const RouteScore got = score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 4, .kind = ScoredLegKind::OPEN_HOLD, .run = true}}); + return all_of({ + expect(got, RouteVerdict::FAIL, "an open hold that may stop a tile short"), + expect(score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::OPEN_HOLD, .run = true}, + {.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::TO_WALL, .run = true}}), + RouteVerdict::PASS, "an open hold that overshoots only toward a wall, then the wall"), + }); +} + +UnitTestResult test_wall_leg_through_a_warp(){ + const ToyMap toy({"..D..#"}); + const RouteScore got = score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}}); + return all_of({ + expect(got, RouteVerdict::FAIL, "a hold that walks into a warp"), + expect(score(toy, {{0, 0}}, {2, 0}, {{.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::TO_WALL}}), + RouteVerdict::PASS, "a hold that ends in the warp it is for"), + }); +} + +UnitTestResult test_trigger_stops_a_run(){ + const ToyMap toy({"..T...."}); + return all_of({expect(score(toy, {{0, 0}}, {2, 0}, {{.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::TO_WALL, .run = true}}), + RouteVerdict::PASS, "a run that the goal's trigger stops")}); +} + +UnitTestResult test_grass_charges_interruptions(){ + const ToyMap toy({".\"\"\"..#"}); + const RouteScore got = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + if (got.verdict != RouteVerdict::PASS || got.recoveries != 3 || got.replans != 0){ + return std::format("{}: {} recoveries, {} replans ({})", verdict_name(got.verdict), got.recoveries, got.replans, got.why); + } + if (got.expected_ms <= (double)got.nominal_ms || got.worst_ms <= got.nominal_ms){ + return std::format("expected {} ms, worst {} ms, nominal {} ms", got.expected_ms, got.worst_ms, got.nominal_ms); + } + return true; +} + +UnitTestResult test_taps_in_grass_need_a_replan(){ + // A lost tap in the grass leaves us a tile either way; the taps after it + // cannot tell, so without a replanner the plan fails. + const ToyMap toy({".\"\"\"...."}); + const std::vector taps{{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}; + const RouteScore failed = score(toy, {{0, 0}}, {5, 0}, taps); + // A replanner that goes east to the wall absorbs it. + const ToyMap walled({".\"\"\"..#"}); + const RouteReplanner to_wall = [](const std::vector&){ + return std::optional>({{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + }; + const RouteScore replanned = score(walled, {{0, 0}}, {5, 0}, taps, to_wall); + if (replanned.replans != 3){ + return std::format("{} replans", replanned.replans); + } + return all_of({ + expect(failed, RouteVerdict::FAIL, "taps in grass without a replanner"), + expect(replanned, RouteVerdict::PASS, "taps in grass with a wall to replan to"), + }); +} + +UnitTestResult test_recovery_back_through_the_grass_strands(){ + // The recovery walks back to the west wall, still in the grass, and + // taps east through it: an interruption there leads to the same + // recovery again, from tiles never known. + const ToyMap toy({"#\"\"\"\"...."}); + const std::vector taps{{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}; + const RouteReplanner back = [](const std::vector&){ + return std::optional>({{.direction = Direction::WEST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}, + {.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}); + }; + return all_of({expect(score(toy, {{1, 0}}, {6, 0}, taps, back), RouteVerdict::STRAND, "a recovery back through the grass")}); +} + +UnitTestResult test_recovery_from_a_wall_out_of_the_grass_retries(){ + // The same, but the west wall stops us on a tile out of the grass: the + // recovery starts from a known tile each time, so an interruption on + // the way back is a retry that ends, not a strand (00.04b + // to_catch_grass, whose goal is in the grass). + const ToyMap toy({"#.\"\"\"...."}); + const std::vector taps{{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}; + const RouteReplanner back = [](const std::vector&){ + return std::optional>({{.direction = Direction::WEST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}, + {.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}); + }; + return all_of({expect(score(toy, {{1, 0}}, {6, 0}, taps, back), RouteVerdict::PASS, "a recovery from a wall out of the grass")}); +} + +UnitTestResult test_too_many_recoveries(){ + const ToyMap toy({".\"\"\"..#"}); + const RouteReplanner to_wall = [](const std::vector&){ + return std::optional>({{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + }; + InterruptModel model = toy_model(); + model.max_recoveries = 0; + return all_of({expect(score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}, to_wall, model), + RouteVerdict::RETRIES, "a replan with no recoveries allowed")}); +} + +UnitTestResult test_trainer_sight_once(){ + const ToyMap toy({".ss...#"}); + const RouteScore got = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + if (got.recoveries != 1 || got.expected_ms < (double)(got.nominal_ms + 45000)){ + return std::format("{} recoveries, expected {} ms", got.recoveries, got.expected_ms); + } + return true; +} + + +struct RouteScorerInput{ + std::string name; + UnitTestResult (*test)(); +}; + +struct RouteScorerExpectation{ + std::string_view description; +}; + +struct RouteScorerCase{ + RouteScorerInput input; + RouteScorerExpectation expectation; +}; + +class Test_RouteScorer : public UnitTest{ +public: + explicit Test_RouteScorer(RouteScorerCase scenario) + : UnitTest("Pokemon::Navigation - RouteScorer: " + scenario.input.name) + , m_case(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.test(); + } + +private: + RouteScorerCase m_case; +}; + +const RouteScorerCase ROUTE_SCORER_CASES[] = { + { + .input = {.name = "taps take a tap each", .test = test_taps_time}, + .expectation = {.description = "4 taps cost 4 taps and a press"}, + }, + { + .input = {.name = "a run to a wall beats taps", .test = test_run_to_wall_beats_taps}, + .expectation = {.description = "run to the wall is faster than the same tiles in taps"}, + }, + { + .input = {.name = "walls bring a set of tiles to one", .test = test_wall_collapses_a_set}, + .expectation = {.description = "PASS"}, + }, + { + .input = {.name = "an open hold with nothing to stop it fails", .test = test_open_hold_off_the_goal}, + .expectation = {.description = "FAIL: may end off the goal"}, + }, + { + .input = {.name = "an open hold may not overshoot into grass", .test = test_open_hold_into_grass}, + .expectation = {.description = "FAIL: overshoot onto grass"}, + }, + { + .input = {.name = "an open hold may not overshoot onto a ledge", .test = test_open_hold_onto_a_ledge}, + .expectation = {.description = "FAIL: overshoot over a ledge"}, + }, + { + .input = {.name = "an open hold may overshoot toward a wall", .test = test_open_hold_before_a_wall}, + .expectation = {.description = "FAIL when short of the goal, PASS with the wall after it"}, + }, + { + .input = {.name = "a hold may not walk into a warp", .test = test_wall_leg_through_a_warp}, + .expectation = {.description = "FAIL through a warp, PASS into the goal warp"}, + }, + { + .input = {.name = "the goal's trigger stops a run", .test = test_trigger_stops_a_run}, + .expectation = {.description = "PASS"}, + }, + { + .input = {.name = "grass charges interruptions", .test = test_grass_charges_interruptions}, + .expectation = {.description = "3 recoveries, expected and worst above nominal"}, + }, + { + .input = {.name = "taps in grass need a replan", .test = test_taps_in_grass_need_a_replan}, + .expectation = {.description = "FAIL without a replanner, PASS with 3 replans"}, + }, + { + .input = {.name = "a recovery back through the grass strands", .test = test_recovery_back_through_the_grass_strands}, + .expectation = {.description = "STRAND"}, + }, + { + .input = {.name = "a recovery from a wall out of the grass retries", .test = test_recovery_from_a_wall_out_of_the_grass_retries}, + .expectation = {.description = "PASS"}, + }, + { + .input = {.name = "recoveries in a row are capped", .test = test_too_many_recoveries}, + .expectation = {.description = "RETRIES"}, + }, + { + .input = {.name = "a trainer sees us once", .test = test_trainer_sight_once}, + .expectation = {.description = "one trainer battle charged"}, + }, +}; + +} // namespace + + +void add_tests_RouteScorer(UnitTestDatabase& database){ + for (const auto& scenario : ROUTE_SCORER_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.h new file mode 100644 index 0000000000..db3576e784 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.h @@ -0,0 +1,23 @@ +/* Route Scorer Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_RouteScorer_Tests_H +#define PokemonAutomation_Pokemon_RouteScorer_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers route scorer unit tests. +void add_tests_RouteScorer(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index b96f9e31c0..8c3b8bbb6a 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1483,6 +1483,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_LegPlanner.h Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.h + Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h + Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp + Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h Source/Pokemon/Navigation/Pokemon_LegWalker.cpp Source/Pokemon/Navigation/Pokemon_LegWalker.h Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp @@ -1500,6 +1503,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_RouteLog.h Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.h + Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp + Source/Pokemon/Navigation/Pokemon_RouteScorer.h + Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp + Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.h Source/Pokemon/Options/Pokemon_BoxSortingTable.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.h Source/Pokemon/Options/Pokemon_EncounterBotOptions.h From afb70acce35806158cd5af0ba8f7c3de53ee8a4d Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 17:04:07 -0800 Subject: [PATCH 2/2] Pokemon Navigation tests: each case is a name, an input and an expectation The planner and scorer cases kept their name inside the input; it moves to the case itself. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_RobustLegPlanner_Tests.cpp | 98 ++++++++++++------- .../Navigation/Pokemon_RouteScorer_Tests.cpp | 49 ++++++---- 2 files changed, 96 insertions(+), 51 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp index b9866592b5..23af2621f7 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp @@ -109,7 +109,6 @@ constexpr RobustLegCosts HELD{.open_error = 1, .open_error_per = 0, .hold_open_l struct PlanInput{ - std::string_view name; std::vector rows; bool wraps = false; std::vector from; @@ -120,6 +119,7 @@ struct PlanExpectation{ std::string_view legs; // as describe() writes them }; struct PlanCase{ + std::string_view name; PlanInput input; PlanExpectation expectation; }; @@ -127,7 +127,7 @@ struct PlanCase{ class Test_RobustLegPlanner_Plan : public UnitTest{ public: explicit Test_RobustLegPlanner_Plan(PlanCase scenario) - : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.input.name)) + : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.name)) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -149,117 +149,138 @@ class Test_RobustLegPlanner_Plan : public UnitTest{ // Open legs on default costs may end a tile either way (two up to 5 tiles). const PlanCase PLAN_CASES[] = { { - .input = {.name = "a wall gathers the possible tiles", .rows = {"...#"}, .from = {{0, 0}, {1, 0}}, .goal = {2, 0}}, + .name = "a wall gathers the possible tiles", + .input = {.rows = {"...#"}, .from = {{0, 0}, {1, 0}}, .goal = {2, 0}}, .expectation = {.legs = "east 2 to wall: (2, 0)"}, }, { - .input = {.name = "no plan ends in the open while open legs may be off", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}}, + .name = "no plan ends in the open while open legs may be off", + .input = {.rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}}, .expectation = {.legs = "none"}, }, { - .input = {.name = "an exact open leg ends in the open", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, .costs = EXACT}, + .name = "an exact open leg ends in the open", + .input = {.rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, .costs = EXACT}, .expectation = {.legs = "east 3 open: (3, 0)"}, }, { + .name = "open_error_per 0 with no open_error is exact", .input = { - .name = "open_error_per 0 with no open_error is exact", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, + .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, .costs = {.open_error = 0, .open_error_per = 0}, }, .expectation = {.legs = "east 3 open: (3, 0)"}, }, { + .name = "open_error_per 0 keeps open_error", .input = { - .name = "open_error_per 0 keeps open_error", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, + .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, .costs = {.open_error = 1, .open_error_per = 0}, }, .expectation = {.legs = "none"}, }, { - .input = {.name = "a door is not a wall", .rows = {"#..D"}, .from = {{1, 0}}, .goal = {2, 0}, .costs = EXACT}, + .name = "a door is not a wall", + .input = {.rows = {"#..D"}, .from = {{1, 0}}, .goal = {2, 0}, .costs = EXACT}, .expectation = {.legs = "east 1 open: (2, 0)"}, }, { - .input = {.name = "no leg along a wander zone", .rows = {".www.", "....."}, .from = {{1, 0}}, .goal = {4, 0}, .costs = EXACT}, + .name = "no leg along a wander zone", + .input = {.rows = {".www.", "....."}, .from = {{1, 0}}, .goal = {4, 0}, .costs = EXACT}, .expectation = {.legs = "south 1 to wall: (1, 1); east 3 to wall: (4, 1); north 1 to wall: (4, 0)"}, }, { - .input = {.name = "a ledge hop counts 2 tiles", .rows = {".", "v", "."}, .from = {{0, 0}}, .goal = {0, 2}}, + .name = "a ledge hop counts 2 tiles", + .input = {.rows = {".", "v", "."}, .from = {{0, 0}}, .goal = {0, 2}}, .expectation = {.legs = "south 2 to wall: (0, 2)"}, }, { - .input = {.name = "a ledge cannot be climbed", .rows = {".", "v", "."}, .from = {{0, 2}}, .goal = {0, 0}}, + .name = "a ledge cannot be climbed", + .input = {.rows = {".", "v", "."}, .from = {{0, 2}}, .goal = {0, 0}}, .expectation = {.legs = "none"}, }, { - .input = {.name = "tall grass costs less than a detour", .rows = {".\"\"..", "....."}, .from = {{0, 0}}, .goal = {4, 0}}, + .name = "tall grass costs less than a detour", + .input = {.rows = {".\"\"..", "....."}, .from = {{0, 0}}, .goal = {4, 0}}, .expectation = {.legs = "east 4 to wall: (4, 0)"}, }, { + .name = "costly tall grass is walked round", .input = { - .name = "costly tall grass is walked round", .rows = {".\"\"..", "....."}, .from = {{0, 0}}, .goal = {4, 0}, + .rows = {".\"\"..", "....."}, .from = {{0, 0}}, .goal = {4, 0}, .costs = {.per_wild_tile = 20}, }, .expectation = {.legs = "south 1 to wall: (0, 1); east 4 to wall: (4, 1); north 1 to wall: (4, 0)"}, }, { // Only an open leg reaches the second row; a wall then gathers. - .input = {.name = "an open leg spreads, a wall gathers", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}}, + .name = "an open leg spreads, a wall gathers", + .input = {.rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}}, .expectation = {.legs = "east 1 open: (1, 0) (2, 0); south 1 to wall: (1, 1) (2, 1); east 2 to wall: (3, 1)"}, }, { + .name = "a spread wider than max_spread is not planned", .input = { - .name = "a spread wider than max_spread is not planned", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, + .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = {.max_spread = 1}, }, .expectation = {.legs = "none"}, }, { + .name = "the search gives up past max_searched", .input = { - .name = "the search gives up past max_searched", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, + .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = {.max_searched = 1}, }, .expectation = {.legs = "none"}, }, { + .name = "two open legs the same way are one", .input = { - .name = "two open legs the same way are one", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, + .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, .costs = {.exact_open_tiles = 12, .max_open_tiles = 2}, }, .expectation = {.legs = "east 3 open: (3, 0)"}, }, { - .input = {.name = "a walk that is never stopped is not a wall", .rows = {"...."}, .wraps = true, .from = {{0, 0}}, .goal = {2, 0}, .costs = EXACT}, + .name = "a walk that is never stopped is not a wall", + .input = {.rows = {"...."}, .wraps = true, .from = {{0, 0}}, .goal = {2, 0}, .costs = EXACT}, .expectation = {.legs = "east 2 open: (2, 0)"}, }, { - .input = {.name = "an open leg that may end off is held", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = HELD}, + .name = "an open leg that may end off is held", + .input = {.rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = HELD}, .expectation = {.legs = "east 1 held: (1, 0) (2, 0); south 1 to wall: (1, 1) (2, 1); east 2 to wall: (3, 1)"}, }, { - .input = {.name = "a held leg is refused when its long end lands in tall grass", .rows = {"..\"..", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = HELD}, + .name = "a held leg is refused when its long end lands in tall grass", + .input = {.rows = {"..\"..", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = HELD}, .expectation = {.legs = "none"}, }, { - .input = {.name = "a held leg is refused when its long end lands where someone wanders", .rows = {"..w..", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = HELD}, + .name = "a held leg is refused when its long end lands where someone wanders", + .input = {.rows = {"..w..", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = HELD}, .expectation = {.legs = "none"}, }, { - .input = {.name = "a held leg south lines up a wall leg", .rows = {".##", "...", "...", ".##", ".##"}, .from = {{0, 0}}, .goal = {2, 2}, .costs = HELD}, + .name = "a held leg south lines up a wall leg", + .input = {.rows = {".##", "...", "...", ".##", ".##"}, .from = {{0, 0}}, .goal = {2, 2}, .costs = HELD}, .expectation = {.legs = "south 1 held: (0, 1) (0, 2); east 2 to wall: (2, 1) (2, 2); south 1 to wall: (2, 2)"}, }, { - .input = {.name = "a held leg is refused when its long end hops a ledge", .rows = {".##", "...", "v..", ".##", ".##"}, .from = {{0, 0}}, .goal = {2, 2}, .costs = HELD}, + .name = "a held leg is refused when its long end hops a ledge", + .input = {.rows = {".##", "...", "v..", ".##", ".##"}, .from = {{0, 0}}, .goal = {2, 2}, .costs = HELD}, .expectation = {.legs = "none"}, }, { - .input = {.name = "open legs are tapped while hold_open_legs is off", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = {.open_error = 1, .open_error_per = 0}}, + .name = "open legs are tapped while hold_open_legs is off", + .input = {.rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, .costs = {.open_error = 1, .open_error_per = 0}}, .expectation = {.legs = "east 1 open: (1, 0) (2, 0); south 1 to wall: (1, 1) (2, 1); east 2 to wall: (3, 1)"}, }, }; struct CostInput{ - std::string_view name; std::vector rows; TilePos from; Legs legs; @@ -269,6 +290,7 @@ struct CostExpectation{ long long cost = 0; }; struct CostCase{ + std::string_view name; CostInput input; CostExpectation expectation; }; @@ -276,7 +298,7 @@ struct CostCase{ class Test_RobustLegPlanner_Cost : public UnitTest{ public: explicit Test_RobustLegPlanner_Cost(CostCase scenario) - : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.input.name)) + : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.name)) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -296,38 +318,44 @@ class Test_RobustLegPlanner_Cost : public UnitTest{ // leg that stops in the open. const CostCase COST_CASES[] = { { - .input = {.name = "a wall leg costs a leg and its tiles", .rows = {"...#"}, .from = {0, 0}, .legs = {{Direction::EAST, 2, true, {{2, 0}}}}}, + .name = "a wall leg costs a leg and its tiles", + .input = {.rows = {"...#"}, .from = {0, 0}, .legs = {{Direction::EAST, 2, true, {{2, 0}}}}}, .expectation = {.cost = 8 + 2}, }, { + .name = "an open leg costs its stop and open tiles on top", .input = { - .name = "an open leg costs its stop and open tiles on top", .rows = {"...#"}, .from = {0, 0}, + .rows = {"...#"}, .from = {0, 0}, .legs = {{Direction::EAST, 1, false, {{1, 0}}}}, .costs = {.exact_open_tiles = 12, .per_open_tile = 2}, }, .expectation = {.cost = 8 + 50 + 3}, }, { - .input = {.name = "each grass tile entered costs extra", .rows = {".\"\"#"}, .from = {0, 0}, .legs = {{Direction::EAST, 2, true, {{2, 0}}}}}, + .name = "each grass tile entered costs extra", + .input = {.rows = {".\"\"#"}, .from = {0, 0}, .legs = {{Direction::EAST, 2, true, {{2, 0}}}}}, .expectation = {.cost = 8 + 2 + 2 * 4}, }, { + .name = "a cost with open_error_per 0", .input = { - .name = "a cost with open_error_per 0", .rows = {"........"}, .from = {0, 0}, + .rows = {"........"}, .from = {0, 0}, .legs = {{Direction::EAST, 3, false, {{3, 0}}}}, .costs = {.open_error_per = 0}, }, .expectation = {.cost = 8 + 50 + 3}, }, { + .name = "a held leg pays no per_open_tile", .input = { - .name = "a held leg pays no per_open_tile", .rows = {"........"}, .from = {0, 0}, + .rows = {"........"}, .from = {0, 0}, .legs = {{Direction::EAST, 3, false, {{2, 0}, {3, 0}, {4, 0}}, true}}, .costs = {.open_error = 1, .open_error_per = 0, .per_open_tile = 2, .hold_open_legs = true}, }, .expectation = {.cost = 8 + 50 + 3}, }, { + .name = "held legs the same way are not joined", .input = { - .name = "held legs the same way are not joined", .rows = {"........"}, .from = {0, 0}, + .rows = {"........"}, .from = {0, 0}, .legs = { {Direction::EAST, 2, false, {{1, 0}, {2, 0}, {3, 0}}, true}, {Direction::EAST, 2, false, {{2, 0}, {3, 0}, {4, 0}, {5, 0}}, true}, @@ -337,15 +365,17 @@ const CostCase COST_CASES[] = { .expectation = {.cost = 2 * (8 + 50 + 2)}, }, { + .name = "each grass tile of an open leg costs per_open_wild_tile more", .input = { - .name = "each grass tile of an open leg costs per_open_wild_tile more", .rows = {".\"\"...."}, .from = {0, 0}, + .rows = {".\"\"...."}, .from = {0, 0}, .legs = {{Direction::EAST, 3, false, {{3, 0}}}}, .costs = {.exact_open_tiles = 12, .per_open_wild_tile = 10}, }, .expectation = {.cost = 8 + 50 + 3 + 2 * (4 + 10)}, }, { + .name = "per_open_wild_tile leaves a wall leg's grass alone", .input = { - .name = "per_open_wild_tile leaves a wall leg's grass alone", .rows = {".\"\"#"}, .from = {0, 0}, + .rows = {".\"\"#"}, .from = {0, 0}, .legs = {{Direction::EAST, 2, true, {{2, 0}}}}, .costs = {.per_open_wild_tile = 10}, }, .expectation = {.cost = 8 + 2 + 2 * 4}, diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp index a80bb7f59d..99b46637a0 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp @@ -277,7 +277,6 @@ UnitTestResult test_trainer_sight_once(){ struct RouteScorerInput{ - std::string name; UnitTestResult (*test)(); }; @@ -286,6 +285,7 @@ struct RouteScorerExpectation{ }; struct RouteScorerCase{ + std::string name; RouteScorerInput input; RouteScorerExpectation expectation; }; @@ -293,7 +293,7 @@ struct RouteScorerCase{ class Test_RouteScorer : public UnitTest{ public: explicit Test_RouteScorer(RouteScorerCase scenario) - : UnitTest("Pokemon::Navigation - RouteScorer: " + scenario.input.name) + : UnitTest("Pokemon::Navigation - RouteScorer: " + scenario.name) , m_case(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -306,63 +306,78 @@ class Test_RouteScorer : public UnitTest{ const RouteScorerCase ROUTE_SCORER_CASES[] = { { - .input = {.name = "taps take a tap each", .test = test_taps_time}, + .name = "taps take a tap each", + .input = {.test = test_taps_time}, .expectation = {.description = "4 taps cost 4 taps and a press"}, }, { - .input = {.name = "a run to a wall beats taps", .test = test_run_to_wall_beats_taps}, + .name = "a run to a wall beats taps", + .input = {.test = test_run_to_wall_beats_taps}, .expectation = {.description = "run to the wall is faster than the same tiles in taps"}, }, { - .input = {.name = "walls bring a set of tiles to one", .test = test_wall_collapses_a_set}, + .name = "walls bring a set of tiles to one", + .input = {.test = test_wall_collapses_a_set}, .expectation = {.description = "PASS"}, }, { - .input = {.name = "an open hold with nothing to stop it fails", .test = test_open_hold_off_the_goal}, + .name = "an open hold with nothing to stop it fails", + .input = {.test = test_open_hold_off_the_goal}, .expectation = {.description = "FAIL: may end off the goal"}, }, { - .input = {.name = "an open hold may not overshoot into grass", .test = test_open_hold_into_grass}, + .name = "an open hold may not overshoot into grass", + .input = {.test = test_open_hold_into_grass}, .expectation = {.description = "FAIL: overshoot onto grass"}, }, { - .input = {.name = "an open hold may not overshoot onto a ledge", .test = test_open_hold_onto_a_ledge}, + .name = "an open hold may not overshoot onto a ledge", + .input = {.test = test_open_hold_onto_a_ledge}, .expectation = {.description = "FAIL: overshoot over a ledge"}, }, { - .input = {.name = "an open hold may overshoot toward a wall", .test = test_open_hold_before_a_wall}, + .name = "an open hold may overshoot toward a wall", + .input = {.test = test_open_hold_before_a_wall}, .expectation = {.description = "FAIL when short of the goal, PASS with the wall after it"}, }, { - .input = {.name = "a hold may not walk into a warp", .test = test_wall_leg_through_a_warp}, + .name = "a hold may not walk into a warp", + .input = {.test = test_wall_leg_through_a_warp}, .expectation = {.description = "FAIL through a warp, PASS into the goal warp"}, }, { - .input = {.name = "the goal's trigger stops a run", .test = test_trigger_stops_a_run}, + .name = "the goal's trigger stops a run", + .input = {.test = test_trigger_stops_a_run}, .expectation = {.description = "PASS"}, }, { - .input = {.name = "grass charges interruptions", .test = test_grass_charges_interruptions}, + .name = "grass charges interruptions", + .input = {.test = test_grass_charges_interruptions}, .expectation = {.description = "3 recoveries, expected and worst above nominal"}, }, { - .input = {.name = "taps in grass need a replan", .test = test_taps_in_grass_need_a_replan}, + .name = "taps in grass need a replan", + .input = {.test = test_taps_in_grass_need_a_replan}, .expectation = {.description = "FAIL without a replanner, PASS with 3 replans"}, }, { - .input = {.name = "a recovery back through the grass strands", .test = test_recovery_back_through_the_grass_strands}, + .name = "a recovery back through the grass strands", + .input = {.test = test_recovery_back_through_the_grass_strands}, .expectation = {.description = "STRAND"}, }, { - .input = {.name = "a recovery from a wall out of the grass retries", .test = test_recovery_from_a_wall_out_of_the_grass_retries}, + .name = "a recovery from a wall out of the grass retries", + .input = {.test = test_recovery_from_a_wall_out_of_the_grass_retries}, .expectation = {.description = "PASS"}, }, { - .input = {.name = "recoveries in a row are capped", .test = test_too_many_recoveries}, + .name = "recoveries in a row are capped", + .input = {.test = test_too_many_recoveries}, .expectation = {.description = "RETRIES"}, }, { - .input = {.name = "a trainer sees us once", .test = test_trainer_sight_once}, + .name = "a trainer sees us once", + .input = {.test = test_trainer_sight_once}, .expectation = {.description = "one trainer battle charged"}, }, };