From a24eaee8eb68becabc0079f067732a12d43561d0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 20:48:34 -0800 Subject: [PATCH 1/3] Pokemon Navigation: robust leg planner, shared by the tile games BDSP's search over the sets of tiles a player may stand on after an uncertain open leg, lifted as a template over a step model so it can plan on any state (a world tile, or a map and a tile). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../Navigation/Pokemon_RobustLegPlanner.h | 431 ++++++++++++++++++ .../Pokemon_RobustLegPlanner_Tests.cpp | 220 +++++++++ .../Pokemon_RobustLegPlanner_Tests.h | 23 + SerialPrograms/cmake/SourceFiles.cmake | 3 + 5 files changed, 679 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 diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 8e3eb9c1ec..7de3fca05e 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -34,6 +34,7 @@ #include "Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.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" @@ -76,6 +77,7 @@ 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); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h new file mode 100644 index 0000000000..c4bff5a757 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h @@ -0,0 +1,431 @@ +/* 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::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. + * + */ + +#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; +}; + + +// 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. + 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; + 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{ + +// Where the player stops walking `direction` until stopped. +template +struct WallHit{ + State stop; + size_t tiles = 0; + bool held = false; +}; +template +WallHit slide_to_wall(const Model& model, const typename Model::State& from, Direction direction){ + WallHit hit{from}; + while (true){ + 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; + } +} + +// 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; +}; +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; +} + +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()); +} +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; +}; + +// 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. +template +std::optional> open_leg( + const Model& model, const std::vector& spread, Direction direction, int tiles, const RobustLegCosts& costs +){ + Expansion expansion; + int wild = 0; + int wander = 0; + const int error = tiles <= costs.exact_open_tiles ? 0 : costs.open_error + tiles / costs.open_error_per; + for (const auto& place : spread){ + for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ + const auto stepped = step_tiles(model, place, direction, n); + if (!stepped || stepped->along_wander){ + return std::nullopt; + } + wild = std::max(wild, stepped->wild); + wander = std::max(wander, stepped->wander); + expansion.leg.after.push_back(stepped->end); + } + } + expansion.cost = (long long)costs.per_leg + costs.leg_not_at_wall + + (long long)(costs.per_tile + costs.per_open_tile) * tiles + + (long long)costs.per_wild_tile * wild + (long long)costs.per_wander_tile * wander; + expansion.leg.direction = direction; + expansion.leg.tiles = (size_t)tiles; + return expansion; +} + +// 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() && consolidated.back().direction == leg.direction && !consolidated.back().to_wall){ + consolidated.back().tiles += leg.tiles; + consolidated.back().to_wall = leg.to_wall; + consolidated.back().after = leg.after; + }else{ + consolidated.push_back(leg); + } + } + return consolidated; +} + +// 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){ + if (auto wall = to_wall_leg(m_model, spread, direction, m_costs)){ + relax(spread, cost, std::move(*wall)); + } + 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; + } + 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 RobustLeg& prev = m_nodes.at(spread).leg; + if (expansion.leg.direction == prev.direction && !prev.to_wall){ + 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 && previous->direction == leg.direction && !previous->to_wall){ + 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..7b5ab5dff6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp @@ -0,0 +1,220 @@ +/* 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, and open legs may end a tile off. + * + */ + +#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. +class ToyGame{ +public: + using State = TilePos; + struct StateLess{ + bool operator()(const TilePos& a, const TilePos& b) const{ + return a.y != b.y ? a.y < b.y : a.x < b.x; + } + }; + + explicit ToyGame(std::vector rows) + : m_rows(std::move(rows)) + {} + + std::optional step(const State& state, Direction direction) const{ + const TilePos next = state.next(direction); + const char tile = at(next); + if (tile == '#' || tile == 'D'){ + return std::nullopt; + } + return next; + } + size_t step_tiles(const State&, const State&) const{ + return 1; + } + bool held_at(const State& state, Direction direction) const{ + return at(state.next(direction)) == '#'; + } + bool wild(const State& state) const{ + return at(state) == '"'; + } + bool wander(const State& state) const{ + return at(state) == 'w'; + } + +private: + 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; +}; + +using Legs = std::vector>; + +std::string describe(const std::optional& legs){ + if (!legs){ + return " none"; + } + std::string text; + for (const RobustLeg& leg : *legs){ + text += std::format("\n {} {}{} to", direction_name(leg.direction), leg.tiles, leg.to_wall ? " (to wall)" : " (open)"); + for (const TilePos& pos : leg.after){ + text += " " + to_string(pos); + } + } + return text; +} + +std::optional plan(const ToyGame& game, std::vector from, TilePos to, const RobustLegCosts& costs){ + return plan_robust_legs(game, std::move(from), std::function([to](const TilePos& pos){ return pos == to; }), costs); +} + +RobustLegCosts exact_costs(){ + RobustLegCosts costs; + costs.exact_open_tiles = costs.max_open_tiles; + return costs; +} + + +UnitTestResult test_wall_gathers_spread(){ + // The player is on one of two tiles; walking east to the wall puts them + // on the goal either way. + const ToyGame game({ + "...#", + }); + const auto legs = plan(game, {{0, 0}, {1, 0}}, {2, 0}, RobustLegCosts()); + if (!legs || legs->size() != 1 || !(*legs)[0].to_wall || (*legs)[0].tiles != 2 || (*legs)[0].after != std::vector{{2, 0}}){ + return "Expected one leg east 2 to the wall:" + describe(legs); + } + return true; +} + +UnitTestResult test_open_leg_spreads(){ + // The goal is in the middle of a row with no wall near it: an open leg + // may end a tile either side, so there is no robust plan. With exact + // open legs, one open leg reaches it. + const ToyGame game({ + "........", + }); + const auto uncertain = plan(game, {{0, 0}}, {3, 0}, RobustLegCosts()); + if (uncertain){ + return "Expected no plan with uncertain open legs:" + describe(uncertain); + } + const auto exact = plan(game, {{0, 0}}, {3, 0}, exact_costs()); + if (!exact || exact->size() != 1 || (*exact)[0].to_wall || (*exact)[0].tiles != 3){ + return "Expected one open leg east 3:" + describe(exact); + } + return true; +} + +UnitTestResult test_door_is_not_a_wall(){ + // Walking east would stop at the door, but holding on enters it: the + // leg to the goal next to it must be an open one. + const ToyGame game({ + "#..D", + }); + const auto legs = plan(game, {{1, 0}}, {2, 0}, exact_costs()); + if (!legs || legs->size() != 1 || (*legs)[0].to_wall || (*legs)[0].tiles != 1){ + return "Expected one open leg east 1:" + describe(legs); + } + return true; +} + +UnitTestResult test_avoids_wander_run(){ + // The top row runs along where someone wanders; the bottom row is one + // longer but clear. + const ToyGame game({ + ".www.", + ".....", + }); + const auto legs = plan(game, {{1, 0}}, {4, 0}, exact_costs()); + if (!legs){ + return "No plan."; + } + for (const RobustLeg& leg : *legs){ + if (leg.direction == Direction::EAST && leg.after[0].y == 0){ + return "Walked east along the wander zone:" + describe(legs); + } + } + return true; +} + +UnitTestResult test_cost_of_plan(){ + // A wall leg costs a leg and its tiles; an open one its stop and open + // tiles on top. + const ToyGame game({ + "...#", + }); + RobustLegCosts costs = exact_costs(); + costs.per_open_tile = 2; + const Legs wall{{Direction::EAST, 2, true, {{2, 0}}}}; + const Legs open{{Direction::EAST, 1, false, {{1, 0}}}}; + const long long wall_cost = robust_legs_cost(game, {{0, 0}}, wall, costs); + const long long open_cost = robust_legs_cost(game, {{0, 0}}, open, costs); + if (wall_cost != 8 + 2 || open_cost != 8 + 50 + 3){ + return std::format("Expected costs 10 and 61, got {} and {}.", wall_cost, open_cost); + } + return true; +} + + +struct RobustLegPlannerTestCase{ + std::string name; + UnitTestResult (*test)(); +}; + +class Test_RobustLegPlanner : public UnitTest{ +public: + explicit Test_RobustLegPlanner(RobustLegPlannerTestCase scenario) + : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.test(); + } + +private: + RobustLegPlannerTestCase m_scenario; +}; + +const RobustLegPlannerTestCase ROBUST_LEG_PLANNER_CASES[] = { + {.name = "a wall gathers the possible tiles", .test = test_wall_gathers_spread}, + {.name = "an open leg may end a tile off", .test = test_open_leg_spreads}, + {.name = "a door is not a wall", .test = test_door_is_not_a_wall}, + {.name = "no leg along a wander zone", .test = test_avoids_wander_run}, + {.name = "cost of given legs", .test = test_cost_of_plan}, +}; + +} // namespace + + +void add_tests_RobustLegPlanner(UnitTestDatabase& database){ + for (const auto& scenario : ROBUST_LEG_PLANNER_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/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a5f48d3bcb..5f6cd2bafb 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1476,6 +1476,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 From 7c954ac2f969097ae4bacd9776020f1e75223015 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 20:50:22 -0800 Subject: [PATCH 2/3] Pokemon Navigation: robust leg planner: document helpers; tests as input and expectation cases Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Navigation/Pokemon_RobustLegPlanner.h | 4 ++ .../Pokemon_RobustLegPlanner_Tests.cpp | 53 ++++++++++++++----- 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h index c4bff5a757..882e422c7f 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h @@ -117,6 +117,7 @@ struct WallHit{ size_t tiles = 0; bool held = false; }; +// Walks `direction` from `from` until the player is stopped. template WallHit slide_to_wall(const Model& model, const typename Model::State& from, Direction direction){ WallHit hit{from}; @@ -141,6 +142,7 @@ struct Stepped{ 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}; @@ -168,12 +170,14 @@ std::optional> step_tiles(const Model& model, typ return stepped; } +// 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{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp index 7b5ab5dff6..f7b73b7234 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon_RobustLegPlanner.h" @@ -79,7 +80,7 @@ std::string describe(const std::optional& legs){ for (const RobustLeg& leg : *legs){ text += std::format("\n {} {}{} to", direction_name(leg.direction), leg.tiles, leg.to_wall ? " (to wall)" : " (open)"); for (const TilePos& pos : leg.after){ - text += " " + to_string(pos); + text += std::format(" {}", to_string(pos)); } } return text; @@ -104,7 +105,7 @@ UnitTestResult test_wall_gathers_spread(){ }); const auto legs = plan(game, {{0, 0}, {1, 0}}, {2, 0}, RobustLegCosts()); if (!legs || legs->size() != 1 || !(*legs)[0].to_wall || (*legs)[0].tiles != 2 || (*legs)[0].after != std::vector{{2, 0}}){ - return "Expected one leg east 2 to the wall:" + describe(legs); + return std::format("Expected one leg east 2 to the wall:{}", describe(legs)); } return true; } @@ -118,11 +119,11 @@ UnitTestResult test_open_leg_spreads(){ }); const auto uncertain = plan(game, {{0, 0}}, {3, 0}, RobustLegCosts()); if (uncertain){ - return "Expected no plan with uncertain open legs:" + describe(uncertain); + return std::format("Expected no plan with uncertain open legs:{}", describe(uncertain)); } const auto exact = plan(game, {{0, 0}}, {3, 0}, exact_costs()); if (!exact || exact->size() != 1 || (*exact)[0].to_wall || (*exact)[0].tiles != 3){ - return "Expected one open leg east 3:" + describe(exact); + return std::format("Expected one open leg east 3:{}", describe(exact)); } return true; } @@ -135,7 +136,7 @@ UnitTestResult test_door_is_not_a_wall(){ }); const auto legs = plan(game, {{1, 0}}, {2, 0}, exact_costs()); if (!legs || legs->size() != 1 || (*legs)[0].to_wall || (*legs)[0].tiles != 1){ - return "Expected one open leg east 1:" + describe(legs); + return std::format("Expected one open leg east 1:{}", describe(legs)); } return true; } @@ -153,7 +154,7 @@ UnitTestResult test_avoids_wander_run(){ } for (const RobustLeg& leg : *legs){ if (leg.direction == Direction::EAST && leg.after[0].y == 0){ - return "Walked east along the wander zone:" + describe(legs); + return std::format("Walked east along the wander zone:{}", describe(legs)); } } return true; @@ -178,19 +179,28 @@ UnitTestResult test_cost_of_plan(){ } -struct RobustLegPlannerTestCase{ +struct RobustLegPlannerInput{ std::string name; UnitTestResult (*test)(); }; +struct RobustLegPlannerExpectation{ + std::string_view description; +}; + +struct RobustLegPlannerTestCase{ + RobustLegPlannerInput input; + RobustLegPlannerExpectation expectation; +}; + class Test_RobustLegPlanner : public UnitTest{ public: explicit Test_RobustLegPlanner(RobustLegPlannerTestCase scenario) - : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.name)) + : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.input.name)) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - return m_scenario.test(); + return m_scenario.input.test(); } private: @@ -198,11 +208,26 @@ class Test_RobustLegPlanner : public UnitTest{ }; const RobustLegPlannerTestCase ROBUST_LEG_PLANNER_CASES[] = { - {.name = "a wall gathers the possible tiles", .test = test_wall_gathers_spread}, - {.name = "an open leg may end a tile off", .test = test_open_leg_spreads}, - {.name = "a door is not a wall", .test = test_door_is_not_a_wall}, - {.name = "no leg along a wander zone", .test = test_avoids_wander_run}, - {.name = "cost of given legs", .test = test_cost_of_plan}, + { + .input = {.name = "a wall gathers the possible tiles", .test = test_wall_gathers_spread}, + .expectation = {.description = "a leg to a wall ends every possible start on one tile"}, + }, + { + .input = {.name = "an open leg may end a tile off", .test = test_open_leg_spreads}, + .expectation = {.description = "no plan ends on an open tile unless open legs are exact"}, + }, + { + .input = {.name = "a door is not a wall", .test = test_door_is_not_a_wall}, + .expectation = {.description = "a stop that does not hold the player is not a wall leg"}, + }, + { + .input = {.name = "no leg along a wander zone", .test = test_avoids_wander_run}, + .expectation = {.description = "goes round a row where someone wanders"}, + }, + { + .input = {.name = "cost of given legs", .test = test_cost_of_plan}, + .expectation = {.description = "charges a wall leg its tiles and an open leg its stop on top"}, + }, }; } // namespace From 1ca9ec484722bf29b436f09c6f66be5649d388c0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 00:18:49 -0800 Subject: [PATCH 3/3] Pokemon Navigation: robust leg planner tests as data; open_error_per 0; capped slide (#412 review) Each row now holds the map, starts, goal and costs, and the expected plan as text; one runner compares describe() output. New rows cover a ledge hop, tall grass, max_spread, max_searched, joined open legs and a walk that never stops. open_error_per 0 adds no growth instead of dividing by zero, and slide_to_wall() gives up as not held after 1024 steps. The header says how this step model relates to LegPlanner's and that warps are the caller's job. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Navigation/Pokemon_RobustLegPlanner.h | 36 +- .../Pokemon_RobustLegPlanner_Tests.cpp | 329 +++++++++++------- 2 files changed, 228 insertions(+), 137 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h index 882e422c7f..6c527a19fb 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h @@ -12,7 +12,8 @@ * 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 + * 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; @@ -27,6 +28,12 @@ * 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 @@ -66,7 +73,8 @@ struct RobustLegCosts{ 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. + // 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 @@ -110,6 +118,11 @@ long long robust_legs_cost( 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{ @@ -117,11 +130,12 @@ struct WallHit{ size_t tiles = 0; bool held = false; }; -// Walks `direction` from `from` until the player is stopped. +// 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}; - while (true){ + 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); @@ -130,6 +144,18 @@ WallHit slide_to_wall(const Model& model, const typename 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 @@ -237,7 +263,7 @@ std::optional> open_leg( Expansion expansion; int wild = 0; int wander = 0; - const int error = tiles <= costs.exact_open_tiles ? 0 : costs.open_error + tiles / costs.open_error_per; + const int error = open_leg_error(tiles, costs); for (const auto& place : spread){ for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ const auto stepped = step_tiles(model, place, direction, n); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp index f7b73b7234..6333649e2c 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp @@ -3,14 +3,17 @@ * 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, and open legs may end a tile off. + * 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" @@ -24,33 +27,37 @@ 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. +// 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; - struct StateLess{ - bool operator()(const TilePos& a, const TilePos& b) const{ - return a.y != b.y ? a.y < b.y : a.x < b.x; - } - }; + using StateLess = std::less; - explicit ToyGame(std::vector rows) - : m_rows(std::move(rows)) + 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{ - const TilePos next = state.next(direction); + TilePos next = wrapped(state.next(direction)); const char tile = at(next); - if (tile == '#' || tile == 'D'){ + 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&, const State&) const{ - return 1; + 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(state.next(direction)) == '#'; + return at(wrapped(state.next(direction))) != 'D'; } bool wild(const State& state) const{ return at(state) == '"'; @@ -60,6 +67,13 @@ class ToyGame{ } 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 '#'; @@ -68,165 +82,213 @@ class ToyGame{ } 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"; + return "none"; } std::string text; for (const RobustLeg& leg : *legs){ - text += std::format("\n {} {}{} to", direction_name(leg.direction), leg.tiles, leg.to_wall ? " (to wall)" : " (open)"); + text += std::format("{}{} {} {}:", text.empty() ? "" : "; ", direction_name(leg.direction), leg.tiles, leg.to_wall ? "to wall" : "open"); for (const TilePos& pos : leg.after){ - text += std::format(" {}", to_string(pos)); + text += " " + to_string(pos); } } return text; } -std::optional plan(const ToyGame& game, std::vector from, TilePos to, const RobustLegCosts& costs){ - return plan_robust_legs(game, std::move(from), std::function([to](const TilePos& pos){ return pos == to; }), costs); -} - -RobustLegCosts exact_costs(){ - RobustLegCosts costs; - costs.exact_open_tiles = costs.max_open_tiles; - return costs; -} +constexpr RobustLegCosts EXACT{.exact_open_tiles = 12}; -UnitTestResult test_wall_gathers_spread(){ - // The player is on one of two tiles; walking east to the wall puts them - // on the goal either way. - const ToyGame game({ - "...#", - }); - const auto legs = plan(game, {{0, 0}, {1, 0}}, {2, 0}, RobustLegCosts()); - if (!legs || legs->size() != 1 || !(*legs)[0].to_wall || (*legs)[0].tiles != 2 || (*legs)[0].after != std::vector{{2, 0}}){ - return std::format("Expected one leg east 2 to the wall:{}", describe(legs)); - } - return true; -} - -UnitTestResult test_open_leg_spreads(){ - // The goal is in the middle of a row with no wall near it: an open leg - // may end a tile either side, so there is no robust plan. With exact - // open legs, one open leg reaches it. - const ToyGame game({ - "........", - }); - const auto uncertain = plan(game, {{0, 0}}, {3, 0}, RobustLegCosts()); - if (uncertain){ - return std::format("Expected no plan with uncertain open legs:{}", describe(uncertain)); - } - const auto exact = plan(game, {{0, 0}}, {3, 0}, exact_costs()); - if (!exact || exact->size() != 1 || (*exact)[0].to_wall || (*exact)[0].tiles != 3){ - return std::format("Expected one open leg east 3:{}", describe(exact)); - } - return true; -} - -UnitTestResult test_door_is_not_a_wall(){ - // Walking east would stop at the door, but holding on enters it: the - // leg to the goal next to it must be an open one. - const ToyGame game({ - "#..D", - }); - const auto legs = plan(game, {{1, 0}}, {2, 0}, exact_costs()); - if (!legs || legs->size() != 1 || (*legs)[0].to_wall || (*legs)[0].tiles != 1){ - return std::format("Expected one open leg east 1:{}", describe(legs)); - } - return 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; +}; -UnitTestResult test_avoids_wander_run(){ - // The top row runs along where someone wanders; the bottom row is one - // longer but clear. - const ToyGame game({ - ".www.", - ".....", - }); - const auto legs = plan(game, {{1, 0}}, {4, 0}, exact_costs()); - if (!legs){ - return "No plan."; - } - for (const RobustLeg& leg : *legs){ - if (leg.direction == Direction::EAST && leg.after[0].y == 0){ - return std::format("Walked east along the wander zone:{}", describe(legs)); +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; } - return true; -} +private: + PlanCase m_scenario; +}; -UnitTestResult test_cost_of_plan(){ - // A wall leg costs a leg and its tiles; an open one its stop and open - // tiles on top. - const ToyGame game({ - "...#", - }); - RobustLegCosts costs = exact_costs(); - costs.per_open_tile = 2; - const Legs wall{{Direction::EAST, 2, true, {{2, 0}}}}; - const Legs open{{Direction::EAST, 1, false, {{1, 0}}}}; - const long long wall_cost = robust_legs_cost(game, {{0, 0}}, wall, costs); - const long long open_cost = robust_legs_cost(game, {{0, 0}}, open, costs); - if (wall_cost != 8 + 2 || open_cost != 8 + 50 + 3){ - return std::format("Expected costs 10 and 61, got {} and {}.", wall_cost, open_cost); - } - return true; -} +// 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)"}, + }, +}; -struct RobustLegPlannerInput{ - std::string name; - UnitTestResult (*test)(); +struct CostInput{ + std::string_view name; + std::vector rows; + TilePos from; + Legs legs; + RobustLegCosts costs; }; - -struct RobustLegPlannerExpectation{ - std::string_view description; +struct CostExpectation{ + long long cost = 0; }; - -struct RobustLegPlannerTestCase{ - RobustLegPlannerInput input; - RobustLegPlannerExpectation expectation; +struct CostCase{ + CostInput input; + CostExpectation expectation; }; -class Test_RobustLegPlanner : public UnitTest{ +class Test_RobustLegPlanner_Cost : public UnitTest{ public: - explicit Test_RobustLegPlanner(RobustLegPlannerTestCase scenario) + 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{ - return m_scenario.input.test(); + 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: - RobustLegPlannerTestCase m_scenario; + CostCase m_scenario; }; -const RobustLegPlannerTestCase ROBUST_LEG_PLANNER_CASES[] = { - { - .input = {.name = "a wall gathers the possible tiles", .test = test_wall_gathers_spread}, - .expectation = {.description = "a leg to a wall ends every possible start on one tile"}, - }, +// 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 = "an open leg may end a tile off", .test = test_open_leg_spreads}, - .expectation = {.description = "no plan ends on an open tile unless open legs are exact"}, + .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 = "a door is not a wall", .test = test_door_is_not_a_wall}, - .expectation = {.description = "a stop that does not hold the player is not a wall leg"}, + .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 = "no leg along a wander zone", .test = test_avoids_wander_run}, - .expectation = {.description = "goes round a row where someone wanders"}, + .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 = "cost of given legs", .test = test_cost_of_plan}, - .expectation = {.description = "charges a wall leg its tiles and an open leg its stop on top"}, + .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}, }, }; @@ -234,8 +296,11 @@ const RobustLegPlannerTestCase ROBUST_LEG_PLANNER_CASES[] = { void add_tests_RobustLegPlanner(UnitTestDatabase& database){ - for (const auto& scenario : ROBUST_LEG_PLANNER_CASES){ - database.add(scenario); + for (const PlanCase& scenario : PLAN_CASES){ + database.add(scenario); + } + for (const CostCase& scenario : COST_CASES){ + database.add(scenario); } }