From 1fe2192401fcdd5cd1520586f70227c08cfc1a71 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 10:14:26 -0800 Subject: [PATCH 01/39] PokemonFRLG: S12, Fuchsia Gym and Koga (12.01, 12.02) on the 11.03 stack The change of #414 (frlg/stage12-koga, without the player-girl merge it carries from frlg/stage8-rocktunnel), brought over as one patch on top of 11.03. 12.01 now starts where 11.03's Fly lands, below Fuchsia's Center facing south, and walks in to the nurse; the chain test and the whole-story sim lose their exception for it. The segment 12 golden gets its own header. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldMaps.cpp | 3 + .../PokemonFRLG/PokemonFRLG_Tests.cpp | 1 + .../PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp | 270 ++++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryParty.cpp | 3 + .../PokemonFRLG_AutoStoryPlanGolden12.h | 28 ++ .../PokemonFRLG_AutoStoryRows_Tests.h | 2 + .../PokemonFRLG_AutoStoryRunPlan_Tests.cpp | 8 +- .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 14 +- .../AutoStory/StoryData/frlg-12.01.plan.json | 162 +++++++++++ .../AutoStory/StoryData/frlg-12.02.plan.json | 90 ++++++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 11 files changed, 573 insertions(+), 10 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.02.plan.json diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp index 1f2bc021b7..a08ef364d2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp @@ -136,6 +136,9 @@ constexpr std::string_view MAP_NAMES[] = { "SafariZone_North", "SafariZone_West", "SafariZone_SecretHouse", + // Koga's gym, and the Warden's house (GOLD TEETH for HM04). + "FuchsiaCity_Gym", + "FuchsiaCity_WardensHouse", "CeruleanCave_1F", "CeruleanCave_2F", "CeruleanCave_B1F", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 7774bb1077..711264cdd4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -330,6 +330,7 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& database){ add_tests_AutoStorySnorlax(database); add_tests_AutoStorySlope(database); add_tests_AutoStorySafari(database); + add_tests_AutoStoryFuchsiaGym(database); } void add_tests(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp new file mode 100644 index 0000000000..c461dd1832 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp @@ -0,0 +1,270 @@ +/* AutoStory Fuchsia Gym Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Rows 12.01 and 12.02 (StoryData/frlg-12.01.plan.json, 12.02) on the + * overworld sim: from Fuchsia's nurse into the gym past Jugglers Kayden + * and Kirk and round its top edge to west of Koga; and from Koga out to + * the Warden and back to the nurse. And the lead's attacks against the + * gym's parties. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryParty.h" +#include "PokemonFRLG_AutoStoryRooms.h" +#include "PokemonFRLG_AutoStoryMember.h" +#include "PokemonFRLG_AutoStoryRowSim.h" +#include "PokemonFRLG_AutoStoryRows_Tests.h" +#include "PokemonFRLG_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +const std::string GYM = "FuchsiaCity_Gym"; + +struct AutoStoryFuchsiaGymInput{ + std::string name; + std::function body; +}; + +struct AutoStoryFuchsiaGymExpectation{ + std::string_view description; +}; + +struct AutoStoryFuchsiaGymCase{ + AutoStoryFuchsiaGymInput input; + AutoStoryFuchsiaGymExpectation expectation; +}; + +class Test_AutoStoryFuchsiaGym : public UnitTest{ +public: + explicit Test_AutoStoryFuchsiaGym(AutoStoryFuchsiaGymCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStory - Simulation: {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_case.input.body(); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + } + } + +private: + AutoStoryFuchsiaGymCase m_case; +}; + +const StoryCheckpoint& checkpoint(std::string_view id){ + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id == id){ + return row; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No checkpoint {}.", id)); +} + +// The rows on the sim, which can't walk into a Center with no map. Kept +// across sims: the trainers fought. +struct GymWalk{ + StoryPose at; + std::optional sim; + std::vector fought; + + explicit GymWalk(StoryPose start) + : at(std::move(start)) + { + place(); + } + // A fresh sim on `at`, after a step it can't walk. + void place(){ + if (sim){ + const std::vector& beaten = sim->state().trainers_beaten; + fought.insert(fought.end(), beaten.begin(), beaten.end()); + } + sim.emplace(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + } + std::vector all_fought() const{ + std::vector all = fought; + const std::vector& beaten = sim->state().trainers_beaten; + all.insert(all.end(), beaten.begin(), beaten.end()); + return all; + } +}; + +// A step of a row on the sim: row_step_on_sim(), but the way into a +// Center, which has no map, and Koga's battle, which a talk starts, leave +// the player where the table says. +std::string gym_step_on_sim(const StoryStep& step, const std::string& id, GymWalk& walk){ + const bool center = step.action == CENTER_ENTER_VARIANT; + if (center || (step.kind == StoryStepKind::BATTLE && step.name == "koga")){ + walk.at = *story_pose(Pokemon::pose_of(*step.pose_after)); + if (center){ + walk.place(); + } + return ""; + } + return row_step_on_sim(*walk.sim, walk.at, step, id); +} + +// Row `id`'s steps on the sim from `walk.at`: the failure, or empty. +std::string row_on_sim(std::string_view id, GymWalk& walk){ + const StoryCheckpoint& row = checkpoint(id); + for (const StoryStep& step : row.steps){ + if (const std::string failure = gym_step_on_sim(step, row.id, walk); !failure.empty()){ + return std::format("{}: ended on {}; {}", id, to_string(walk.sim->state().position), failure); + } + if (!walk.sim->state().violations.empty()){ + return std::format("{}/{}: a violation on the way: {}", id, step.name, walk.sim->state().violations.back()); + } + } + return ""; +} + +// 12.01 from the nurse: the gym, Kayden fought from (14, 16) and Kirk from +// (14, 11), round the top edge to west of Koga, where 12.02 starts; then +// 12.02 from there to the Warden and the nurse, meeting no one else. The +// sim's lookers see every way at once, so Edgar, whose lines the legs to +// the walls cross, always stops the walk there: the worst case, which +// the console meets only when he looks that way. +UnitTestResult test_gym_rows(){ + GymWalk walk(*story_pose(Pokemon::pose_of(*checkpoint("12.01").start))); + if (const std::string failure = row_on_sim("12.01", walk); !failure.empty()){ + return failure; + } + const MapPosition west_of_koga{GYM, {6, 13}}; + if (!(walk.sim->state().position == west_of_koga) || walk.sim->state().facing != Direction::EAST){ + return std::format("12.01: ended on {}, not west of Koga {} facing east.", to_string(walk.sim->state().position), to_string(west_of_koga)); + } + if (walk.all_fought() != std::vector{"rocker", "rocker", "man"}){ + return std::format("12.01: fought {} trainers, not Kayden, Kirk and Edgar.", walk.all_fought().size()); + } + const StoryPose next = *story_pose(Pokemon::pose_of(*checkpoint("12.02").start)); + if (next.map != GYM || !(next.tile == west_of_koga.point)){ + return "12.02 doesn't start where 12.01 ends."; + } + if (const std::string failure = row_on_sim("12.02", walk); !failure.empty()){ + return failure; + } + if (walk.all_fought().size() != 3){ + return "12.02: fought a trainer after Koga."; + } + if (walk.at.map != "FuchsiaCity_PokemonCenter_1F"){ + return std::format("12.02: ended on {}, not at Fuchsia's nurse.", walk.at.map); + } + return true; +} + +// The lead as pokeguy brings it to the gym after HM03 (12.01): Surf over +// Water Gun, Water Pulse, Bite, Mega Kick. It picks Surf against Koga's +// Poison types (pokeguy: Surf throughout) and Surf or Bite, never Mega +// Kick (5 PP) or Water Pulse, against the Jugglers' Psychic types. +UnitTestResult test_lead_moves_in_gym(){ + PartyMember lead; + lead.species = "blastoise"; + lead.moves_read = true; + lead.level = 39; + lead.moves = {{"surf", 15}, {"water-pulse", 20}, {"bite", 25}, {"mega-kick", 5}}; + constexpr size_t SURF = 0; + constexpr size_t BITE = 2; + for (std::string_view foe : {"koffing", "muk", "weezing"}){ + if (attack_slot_against(lead, {std::string(foe)}) != SURF){ + return std::format("Against {}: expected Surf.", foe); + } + } + for (std::string_view foe : {"drowzee", "kadabra", "hypno"}){ + const std::optional slot = attack_slot_against(lead, {std::string(foe)}); + if (slot != SURF && slot != BITE){ + return std::format("Against {}: expected Surf or Bite.", foe); + } + } + return true; +} + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +// Battle checkpoint `id`'s precondition: a LEVEL step on the lead before +// its battle `battle`, at least `pokeguy`, pokeguy's level there (whose +// sims stand for the fight at that level or above). A lead at that level +// passes it; one a level below stops the checkpoint before the fight. +UnitTestResult check_lead_level_precondition(Logger& logger, std::string_view id, std::string_view battle, unsigned pokeguy){ + std::optional check; + for (const StoryStep& step : checkpoint(id).steps){ + if (step.kind == StoryStepKind::BATTLE && step.name == battle){ + break; + } + if (step.action == LEVEL_ACTION){ + check = level_check_of(step.args); + } + } + if (!check || check->slot != 0 || check->level != pokeguy){ + return std::format("{}: expected a LEVEL step on the lead, at least Lv{}, before {}.", id, pokeguy, battle); + } + for (const unsigned level : {pokeguy, pokeguy - 1}){ + const MemberReader lead = [level](size_t slot) -> std::optional{ + if (slot != 0){ + return std::nullopt; + } + return MemberInfo{.species = "blastoise", .level = level}; + }; + const LevelResult result = run_level_check(logger, lead, *check); + const LevelEnd expected = level >= pokeguy ? LevelEnd::REACHED : LevelEnd::BELOW; + if (result.end != expected || result.level != level){ + return std::format("{}: a Lv{} lead {} the Lv{} check.", id, level, level >= pokeguy ? "fails" : "passes", pokeguy); + } + } + return true; +} + +const AutoStoryFuchsiaGymCase AUTO_STORY_FUCHSIA_GYM_CASES[] = { + { + .input = {.name = "12.01 past Kayden and Kirk to west of Koga and 12.02 to the Warden and the nurse", .body = test_gym_rows}, + .expectation = {.description = "Kayden and Kirk fought where the table steps into their lines, no one else; ends at Fuchsia's nurse"}, + }, + { + .input = {.name = "the lead's attacks in Fuchsia Gym", .body = test_lead_moves_in_gym}, + .expectation = {.description = "Surf against Koga's Pokemon, Surf or Bite against the Jugglers'"}, + }, + { + .input = {.name = "12.02 stops before Koga unless the lead is at least pokeguy's Lv39", .body = []{ + QuietLogger logger; + return check_lead_level_precondition(logger, "12.02", "koga", 39); + }}, + .expectation = {.description = "a Lv39 lead passes the LEVEL step, a Lv38 one stops there"}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryFuchsiaGym(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_FUCHSIA_GYM_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp index 40ec1ce9fe..e23600b0b1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp @@ -116,6 +116,9 @@ struct Attack{ std::string_view move; }; constexpr Attack ATTACKS[] = { + // From HM03 (12.01) on, as pokeguy: Surf on everything it is not + // resisted by (1:15:14 on). + {.line = "squirtle", .move = "surf"}, // Blastoise's strongest STAB move: a tie with Bite against Pidgeotto // went to Bite, and one with Bubble against Growlithe to Bubble, and // the Tower rival won (console B, 2026-11-12). diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h new file mode 100644 index 0000000000..f55057d2e3 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h @@ -0,0 +1,28 @@ +/* FRLG AutoStory Plan Golden, Segment 12 + * + * From: https://github.com/PokemonAutomation/ + * + * The golden's lines from segment 12 on, after + * PokemonFRLG_AutoStoryPlanGolden11.h's. The test reads FRLG_PLAN_GOLDEN, + * FRLG_PLAN_GOLDEN_10, FRLG_PLAN_GOLDEN_11, then these. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryPlanGolden12_H +#define PokemonAutomation_PokemonFRLG_AutoStoryPlanGolden12_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +// The stored plan lines from segment 12 on, after FRLG_PLAN_GOLDEN_11's. +inline constexpr std::string_view FRLG_PLAN_GOLDEN_12[] = { + "", +}; + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h index 2f521f46bc..290e02f540 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h @@ -34,6 +34,8 @@ void add_tests_AutoStorySnorlax(UnitTestDatabase& database); void add_tests_AutoStorySlope(UnitTestDatabase& database); // Row 11.03 on the sims (PokemonFRLG_AutoStorySafari_Tests.cpp). void add_tests_AutoStorySafari(UnitTestDatabase& database); +// Rows 12.01 and 12.02, Fuchsia Gym, on the overworld sim (PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp). +void add_tests_AutoStoryFuchsiaGym(UnitTestDatabase& database); } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp index ee277c2cfd..d94dd1cedd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp @@ -139,7 +139,7 @@ class Test_RunPlan : public UnitTest{ const RunPlanScenario m_scenario; }; -const std::string TODAY = "01.01 01.03 01.04 01.05 02.01 02.02 02.03 03.01 03.02 03.03 04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03"; +const std::string TODAY = "01.01 01.03 01.04 01.05 02.01 02.02 02.03 03.01 03.02 03.03 04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02"; const RunPlanScenario RUN_PLAN_CASES[] = { { @@ -230,11 +230,11 @@ const RunPlanScenario RUN_PLAN_CASES[] = { }, { .input = {.name = "Gift RNG off: 04.03 is passed over", .first = "04.01"}, - .expectation = {.expected_ids = "04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03"}, + .expectation = {.expected_ids = "04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02"}, }, { .input = {.name = "Gift RNG off: 04.03 runs when started at", .first = "04.03"}, - .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03"}, + .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02"}, }, { .input = { .name = "Gift RNG: started at 04.03, from the save beside the salesman", @@ -273,7 +273,7 @@ const RunPlanScenario RUN_PLAN_CASES[] = { }, { .input = {.name = "Starter RNG alone: 04.03 runs when started at", .first = "04.03", .handoffs = {.starter_rng = true}}, - .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03"}, + .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02"}, }, { .input = { .name = "Starter RNG first, with both on", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index c59345bf22..3f232448e2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -37,6 +37,7 @@ #include "PokemonFRLG_AutoStoryPlanGolden.h" #include "PokemonFRLG_AutoStoryPlanGolden10.h" #include "PokemonFRLG_AutoStoryPlanGolden11.h" +#include "PokemonFRLG_AutoStoryPlanGolden12.h" #include "PokemonFRLG_AutoStoryMoveData.h" #include "PokemonFRLG_AutoStoryStepTable.h" #include "PokemonFRLG_AutoStoryTable.h" @@ -283,8 +284,8 @@ UnitTestResult check_checkpoint(const StoryCheckpoint& checkpoint, StoryPose& po // before leaves the player, and adds the plans to `golden`. UnitTestResult chain_story_routes(std::vector& golden){ const std::vector& checkpoints = story_checkpoints(); - if (checkpoints.size() != 50 || checkpoints[0].start){ - return "Expected 50 checkpoints, the first from a new game."; + if (checkpoints.size() != 52 || checkpoints[0].start){ + return "Expected 52 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ @@ -314,7 +315,7 @@ UnitTestResult test_routes_and_chain(){ // PokemonFRLG_AutoStoryPlanGolden.h. A change that should not alter any // plan must leave this byte-identical. To regenerate after an intended plan // change: run this suite, and replace the lines of FRLG_PLAN_GOLDEN, -// FRLG_PLAN_GOLDEN_10 (segment 10) and FRLG_PLAN_GOLDEN_11 (segment 11 on) +// FRLG_PLAN_GOLDEN_10 (segment 10), FRLG_PLAN_GOLDEN_11 (segment 11) and FRLG_PLAN_GOLDEN_12 (segment 12 on) // with the lines the failure lists after "GOLDEN|". UnitTestResult test_golden_plans(){ std::vector actual; @@ -325,6 +326,7 @@ UnitTestResult test_golden_plans(){ std::vector golden(std::begin(FRLG_PLAN_GOLDEN), std::end(FRLG_PLAN_GOLDEN)); golden.insert(golden.end(), std::begin(FRLG_PLAN_GOLDEN_10), std::end(FRLG_PLAN_GOLDEN_10)); golden.insert(golden.end(), std::begin(FRLG_PLAN_GOLDEN_11), std::end(FRLG_PLAN_GOLDEN_11)); + golden.insert(golden.end(), std::begin(FRLG_PLAN_GOLDEN_12), std::end(FRLG_PLAN_GOLDEN_12)); const size_t stored = golden.size(); size_t first_diff = 0; while (first_diff < actual.size() && first_diff < stored && actual[first_diff] == golden[first_diff]){ @@ -701,7 +703,7 @@ UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::set Date: Thu, 12 Nov 2026 10:20:55 -0800 Subject: [PATCH 02/39] PokemonFRLG: 12.01 out of the Center by its walls, 12.02 taps to the Warden; S12 golden The scene end pose sweep moved the Center script's end a tile off the nurse, and 12.01's walk out then missed the mat: legs to the Center's west and north walls first. 12.02's open leg east onto the tile below the Warden wasn't found again before the A press: a tap from the house's west wall. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryPlanGolden12.h | 48 ++++++++++++++++++- .../AutoStory/StoryData/frlg-12.01.plan.json | 9 ++++ .../AutoStory/StoryData/frlg-12.02.plan.json | 20 +++++++- 3 files changed, 75 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h index f55057d2e3..8544908867 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h @@ -19,7 +19,53 @@ namespace PokemonFRLG{ // The stored plan lines from segment 12 on, after FRLG_PLAN_GOLDEN_11's. inline constexpr std::string_view FRLG_PLAN_GOLDEN_12[] = { - "", + "12.01 face_center_door from FuchsiaCity (25, 32) facing south to FuchsiaCity (25, 32) facing north", + "12.01 face north -> FuchsiaCity (25, 32)", + "12.01 gym_east_wall from FuchsiaCity_PokemonCenter_1F (0, 2) facing north to FuchsiaCity_Gym (14, 21) facing north", + "12.01 walk south 3 (to wall) -> FuchsiaCity_PokemonCenter_1F (0, 5) [walk only]", + "12.01 walk east 7 -> FuchsiaCity_PokemonCenter_1F (7, 5) [walk only]", + "12.01 walk south 4 (warp) -> FuchsiaCity (25, 32) [walk only]", + "12.01 walk south 1 -> FuchsiaCity (25, 33)", + "12.01 walk west 16 -> FuchsiaCity (9, 33)", + "12.01 walk north 1 (warp) -> FuchsiaCity_Gym (7, 21)", + "12.01 walk east 7 (to wall) -> FuchsiaCity_Gym (14, 21) [walk only]", + "12.01 face north -> FuchsiaCity_Gym (14, 21) [walk only]", + "12.01 west_of_koga from FuchsiaCity_Gym (6, 13) facing south to FuchsiaCity_Gym (6, 13) facing east", + "12.01 face east -> FuchsiaCity_Gym (6, 13) [walk only]", + "12.02 below_warden from FuchsiaCity_Gym (6, 13) facing east to FuchsiaCity_WardensHouse (1, 6) facing north", + "12.02 walk north 1 (to wall) -> FuchsiaCity_Gym (6, 12) [walk only]", + "12.02 walk west 6 (to wall) -> FuchsiaCity_Gym (0, 12) [walk only]", + "12.02 walk north 1 (to wall) -> FuchsiaCity_Gym (0, 11) [walk only]", + "12.02 walk east 2 (to wall) -> FuchsiaCity_Gym (2, 11) [walk only]", + "12.02 walk north 1 -> FuchsiaCity_Gym (2, 10) [walk only]", + "12.02 walk east 7 (to wall) -> FuchsiaCity_Gym (9, 10) [walk only]", + "12.02 walk north 8 (to wall) -> FuchsiaCity_Gym (9, 2) [walk only]", + "12.02 walk east 5 (to wall) -> FuchsiaCity_Gym (14, 2) [walk only]", + "12.02 walk south 19 (to wall) -> FuchsiaCity_Gym (14, 21) [walk only]", + "12.02 walk west 7 -> FuchsiaCity_Gym (7, 21) [walk only] [tapped]", + "12.02 walk south 1 (warp) -> FuchsiaCity (9, 33) [walk only]", + "12.02 walk south 4 (to wall) -> FuchsiaCity (9, 37)", + "12.02 walk west 7 (to wall) -> FuchsiaCity (2, 37)", + "12.02 walk north 12 -> FuchsiaCity (2, 25)", + "12.02 walk east 28 (to wall) -> FuchsiaCity (30, 25)", + "12.02 walk south 7 -> FuchsiaCity (30, 32)", + "12.02 walk east 3 -> FuchsiaCity (33, 32)", + "12.02 walk north 1 (warp) -> FuchsiaCity_WardensHouse (6, 9)", + "12.02 walk west 5 (to wall) -> FuchsiaCity_WardensHouse (1, 9) [walk only]", + "12.02 walk north 3 (to wall) -> FuchsiaCity_WardensHouse (1, 6) [walk only]", + "12.02 face_warden from FuchsiaCity_WardensHouse (3, 6) facing east to FuchsiaCity_WardensHouse (3, 6) facing north", + "12.02 face north -> FuchsiaCity_WardensHouse (3, 6) [walk only]", + "12.02 below_center_door from FuchsiaCity_WardensHouse (3, 6) facing north to FuchsiaCity (25, 32) facing north", + "12.02 walk east 3 -> FuchsiaCity_WardensHouse (6, 6) [walk only]", + "12.02 walk south 4 (warp) -> FuchsiaCity (33, 32) [walk only]", + "12.02 walk west 4 -> FuchsiaCity (29, 32)", + "12.02 walk north 7 -> FuchsiaCity (29, 25)", + "12.02 walk west 27 (to wall) -> FuchsiaCity (2, 25)", + "12.02 walk south 12 (to wall) -> FuchsiaCity (2, 37)", + "12.02 walk east 9 (to wall) -> FuchsiaCity (11, 37)", + "12.02 walk north 5 (to wall) -> FuchsiaCity (11, 32)", + "12.02 walk east 14 -> FuchsiaCity (25, 32)", + "12.02 face north -> FuchsiaCity (25, 32)", }; } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json index 161b954cd5..e30c1496be 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json @@ -39,6 +39,15 @@ }, "why": "HM03 Surf in place of Water Gun, as pokeguy (1:14:55 to 1:15:13: Surf, Water Pulse, Bite, Mega Kick after it), unless the lead knows it; an HM, so not a one-shot TM" }, + { + "id": "center_northwest_corner", + "kind": "legs", + "action": "run", + "args": { + "legs": [{"direction": "west", "tiles": 7}, {"direction": "north", "tiles": 2}] + }, + "why": "from the nurse to the Center's wall west (0, 4) and up to the wall (0, 2): legs to walls, so the walk out starts from a known tile even if the Center script left the player a tile off the nurse" + }, { "id": "gym_east_wall", "kind": "route", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.02.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.02.plan.json index 15b99673b6..e0f08da40a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.02.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.02.plan.json @@ -32,10 +32,28 @@ "id": "below_warden", "kind": "route", "action": "run", + "args": { + "target": {"map": "FuchsiaCity_WardensHouse", "tiles": [[1, 6]], "facing": "north"} + }, + "why": "out of the gym by the way in, Koga's win having beaten every gym trainer (FuchsiaCity_Gym_EventScript_DefeatedKoga, set_gym_trainers 5); east along the city's south row to the Warden's door (33, 31) and in, west along row 9 and up the west wall to (1, 6) (pokeguy 1:18:04 to 1:18:24)" + }, + { + "id": "beside_warden", + "kind": "legs", + "action": "taps", + "args": { + "legs": [{"direction": "east", "tiles": 2}] + }, + "why": "a tap a tile from the wall (1, 6) east to below the Warden (3, 6): no wall there stops a run" + }, + { + "id": "face_warden", + "kind": "route", + "action": "run", "args": { "target": {"map": "FuchsiaCity_WardensHouse", "tiles": [[3, 6]], "facing": "north"} }, - "why": "out of the gym by the way in, Koga's win having beaten every gym trainer (FuchsiaCity_Gym_EventScript_DefeatedKoga, set_gym_trainers 5); east along the city's south row to the Warden's door (33, 31) and up to below the Warden (3, 5) (pokeguy 1:18:04 to 1:18:24)" + "why": "turn to the Warden (3, 5)" }, { "id": "talk_warden", From 52ede519080ff7f4b4a5edb5a76c6095a115d96b Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 10:21:44 -0800 Subject: [PATCH 03/39] PokemonFRLG: segment 12's row tests registered from their own header PokemonFRLG_AutoStoryRows_Tests.h stays as 11.03 left it (header_symbols at its limit of 8). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 1 + .../PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp | 2 +- .../PokemonFRLG_AutoStoryRows12_Tests.h | 27 +++++++++++++++++++ .../PokemonFRLG_AutoStoryRows_Tests.h | 2 -- SerialPrograms/cmake/SourceFiles.cmake | 1 + 5 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 711264cdd4..80ba736ea8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -53,6 +53,7 @@ #include "Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.h" #include "Programs/AutoStory/Data/Json_Tests.h" diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp index c461dd1832..56111da81c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp @@ -27,7 +27,7 @@ #include "PokemonFRLG_AutoStoryRooms.h" #include "PokemonFRLG_AutoStoryMember.h" #include "PokemonFRLG_AutoStoryRowSim.h" -#include "PokemonFRLG_AutoStoryRows_Tests.h" +#include "PokemonFRLG_AutoStoryRows12_Tests.h" #include "PokemonFRLG_AutoStoryTable.h" namespace PokemonAutomation{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h new file mode 100644 index 0000000000..0724048577 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h @@ -0,0 +1,27 @@ +/* AutoStory Row Tests, Segment 12 + * + * From: https://github.com/PokemonAutomation/ + * + * Registration of the tests that run segment 12's rows on the overworld + * sim, beside PokemonFRLG_AutoStoryRows_Tests.h's earlier stretches. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRows12_Tests_H +#define PokemonAutomation_PokemonFRLG_AutoStoryRows12_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Rows 12.01 and 12.02, Fuchsia Gym, on the overworld sim (PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp). +void add_tests_AutoStoryFuchsiaGym(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h index 290e02f540..2f521f46bc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h @@ -34,8 +34,6 @@ void add_tests_AutoStorySnorlax(UnitTestDatabase& database); void add_tests_AutoStorySlope(UnitTestDatabase& database); // Row 11.03 on the sims (PokemonFRLG_AutoStorySafari_Tests.cpp). void add_tests_AutoStorySafari(UnitTestDatabase& database); -// Rows 12.01 and 12.02, Fuchsia Gym, on the overworld sim (PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp). -void add_tests_AutoStoryFuchsiaGym(UnitTestDatabase& database); } // namespace PokemonFRLG diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a1620240f9..e343df04ad 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2155,6 +2155,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRooms_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSimStubs.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngReturns.h From 78f3dac4800a93237d876977f984f1b481d8111a Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 10:31:09 -0800 Subject: [PATCH 04/39] PokemonFRLG: 12.01 passes Juggler Kayden on his turn south, as pokeguy Kayden (FACE_DOWN_AND_RIGHT) turns south or east every 32 to 80 frames. The sim models that (SimScript::trainer_turns), and a new STEP variant, trainer_pass, waits for a turn away and crosses the line on it, fighting the trainer as a fallback if seen. 12.01 uses it in place of the fight. The console has no sprite of the trainer to read yet, so there it crosses unwatched with the fallback. Koga at full HP: 88.0% (vs 70.1% recorded). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldSim.cpp | 36 +++++++++- .../Overworld/PokemonFRLG_OverworldSim.h | 5 ++ .../Overworld/PokemonFRLG_OverworldSimState.h | 14 ++++ .../PokemonFRLG_AutoStoryActions.cpp | 18 +++++ .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 58 ++++++++++++++++ .../PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp | 67 +++++++++++++++---- .../AutoStory/PokemonFRLG_AutoStoryRowSim.cpp | 54 +++++++++++++++ .../PokemonFRLG_AutoStoryStepTable.cpp | 11 +++ .../PokemonFRLG_AutoStoryTrainerLine.h | 24 +++++++ .../AutoStory/StoryData/frlg-12.01.plan.json | 30 ++++----- 10 files changed, 285 insertions(+), 32 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 96d07b3d6f..4b53260e84 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -327,12 +327,46 @@ std::optional OverworldSim::press(Direction direction) const return step; } +std::optional OverworldSim::trainer_facing(const MapPosition& home) const{ + return trainer_facing_at(home, m_now); +} + +std::optional OverworldSim::trainer_facing_at(const MapPosition& home, Milliseconds when) const{ + const auto found = m_script.trainer_turns.find(to_string(home)); + if (found == m_script.trainer_turns.end() || found->second.ways.empty()){ + return std::nullopt; + } + const SimTrainerTurns& turns = found->second; + static constexpr int64_t DELAY_FRAMES[] = {32, 48, 64, 80}; + std::mt19937 rng(turns.seed); + Direction facing = turns.ways[0]; + // Each turn: the delay, then a frame for the turn itself; 60 frames a + // second. + int64_t frame = 0; + while (true){ + frame += DELAY_FRAMES[rng() & 3] + 1; + if (frame * 1000 / 60 > when.count()){ + return facing; + } + facing = turns.ways[rng() % turns.ways.size()]; + } +} + // A trainer on the player's map who sees them now walks up and speaks. bool OverworldSim::trainer_sees(Milliseconds pressed){ std::vector& objects = m_maps[m_map].objects; for (size_t c = 0; c < objects.size(); c++){ MapObject& trainer = objects[c]; - if (!trainer.trainer || !trainer_may_see(map(), trainer, m_player.position)){ + if (!trainer.trainer){ + continue; + } + // One who turns on a timer sees only the way they face as the step + // ends. + MapObject looking = trainer; + if (const std::optional facing = trainer_facing_at(MapPosition{map().name, {trainer.x, trainer.y}}, pressed + tile_time())){ + looking.trainer->looks = {*facing}; + } + if (!trainer_may_see(map(), looking, m_player.position)){ continue; } const Pokemon::TileBox box = trainer.wander.value_or(Pokemon::TileBox{trainer.x, trainer.y, trainer.x, trainer.y}); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 2a4c86864d..ea6f270779 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -112,6 +112,10 @@ class OverworldSim{ // Returns whether it was there. (PokemonFRLG_OverworldSimField.cpp) bool use_field(SimField field, size_t floor = 0); + // The way the trainer standing on `home` faces now, if they turn on a + // timer (SimScript::trainer_turns). + std::optional trainer_facing(const MapPosition& home) const; + private: // A screen that shows at `at`; `unfreeze`: the player can move again. struct Pending{ @@ -190,6 +194,7 @@ class OverworldSim{ return m_state.on_bike ? m_script.timing.bike_tile : m_script.timing.tile; } bool trainer_sees(Milliseconds pressed); + std::optional trainer_facing_at(const MapPosition& home, Milliseconds when) const; void update_view(); void note(const std::string& line); void violation(const std::string& line); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h index e985f46736..6315676aa1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h @@ -26,6 +26,17 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ +// A trainer who turns on a timer (pokefirered MovementType_FaceDownAndRight +// and its kin): `ways[0]` at first, then after 32, 48, 64 or 80 frames +// (gMovementDelaysShort) one of `ways` at random, from `seed`, and again. +// They turn to the player only when the player runs +// (TryGetTrainerEncounterDirection()), which the sim's player doesn't, and +// see only the way they face. +struct SimTrainerTurns{ + std::vector ways; + uint32_t seed = 0; +}; + // What a test sets up beyond the maps. struct SimScript{ std::vector encounters; @@ -42,6 +53,9 @@ struct SimScript{ // don't mark as grass: Mt. Moon B2F's tiles closed on one side ('8') // are cave floor too (console B, 2026-11-03). std::set wild_floor_maps; + // Trainers who turn on a timer, by the tile they stand on + // (to_string(MapPosition)); the others see every way they look. + std::map trainer_turns; // Whether the game holds the player up a tile on a step onto a // connected map. It did north onto Nugget Bridge (console B, // 2026-11-03, rows 05.05 and 05.09), not south from Route 6 into diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 850068b884..199ccfb541 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -613,6 +613,24 @@ std::optional step_until_seen(int max_tiles, const std::function& s return std::nullopt; } +bool wait_for_turn_away( + int polls, Direction away, + const std::function()>& read, const std::function& wait +){ + bool other_way = false; + for (int poll = 0; poll < polls; poll++){ + if (poll > 0){ + wait(); + } + const std::optional facing = read(); + if (facing && *facing == away && other_way){ + return true; + } + other_way = other_way || (facing && *facing != away); + } + return false; +} + void wait_out_battle_exit(ConsoleHandle& console, ProControllerContext& context){ context.wait_for_all_requests(); ConsoleScreenLook eyes(console, context); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 9345eb5aac..714abf89f2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -213,6 +213,62 @@ Outcome take_warp_step(StoryEnv& env, const RunState& state, const RouteStep& wa return Pokemon::outcome_ok(); } +Outcome battle(StoryEnv& env, const StoryStep& step); + +// The battle of a TRAINER_PASS_VARIANT step's trainer, as a BATTLE step. +StoryStep pass_fallback_battle(const StoryStep& step){ + StoryStep fight; + fight.kind = StoryStepKind::BATTLE; + fight.name = step.name + " (fallback battle)"; + fight.args = { + {"trainer", arg(step, "trainer")}, + {"foes", arg>(step, "foes")}, + {"use_items", std::vector()}, + {"may_lose", false}, + {"run", false}, + }; + return fight; +} + +// TRAINER_PASS_VARIANT on the console. No sprite of the trainer is in +// Resources yet to read their facing on screen, so wait_for_turn_away() +// has nothing to read: the crossing starts at once, logged, and the +// battle is the fallback when the trainer sees the player. The line is +// one tile deep where the crossing meets it, its first tile. +Outcome pass_trainer(StoryEnv& env, const RunState& state, const StoryStep& step){ + const Direction direction = arg(step, "direction"); + const int tiles = (int)arg(step, "tiles"); + env.console.log(std::format("Story: {}: the trainer's facing can't be read on the console yet; crossing unwatched.", step.name), COLOR_ORANGE); + // The tiles crossed without a stop on the line, the last step watched + // for the trainer's message. + std::optional facing = facing_of(state.pose); + for (int c = 1; c < tiles; c++){ + step_once(env.console, env.context, direction, facing); + facing = direction; + } + if (step_into_line(env.console, env.context, direction, facing, 1)){ + // Seen on the line's tile, the crossing's first: the steps after + // it were lost to the trainer's "!". + env.console.log(std::format("Story: {}: the trainer saw the player; fighting them (fallback).", step.name), COLOR_ORANGE); + const Outcome fought = battle(env, pass_fallback_battle(step)); + if (!fought.succeeded()){ + return fought; + } + for (int c = 1; c < tiles; c++){ + step_once(env.console, env.context, direction, direction); + } + } + const std::vector at = Pokemon::tiles_of(state.pose); + if (at.size() != 1){ + return Pokemon::outcome_ok(); + } + TilePos onto = at[0]; + for (int c = 0; c < tiles; c++){ + onto = onto.next(direction); + } + return Pokemon::outcome_ok(to_pose(StoryPose{state.pose.map, onto, direction})); +} + Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ const Direction direction = arg(step, "direction"); int tiles_stepped = 1; @@ -223,6 +279,8 @@ Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ } env.console.log(std::format("Story: {}: a trainer saw the player after {} tile(s).", step.name, *stepped)); tiles_stepped = *stepped; + }else if (step.action == TRAINER_PASS_VARIANT){ + return pass_trainer(env, state, step); }else if (step.action == TRAINER_WAIT_VARIANT){ if (!step_into_line(env.console, env.context, direction, facing_of(state.pose), 1, TRAINER_WAIT_WATCH)){ return Pokemon::outcome_failed("no_trainer", std::format("{} s on the tile {}", TRAINER_WAIT_WATCH.count() / 1000, direction_name(direction))); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp index 56111da81c..1d68ffae31 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp @@ -11,6 +11,7 @@ */ #include +#include #include #include #include @@ -84,11 +85,13 @@ const StoryCheckpoint& checkpoint(std::string_view id){ // across sims: the trainers fought. struct GymWalk{ StoryPose at; + SimScript script; std::optional sim; std::vector fought; - explicit GymWalk(StoryPose start) + GymWalk(StoryPose start, SimScript sim_script) : at(std::move(start)) + , script(std::move(sim_script)) { place(); } @@ -98,7 +101,7 @@ struct GymWalk{ const std::vector& beaten = sim->state().trainers_beaten; fought.insert(fought.end(), beaten.begin(), beaten.end()); } - sim.emplace(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + sim.emplace(story_maps(), MapPosition{at.map, at.tile}, *at.facing, script); } std::vector all_fought() const{ std::vector all = fought; @@ -137,14 +140,33 @@ std::string row_on_sim(std::string_view id, GymWalk& walk){ return ""; } -// 12.01 from the nurse: the gym, Kayden fought from (14, 16) and Kirk from -// (14, 11), round the top edge to west of Koga, where 12.02 starts; then +// Juggler Kayden (12, 16) turns south or east on a timer +// (MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT), from `seed`; or, for the fallback, +// never turns from east. +SimScript kayden_turns(uint32_t seed, bool only_east){ + SimScript script; + std::vector ways{Direction::SOUTH, Direction::EAST}; + if (only_east){ + ways = {Direction::EAST}; + } + script.trainer_turns[to_string(MapPosition{GYM, {12, 16}})] = SimTrainerTurns{.ways = ways, .seed = seed}; + return script; +} + +// The gym's trainers by sprite: Kayden and Kirk are both rockers, Edgar +// a man. +const std::vector KIRK_AND_EDGAR{"rocker", "man"}; +const std::vector KAYDEN_KIRK_AND_EDGAR{"rocker", "rocker", "man"}; + +// 12.01 from the nurse with `script`: the gym, past Kayden's east line +// (13..14, 16) on his turn south, Kirk fought from (14, 11), round the top +// edge to west of Koga, where 12.02 starts, fighting `expected`; then // 12.02 from there to the Warden and the nurse, meeting no one else. The -// sim's lookers see every way at once, so Edgar, whose lines the legs to -// the walls cross, always stops the walk there: the worst case, which -// the console meets only when he looks that way. -UnitTestResult test_gym_rows(){ - GymWalk walk(*story_pose(Pokemon::pose_of(*checkpoint("12.01").start))); +// sim's other lookers see every way at once, so Edgar, whose lines the +// legs to the walls cross, always stops the walk there: the worst case, +// which the console meets only when he looks that way. +UnitTestResult test_gym_rows(const SimScript& script, const std::vector& expected){ + GymWalk walk(*story_pose(Pokemon::pose_of(*checkpoint("12.01").start)), script); if (const std::string failure = row_on_sim("12.01", walk); !failure.empty()){ return failure; } @@ -152,8 +174,8 @@ UnitTestResult test_gym_rows(){ if (!(walk.sim->state().position == west_of_koga) || walk.sim->state().facing != Direction::EAST){ return std::format("12.01: ended on {}, not west of Koga {} facing east.", to_string(walk.sim->state().position), to_string(west_of_koga)); } - if (walk.all_fought() != std::vector{"rocker", "rocker", "man"}){ - return std::format("12.01: fought {} trainers, not Kayden, Kirk and Edgar.", walk.all_fought().size()); + if (walk.all_fought() != expected){ + return std::format("12.01: fought {} trainers, expected {}.", walk.all_fought().size(), expected.size()); } const StoryPose next = *story_pose(Pokemon::pose_of(*checkpoint("12.02").start)); if (next.map != GYM || !(next.tile == west_of_koga.point)){ @@ -162,7 +184,7 @@ UnitTestResult test_gym_rows(){ if (const std::string failure = row_on_sim("12.02", walk); !failure.empty()){ return failure; } - if (walk.all_fought().size() != 3){ + if (walk.all_fought().size() != expected.size()){ return "12.02: fought a trainer after Koga."; } if (walk.at.map != "FuchsiaCity_PokemonCenter_1F"){ @@ -171,6 +193,17 @@ UnitTestResult test_gym_rows(){ return true; } +// Pokeguy's pass on twenty of Kayden's turn timings: no battle with him. +UnitTestResult test_gym_rows_pass_kayden(){ + for (uint32_t seed = 1; seed <= 20; seed++){ + const UnitTestResult result = test_gym_rows(kayden_turns(seed, false), KIRK_AND_EDGAR); + if (result.result != UnitTestResult::PASSED){ + return std::format("seed {}: {}", seed, result.message); + } + } + return true; +} + // The lead as pokeguy brings it to the gym after HM03 (12.01): Surf over // Water Gun, Water Pulse, Bite, Mega Kick. It picks Surf against Koga's // Poison types (pokeguy: Surf throughout) and Surf or Bite, never Mega @@ -238,8 +271,14 @@ UnitTestResult check_lead_level_precondition(Logger& logger, std::string_view id const AutoStoryFuchsiaGymCase AUTO_STORY_FUCHSIA_GYM_CASES[] = { { - .input = {.name = "12.01 past Kayden and Kirk to west of Koga and 12.02 to the Warden and the nurse", .body = test_gym_rows}, - .expectation = {.description = "Kayden and Kirk fought where the table steps into their lines, no one else; ends at Fuchsia's nurse"}, + .input = {.name = "12.01 past Kayden on his turn south, Kirk fought, to west of Koga and 12.02 to the Warden and the nurse", .body = test_gym_rows_pass_kayden}, + .expectation = {.description = "on 20 timings of Kayden's turns, only Kirk (and the sim's always-looking Edgar) fought; ends at Fuchsia's nurse"}, + }, + { + .input = {.name = "12.01 fights Kayden when he never turns south (fallback)", .body = []{ + return test_gym_rows(kayden_turns(1, true), KAYDEN_KIRK_AND_EDGAR); + }}, + .expectation = {.description = "the pass waits, crosses, is seen, fights Kayden, and the row still ends west of Koga and at the nurse"}, }, { .input = {.name = "the lead's attacks in Fuchsia Gym", .body = test_lead_moves_in_gym}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp index 102739fb16..a1bf8c62da 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -264,6 +264,13 @@ Outcome StoryMapsSim::step_ahead(const Pokemon::Pose& pose, const StoryStep& ste } const Direction direction = Pokemon::story_arg(step.args, "direction"); const MapData* map = map_named(at->map); + if (step.action == TRAINER_PASS_VARIANT){ + TilePos onto = at->tile; + for (int64_t c = 0; c < Pokemon::story_arg(step.args, "tiles"); c++){ + onto = onto.next(direction); + } + return Pokemon::outcome_ok(to_pose(StoryPose{at->map, onto, direction})); + } if (step.action != TRAINER_LINE_VARIANT || map == nullptr){ return Pokemon::outcome_ok(to_pose(StoryPose{at->map, at->tile.next(direction), direction})); } @@ -468,6 +475,50 @@ void sim_wait_out_battle_exit(OverworldSim& sim){ } // namespace +namespace{ + +// pass_trainer() on the sim, with the trainer's facing read from the sim: +// wait_for_turn_away(), the crossing, and the trainer's battle if they +// see the player. +std::string sim_pass_trainer(OverworldSim& sim, StoryPose& at, const StoryStep& step){ + const Direction direction = Pokemon::story_arg(step.args, "direction"); + const int tiles = (int)Pokemon::story_arg(step.args, "tiles"); + const Direction away = Pokemon::story_arg(step.args, "away"); + const MapPosition trainer{at.map, { + at.tile.x + (int)Pokemon::story_arg(step.args, "trainer_dx"), + at.tile.y + (int)Pokemon::story_arg(step.args, "trainer_dy"), + }}; + wait_for_turn_away( + (int)(TRAINER_PASS_WATCH / TRAINER_PASS_POLL), away, + [&]{ return sim.trainer_facing(trainer); }, + [&]{ sim.watch({}, TRAINER_PASS_POLL); } + ); + for (int c = 1; c < tiles; c++){ + sim_step_once(sim, direction); + } + sim_step_once(sim, direction); + if (sim.watch({SimWatcher::MESSAGE}, TRAINER_LINE_WATCH)){ + if (!sim.close_message() || sim.handle_battle(SimBattleChoice::FIGHT) != SimBattleEnd::ENDED){ + return "no battle after the trainer's message."; + } + if (const std::string failure = battle_end_on_sim(sim); !failure.empty()){ + return failure; + } + sim_wait_out_battle_exit(sim); + for (int c = 1; c < tiles; c++){ + sim_step_once(sim, direction); + } + } + TilePos onto = at.tile; + for (int c = 0; c < tiles; c++){ + onto = onto.next(direction); + } + at = StoryPose{at.map, onto, direction}; + return sim.state().position == MapPosition{at.map, at.tile} ? "" : "expected to end on " + to_string(MapPosition{at.map, at.tile}) + "."; +} + +} // namespace + // A ROUTE or LEGS by the sim's walker, fighting a trainer who sees the // player on the way. std::string OverworldStepSim::walk(const StoryStep& step){ @@ -504,6 +555,9 @@ std::string OverworldStepSim::step_ahead(const StoryStep& step){ return step_onto_warp(*warp); } } + if (step.action == TRAINER_PASS_VARIANT){ + return sim_pass_trainer(m_sim, m_at, step); + } const auto tap = [this, direction]{ sim_step_once(m_sim, direction); }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index 9402a4f78c..ad1247bbf9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -172,6 +172,17 @@ std::vector movement_variant_specs(std::span()>& read, const std::function& wait +); + // From the overworld: step_until_seen() `direction`, turning first // unless `facing` is `direction`, each step watched `watch` for a // trainer's message, and at least WILD_BATTLE_IN_LINE_WATCH for a wild diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json index e30c1496be..25974f43eb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json @@ -3,7 +3,7 @@ "game": "frlg", "checkpoint": { "id": "12.01", - "title": "Fuchsia: heal, HM03 Surf over Water Gun, the gym past Jugglers Kayden and Kirk and round the top edge to west of Koga", + "title": "Fuchsia: heal, HM03 Surf over Water Gun, the gym past Juggler Kayden, Juggler Kirk fought, and round the top edge to west of Koga", "start": {"map": "FuchsiaCity", "tiles": [[25, 32]], "facing": "south"}, "events": [ { @@ -67,32 +67,28 @@ "why": "up column 14 from (14, 21) to (14, 17), a tile below Kayden's east line (13..14, 16): a planned route here goes up column 12 or 13 and meets his south line" }, { - "id": "kayden_sight", + "id": "pass_kayden", "kind": "step", - "action": "trainer_wait", - "args": { - "direction": "north" - }, - "why": "onto (14, 16), the second tile of Kayden's east line: he faces south or east (MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT), and once he faces east he walks to (13, 16). Every way north crosses his line and none ends on a wall there, so he is fought, not passed (pokeguy passed him while he faced south, 1:15:14)" - }, - { - "id": "kayden", - "kind": "battle", + "action": "trainer_pass", "args": { + "direction": "north", + "tiles": 2, + "away": "south", + "trainer_dx": -2, + "trainer_dy": -1, "trainer": "TRAINER_JUGGLER_KAYDEN", "foes": ["hypno"] }, - "declared_after": {"map": "FuchsiaCity_Gym", "tiles": [[14, 16]], "facing": "north"}, - "why": "Juggler Kayden (TRAINER_JUGGLER_KAYDEN): Hypno Lv38" + "why": "from (14, 17) across Kayden's east line (13..14, 16) to (14, 15) while he faces south, as pokeguy slips past him (1:15:14): he turns south or east every 32 to 80 frames (MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT), so the step waits for a turn south and crosses on it; if he sees the player anyway, his battle (Hypno Lv38) is fought there (fallback, logged)" }, { "id": "east_column_to_kirk", "kind": "legs", "action": "run", "args": { - "legs": [{"direction": "north", "tiles": 4}] + "legs": [{"direction": "north", "tiles": 3}] }, - "why": "up column 14 from (14, 16) to (14, 12), a tile below Juggler Kirk's line (12..14, 11)" + "why": "up column 14 from (14, 15) to (14, 12), a tile below Juggler Kirk's line (12..14, 11)" }, { "id": "kirk_line", @@ -156,9 +152,9 @@ "notes": { "checkpoint": [ "Starts where 11.03's Fly lands, below Fuchsia's Center facing south, and goes in to the nurse (pokeguy bikes straight into the gym from there, 1:14:38; the Center heal is ours).", - "PokeGuy's way (1:14:38 to 1:16:33): into the gym, Surf taught over Water Gun, Juggler Kirk fought (forced), round the top edge, Koga from the west. He fights nobody else; this row also fights Juggler Kayden (Hypno Lv38), whose east line every way north crosses with no wall to end a leg on (a deviation, for the user).", + "PokeGuy's way (1:14:38 to 1:16:33): into the gym, Surf taught over Water Gun, Juggler Kirk fought (forced), round the top edge, Koga from the west; Juggler Kayden passed while he faces south (1:15:14). He fights nobody else, nor does this row: Kayden's battle is only its fallback.", "The gym (FuchsiaCity_Gym map.json), 15 x 23, no running, its invisible walls in the map: Koga (7, 13) in the middle box, entered only from row 12 on the west. Its trainers and lines: Kayden (12, 16) south and east 4, Shawn (2, 9) west 1, Kirk (11, 11) east 3, Edgar (13, 4) every way 2, Phil (4, 6) every way 2, Nate (2, 16) south 4. Every way north crosses Kirk's line and one of Kayden's and Edgar's; the legs across a looker's line end on walls.", - "Ends west of Koga and saves there: his own pre-battle checkpoint (battle-checkpoint-retry), 12.02. Koga is a D7 fight: pokeguy entered at 34/122 HP and the PokemonSimulation benchmark wins 70.1% from that; this row enters at full HP and PP after the Center (the full-heal comparison is still pending there)." + "Ends west of Koga and saves there: his own pre-battle checkpoint (battle-checkpoint-retry), 12.02. Koga is a D7 fight: pokeguy entered at 34/122 HP and the PokemonSimulation benchmark wins 70.1% (64.5%-75.2%, 1700 trials) from that; this row enters at full HP and PP after the Center, which wins 88.0% (82.4%-92.3%, 840 trials; same C2 policy df4fece, seed 4)." ] } }, From 9ad59b4b246fd9b2b0e9020ff682fe0682def697 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 10:42:29 -0800 Subject: [PATCH 05/39] PokemonFRLG: trainer pass and the sim's trainer turns in their own files; 12.02 sim after Koga - trainer_pass gets a STEP row, so its args lint; the console pass moves to AutoStoryTrainerPass.{h,cpp}, the sim's trainer sight and timer turns to OverworldSimTrainers.cpp and OverworldSimTrainerTurns.h (trainer_facing() is a friend, not a public method). - The line check counts a pass's end as its last tile; Kayden leaves the fought list (38 trainers). - The gym sim marks every gym trainer beaten after Koga, as the game does (set_gym_trainers 5), so 12.02's way out doesn't meet an unbeaten Kayden. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldSim.cpp | 69 -- .../Overworld/PokemonFRLG_OverworldSim.h | 975 +++++++++--------- .../Overworld/PokemonFRLG_OverworldSimState.h | 12 +- .../PokemonFRLG_OverworldSimTrainerTurns.h | 48 + .../PokemonFRLG_OverworldSimTrainers.cpp | 100 ++ .../PokemonFRLG_AutoStoryActions.cpp | 18 - .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 59 +- .../PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp | 22 +- .../AutoStory/PokemonFRLG_AutoStoryRowSim.cpp | 3 +- .../PokemonFRLG_AutoStoryStepTable.cpp | 2 + .../PokemonFRLG_AutoStoryTrainerLine.h | 24 - .../PokemonFRLG_AutoStoryTrainerPass.cpp | 111 ++ .../PokemonFRLG_AutoStoryTrainerPass.h | 65 ++ .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 20 +- SerialPrograms/cmake/SourceFiles.cmake | 4 + 15 files changed, 856 insertions(+), 676 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainerTurns.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainers.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 4b53260e84..3697e679ef 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -126,14 +126,6 @@ std::optional ledge_direction(TileKind tile){ } } -// The tile next to `player` a trainer standing on `box` walks up to. -TilePos trainer_stop(const Pokemon::TileBox& box, const TilePos& player){ - if (box.x0 <= player.x && player.x <= box.x1){ - return TilePos{player.x, box.y0 > player.y ? player.y + 1 : player.y - 1}; - } - return TilePos{box.x0 > player.x ? player.x + 1 : player.x - 1, player.y}; -} - } // namespace @@ -327,67 +319,6 @@ std::optional OverworldSim::press(Direction direction) const return step; } -std::optional OverworldSim::trainer_facing(const MapPosition& home) const{ - return trainer_facing_at(home, m_now); -} - -std::optional OverworldSim::trainer_facing_at(const MapPosition& home, Milliseconds when) const{ - const auto found = m_script.trainer_turns.find(to_string(home)); - if (found == m_script.trainer_turns.end() || found->second.ways.empty()){ - return std::nullopt; - } - const SimTrainerTurns& turns = found->second; - static constexpr int64_t DELAY_FRAMES[] = {32, 48, 64, 80}; - std::mt19937 rng(turns.seed); - Direction facing = turns.ways[0]; - // Each turn: the delay, then a frame for the turn itself; 60 frames a - // second. - int64_t frame = 0; - while (true){ - frame += DELAY_FRAMES[rng() & 3] + 1; - if (frame * 1000 / 60 > when.count()){ - return facing; - } - facing = turns.ways[rng() % turns.ways.size()]; - } -} - -// A trainer on the player's map who sees them now walks up and speaks. -bool OverworldSim::trainer_sees(Milliseconds pressed){ - std::vector& objects = m_maps[m_map].objects; - for (size_t c = 0; c < objects.size(); c++){ - MapObject& trainer = objects[c]; - if (!trainer.trainer){ - continue; - } - // One who turns on a timer sees only the way they face as the step - // ends. - MapObject looking = trainer; - if (const std::optional facing = trainer_facing_at(MapPosition{map().name, {trainer.x, trainer.y}}, pressed + tile_time())){ - looking.trainer->looks = {*facing}; - } - if (!trainer_may_see(map(), looking, m_player.position)){ - continue; - } - const Pokemon::TileBox box = trainer.wander.value_or(Pokemon::TileBox{trainer.x, trainer.y, trainer.x, trainer.y}); - const TilePos stop = trainer_stop(box, m_player.position); - const int approach = std::abs(stop.x - trainer.x) + std::abs(stop.y - trainer.y); - trainer.x = stop.x; - trainer.y = stop.y; - trainer.wander.reset(); - // The player turns to face the trainer. - for (Direction direction : {Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST}){ - m_state.facing = m_player.position.next(direction) == stop ? direction : m_state.facing; - } - m_trainer_speaking = c; - m_frozen = true; - schedule(pressed + m_script.timing.tile * (1 + approach) + m_script.timing.trainer_notice, SimScreen::MESSAGE, false); - note(std::format("{} on {} sees the player, walks up {} tile(s) to {}.", trainer.name, map().name, approach, to_string(stop))); - return true; - } - return false; -} - // The player has taken `step`, pressed at `pressed`. Returns whether the // game stopped them there: a warp, a trainer, a wild battle. bool OverworldSim::after_step(const Step& step, Milliseconds pressed){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index ea6f270779..f7c880fd3c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -1,488 +1,487 @@ -/* Overworld Sim - * - * From: https://github.com/PokemonAutomation/ - * - * A whole-tile model of FireRed's overworld, for running the walker - * (run_route(), Pokemon::walk_leg_with()) without a console. The player - * moves a tile per 16 frames while the D-pad is held, by the maps' step - * rules (classify_step()), and also hops ledges the way they face, takes - * warps with a fade, reads signs walked into moving north or south, and is - * seen by trainers along their sight. Wild battles start on the steps a - * test chooses. Each of these shows a screen at a time after the step's - * press, which the walker's watchers see or miss as the console's do. - * - * Every console failure of the walker becomes a test here (red first). - * OverworldSimWalker is the console side of run_route() (RouteCalls) on - * the sim, step for step as walk_overworld_route_with_recovery() does it, - * with the walker's rules as switches, so a test can show a failure with - * the rule that was missing and its absence with the rule. - * - * A step onto a connected map waits a tile first, as the console does - * while the game loads the map. - * - * Not modelled: running, HP and status, and wild battles on the water. - * Surf and Fly are (SimField::SURF, SimField::FLY). Wandering people stand on - * their tile. The Bicycle is: its pace, its taps (each a tile, some - * dropped when they come too fast), SELECT and doors taking the player - * off it. - * - */ - -#ifndef PokemonAutomation_PokemonFRLG_OverworldSim_H -#define PokemonAutomation_PokemonFRLG_OverworldSim_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" -#include "PokemonFRLG_MovementMechanics.h" -#include "PokemonFRLG_BikeSpinPresses.h" -#include "PokemonFRLG_BikeSpinMechanics.h" -#include "PokemonFRLG_OverworldBikeTaps.h" -#include "PokemonFRLG_OverworldRecovery.h" -#include "PokemonFRLG_OverworldRoute.h" -#include "PokemonFRLG_OverworldSimField.h" -#include "PokemonFRLG_OverworldWalk.h" -#include "PokemonFRLG_OverworldSpin.h" -#include "PokemonFRLG_OverworldSimState.h" -#include "PokemonFRLG_OverworldSimScreens.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -// Simulates overworld movement, encounters and dialogs. -class OverworldSim{ -public: - OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script = {}); - - const SimState& state() const{ return m_state; } - - // Whether the walker's screen check reads its last step tap as a - // step: one that moved the player from `before`, but for - // SimScript::unseen_step_taps, or a turn tap since `turn_taps_before` - // (SimState::turn_taps) that SimScript::seen_turn_taps names. - bool reads_step_tap_as_step(const MapPosition& before, int turn_taps_before); - - // Holds `direction` for `duration` then lets go for `release`, while - // `watchers` watch until `watch` (at least the hold and release) from - // the start. Returns the first that saw its screen, as run_until(). - std::optional hold( - Direction direction, Milliseconds duration, Milliseconds release, Milliseconds watch, - const std::vector& watchers - ); - - // A press of `direction` for `duration` (at most MovementMechanics:: - // LONGEST_TAP), then `release`, as the console measured it: a player - // facing another way only turns; one facing that way steps once, - // unless the tap starts inside the lockout after the last step tap - // (STEP_TAP_LOCKOUT), which the game ignores, as it does any tap - // inside the lockout after a battle (BATTLE_EXIT_LOCKOUT); holds - // aren't held up by that lockout yet. A tap that starts as - // the last one ends, with no release between, holds it on. A turn may - // be dropped by fault injection (SimScript::dropped_turn_taps). - void tap( - Direction direction, - Milliseconds duration = MovementMechanics::TURN_TAP, - Milliseconds release = MovementMechanics::TURN_SETTLE - ); - - // Watches `watchers` for `duration`, as wait_until(). - std::optional watch(const std::vector& watchers, Milliseconds duration); - - // Runs from or fights the battle on screen, back to the overworld. A - // trainer's battle can't be run from; a battle that isn't there is - // waited out (the story's battle loop gives up after 15 s). - SimBattleEnd handle_battle(SimBattleChoice choice); - - // Closes the message on screen with B. Returns whether a trainer's - // battle follows it. - bool close_message(); - - // A on what the player faces, as `field` says (`floor`: the lift's). - // Returns whether it was there. (PokemonFRLG_OverworldSimField.cpp) - bool use_field(SimField field, size_t floor = 0); - - // The way the trainer standing on `home` faces now, if they turn on a - // timer (SimScript::trainer_turns). - std::optional trainer_facing(const MapPosition& home) const; - -private: - // A screen that shows at `at`; `unfreeze`: the player can move again. - struct Pending{ - Milliseconds at; - SimScreen screen; - bool unfreeze; - }; - // Where one press of the D-pad takes the player. - struct Step{ - int map = 0; - PlayerState player; - bool warped = false; - // The way the warp left the player facing (arrival_facing()), if - // not the way they moved. - std::optional facing = std::nullopt; - bool ledge = false; - // The step landed on a spinner, which slid the player to `player`. - std::optional spin = {}; - }; - - void advance_to(Milliseconds time); - void show(SimScreen screen, Milliseconds at); - void schedule(Milliseconds at, SimScreen screen, bool unfreeze); - bool sees(SimWatcher watcher, SimScreen screen) const; - std::optional first_seen(SimWatcher watcher, Milliseconds from, Milliseconds to) const; - std::optional watch_until(const std::vector& watchers, Milliseconds from, Milliseconds to); - // A tap, for the next one's lockout and to hold on: when it started - // and ended, the player's facing before it and the steps it took. - struct TapPress{ - Direction direction = Direction::NORTH; - Milliseconds start{0}; - Milliseconds end{0}; - Direction facing_before = Direction::NORTH; - int steps = 0; - }; - void walk_hold(Direction direction, Milliseconds duration, int short_by); - void take_steps(Direction direction, Milliseconds pressed, Milliseconds end, int left); - void step_tap(Direction direction, Milliseconds duration); - void hold_on(Direction direction, Milliseconds end); - void stuck_hold(Direction direction); - void bump(Direction direction, Milliseconds pressed); - std::optional press(Direction direction) const; - std::optional take_warp(int map_index, const TilePos& tile) const; - std::optional cross_edge(Direction direction) const; - // The lift's door to the floor picked, if `map_index` is a lift and - // one was picked. - std::optional lift_warp(int map_index) const; - // A step that landed on a spinner slides on to the slide's end; false - // if the slide never stops. - bool slide_on(Step& step) const; - // The slide's time after `step`, and its facing; 0 for no slide. - Milliseconds after_slide(const Step& step); - // What the maps can't say, from code (add_coded_objects()). - void add_coded_field(); - bool cut_tree(); - bool choose_lift_floor(size_t floor); - bool push_poster_switch(); - bool start_surf(); - bool fly_to_town(size_t town); - // The trees cut come back, as after a warp. - void regrow_cut_trees(); - bool after_step(const Step& step, Milliseconds pressed); - bool wild_battle(Milliseconds pressed); - std::optional next_encounter(); - bool rolls_encounter(int rate); - bool drops_turn_tap(); - bool press_select(); - // Whether the Bicycle tap starting at `start` is dropped, too soon - // after the last one. - bool drops_bike_tap(Milliseconds start); - // How long a tile takes: on the water, on the Bicycle or on foot. - Milliseconds tile_time() const{ - if (m_player.surfing){ - return m_script.timing.surf_tile; - } - return m_state.on_bike ? m_script.timing.bike_tile : m_script.timing.tile; - } - bool trainer_sees(Milliseconds pressed); - std::optional trainer_facing_at(const MapPosition& home, Milliseconds when) const; - void update_view(); - void note(const std::string& line); - void violation(const std::string& line); - const MapData& map() const{ return m_maps[m_map]; } - - std::vector m_maps; - SimScript m_script; - int m_map = 0; - PlayerState m_player; - Milliseconds m_now{0}; - std::vector m_pending; // in time order - // The game has stopped the player: a battle, a message, a warp. - bool m_frozen = false; - // A battle is on screen or about to show. - bool m_battle_pending = false; - // The trainer (an object of the player's map) whose message is up or - // about to show, and whose battle follows it. - std::optional m_trainer_speaking; - // The trainer whose battle is on screen or about to show. - std::optional m_trainer; - // The trees cut since the last warp, and their maps. - std::vector> m_cut_trees; - // The floor picked on the lift's panel, if any. - std::optional m_lift_floor; - int m_grass_steps = 0; - // The game's wild encounter state (SimScript::encounter_rates). - std::mt19937 m_encounter_rng; - int m_steps_since_encounter = 0; - int m_encounter_rate_buff = 0; - // The turn taps so far, for SimScript::dropped_turn_taps. - // Steps onto a warp so far, and the fault on one - // (SimScript::black_without_warp): its black without the warp. - int m_warp_steps = 0; - bool black_without_warp(Milliseconds pressed); - // The last tap, until a hold. - std::optional m_last_tap; - // When the last Bicycle tap started, and how many came too soon. - std::optional m_last_bike_tap; - int m_fast_bike_taps = 0; - // A hold of `direction` for `duration`: counts the leg a tap on the - // Bicycle starts (SimState::bike_legs), and takes the player off the - // Bicycle if SimScript::off_bike_at_legs names it. - void count_bike_leg(Direction direction, Milliseconds duration); - // The way of the last Bicycle tap, unless another press came since. - std::optional m_bike_leg_direction; - // When the last tap that stepped started. - std::optional m_last_step_tap; - // The end of the lockout after the last battle. - Milliseconds m_battle_lockout_end{0}; - Milliseconds m_wild_battle_from{0}; - int m_holds = 0; - SimState m_state; -}; - - -// The walker's rules that console failures added, each on unless a test -// turns it off to show the failure it fixed. -struct SimWalkerRules{ - // Fail before a step unless the overworld is up (START menu left open, - // console B, 2026-11-01, Viridian Forest). - bool check_overworld = true; - // A battle needs an HP box or the battle menu: black below a small room - // isn't one (console B, 2026-11-01, Viridian Forest's north gate). - bool battle_needs_hp_box = true; - // A trainer's battle after their message is fought, not taken for a - // wild one and run from (console B, 2026-11-01, Viridian Forest). - bool fight_trainer_after_message = true; - // How long the walker watches after a leg through grass for a battle - // whose flashes it missed. It watched 500 ms, and walked the next leg - // into the battle (console B, 2026-11-01, Route 1, run 7 and r14). - Milliseconds after_wild_leg_watch = OverworldWalkSteps::AFTER_WILD_LEG_WATCH; - // A leg to a wall held again after an interrupt stops when it is - // interrupted again right away: by a sign it is held into. Without it - // the walker read the sign 6 times (console B, 2026-11-01, r16). - bool stop_if_blocked = true; - // How long a hold's watch goes on past the hold and its release. 0 as - // now; the tile-at-a-time build watched each step for 900 ms, and saw - // the warp's fade on the step onto the forest's north gate as a battle. - Milliseconds watch_past_hold{0}; - // A leg onto a warp whose fade was a wild battle's (its wipe passes for - // the fade) stops before the warp, and the player is found again on it. - // Without it the walker stopped as off the route (console B, - // 2026-11-03, Mt. Moon 1F, row 04.05). - bool find_player_after_warp_battle = true; - // After a leg's watch saw nothing, a battle's text box on screen (its - // HP boxes still to come) is watched on for, and the leg taken as - // stopped part-way. Without it the walker took "south 15 (to wall)" - // as walked and the next leg into the battle (console B, 2026-11-03, - // Mt. Moon B1F, row 04.05). - bool watch_on_for_unseen_battle = true; - // The same after a leg the maps see no wild tiles on (RouteStep::wild), - // which the leg and its watch don't watch for battles: on Mt. Moon - // B2F's tiles closed on one side, which the maps don't mark as wild, a - // battle on "east 7 (to wall)" left black after the leg, the leg was - // taken as walked and the next one held from where the battle was - // (console B, 2026-11-03, row 04.05). - bool watch_on_after_unmarked_leg = true; - // Before a step, a battle on its way (its text box or wipe) is watched - // on for, and the step before it taken as stopped part-way, not the - // step held from where the battle left the player. - bool battle_before_step = true; - // A hold over a step onto a connected map is a tile longer for it - // (RouteStep::connection_steps). Without it the open leg north from - // Cerulean City onto Nugget Bridge ended a tile short (console B, - // 2026-11-03, rows 05.05 and 05.09). - bool hold_over_connections = true; - // An open leg after whose hold a wild battle was seen is placed by the - // battle's first timed screen event (place_late_stop()). Without it the - // player may be anywhere on the leg: on Route 10, "east 11" was found - // again from all 12 of its tiles (console B, 2026-11-09, 07.02 run 2). - bool place_late_battle = true; - // A message after the hold of an open leg that ends below a sign - // (RouteStep::sign_ahead) places the player on its end. Without it - // the walker found the player at walls and held the same leg into the - // sign 9 times (console B, 2026-11-12, 11.03, Safari Zone West). - bool place_by_sign = true; - // The watch for a warp's fade starts with the hold onto the warp - // (Pokemon::WatchAlong), not when it ends. Without it a fade over - // before the hold ended was missed, and the walk stopped on "no fade in - // and out after walking onto the warp" though it had warped (console B, - // 2026-11-09 01:41, 07.02, the warp to CeruleanCity: the watch started - // about 1.3 s into the hold). - bool watch_fade_along_hold = true; - // A warp's fade is taken as the warp only once the screen after it - // shows the player off the map they held from (warp_left_scene()). - // Without it a black that cleared with the player where they were was - // taken as the warp (console B, 2026-11-10 01:44, 09.01 run 4). - bool confirm_warp_destination = true; - // A warp whose fade was over before the watch for it began is taken by - // the screen after it: another scene than before the hold, held still - // (OverworldWalkSteps::arrived_without_fade()). Without it the walker - // tapped twice into the Department Store lift's back wall and failed - // on "no fade in and out after walking onto the warp" with the player - // inside the lift (console B, 2026-11-12 00:39, 10.01 lift_to_1f): the - // lift room is mostly black, so a watch started after the fade never - // sees black end. - bool scene_confirms_missed_fade = true; - // A turn tap is checked by the facing on screen, and tapped again - // while the player faces another way (OverworldWalkSteps::turn_to()). - // Without it a dropped tap left a one-tile leg turning the player - // only, taken as walked (console B, 2026-11-09, 08.01 run 2). - bool confirm_turn = true; - // The speed the walker goes at: its turn taps - // (OverworldWalkSteps::turns_first()) and its holds' tile time. - MoveSpeed speed = MoveSpeed::WALK; - // An open leg on the Bicycle is counted out a tap at a time, each a - // tile (count_bike_taps()), and one that doesn't move finds the player - // ahead of a block. Without it the leg is one hold, and a start off - // along the leg ends it off with nothing to show it (console B, - // 2026-11-09, 08.03: three runs 3 tiles east after Route 8's legs). - bool count_bike_taps = true; - // How far apart, start to start, the counted taps are - // (MovementMechanics::BIKE_TAP_PERIOD). - Milliseconds bike_tap_period = MovementMechanics::BIKE_TAP_PERIOD; - // After a warp, which takes the player off the Bicycle, the next leg - // where it may be ridden gets on again with SELECT. Without it the - // walker held on-foot legs at the Bicycle's pace. - bool get_back_on_bike = true; - // A dark cave's overworld isn't a battle on its way - // (OverworldWalkSteps::dark_cave_screen()). Without it the check - // before each step watched for a battle on it (console B, 2026-11-09, - // 08.01: "running from a wild Pokemon", then "not a battle"). - bool dark_cave_not_battle = true; - // A stop on an open leg that started in a dark cave may be anywhere on - // the leg (whole_leg()). Without it the stop is placed by the dark - // screen's black, read as the battle at the hold's start: a battle at - // the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 tiles in, - // and the player was found again at a wall 5 tiles off (console B, - // 2026-11-09, 08.01). - bool whole_leg_in_dark = true; - // The end of a trainer's battle the walker fought, as the story's - // battle loop takes it on the screen the sim shows after it: its - // failure, or empty. By default the battle just ends. - std::function trainer_battle_end = [](const OverworldSim&){ - return std::string(); - }; -}; - -// OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the -// overworld only; with `confirm` false, the one tap before it. -void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm = SimWalkerRules{}.confirm_turn); - -// AutoStory's step_once() on `sim`: turns the player if they face another -// way, then one step tap. -void sim_step_once(OverworldSim& sim, Direction direction); - -// The console side of run_route() on an OverworldSim, as -// walk_overworld_route_with_recovery() does it, with the story's -// interrupts: a wild battle (flashes, or seen late) is fought or run from, -// a message is closed and a trainer's battle after it fought. -class OverworldSimWalker{ -public: - // `interrupts`: whose detection delays place a stopped leg, the - // walker's own or a caller's (story_interrupts()). Each set lists a - // wild battle, one seen late and a message for `wild`, and a message - // for `other`, in that order. - OverworldSimWalker( - OverworldSim& sim, SimWalkerRules rules = {}, - const OverworldInterruptSet& interrupts = default_overworld_interrupts() - ); - - // RouteCalls whose `fail` throws OperationFailedException, as the - // console's does. - RouteCalls calls(); - - // run_route() from the sim's facing, planned with `planning`. Returns - // the failure's message, or empty if the route was walked. - std::string run(const std::vector& route, const RoutePlanning& planning); - - const std::vector& log() const{ return m_log; } - -private: - // One of the story's interrupts (story_interrupts()), with the - // walker's detection delay for it. - struct Interrupt{ - std::string name; - SimWatcher watcher; - Milliseconds delay; - bool battle; - }; - StepOutcome walk(const RouteStep& step, std::optional facing); - StepOutcome walk_ridden(const RouteStep& step, std::optional facing); - // count_bike_taps() on the sim. - StepOutcome walk_bike_taps(const RouteStep& step); - BikeTap bike_tap(const RouteStep& step); - // count_bike_taps() on foot (counts_step_taps()). - StepOutcome walk_step_taps(const RouteStep& step); - BikeTap step_tap(const RouteStep& step, int tap); - std::optional late_stop(const RouteStep& step); - // stop_tiles(); without SimWalkerRules::whole_leg_in_dark, the dark - // screen places the stop at the hold's start. - WalkedTiles dark_stop(const RouteStep& step, WalkedTiles timed) const{ - if (m_leg_dark && !m_rules.whole_leg_in_dark){ - return walked_near(step, 0, MovementMechanics::TILE_TIME); - } - return stop_tiles(step, timed, m_leg_dark); - } - std::optional walk_step(const RouteStep& step, std::optional facing); - // start_surf(): turned to the water, A, YES, and the jump onto it. - // Nothing: a Surf is never stopped part-way. - // (PokemonFRLG_OverworldSimField.cpp) - std::optional surf(const RouteStep& step); - bool after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); - bool fade_over_since(Milliseconds from) const; - // after_warp() on a fade seen with no warp: fails, or with - // SimWalkerRules::confirm_warp_destination off, takes it as the warp. - bool black_without_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); - [[noreturn]] void fail_off_route(const RouteStep& step); - std::optional hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts); - size_t clear_late(const std::vector& interrupts, Milliseconds watch, size_t max); - size_t clear_unseen_battle(const RouteStep& step); - bool battle_on_its_way() const; - void clear(const Interrupt& interrupt); - void hold_to_warp(const RouteStep& step); - StepEnd watch_for_trainer(const RouteStep& step, int approach_tiles); - bool moved_past_wall(const RouteStep& step); - void check_overworld(const RouteStep& step); - // After a leg onto a spinner: the slide's time. - void wait_out_slide(const RouteStep& step); - const std::vector& interrupts(const RouteStep& step) const; - std::vector watchers(const std::vector& interrupts) const; - [[noreturn]] void fail(const std::string& message); - - OverworldSim& m_sim; - SimWalkerRules m_rules; - std::vector m_wild; - std::vector m_other; - std::vector m_log; - // When the last WALK leg's first hold started, on the sim's clock, - // and whether its map was dark then. - Milliseconds m_leg_start{0}; - bool m_leg_dark = false; - // Whether the walker takes the player to ride the Bicycle, and the - // speed of the step under way. - bool m_riding = false; - MoveSpeed m_speed = MoveSpeed::WALK; -}; - - -// Register overworld simulation unit tests. -void add_tests_OverworldSim(UnitTestDatabase& database); -// Register the tests of a warp's fade over before the hold onto it ends. -void add_tests_OverworldWarpFade(UnitTestDatabase& database); -// Register the tests of the way a warp leaves the player facing. -void add_tests_OverworldStairs(UnitTestDatabase& database); - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif +/* Overworld Sim + * + * From: https://github.com/PokemonAutomation/ + * + * A whole-tile model of FireRed's overworld, for running the walker + * (run_route(), Pokemon::walk_leg_with()) without a console. The player + * moves a tile per 16 frames while the D-pad is held, by the maps' step + * rules (classify_step()), and also hops ledges the way they face, takes + * warps with a fade, reads signs walked into moving north or south, and is + * seen by trainers along their sight. Wild battles start on the steps a + * test chooses. Each of these shows a screen at a time after the step's + * press, which the walker's watchers see or miss as the console's do. + * + * Every console failure of the walker becomes a test here (red first). + * OverworldSimWalker is the console side of run_route() (RouteCalls) on + * the sim, step for step as walk_overworld_route_with_recovery() does it, + * with the walker's rules as switches, so a test can show a failure with + * the rule that was missing and its absence with the rule. + * + * A step onto a connected map waits a tile first, as the console does + * while the game loads the map. + * + * Not modelled: running, HP and status, and wild battles on the water. + * Surf and Fly are (SimField::SURF, SimField::FLY). Wandering people stand on + * their tile. The Bicycle is: its pace, its taps (each a tile, some + * dropped when they come too fast), SELECT and doors taking the player + * off it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldSim_H +#define PokemonAutomation_PokemonFRLG_OverworldSim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "PokemonFRLG_MovementMechanics.h" +#include "PokemonFRLG_BikeSpinPresses.h" +#include "PokemonFRLG_BikeSpinMechanics.h" +#include "PokemonFRLG_OverworldBikeTaps.h" +#include "PokemonFRLG_OverworldRecovery.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldSimField.h" +#include "PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_OverworldSpin.h" +#include "PokemonFRLG_OverworldSimState.h" +#include "PokemonFRLG_OverworldSimScreens.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Simulates overworld movement, encounters and dialogs. +class OverworldSim{ +public: + OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script = {}); + + const SimState& state() const{ return m_state; } + + // Whether the walker's screen check reads its last step tap as a + // step: one that moved the player from `before`, but for + // SimScript::unseen_step_taps, or a turn tap since `turn_taps_before` + // (SimState::turn_taps) that SimScript::seen_turn_taps names. + bool reads_step_tap_as_step(const MapPosition& before, int turn_taps_before); + + // Holds `direction` for `duration` then lets go for `release`, while + // `watchers` watch until `watch` (at least the hold and release) from + // the start. Returns the first that saw its screen, as run_until(). + std::optional hold( + Direction direction, Milliseconds duration, Milliseconds release, Milliseconds watch, + const std::vector& watchers + ); + + // A press of `direction` for `duration` (at most MovementMechanics:: + // LONGEST_TAP), then `release`, as the console measured it: a player + // facing another way only turns; one facing that way steps once, + // unless the tap starts inside the lockout after the last step tap + // (STEP_TAP_LOCKOUT), which the game ignores, as it does any tap + // inside the lockout after a battle (BATTLE_EXIT_LOCKOUT); holds + // aren't held up by that lockout yet. A tap that starts as + // the last one ends, with no release between, holds it on. A turn may + // be dropped by fault injection (SimScript::dropped_turn_taps). + void tap( + Direction direction, + Milliseconds duration = MovementMechanics::TURN_TAP, + Milliseconds release = MovementMechanics::TURN_SETTLE + ); + + // Watches `watchers` for `duration`, as wait_until(). + std::optional watch(const std::vector& watchers, Milliseconds duration); + + // Runs from or fights the battle on screen, back to the overworld. A + // trainer's battle can't be run from; a battle that isn't there is + // waited out (the story's battle loop gives up after 15 s). + SimBattleEnd handle_battle(SimBattleChoice choice); + + // Closes the message on screen with B. Returns whether a trainer's + // battle follows it. + bool close_message(); + + // A on what the player faces, as `field` says (`floor`: the lift's). + // Returns whether it was there. (PokemonFRLG_OverworldSimField.cpp) + bool use_field(SimField field, size_t floor = 0); + +private: + // A screen that shows at `at`; `unfreeze`: the player can move again. + struct Pending{ + Milliseconds at; + SimScreen screen; + bool unfreeze; + }; + // Where one press of the D-pad takes the player. + struct Step{ + int map = 0; + PlayerState player; + bool warped = false; + // The way the warp left the player facing (arrival_facing()), if + // not the way they moved. + std::optional facing = std::nullopt; + bool ledge = false; + // The step landed on a spinner, which slid the player to `player`. + std::optional spin = {}; + }; + + void advance_to(Milliseconds time); + void show(SimScreen screen, Milliseconds at); + void schedule(Milliseconds at, SimScreen screen, bool unfreeze); + bool sees(SimWatcher watcher, SimScreen screen) const; + std::optional first_seen(SimWatcher watcher, Milliseconds from, Milliseconds to) const; + std::optional watch_until(const std::vector& watchers, Milliseconds from, Milliseconds to); + // A tap, for the next one's lockout and to hold on: when it started + // and ended, the player's facing before it and the steps it took. + struct TapPress{ + Direction direction = Direction::NORTH; + Milliseconds start{0}; + Milliseconds end{0}; + Direction facing_before = Direction::NORTH; + int steps = 0; + }; + void walk_hold(Direction direction, Milliseconds duration, int short_by); + void take_steps(Direction direction, Milliseconds pressed, Milliseconds end, int left); + void step_tap(Direction direction, Milliseconds duration); + void hold_on(Direction direction, Milliseconds end); + void stuck_hold(Direction direction); + void bump(Direction direction, Milliseconds pressed); + std::optional press(Direction direction) const; + std::optional take_warp(int map_index, const TilePos& tile) const; + std::optional cross_edge(Direction direction) const; + // The lift's door to the floor picked, if `map_index` is a lift and + // one was picked. + std::optional lift_warp(int map_index) const; + // A step that landed on a spinner slides on to the slide's end; false + // if the slide never stops. + bool slide_on(Step& step) const; + // The slide's time after `step`, and its facing; 0 for no slide. + Milliseconds after_slide(const Step& step); + // What the maps can't say, from code (add_coded_objects()). + void add_coded_field(); + bool cut_tree(); + bool choose_lift_floor(size_t floor); + bool push_poster_switch(); + bool start_surf(); + bool fly_to_town(size_t town); + // The trees cut come back, as after a warp. + void regrow_cut_trees(); + bool after_step(const Step& step, Milliseconds pressed); + bool wild_battle(Milliseconds pressed); + std::optional next_encounter(); + bool rolls_encounter(int rate); + bool drops_turn_tap(); + bool press_select(); + // Whether the Bicycle tap starting at `start` is dropped, too soon + // after the last one. + bool drops_bike_tap(Milliseconds start); + // How long a tile takes: on the water, on the Bicycle or on foot. + Milliseconds tile_time() const{ + if (m_player.surfing){ + return m_script.timing.surf_tile; + } + return m_state.on_bike ? m_script.timing.bike_tile : m_script.timing.tile; + } + // (PokemonFRLG_OverworldSimTrainers.cpp) + bool trainer_sees(Milliseconds pressed); + // The way the trainer standing on `home` faces now, if they turn on a + // timer (SimScript::trainer_turns). (PokemonFRLG_OverworldSimTrainers.cpp) + friend std::optional trainer_facing(const OverworldSim& sim, const MapPosition& home); + void update_view(); + void note(const std::string& line); + void violation(const std::string& line); + const MapData& map() const{ return m_maps[m_map]; } + + std::vector m_maps; + SimScript m_script; + int m_map = 0; + PlayerState m_player; + Milliseconds m_now{0}; + std::vector m_pending; // in time order + // The game has stopped the player: a battle, a message, a warp. + bool m_frozen = false; + // A battle is on screen or about to show. + bool m_battle_pending = false; + // The trainer (an object of the player's map) whose message is up or + // about to show, and whose battle follows it. + std::optional m_trainer_speaking; + // The trainer whose battle is on screen or about to show. + std::optional m_trainer; + // The trees cut since the last warp, and their maps. + std::vector> m_cut_trees; + // The floor picked on the lift's panel, if any. + std::optional m_lift_floor; + int m_grass_steps = 0; + // The game's wild encounter state (SimScript::encounter_rates). + std::mt19937 m_encounter_rng; + int m_steps_since_encounter = 0; + int m_encounter_rate_buff = 0; + // The turn taps so far, for SimScript::dropped_turn_taps. + // Steps onto a warp so far, and the fault on one + // (SimScript::black_without_warp): its black without the warp. + int m_warp_steps = 0; + bool black_without_warp(Milliseconds pressed); + // The last tap, until a hold. + std::optional m_last_tap; + // When the last Bicycle tap started, and how many came too soon. + std::optional m_last_bike_tap; + int m_fast_bike_taps = 0; + // A hold of `direction` for `duration`: counts the leg a tap on the + // Bicycle starts (SimState::bike_legs), and takes the player off the + // Bicycle if SimScript::off_bike_at_legs names it. + void count_bike_leg(Direction direction, Milliseconds duration); + // The way of the last Bicycle tap, unless another press came since. + std::optional m_bike_leg_direction; + // When the last tap that stepped started. + std::optional m_last_step_tap; + // The end of the lockout after the last battle. + Milliseconds m_battle_lockout_end{0}; + Milliseconds m_wild_battle_from{0}; + int m_holds = 0; + SimState m_state; +}; + + +// The walker's rules that console failures added, each on unless a test +// turns it off to show the failure it fixed. +struct SimWalkerRules{ + // Fail before a step unless the overworld is up (START menu left open, + // console B, 2026-11-01, Viridian Forest). + bool check_overworld = true; + // A battle needs an HP box or the battle menu: black below a small room + // isn't one (console B, 2026-11-01, Viridian Forest's north gate). + bool battle_needs_hp_box = true; + // A trainer's battle after their message is fought, not taken for a + // wild one and run from (console B, 2026-11-01, Viridian Forest). + bool fight_trainer_after_message = true; + // How long the walker watches after a leg through grass for a battle + // whose flashes it missed. It watched 500 ms, and walked the next leg + // into the battle (console B, 2026-11-01, Route 1, run 7 and r14). + Milliseconds after_wild_leg_watch = OverworldWalkSteps::AFTER_WILD_LEG_WATCH; + // A leg to a wall held again after an interrupt stops when it is + // interrupted again right away: by a sign it is held into. Without it + // the walker read the sign 6 times (console B, 2026-11-01, r16). + bool stop_if_blocked = true; + // How long a hold's watch goes on past the hold and its release. 0 as + // now; the tile-at-a-time build watched each step for 900 ms, and saw + // the warp's fade on the step onto the forest's north gate as a battle. + Milliseconds watch_past_hold{0}; + // A leg onto a warp whose fade was a wild battle's (its wipe passes for + // the fade) stops before the warp, and the player is found again on it. + // Without it the walker stopped as off the route (console B, + // 2026-11-03, Mt. Moon 1F, row 04.05). + bool find_player_after_warp_battle = true; + // After a leg's watch saw nothing, a battle's text box on screen (its + // HP boxes still to come) is watched on for, and the leg taken as + // stopped part-way. Without it the walker took "south 15 (to wall)" + // as walked and the next leg into the battle (console B, 2026-11-03, + // Mt. Moon B1F, row 04.05). + bool watch_on_for_unseen_battle = true; + // The same after a leg the maps see no wild tiles on (RouteStep::wild), + // which the leg and its watch don't watch for battles: on Mt. Moon + // B2F's tiles closed on one side, which the maps don't mark as wild, a + // battle on "east 7 (to wall)" left black after the leg, the leg was + // taken as walked and the next one held from where the battle was + // (console B, 2026-11-03, row 04.05). + bool watch_on_after_unmarked_leg = true; + // Before a step, a battle on its way (its text box or wipe) is watched + // on for, and the step before it taken as stopped part-way, not the + // step held from where the battle left the player. + bool battle_before_step = true; + // A hold over a step onto a connected map is a tile longer for it + // (RouteStep::connection_steps). Without it the open leg north from + // Cerulean City onto Nugget Bridge ended a tile short (console B, + // 2026-11-03, rows 05.05 and 05.09). + bool hold_over_connections = true; + // An open leg after whose hold a wild battle was seen is placed by the + // battle's first timed screen event (place_late_stop()). Without it the + // player may be anywhere on the leg: on Route 10, "east 11" was found + // again from all 12 of its tiles (console B, 2026-11-09, 07.02 run 2). + bool place_late_battle = true; + // A message after the hold of an open leg that ends below a sign + // (RouteStep::sign_ahead) places the player on its end. Without it + // the walker found the player at walls and held the same leg into the + // sign 9 times (console B, 2026-11-12, 11.03, Safari Zone West). + bool place_by_sign = true; + // The watch for a warp's fade starts with the hold onto the warp + // (Pokemon::WatchAlong), not when it ends. Without it a fade over + // before the hold ended was missed, and the walk stopped on "no fade in + // and out after walking onto the warp" though it had warped (console B, + // 2026-11-09 01:41, 07.02, the warp to CeruleanCity: the watch started + // about 1.3 s into the hold). + bool watch_fade_along_hold = true; + // A warp's fade is taken as the warp only once the screen after it + // shows the player off the map they held from (warp_left_scene()). + // Without it a black that cleared with the player where they were was + // taken as the warp (console B, 2026-11-10 01:44, 09.01 run 4). + bool confirm_warp_destination = true; + // A warp whose fade was over before the watch for it began is taken by + // the screen after it: another scene than before the hold, held still + // (OverworldWalkSteps::arrived_without_fade()). Without it the walker + // tapped twice into the Department Store lift's back wall and failed + // on "no fade in and out after walking onto the warp" with the player + // inside the lift (console B, 2026-11-12 00:39, 10.01 lift_to_1f): the + // lift room is mostly black, so a watch started after the fade never + // sees black end. + bool scene_confirms_missed_fade = true; + // A turn tap is checked by the facing on screen, and tapped again + // while the player faces another way (OverworldWalkSteps::turn_to()). + // Without it a dropped tap left a one-tile leg turning the player + // only, taken as walked (console B, 2026-11-09, 08.01 run 2). + bool confirm_turn = true; + // The speed the walker goes at: its turn taps + // (OverworldWalkSteps::turns_first()) and its holds' tile time. + MoveSpeed speed = MoveSpeed::WALK; + // An open leg on the Bicycle is counted out a tap at a time, each a + // tile (count_bike_taps()), and one that doesn't move finds the player + // ahead of a block. Without it the leg is one hold, and a start off + // along the leg ends it off with nothing to show it (console B, + // 2026-11-09, 08.03: three runs 3 tiles east after Route 8's legs). + bool count_bike_taps = true; + // How far apart, start to start, the counted taps are + // (MovementMechanics::BIKE_TAP_PERIOD). + Milliseconds bike_tap_period = MovementMechanics::BIKE_TAP_PERIOD; + // After a warp, which takes the player off the Bicycle, the next leg + // where it may be ridden gets on again with SELECT. Without it the + // walker held on-foot legs at the Bicycle's pace. + bool get_back_on_bike = true; + // A dark cave's overworld isn't a battle on its way + // (OverworldWalkSteps::dark_cave_screen()). Without it the check + // before each step watched for a battle on it (console B, 2026-11-09, + // 08.01: "running from a wild Pokemon", then "not a battle"). + bool dark_cave_not_battle = true; + // A stop on an open leg that started in a dark cave may be anywhere on + // the leg (whole_leg()). Without it the stop is placed by the dark + // screen's black, read as the battle at the hold's start: a battle at + // the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 tiles in, + // and the player was found again at a wall 5 tiles off (console B, + // 2026-11-09, 08.01). + bool whole_leg_in_dark = true; + // The end of a trainer's battle the walker fought, as the story's + // battle loop takes it on the screen the sim shows after it: its + // failure, or empty. By default the battle just ends. + std::function trainer_battle_end = [](const OverworldSim&){ + return std::string(); + }; +}; + +// OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the +// overworld only; with `confirm` false, the one tap before it. +void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm = SimWalkerRules{}.confirm_turn); + +// AutoStory's step_once() on `sim`: turns the player if they face another +// way, then one step tap. +void sim_step_once(OverworldSim& sim, Direction direction); + +// The console side of run_route() on an OverworldSim, as +// walk_overworld_route_with_recovery() does it, with the story's +// interrupts: a wild battle (flashes, or seen late) is fought or run from, +// a message is closed and a trainer's battle after it fought. +class OverworldSimWalker{ +public: + // `interrupts`: whose detection delays place a stopped leg, the + // walker's own or a caller's (story_interrupts()). Each set lists a + // wild battle, one seen late and a message for `wild`, and a message + // for `other`, in that order. + OverworldSimWalker( + OverworldSim& sim, SimWalkerRules rules = {}, + const OverworldInterruptSet& interrupts = default_overworld_interrupts() + ); + + // RouteCalls whose `fail` throws OperationFailedException, as the + // console's does. + RouteCalls calls(); + + // run_route() from the sim's facing, planned with `planning`. Returns + // the failure's message, or empty if the route was walked. + std::string run(const std::vector& route, const RoutePlanning& planning); + + const std::vector& log() const{ return m_log; } + +private: + // One of the story's interrupts (story_interrupts()), with the + // walker's detection delay for it. + struct Interrupt{ + std::string name; + SimWatcher watcher; + Milliseconds delay; + bool battle; + }; + StepOutcome walk(const RouteStep& step, std::optional facing); + StepOutcome walk_ridden(const RouteStep& step, std::optional facing); + // count_bike_taps() on the sim. + StepOutcome walk_bike_taps(const RouteStep& step); + BikeTap bike_tap(const RouteStep& step); + // count_bike_taps() on foot (counts_step_taps()). + StepOutcome walk_step_taps(const RouteStep& step); + BikeTap step_tap(const RouteStep& step, int tap); + std::optional late_stop(const RouteStep& step); + // stop_tiles(); without SimWalkerRules::whole_leg_in_dark, the dark + // screen places the stop at the hold's start. + WalkedTiles dark_stop(const RouteStep& step, WalkedTiles timed) const{ + if (m_leg_dark && !m_rules.whole_leg_in_dark){ + return walked_near(step, 0, MovementMechanics::TILE_TIME); + } + return stop_tiles(step, timed, m_leg_dark); + } + std::optional walk_step(const RouteStep& step, std::optional facing); + // start_surf(): turned to the water, A, YES, and the jump onto it. + // Nothing: a Surf is never stopped part-way. + // (PokemonFRLG_OverworldSimField.cpp) + std::optional surf(const RouteStep& step); + bool after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); + bool fade_over_since(Milliseconds from) const; + // after_warp() on a fade seen with no warp: fails, or with + // SimWalkerRules::confirm_warp_destination off, takes it as the warp. + bool black_without_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); + [[noreturn]] void fail_off_route(const RouteStep& step); + std::optional hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts); + size_t clear_late(const std::vector& interrupts, Milliseconds watch, size_t max); + size_t clear_unseen_battle(const RouteStep& step); + bool battle_on_its_way() const; + void clear(const Interrupt& interrupt); + void hold_to_warp(const RouteStep& step); + StepEnd watch_for_trainer(const RouteStep& step, int approach_tiles); + bool moved_past_wall(const RouteStep& step); + void check_overworld(const RouteStep& step); + // After a leg onto a spinner: the slide's time. + void wait_out_slide(const RouteStep& step); + const std::vector& interrupts(const RouteStep& step) const; + std::vector watchers(const std::vector& interrupts) const; + [[noreturn]] void fail(const std::string& message); + + OverworldSim& m_sim; + SimWalkerRules m_rules; + std::vector m_wild; + std::vector m_other; + std::vector m_log; + // When the last WALK leg's first hold started, on the sim's clock, + // and whether its map was dark then. + Milliseconds m_leg_start{0}; + bool m_leg_dark = false; + // Whether the walker takes the player to ride the Bicycle, and the + // speed of the step under way. + bool m_riding = false; + MoveSpeed m_speed = MoveSpeed::WALK; +}; + + +// Register overworld simulation unit tests. +void add_tests_OverworldSim(UnitTestDatabase& database); +// Register the tests of a warp's fade over before the hold onto it ends. +void add_tests_OverworldWarpFade(UnitTestDatabase& database); +// Register the tests of the way a warp leaves the player facing. +void add_tests_OverworldStairs(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h index 6315676aa1..5c05786a6a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h @@ -20,23 +20,13 @@ #include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" #include "PokemonFRLG_OverworldRoute.h" #include "PokemonFRLG_OverworldSimScreens.h" +#include "PokemonFRLG_OverworldSimTrainerTurns.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ -// A trainer who turns on a timer (pokefirered MovementType_FaceDownAndRight -// and its kin): `ways[0]` at first, then after 32, 48, 64 or 80 frames -// (gMovementDelaysShort) one of `ways` at random, from `seed`, and again. -// They turn to the player only when the player runs -// (TryGetTrainerEncounterDirection()), which the sim's player doesn't, and -// see only the way they face. -struct SimTrainerTurns{ - std::vector ways; - uint32_t seed = 0; -}; - // What a test sets up beyond the maps. struct SimScript{ std::vector encounters; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainerTurns.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainerTurns.h new file mode 100644 index 0000000000..186a4508bd --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainerTurns.h @@ -0,0 +1,48 @@ +/* Overworld Sim Trainer Turns + * + * From: https://github.com/PokemonAutomation/ + * + * The sim's trainers who turn on a timer, and the way one faces at a time. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldSimTrainerTurns_H +#define PokemonAutomation_PokemonFRLG_OverworldSimTrainerTurns_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonFRLG_OverworldRouteSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// A trainer who turns on a timer (pokefirered MovementType_FaceDownAndRight +// and its kin): `ways[0]` at first, then after 32, 48, 64 or 80 frames +// (gMovementDelaysShort) one of `ways` at random, from `seed`, and again. +// They turn to the player only when the player runs +// (TryGetTrainerEncounterDirection()), which the sim's player doesn't, and +// see only the way they face. +struct SimTrainerTurns{ + std::vector ways; + uint32_t seed = 0; +}; + +// The way the trainer standing on `home` faces at `when` on the sim's +// clock, if `turns` (by to_string(MapPosition)) has them. +std::optional trainer_turns_facing( + const std::map& turns, const MapPosition& home, Milliseconds when +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainers.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainers.cpp new file mode 100644 index 0000000000..a28ecbf994 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainers.cpp @@ -0,0 +1,100 @@ +/* Overworld Sim Trainers + * + * From: https://github.com/PokemonAutomation/ + * + * The sim's trainers: who sees the player, and who turns on a timer. + * + */ + +#include +#include +#include +#include "PokemonFRLG_OverworldObjects.h" +#include "PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_OverworldSimTrainerTurns.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +std::optional trainer_turns_facing( + const std::map& turns, const MapPosition& home, Milliseconds when +){ + const auto found = turns.find(to_string(home)); + if (found == turns.end() || found->second.ways.empty()){ + return std::nullopt; + } + const SimTrainerTurns& trainer = found->second; + static constexpr int64_t DELAY_FRAMES[] = {32, 48, 64, 80}; + std::mt19937 rng(trainer.seed); + Direction facing = trainer.ways[0]; + // Each turn: the delay, then a frame for the turn itself; 60 frames a + // second. + int64_t frame = 0; + while (true){ + frame += DELAY_FRAMES[rng() & 3] + 1; + if (frame * 1000 / 60 > when.count()){ + return facing; + } + facing = trainer.ways[rng() % trainer.ways.size()]; + } +} + +std::optional trainer_facing(const OverworldSim& sim, const MapPosition& home){ + return trainer_turns_facing(sim.m_script.trainer_turns, home, sim.m_now); +} + +namespace{ + +// The tile next to `player` a trainer standing on `box` walks up to. +TilePos trainer_stop(const Pokemon::TileBox& box, const TilePos& player){ + if (box.x0 <= player.x && player.x <= box.x1){ + return TilePos{player.x, box.y0 > player.y ? player.y + 1 : player.y - 1}; + } + return TilePos{box.x0 > player.x ? player.x + 1 : player.x - 1, player.y}; +} + +} // namespace + +// A trainer on the player's map who sees them now walks up and speaks. +bool OverworldSim::trainer_sees(Milliseconds pressed){ + std::vector& objects = m_maps[m_map].objects; + for (size_t c = 0; c < objects.size(); c++){ + MapObject& trainer = objects[c]; + if (!trainer.trainer){ + continue; + } + // One who turns on a timer sees only the way they face as the step + // ends. + MapObject looking = trainer; + if (const std::optional facing = trainer_turns_facing(m_script.trainer_turns, MapPosition{map().name, {trainer.x, trainer.y}}, pressed + tile_time())){ + looking.trainer->looks = {*facing}; + } + if (!trainer_may_see(map(), looking, m_player.position)){ + continue; + } + const Pokemon::TileBox box = trainer.wander.value_or(Pokemon::TileBox{trainer.x, trainer.y, trainer.x, trainer.y}); + const TilePos stop = trainer_stop(box, m_player.position); + const int approach = std::abs(stop.x - trainer.x) + std::abs(stop.y - trainer.y); + trainer.x = stop.x; + trainer.y = stop.y; + trainer.wander.reset(); + // The player turns to face the trainer. + for (Direction direction : {Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST}){ + m_state.facing = m_player.position.next(direction) == stop ? direction : m_state.facing; + } + m_trainer_speaking = c; + m_frozen = true; + schedule(pressed + m_script.timing.tile * (1 + approach) + m_script.timing.trainer_notice, SimScreen::MESSAGE, false); + note(std::format("{} on {} sees the player, walks up {} tile(s) to {}.", trainer.name, map().name, approach, to_string(stop))); + return true; + } + return false; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 199ccfb541..850068b884 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -613,24 +613,6 @@ std::optional step_until_seen(int max_tiles, const std::function& s return std::nullopt; } -bool wait_for_turn_away( - int polls, Direction away, - const std::function()>& read, const std::function& wait -){ - bool other_way = false; - for (int poll = 0; poll < polls; poll++){ - if (poll > 0){ - wait(); - } - const std::optional facing = read(); - if (facing && *facing == away && other_way){ - return true; - } - other_way = other_way || (facing && *facing != away); - } - return false; -} - void wait_out_battle_exit(ConsoleHandle& console, ProControllerContext& context){ context.wait_for_all_requests(); ConsoleScreenLook eyes(console, context); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 714abf89f2..6d4a109468 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -31,6 +31,7 @@ #include "PokemonFRLG_AutoStorySlopeRun.h" #include "PokemonFRLG_AutoStorySummary.h" #include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryTrainerPass.h" #include "PokemonFRLG_AutoStoryTeachScreens.h" #include "PokemonFRLG_AutoStoryTrashCans.h" #include "PokemonFRLG_AutoStoryViridianMart.h" @@ -215,60 +216,6 @@ Outcome take_warp_step(StoryEnv& env, const RunState& state, const RouteStep& wa Outcome battle(StoryEnv& env, const StoryStep& step); -// The battle of a TRAINER_PASS_VARIANT step's trainer, as a BATTLE step. -StoryStep pass_fallback_battle(const StoryStep& step){ - StoryStep fight; - fight.kind = StoryStepKind::BATTLE; - fight.name = step.name + " (fallback battle)"; - fight.args = { - {"trainer", arg(step, "trainer")}, - {"foes", arg>(step, "foes")}, - {"use_items", std::vector()}, - {"may_lose", false}, - {"run", false}, - }; - return fight; -} - -// TRAINER_PASS_VARIANT on the console. No sprite of the trainer is in -// Resources yet to read their facing on screen, so wait_for_turn_away() -// has nothing to read: the crossing starts at once, logged, and the -// battle is the fallback when the trainer sees the player. The line is -// one tile deep where the crossing meets it, its first tile. -Outcome pass_trainer(StoryEnv& env, const RunState& state, const StoryStep& step){ - const Direction direction = arg(step, "direction"); - const int tiles = (int)arg(step, "tiles"); - env.console.log(std::format("Story: {}: the trainer's facing can't be read on the console yet; crossing unwatched.", step.name), COLOR_ORANGE); - // The tiles crossed without a stop on the line, the last step watched - // for the trainer's message. - std::optional facing = facing_of(state.pose); - for (int c = 1; c < tiles; c++){ - step_once(env.console, env.context, direction, facing); - facing = direction; - } - if (step_into_line(env.console, env.context, direction, facing, 1)){ - // Seen on the line's tile, the crossing's first: the steps after - // it were lost to the trainer's "!". - env.console.log(std::format("Story: {}: the trainer saw the player; fighting them (fallback).", step.name), COLOR_ORANGE); - const Outcome fought = battle(env, pass_fallback_battle(step)); - if (!fought.succeeded()){ - return fought; - } - for (int c = 1; c < tiles; c++){ - step_once(env.console, env.context, direction, direction); - } - } - const std::vector at = Pokemon::tiles_of(state.pose); - if (at.size() != 1){ - return Pokemon::outcome_ok(); - } - TilePos onto = at[0]; - for (int c = 0; c < tiles; c++){ - onto = onto.next(direction); - } - return Pokemon::outcome_ok(to_pose(StoryPose{state.pose.map, onto, direction})); -} - Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ const Direction direction = arg(step, "direction"); int tiles_stepped = 1; @@ -280,7 +227,9 @@ Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ env.console.log(std::format("Story: {}: a trainer saw the player after {} tile(s).", step.name, *stepped)); tiles_stepped = *stepped; }else if (step.action == TRAINER_PASS_VARIANT){ - return pass_trainer(env, state, step); + return pass_trainer(env, state, step, [&env](const StoryStep& fight){ + return battle(env, fight); + }); }else if (step.action == TRAINER_WAIT_VARIANT){ if (!step_into_line(env.console, env.context, direction, facing_of(state.pose), 1, TRAINER_WAIT_WATCH)){ return Pokemon::outcome_failed("no_trainer", std::format("{} s on the tile {}", TRAINER_WAIT_WATCH.count() / 1000, direction_name(direction))); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp index 1d68ffae31..e707d93cbb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp @@ -88,6 +88,9 @@ struct GymWalk{ SimScript script; std::optional sim; std::vector fought; + // Koga is beaten: so is every trainer of the gym + // (FuchsiaCity_Gym_EventScript_DefeatedKoga, set_gym_trainers 5). + bool gym_beaten = false; GymWalk(StoryPose start, SimScript sim_script) : at(std::move(start)) @@ -101,7 +104,16 @@ struct GymWalk{ const std::vector& beaten = sim->state().trainers_beaten; fought.insert(fought.end(), beaten.begin(), beaten.end()); } - sim.emplace(story_maps(), MapPosition{at.map, at.tile}, *at.facing, script); + std::vector maps = story_maps(); + for (MapData& map : maps){ + if (!gym_beaten || map.name != GYM){ + continue; + } + for (MapObject& object : map.objects){ + object.trainer.reset(); + } + } + sim.emplace(std::move(maps), MapPosition{at.map, at.tile}, *at.facing, script); } std::vector all_fought() const{ std::vector all = fought; @@ -113,14 +125,14 @@ struct GymWalk{ // A step of a row on the sim: row_step_on_sim(), but the way into a // Center, which has no map, and Koga's battle, which a talk starts, leave -// the player where the table says. +// the player where the table says; and Koga's leaves the gym's trainers +// beaten. std::string gym_step_on_sim(const StoryStep& step, const std::string& id, GymWalk& walk){ const bool center = step.action == CENTER_ENTER_VARIANT; if (center || (step.kind == StoryStepKind::BATTLE && step.name == "koga")){ walk.at = *story_pose(Pokemon::pose_of(*step.pose_after)); - if (center){ - walk.place(); - } + walk.gym_beaten = walk.gym_beaten || !center; + walk.place(); return ""; } return row_step_on_sim(*walk.sim, walk.at, step, id); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp index a1bf8c62da..de33a4ecc4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -25,6 +25,7 @@ #include "PokemonFRLG_AutoStoryRooms.h" #include "PokemonFRLG_AutoStoryRoomLegs.h" #include "PokemonFRLG_AutoStoryRowSim.h" +#include "PokemonFRLG_AutoStoryTrainerPass.h" #include "PokemonFRLG_AutoStoryViridianMart.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_FlyMap.h" @@ -490,7 +491,7 @@ std::string sim_pass_trainer(OverworldSim& sim, StoryPose& at, const StoryStep& }}; wait_for_turn_away( (int)(TRAINER_PASS_WATCH / TRAINER_PASS_POLL), away, - [&]{ return sim.trainer_facing(trainer); }, + [&]{ return trainer_facing(sim, trainer); }, [&]{ sim.watch({}, TRAINER_PASS_POLL); } ); for (int c = 1; c < tiles; c++){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index ad1247bbf9..3eea2c4694 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -21,6 +21,7 @@ #include "PokemonFRLG_AutoStorySlopeRun.h" #include "PokemonFRLG_AutoStoryTeach.h" #include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryTrainerPass.h" #include "PokemonFRLG_AutoStoryTrashCans.h" namespace PokemonAutomation{ @@ -60,6 +61,7 @@ const std::vector& story_action_rows(){ {StoryStepKind::ROUTE, "", StoryActionId::ROUTE}, {StoryStepKind::LEGS, "", StoryActionId::LEGS}, {StoryStepKind::STEP, "", StoryActionId::STEP}, + {StoryStepKind::STEP, TRAINER_PASS_VARIANT, StoryActionId::STEP}, {StoryStepKind::TALK, "", StoryActionId::TALK}, {StoryStepKind::ANSWER, "", StoryActionId::ANSWER}, {StoryStepKind::MASH, "", StoryActionId::MASH}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerLine.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerLine.h index bd7c15f519..d9f175e3f5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerLine.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerLine.h @@ -70,30 +70,6 @@ inline constexpr int TRAINER_LINE_TILES = 3; // one tile. inline const std::string TRAINER_WAIT_VARIANT = "trainer_wait"; -// The variant of a STEP across the line of a trainer who turns on a timer -// (MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT and its kin), as pokeguy passes -// Juggler Kayden in Fuchsia Gym (1:15:14): from outside their sight, the -// trainer (at "trainer_dx", "trainer_dy" tiles from the player) is watched, -// up to TRAINER_PASS_WATCH, until they turn "away", and then the player -// steps "tiles" tiles `direction` across the line. They hold a way at least -// 32 frames (pokefirered gMovementDelaysShort), longer than the step onto -// the line takes, so the crossing starts on a turn seen -// (wait_for_turn_away()), not on a facing that has lasted. If they see the -// player anyway (no turn seen in time, or the facing misread), their -// battle ("trainer", "foes") is fought there and the crossing goes on. -inline const std::string TRAINER_PASS_VARIANT = "trainer_pass"; -inline constexpr Milliseconds TRAINER_PASS_WATCH(20000); -// How often the trainer's facing is read while waiting. -inline constexpr Milliseconds TRAINER_PASS_POLL(50); - -// Reads `read` (the trainer's facing, or nothing if it can't be read), -// then `wait` and again, at most `polls` times, until it reads `away` -// after reading another way. Returns whether it did. -bool wait_for_turn_away( - int polls, Pokemon::Direction away, - const std::function()>& read, const std::function& wait -); - // From the overworld: step_until_seen() `direction`, turning first // unless `facing` is `direction`, each step watched `watch` for a // trainer's message, and at least WILD_BATTLE_IN_LINE_WATCH for a wild diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.cpp new file mode 100644 index 0000000000..954b5bac1f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.cpp @@ -0,0 +1,111 @@ +/* AutoStory Trainer Pass + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Color.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonFRLG_AutoStoryPoses.h" +#include "PokemonFRLG_AutoStoryTrainerLine.h" +#include "PokemonFRLG_AutoStoryTrainerPass.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::Direction; +using Pokemon::Outcome; + + +bool wait_for_turn_away( + int polls, Direction away, + const std::function()>& read, const std::function& wait +){ + bool other_way = false; + for (int poll = 0; poll < polls; poll++){ + if (poll > 0){ + wait(); + } + const std::optional facing = read(); + if (facing && *facing == away && other_way){ + return true; + } + other_way = other_way || (facing && *facing != away); + } + return false; +} + +namespace{ + +template +const Type& arg(const StoryStep& step, std::string_view key){ + return Pokemon::story_arg(step.args, key); +} + +// The battle of a TRAINER_PASS_VARIANT step's trainer, as a BATTLE step. +StoryStep pass_fallback_battle(const StoryStep& step){ + StoryStep fight; + fight.kind = StoryStepKind::BATTLE; + fight.name = std::format("{} (fallback battle)", step.name); + fight.args = { + {"trainer", arg(step, "trainer")}, + {"foes", arg>(step, "foes")}, + {"use_items", std::vector()}, + {"may_lose", false}, + {"run", false}, + }; + return fight; +} + +// The tiles crossed without a stop on the line, the last step watched for +// the trainer's message. Returns whether the trainer saw the player. +bool cross_line(StoryEnv& env, std::optional facing, Direction direction, int tiles){ + for (int c = 1; c < tiles; c++){ + step_once(env.console, env.context, direction, facing); + facing = direction; + } + return step_into_line(env.console, env.context, direction, facing, 1).has_value(); +} + +} // namespace + +Outcome pass_trainer( + StoryEnv& env, const Pokemon::RunState& state, const StoryStep& step, + const std::function& fight +){ + const Direction direction = arg(step, "direction"); + const int tiles = (int)arg(step, "tiles"); + env.console.log(std::format("Story: {}: the trainer's facing can't be read on the console yet; crossing unwatched.", step.name), COLOR_ORANGE); + if (cross_line(env, Pokemon::facing_of(state.pose), direction, tiles)){ + // Seen on the line's tile, the crossing's first: the steps after + // it were lost to the trainer's "!". + env.console.log(std::format("Story: {}: the trainer saw the player; fighting them (fallback).", step.name), COLOR_ORANGE); + const Outcome fought = fight(pass_fallback_battle(step)); + if (!fought.succeeded()){ + return fought; + } + for (int c = 1; c < tiles; c++){ + step_once(env.console, env.context, direction, direction); + } + } + const std::vector at = Pokemon::tiles_of(state.pose); + if (at.size() != 1){ + return Pokemon::outcome_ok(); + } + TilePos onto = at[0]; + for (int c = 0; c < tiles; c++){ + onto = onto.next(direction); + } + return Pokemon::outcome_ok(to_pose(StoryPose{state.pose.map, onto, direction})); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h new file mode 100644 index 0000000000..7391c36540 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h @@ -0,0 +1,65 @@ +/* AutoStory Trainer Pass + * + * From: https://github.com/PokemonAutomation/ + * + * A step across the line of a trainer who turns on a timer, on the turn + * away, as pokeguy passes Juggler Kayden in Fuchsia Gym. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryTrainerPass_H +#define PokemonAutomation_PokemonFRLG_AutoStoryTrainerPass_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonFRLG_AutoStoryEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The variant of a STEP across the line of a trainer who turns on a timer +// (MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT and its kin), as pokeguy passes +// Juggler Kayden in Fuchsia Gym (1:15:14): from outside their sight, the +// trainer (at "trainer_dx", "trainer_dy" tiles from the player) is watched, +// up to TRAINER_PASS_WATCH, until they turn "away", and then the player +// steps "tiles" tiles `direction` across the line. They hold a way at least +// 32 frames (pokefirered gMovementDelaysShort), longer than the step onto +// the line takes, so the crossing starts on a turn seen +// (wait_for_turn_away()), not on a facing that has lasted. If they see the +// player anyway (no turn seen in time, or the facing misread), their +// battle ("trainer", "foes") is fought there and the crossing goes on. +inline const std::string TRAINER_PASS_VARIANT = "trainer_pass"; +// The longest wait for the trainer's turn away. +inline constexpr Milliseconds TRAINER_PASS_WATCH(20000); +// How often the trainer's facing is read while waiting. +inline constexpr Milliseconds TRAINER_PASS_POLL(50); + +// Reads `read` (the trainer's facing, or nothing if it can't be read), +// then `wait` and again, at most `polls` times, until it reads `away` +// after reading another way. Returns whether it did. +bool wait_for_turn_away( + int polls, Pokemon::Direction away, + const std::function()>& read, const std::function& wait +); + +// A TRAINER_PASS_VARIANT `step` on the console, from `state`'s pose; +// `fight` fights the trainer's battle (a BATTLE step) if they see the +// player. The line is one tile deep where the crossing meets it, its +// first tile. No sprite of the trainer is in Resources yet to read their +// facing on screen, so the crossing starts at once, logged. +Pokemon::Outcome pass_trainer( + StoryEnv& env, const Pokemon::RunState& state, const StoryStep& step, + const std::function& fight +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index 3f232448e2..387e877a6e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -41,6 +41,7 @@ #include "PokemonFRLG_AutoStoryMoveData.h" #include "PokemonFRLG_AutoStoryStepTable.h" #include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryTrainerPass.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -492,10 +493,18 @@ const MapObject* trainer_seeing(const MapData& map, const TilePos& tile, const s // The tile a STEP from `pose` ends on: the next one; for a step into a // trainer's line, the first within TRAINER_LINE_TILES that a trainer // other than the `beaten` sees, where step_until_seen() stops, else the -// last. +// last; for a pass across a trainer's line (TRAINER_PASS_VARIANT), its +// last tile. TilePos step_end(const StoryPose& pose, const StoryStep& step, const std::set& beaten){ const MapData* map = find_map_named(pose.map); const Direction direction = Pokemon::story_arg(step.args, "direction"); + if (step.action == TRAINER_PASS_VARIANT){ + TilePos tile = pose.tile; + for (int64_t c = 0; c < Pokemon::story_arg(step.args, "tiles"); c++){ + tile = tile.next(direction); + } + return tile; + } if (step.action != TRAINER_LINE_VARIANT || map == nullptr){ return pose.tile.next(direction); } @@ -703,8 +712,9 @@ UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::set Date: Thu, 12 Nov 2026 10:49:15 -0800 Subject: [PATCH 06/39] PokemonFRLG: read Kayden's facing on screen for trainer_pass The player facing reader's matching now takes a frame position (match_facing_at()), and a trainer facing reader uses it with pokefirered's rocker.png standing frames in npc_blue.pal's colours, kept in the source until Packages carries the sheet. trainer_pass reads the step's "sprite" (12.01: "rocker") while waiting for the turn away; without frames, or with no turn seen in 20 s, it crosses blind, logged. Unit test on synthetic gym frames rendered from the sprite (red with the offset ignored). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_PlayerFacingReader.cpp | 36 ++- .../PokemonFRLG_PlayerFacingReader.h | 11 +- .../PokemonFRLG_TrainerFacingReader.cpp | 211 ++++++++++++++++++ .../PokemonFRLG_TrainerFacingReader.h | 49 ++++ .../PokemonFRLG/PokemonFRLG_Tests.cpp | 9 +- .../PokemonFRLG_AutoStoryStepTable.cpp | 1 + .../PokemonFRLG_AutoStoryTrainerPass.cpp | 33 ++- .../PokemonFRLG_AutoStoryTrainerPass.h | 8 +- .../AutoStory/StoryData/frlg-12.01.plan.json | 1 + SerialPrograms/cmake/SourceFiles.cmake | 2 + 10 files changed, 342 insertions(+), 19 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp index 407420bac7..390c96315d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp @@ -39,10 +39,14 @@ constexpr int SHEET_FIRST_ROW = 12; constexpr int SPRITE_WIDTH = 16; constexpr int SPRITE_ROWS = 19; -// Where the sprite's first drawn row sits on the GBA's 240x160 screen while -// the camera follows the player. Measured on the console. -constexpr int SPRITE_X = 112; -constexpr int SPRITE_Y = 56 + 12; +// Where the player's 16x32 frame sits on the GBA's 240x160 screen while +// the camera follows the player (its first drawn row 12 lower). Measured +// on the console. An object a tile away sits a tile (16 pixels) away. +constexpr int FRAME_X = 112; +constexpr int FRAME_Y = 56; +constexpr int TILE_PIXELS = 16; +constexpr int SPRITE_X = FRAME_X; +constexpr int SPRITE_Y = FRAME_Y + SHEET_FIRST_ROW; constexpr int GBA_WIDTH = 240; constexpr int GBA_HEIGHT = 160; @@ -56,20 +60,22 @@ ImageRGB32 sheet_frame(const ImageViewRGB32& sheet, int frame){ return sheet.sub_image(frame * SHEET_FRAME_WIDTH, SHEET_FIRST_ROW, SPRITE_WIDTH, SPRITE_ROWS).copy(); } -// How far the screen differs from `sprite`, drawn `dy` GBA pixels lower. -double difference(const ImageViewRGB32& game, const ImageViewRGB32& sprite, bool mirror, int dy){ +// How far the screen differs from `sprite`, its first row drawn at GBA +// pixel (`x0`, `y0`). +double difference(const ImageViewRGB32& game, const ImageViewRGB32& sprite, bool mirror, int x0, int y0){ const double scale_x = (double)game.width() / GBA_WIDTH; const double scale_y = (double)game.height() / GBA_HEIGHT; + const int width = (int)sprite.width(); long total = 0; int pixels = 0; - for (int row = 0; row < SPRITE_ROWS; row++){ - for (int col = 0; col < SPRITE_WIDTH; col++){ - const Color expected(sprite.pixel(mirror ? SPRITE_WIDTH - 1 - col : col, row)); + for (int row = 0; row < (int)sprite.height(); row++){ + for (int col = 0; col < width; col++){ + const Color expected(sprite.pixel(mirror ? width - 1 - col : col, row)); if (expected.alpha() == 0){ continue; } - const size_t x = (size_t)((SPRITE_X + col + 0.5) * scale_x); - const size_t y = (size_t)((SPRITE_Y + dy + row + 0.5) * scale_y); + const size_t x = (size_t)((x0 + col + 0.5) * scale_x); + const size_t y = (size_t)((y0 + row + 0.5) * scale_y); if (x >= game.width() || y >= game.height()){ return std::numeric_limits::max(); } @@ -129,6 +135,12 @@ std::optional read_player_facing(const ImageViewRGB32& screen){ } std::optional match_player_facing(const ImageViewRGB32& game, const PlayerSprites& sprites){ + return match_facing_at(game, sprites, SHEET_FIRST_ROW, 0, 0); +} + +std::optional match_facing_at(const ImageViewRGB32& game, const PlayerSprites& sprites, int first_row, int dx_tiles, int dy_tiles){ + const int x0 = FRAME_X + TILE_PIXELS * dx_tiles; + const int y0 = FRAME_Y + TILE_PIXELS * dy_tiles + first_row; struct Candidate{ Direction direction; const ImageViewRGB32& sprite; @@ -148,7 +160,7 @@ std::optional match_player_facing(const ImageViewRGB32& game, const P // A pixel either way, for a box that is slightly off. double score = std::numeric_limits::max(); for (int dy = -1; dy <= 1; dy++){ - score = std::min(score, difference(game, candidate.sprite, candidate.mirror, dy)); + score = std::min(score, difference(game, candidate.sprite, candidate.mirror, x0, y0 + dy)); } if (score < best){ second = best; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h index 4ad7021011..bc1043da5d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h @@ -34,8 +34,9 @@ enum class PlayerGender{ GIRL, }; -// The standing player's frames, as the game draws them, with transparent -// pixels at alpha 0. Facing east is facing west mirrored. +// The standing player's frames (or another person's, match_facing_at()), +// as the game draws them, with transparent pixels at alpha 0. Facing east +// is facing west mirrored. struct PlayerSprites{ ImageRGB32 south; ImageRGB32 north; @@ -58,6 +59,12 @@ std::optional read_player_facing(const ImageViewRGB32& screen); std::optional match_player_facing(const ImageViewRGB32& game, const PlayerSprites& sprites); +// The way a standing person faces whose `sprites` are drawn from row +// `first_row` of their 16x32 frames, `dx_tiles` east and `dy_tiles` south +// of the player, on `game` (as match_player_facing(), which is this at the +// player's own tile). Nothing if no frame matches clearly. +std::optional match_facing_at(const ImageViewRGB32& game, const PlayerSprites& sprites, int first_row, int dx_tiles, int dy_tiles); + // Registers player facing reader unit tests. void add_tests_PlayerFacingReader(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.cpp new file mode 100644 index 0000000000..646d593e64 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.cpp @@ -0,0 +1,211 @@ +/* Trainer Facing Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "PokemonFRLG_TrainerFacingReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +namespace{ + +// rocker.png's standing frames 0 (south), 1 (north) and 2 (west), rows 11 +// to 30 of each 16x32 frame (the rest is empty), as palette indices; 0 is +// transparent. +constexpr int ROCKER_FIRST_ROW = 11; +constexpr int ROCKER_ROWS = 20; +constexpr int SPRITE_WIDTH = 16; +const char* const ROCKER_SOUTH[ROCKER_ROWS] = { + "0000007777000000", + "0000776666770000", + "0007665555667000", + "0007655665567000", + "0076656556566700", + "0076775555776700", + "0f272167761272f0", + "0f272111111272f0", + "00f32f1111f23f00", + "000f22422422f000", + "000f32222223f000", + "0042f433334f2400", + "04222dffffd22240", + "0422dc6cc6cd2240", + "0433dcc55ccd3340", + "00ddfcbbbbcfdd00", + "000d7ffeeff7d000", + "000fd77dd77df000", + "000f66f00f66f000", + "0000ff0000ff0000", +}; +const char* const ROCKER_NORTH[ROCKER_ROWS] = { + "0000007777000000", + "0000776556770000", + "0007655555567000", + "0007655555567000", + "0076655555566700", + "0076665555666700", + "0f276666666672f0", + "0f276666666672f0", + "00f7766666677f00", + "000f77777777f000", + "000f77777777f000", + "0042fd7777df2400", + "04223dffffd32240", + "0422dccccccd2240", + "043fdcbbbbcdf340", + "00ddffbbbbffdd00", + "000d7ffffff7d000", + "000fd77dd77df000", + "000f66f00f66f000", + "0000ff0000ff0000", +}; +const char* const ROCKER_WEST[ROCKER_ROWS] = { + "0000007777000000", + "0000775555770000", + "0007555555567000", + "0776555555557000", + "0755655555666700", + "0075566666666700", + "00f7711766667f00", + "00f1111277777f00", + "004111f27237f000", + "004224227237f000", + "00042222337f0000", + "0000433334f00000", + "0000df744bd00000", + "000075411dbd0000", + "0000db411dbd0000", + "0000df433dfd0000", + "0000d7f44fd00000", + "00000d7777d00000", + "00000d667d000000", + "000000fff0000000", +}; + +// graphics/object_events/palettes/npc_blue.pal. +constexpr uint32_t NPC_BLUE[16] = { + 0xff73c5a4, 0xffffd5b4, 0xfff6bd94, 0xffde9473, 0xff7b4141, 0xffffde4a, 0xffd5ac20, 0xff836200, + 0xffa48bee, 0xff6a52bd, 0xff413962, 0xffee7341, 0xffac4139, 0xff4a3131, 0xffffffff, 0xff000000, +}; + +ImageRGB32 frame_of(const char* const rows[ROCKER_ROWS]){ + ImageRGB32 frame(SPRITE_WIDTH, ROCKER_ROWS); + for (int row = 0; row < ROCKER_ROWS; row++){ + for (int col = 0; col < SPRITE_WIDTH; col++){ + const char digit = rows[row][col]; + const int index = digit <= '9' ? digit - '0' : digit - 'a' + 10; + frame.pixel(col, row) = index == 0 ? 0x00000000 : NPC_BLUE[index]; + } + } + return frame; +} + +} // namespace + + +const PlayerSprites* trainer_sprites(std::string_view sprite){ + static const PlayerSprites ROCKER{frame_of(ROCKER_SOUTH), frame_of(ROCKER_NORTH), frame_of(ROCKER_WEST)}; + return sprite == "rocker" ? &ROCKER : nullptr; +} + +std::optional read_trainer_facing( + const ImageViewRGB32& screen, const PlayerSprites& sprites, int dx_tiles, int dy_tiles +){ + const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); + return match_facing_at(game, sprites, ROCKER_FIRST_ROW, dx_tiles, dy_tiles); +} + + +namespace{ + +constexpr int GBA_WIDTH = 240; +constexpr int GBA_HEIGHT = 160; +constexpr int SCALE = 4; +// Kayden from the tile the pass waits on: two west, one north. +constexpr int KAYDEN_DX = -2; +constexpr int KAYDEN_DY = -1; + +// A GBA screen at SCALE times its size, the gym's floor grey, with +// `sprite` (mirrored if `mirror`) drawn `dx`, `dy` tiles from the +// player's frame (112, 56), and the player's spot left empty. +ImageRGB32 synthetic_game(const ImageViewRGB32* sprite, bool mirror, int dx, int dy){ + ImageRGB32 game(SCALE * GBA_WIDTH, SCALE * GBA_HEIGHT); + game.fill(0xff9c9c94); + const int x0 = 112 + 16 * dx; + const int y0 = 56 + 16 * dy + ROCKER_FIRST_ROW; + for (int row = 0; sprite != nullptr && row < ROCKER_ROWS; row++){ + for (int col = 0; col < SPRITE_WIDTH; col++){ + const uint32_t pixel = sprite->pixel(mirror ? SPRITE_WIDTH - 1 - col : col, row); + if (Color(pixel).alpha() == 0){ + continue; + } + for (int y = 0; y < SCALE; y++){ + for (int x = 0; x < SCALE; x++){ + game.pixel(SCALE * (x0 + col) + x, SCALE * (y0 + row) + y) = pixel; + } + } + } + } + return game; +} + +std::string facing_text(const std::optional& facing){ + return facing ? std::string(direction_name(*facing)) : std::string("nothing"); +} + +// Kayden's frames drawn where he stands from the pass's tile read as the +// way they face; nothing there, or Kayden a tile off, reads as nothing. +class Test_TrainerFacingSynthetic : public UnitTest{ +public: + Test_TrainerFacingSynthetic() + : UnitTest("PokemonFRLG::TrainerFacingReader - rocker frames on a synthetic gym floor") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const PlayerSprites& rocker = *trainer_sprites("rocker"); + struct Case{ + const ImageViewRGB32* sprite; + bool mirror; + int dx; + std::optional expected; + }; + const Case cases[] = { + {&rocker.south, false, KAYDEN_DX, Direction::SOUTH}, + {&rocker.north, false, KAYDEN_DX, Direction::NORTH}, + {&rocker.west, false, KAYDEN_DX, Direction::WEST}, + {&rocker.west, true, KAYDEN_DX, Direction::EAST}, + {nullptr, false, KAYDEN_DX, std::nullopt}, + {&rocker.south, false, KAYDEN_DX + 1, std::nullopt}, + }; + for (const Case& test : cases){ + const ImageRGB32 game = synthetic_game(test.sprite, test.mirror, test.dx, KAYDEN_DY); + const std::optional facing = match_facing_at(game, rocker, ROCKER_FIRST_ROW, KAYDEN_DX, KAYDEN_DY); + if (facing != test.expected){ + return std::format("Read {} instead of {}.", facing_text(facing), facing_text(test.expected)); + } + } + return trainer_sprites("hiker") == nullptr ? UnitTestResult(true) : UnitTestResult("A hiker's frames that aren't there."); + } +}; + +} // namespace + +void add_tests_TrainerFacingReader(UnitTestDatabase& database){ + database.add(); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h new file mode 100644 index 0000000000..fe0f3b1a8d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h @@ -0,0 +1,49 @@ +/* Trainer Facing Reader + * + * From: https://github.com/PokemonAutomation/ + * + * Which way a trainer standing near the player faces, read from the + * overworld with match_facing_at() against their standing frames. The + * frames are pret/pokefirered's: a rocker (OBJ_EVENT_GFX_ROCKER, Juggler + * Kayden in Fuchsia Gym) from graphics/object_events/pics/people/rocker.png + * in the colours the game gives it, graphics/object_events/palettes/ + * npc_blue.pal (gObjectEventGraphicsInfo_Rocker: OBJ_EVENT_PAL_TAG_NPC_BLUE). + * They are kept here, not in Resources, until a Packages change carries + * the sheet. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_TrainerFacingReader_H +#define PokemonAutomation_PokemonFRLG_TrainerFacingReader_H + +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonFRLG_PlayerFacingReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The standing frames of the trainer sprite `sprite` ("rocker"), or null +// for one this reader hasn't got. +const PlayerSprites* trainer_sprites(std::string_view sprite); + +// The way the trainer drawn with `sprites`, standing `dx_tiles` east and +// `dy_tiles` south of the player, faces on the console's `screen`; nothing +// if no frame matches clearly (another person there, mid-turn, a menu). +std::optional read_trainer_facing( + const ImageViewRGB32& screen, const PlayerSprites& sprites, int dx_tiles, int dy_tiles +); + +// Registers the trainer facing reader's tests. +void add_tests_TrainerFacingReader(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 80ba736ea8..0d606cff86 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -44,6 +44,7 @@ #include "Overworld/PokemonFRLG_OverworldSim.h" #include "Overworld/PokemonFRLG_OverworldWalk.h" #include "Overworld/PokemonFRLG_PlayerFacingReader.h" +#include "Overworld/PokemonFRLG_TrainerFacingReader.h" #include "Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h" #include "PokemonFRLG_Navigation.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h" @@ -334,6 +335,12 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& database){ add_tests_AutoStoryFuchsiaGym(database); } +// Which way the player, and a trainer near them, faces on the overworld. +static void add_tests_FacingReaders(UnitTestDatabase& database){ + add_tests_PlayerFacingReader(database); + add_tests_TrainerFacingReader(database); +} + void add_tests(UnitTestDatabase& database){ add_tests_AdvanceWhiteDialogDetector(database); add_tests_AdvanceBattleDialogDetector(database); @@ -369,7 +376,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_OverworldReanchor(database); add_tests_OverworldRecovery(database); add_tests_OverworldSim(database); - add_tests_PlayerFacingReader(database); + add_tests_FacingReaders(database); add_tests_AutoStory(database); add_tests_AutoStoryJson(database); add_tests_AutoStorySimulation(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index 3eea2c4694..29ffa82fd9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -181,6 +181,7 @@ std::vector movement_variant_specs(std::span #include #include "Common/Cpp/Color.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h" #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "PokemonFRLG_AutoStoryPoses.h" @@ -62,6 +65,34 @@ StoryStep pass_fallback_battle(const StoryStep& step){ return fight; } +// Waits for the trainer's turn away (wait_for_turn_away()), reading their +// facing on screen, if the reader has the step's "sprite"; else, or with +// no turn seen in TRAINER_PASS_WATCH, logs that the crossing is blind. +void wait_for_trainer(StoryEnv& env, const StoryStep& step){ + const PlayerSprites* sprites = trainer_sprites(arg(step, "sprite")); + if (sprites == nullptr){ + env.console.log(std::format("Story: {}: no frames of the trainer's sprite to read their facing; crossing blind.", step.name), COLOR_ORANGE); + return; + } + const int dx = (int)arg(step, "trainer_dx"); + const int dy = (int)arg(step, "trainer_dy"); + const Direction away = arg(step, "away"); + const bool turned = wait_for_turn_away( + (int)(TRAINER_PASS_WATCH / TRAINER_PASS_POLL), away, + [&]() -> std::optional{ + env.context.wait_for_all_requests(); + const VideoSnapshot screen = env.console.video().snapshot(); + return screen ? read_trainer_facing(screen, *sprites, dx, dy) : std::nullopt; + }, + [&]{ pbf_wait(env.context, TRAINER_PASS_POLL); } + ); + if (turned){ + env.console.log(std::format("Story: {}: the trainer turned {}; crossing.", step.name, direction_name(away))); + }else{ + env.console.log(std::format("Story: {}: no turn {} seen in {} s; crossing blind.", step.name, direction_name(away), TRAINER_PASS_WATCH.count() / 1000), COLOR_ORANGE); + } +} + // The tiles crossed without a stop on the line, the last step watched for // the trainer's message. Returns whether the trainer saw the player. bool cross_line(StoryEnv& env, std::optional facing, Direction direction, int tiles){ @@ -80,7 +111,7 @@ Outcome pass_trainer( ){ const Direction direction = arg(step, "direction"); const int tiles = (int)arg(step, "tiles"); - env.console.log(std::format("Story: {}: the trainer's facing can't be read on the console yet; crossing unwatched.", step.name), COLOR_ORANGE); + wait_for_trainer(env, step); if (cross_line(env, Pokemon::facing_of(state.pose), direction, tiles)){ // Seen on the line's tile, the crossing's first: the steps after // it were lost to the trainer's "!". diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h index 7391c36540..0dfac43064 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h @@ -25,7 +25,8 @@ namespace PokemonFRLG{ // The variant of a STEP across the line of a trainer who turns on a timer // (MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT and its kin), as pokeguy passes // Juggler Kayden in Fuchsia Gym (1:15:14): from outside their sight, the -// trainer (at "trainer_dx", "trainer_dy" tiles from the player) is watched, +// trainer (at "trainer_dx", "trainer_dy" tiles from the player, drawn with +// "sprite") is watched, // up to TRAINER_PASS_WATCH, until they turn "away", and then the player // steps "tiles" tiles `direction` across the line. They hold a way at least // 32 frames (pokefirered gMovementDelaysShort), longer than the step onto @@ -50,8 +51,9 @@ bool wait_for_turn_away( // A TRAINER_PASS_VARIANT `step` on the console, from `state`'s pose; // `fight` fights the trainer's battle (a BATTLE step) if they see the // player. The line is one tile deep where the crossing meets it, its -// first tile. No sprite of the trainer is in Resources yet to read their -// facing on screen, so the crossing starts at once, logged. +// first tile. The trainer's facing is read on screen with the frames of +// the step's "sprite" (read_trainer_facing()); without them the crossing +// is blind, logged. Pokemon::Outcome pass_trainer( StoryEnv& env, const Pokemon::RunState& state, const StoryStep& step, const std::function& fight diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json index 25974f43eb..a2a7cb611e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json @@ -76,6 +76,7 @@ "away": "south", "trainer_dx": -2, "trainer_dy": -1, + "sprite": "rocker", "trainer": "TRAINER_JUGGLER_KAYDEN", "foes": ["hypno"] }, diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index e695556585..bd412a54cd 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2030,6 +2030,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWildTiles.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PokemonCenterRoom.h Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h From 665d3a66fb8c6225c827494eda8b04363e55e807 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 10:56:20 -0800 Subject: [PATCH 07/39] PokemonFRLG: 12.01 fights Juggler Kayden again (user decision 2026-11-12) Removes trainer_pass, the trainer facing reader, the player reader's match_facing_at() refactor and the sim's timer-turn trainers, back to 52ede5190's code. Keeps the gym sim's rule that Koga's win beats every gym trainer (set_gym_trainers 5). 12.01's notes record the decision and Koga's full-HP win rate (88.0%) next to the recorded 70.1%. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldSim.cpp | 35 + .../Overworld/PokemonFRLG_OverworldSim.h | 970 +++++++++--------- .../Overworld/PokemonFRLG_OverworldSimState.h | 4 - .../PokemonFRLG_OverworldSimTrainerTurns.h | 48 - .../PokemonFRLG_OverworldSimTrainers.cpp | 100 -- .../PokemonFRLG_PlayerFacingReader.cpp | 36 +- .../PokemonFRLG_PlayerFacingReader.h | 11 +- .../PokemonFRLG_TrainerFacingReader.cpp | 211 ---- .../PokemonFRLG_TrainerFacingReader.h | 49 - .../PokemonFRLG/PokemonFRLG_Tests.cpp | 9 +- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 7 - .../PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp | 67 +- .../AutoStory/PokemonFRLG_AutoStoryRowSim.cpp | 55 - .../PokemonFRLG_AutoStoryStepTable.cpp | 14 - .../PokemonFRLG_AutoStoryTrainerPass.cpp | 142 --- .../PokemonFRLG_AutoStoryTrainerPass.h | 67 -- .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 20 +- .../AutoStory/StoryData/frlg-12.01.plan.json | 31 +- SerialPrograms/cmake/SourceFiles.cmake | 6 - 19 files changed, 569 insertions(+), 1313 deletions(-) delete mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainerTurns.h delete mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainers.cpp delete mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.cpp delete mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h delete mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.cpp delete mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 3697e679ef..96d07b3d6f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -126,6 +126,14 @@ std::optional ledge_direction(TileKind tile){ } } +// The tile next to `player` a trainer standing on `box` walks up to. +TilePos trainer_stop(const Pokemon::TileBox& box, const TilePos& player){ + if (box.x0 <= player.x && player.x <= box.x1){ + return TilePos{player.x, box.y0 > player.y ? player.y + 1 : player.y - 1}; + } + return TilePos{box.x0 > player.x ? player.x + 1 : player.x - 1, player.y}; +} + } // namespace @@ -319,6 +327,33 @@ std::optional OverworldSim::press(Direction direction) const return step; } +// A trainer on the player's map who sees them now walks up and speaks. +bool OverworldSim::trainer_sees(Milliseconds pressed){ + std::vector& objects = m_maps[m_map].objects; + for (size_t c = 0; c < objects.size(); c++){ + MapObject& trainer = objects[c]; + if (!trainer.trainer || !trainer_may_see(map(), trainer, m_player.position)){ + continue; + } + const Pokemon::TileBox box = trainer.wander.value_or(Pokemon::TileBox{trainer.x, trainer.y, trainer.x, trainer.y}); + const TilePos stop = trainer_stop(box, m_player.position); + const int approach = std::abs(stop.x - trainer.x) + std::abs(stop.y - trainer.y); + trainer.x = stop.x; + trainer.y = stop.y; + trainer.wander.reset(); + // The player turns to face the trainer. + for (Direction direction : {Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST}){ + m_state.facing = m_player.position.next(direction) == stop ? direction : m_state.facing; + } + m_trainer_speaking = c; + m_frozen = true; + schedule(pressed + m_script.timing.tile * (1 + approach) + m_script.timing.trainer_notice, SimScreen::MESSAGE, false); + note(std::format("{} on {} sees the player, walks up {} tile(s) to {}.", trainer.name, map().name, approach, to_string(stop))); + return true; + } + return false; +} + // The player has taken `step`, pressed at `pressed`. Returns whether the // game stopped them there: a warp, a trainer, a wild battle. bool OverworldSim::after_step(const Step& step, Milliseconds pressed){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index f7c880fd3c..2a4c86864d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -1,487 +1,483 @@ -/* Overworld Sim - * - * From: https://github.com/PokemonAutomation/ - * - * A whole-tile model of FireRed's overworld, for running the walker - * (run_route(), Pokemon::walk_leg_with()) without a console. The player - * moves a tile per 16 frames while the D-pad is held, by the maps' step - * rules (classify_step()), and also hops ledges the way they face, takes - * warps with a fade, reads signs walked into moving north or south, and is - * seen by trainers along their sight. Wild battles start on the steps a - * test chooses. Each of these shows a screen at a time after the step's - * press, which the walker's watchers see or miss as the console's do. - * - * Every console failure of the walker becomes a test here (red first). - * OverworldSimWalker is the console side of run_route() (RouteCalls) on - * the sim, step for step as walk_overworld_route_with_recovery() does it, - * with the walker's rules as switches, so a test can show a failure with - * the rule that was missing and its absence with the rule. - * - * A step onto a connected map waits a tile first, as the console does - * while the game loads the map. - * - * Not modelled: running, HP and status, and wild battles on the water. - * Surf and Fly are (SimField::SURF, SimField::FLY). Wandering people stand on - * their tile. The Bicycle is: its pace, its taps (each a tile, some - * dropped when they come too fast), SELECT and doors taking the player - * off it. - * - */ - -#ifndef PokemonAutomation_PokemonFRLG_OverworldSim_H -#define PokemonAutomation_PokemonFRLG_OverworldSim_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" -#include "PokemonFRLG_MovementMechanics.h" -#include "PokemonFRLG_BikeSpinPresses.h" -#include "PokemonFRLG_BikeSpinMechanics.h" -#include "PokemonFRLG_OverworldBikeTaps.h" -#include "PokemonFRLG_OverworldRecovery.h" -#include "PokemonFRLG_OverworldRoute.h" -#include "PokemonFRLG_OverworldSimField.h" -#include "PokemonFRLG_OverworldWalk.h" -#include "PokemonFRLG_OverworldSpin.h" -#include "PokemonFRLG_OverworldSimState.h" -#include "PokemonFRLG_OverworldSimScreens.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -// Simulates overworld movement, encounters and dialogs. -class OverworldSim{ -public: - OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script = {}); - - const SimState& state() const{ return m_state; } - - // Whether the walker's screen check reads its last step tap as a - // step: one that moved the player from `before`, but for - // SimScript::unseen_step_taps, or a turn tap since `turn_taps_before` - // (SimState::turn_taps) that SimScript::seen_turn_taps names. - bool reads_step_tap_as_step(const MapPosition& before, int turn_taps_before); - - // Holds `direction` for `duration` then lets go for `release`, while - // `watchers` watch until `watch` (at least the hold and release) from - // the start. Returns the first that saw its screen, as run_until(). - std::optional hold( - Direction direction, Milliseconds duration, Milliseconds release, Milliseconds watch, - const std::vector& watchers - ); - - // A press of `direction` for `duration` (at most MovementMechanics:: - // LONGEST_TAP), then `release`, as the console measured it: a player - // facing another way only turns; one facing that way steps once, - // unless the tap starts inside the lockout after the last step tap - // (STEP_TAP_LOCKOUT), which the game ignores, as it does any tap - // inside the lockout after a battle (BATTLE_EXIT_LOCKOUT); holds - // aren't held up by that lockout yet. A tap that starts as - // the last one ends, with no release between, holds it on. A turn may - // be dropped by fault injection (SimScript::dropped_turn_taps). - void tap( - Direction direction, - Milliseconds duration = MovementMechanics::TURN_TAP, - Milliseconds release = MovementMechanics::TURN_SETTLE - ); - - // Watches `watchers` for `duration`, as wait_until(). - std::optional watch(const std::vector& watchers, Milliseconds duration); - - // Runs from or fights the battle on screen, back to the overworld. A - // trainer's battle can't be run from; a battle that isn't there is - // waited out (the story's battle loop gives up after 15 s). - SimBattleEnd handle_battle(SimBattleChoice choice); - - // Closes the message on screen with B. Returns whether a trainer's - // battle follows it. - bool close_message(); - - // A on what the player faces, as `field` says (`floor`: the lift's). - // Returns whether it was there. (PokemonFRLG_OverworldSimField.cpp) - bool use_field(SimField field, size_t floor = 0); - -private: - // A screen that shows at `at`; `unfreeze`: the player can move again. - struct Pending{ - Milliseconds at; - SimScreen screen; - bool unfreeze; - }; - // Where one press of the D-pad takes the player. - struct Step{ - int map = 0; - PlayerState player; - bool warped = false; - // The way the warp left the player facing (arrival_facing()), if - // not the way they moved. - std::optional facing = std::nullopt; - bool ledge = false; - // The step landed on a spinner, which slid the player to `player`. - std::optional spin = {}; - }; - - void advance_to(Milliseconds time); - void show(SimScreen screen, Milliseconds at); - void schedule(Milliseconds at, SimScreen screen, bool unfreeze); - bool sees(SimWatcher watcher, SimScreen screen) const; - std::optional first_seen(SimWatcher watcher, Milliseconds from, Milliseconds to) const; - std::optional watch_until(const std::vector& watchers, Milliseconds from, Milliseconds to); - // A tap, for the next one's lockout and to hold on: when it started - // and ended, the player's facing before it and the steps it took. - struct TapPress{ - Direction direction = Direction::NORTH; - Milliseconds start{0}; - Milliseconds end{0}; - Direction facing_before = Direction::NORTH; - int steps = 0; - }; - void walk_hold(Direction direction, Milliseconds duration, int short_by); - void take_steps(Direction direction, Milliseconds pressed, Milliseconds end, int left); - void step_tap(Direction direction, Milliseconds duration); - void hold_on(Direction direction, Milliseconds end); - void stuck_hold(Direction direction); - void bump(Direction direction, Milliseconds pressed); - std::optional press(Direction direction) const; - std::optional take_warp(int map_index, const TilePos& tile) const; - std::optional cross_edge(Direction direction) const; - // The lift's door to the floor picked, if `map_index` is a lift and - // one was picked. - std::optional lift_warp(int map_index) const; - // A step that landed on a spinner slides on to the slide's end; false - // if the slide never stops. - bool slide_on(Step& step) const; - // The slide's time after `step`, and its facing; 0 for no slide. - Milliseconds after_slide(const Step& step); - // What the maps can't say, from code (add_coded_objects()). - void add_coded_field(); - bool cut_tree(); - bool choose_lift_floor(size_t floor); - bool push_poster_switch(); - bool start_surf(); - bool fly_to_town(size_t town); - // The trees cut come back, as after a warp. - void regrow_cut_trees(); - bool after_step(const Step& step, Milliseconds pressed); - bool wild_battle(Milliseconds pressed); - std::optional next_encounter(); - bool rolls_encounter(int rate); - bool drops_turn_tap(); - bool press_select(); - // Whether the Bicycle tap starting at `start` is dropped, too soon - // after the last one. - bool drops_bike_tap(Milliseconds start); - // How long a tile takes: on the water, on the Bicycle or on foot. - Milliseconds tile_time() const{ - if (m_player.surfing){ - return m_script.timing.surf_tile; - } - return m_state.on_bike ? m_script.timing.bike_tile : m_script.timing.tile; - } - // (PokemonFRLG_OverworldSimTrainers.cpp) - bool trainer_sees(Milliseconds pressed); - // The way the trainer standing on `home` faces now, if they turn on a - // timer (SimScript::trainer_turns). (PokemonFRLG_OverworldSimTrainers.cpp) - friend std::optional trainer_facing(const OverworldSim& sim, const MapPosition& home); - void update_view(); - void note(const std::string& line); - void violation(const std::string& line); - const MapData& map() const{ return m_maps[m_map]; } - - std::vector m_maps; - SimScript m_script; - int m_map = 0; - PlayerState m_player; - Milliseconds m_now{0}; - std::vector m_pending; // in time order - // The game has stopped the player: a battle, a message, a warp. - bool m_frozen = false; - // A battle is on screen or about to show. - bool m_battle_pending = false; - // The trainer (an object of the player's map) whose message is up or - // about to show, and whose battle follows it. - std::optional m_trainer_speaking; - // The trainer whose battle is on screen or about to show. - std::optional m_trainer; - // The trees cut since the last warp, and their maps. - std::vector> m_cut_trees; - // The floor picked on the lift's panel, if any. - std::optional m_lift_floor; - int m_grass_steps = 0; - // The game's wild encounter state (SimScript::encounter_rates). - std::mt19937 m_encounter_rng; - int m_steps_since_encounter = 0; - int m_encounter_rate_buff = 0; - // The turn taps so far, for SimScript::dropped_turn_taps. - // Steps onto a warp so far, and the fault on one - // (SimScript::black_without_warp): its black without the warp. - int m_warp_steps = 0; - bool black_without_warp(Milliseconds pressed); - // The last tap, until a hold. - std::optional m_last_tap; - // When the last Bicycle tap started, and how many came too soon. - std::optional m_last_bike_tap; - int m_fast_bike_taps = 0; - // A hold of `direction` for `duration`: counts the leg a tap on the - // Bicycle starts (SimState::bike_legs), and takes the player off the - // Bicycle if SimScript::off_bike_at_legs names it. - void count_bike_leg(Direction direction, Milliseconds duration); - // The way of the last Bicycle tap, unless another press came since. - std::optional m_bike_leg_direction; - // When the last tap that stepped started. - std::optional m_last_step_tap; - // The end of the lockout after the last battle. - Milliseconds m_battle_lockout_end{0}; - Milliseconds m_wild_battle_from{0}; - int m_holds = 0; - SimState m_state; -}; - - -// The walker's rules that console failures added, each on unless a test -// turns it off to show the failure it fixed. -struct SimWalkerRules{ - // Fail before a step unless the overworld is up (START menu left open, - // console B, 2026-11-01, Viridian Forest). - bool check_overworld = true; - // A battle needs an HP box or the battle menu: black below a small room - // isn't one (console B, 2026-11-01, Viridian Forest's north gate). - bool battle_needs_hp_box = true; - // A trainer's battle after their message is fought, not taken for a - // wild one and run from (console B, 2026-11-01, Viridian Forest). - bool fight_trainer_after_message = true; - // How long the walker watches after a leg through grass for a battle - // whose flashes it missed. It watched 500 ms, and walked the next leg - // into the battle (console B, 2026-11-01, Route 1, run 7 and r14). - Milliseconds after_wild_leg_watch = OverworldWalkSteps::AFTER_WILD_LEG_WATCH; - // A leg to a wall held again after an interrupt stops when it is - // interrupted again right away: by a sign it is held into. Without it - // the walker read the sign 6 times (console B, 2026-11-01, r16). - bool stop_if_blocked = true; - // How long a hold's watch goes on past the hold and its release. 0 as - // now; the tile-at-a-time build watched each step for 900 ms, and saw - // the warp's fade on the step onto the forest's north gate as a battle. - Milliseconds watch_past_hold{0}; - // A leg onto a warp whose fade was a wild battle's (its wipe passes for - // the fade) stops before the warp, and the player is found again on it. - // Without it the walker stopped as off the route (console B, - // 2026-11-03, Mt. Moon 1F, row 04.05). - bool find_player_after_warp_battle = true; - // After a leg's watch saw nothing, a battle's text box on screen (its - // HP boxes still to come) is watched on for, and the leg taken as - // stopped part-way. Without it the walker took "south 15 (to wall)" - // as walked and the next leg into the battle (console B, 2026-11-03, - // Mt. Moon B1F, row 04.05). - bool watch_on_for_unseen_battle = true; - // The same after a leg the maps see no wild tiles on (RouteStep::wild), - // which the leg and its watch don't watch for battles: on Mt. Moon - // B2F's tiles closed on one side, which the maps don't mark as wild, a - // battle on "east 7 (to wall)" left black after the leg, the leg was - // taken as walked and the next one held from where the battle was - // (console B, 2026-11-03, row 04.05). - bool watch_on_after_unmarked_leg = true; - // Before a step, a battle on its way (its text box or wipe) is watched - // on for, and the step before it taken as stopped part-way, not the - // step held from where the battle left the player. - bool battle_before_step = true; - // A hold over a step onto a connected map is a tile longer for it - // (RouteStep::connection_steps). Without it the open leg north from - // Cerulean City onto Nugget Bridge ended a tile short (console B, - // 2026-11-03, rows 05.05 and 05.09). - bool hold_over_connections = true; - // An open leg after whose hold a wild battle was seen is placed by the - // battle's first timed screen event (place_late_stop()). Without it the - // player may be anywhere on the leg: on Route 10, "east 11" was found - // again from all 12 of its tiles (console B, 2026-11-09, 07.02 run 2). - bool place_late_battle = true; - // A message after the hold of an open leg that ends below a sign - // (RouteStep::sign_ahead) places the player on its end. Without it - // the walker found the player at walls and held the same leg into the - // sign 9 times (console B, 2026-11-12, 11.03, Safari Zone West). - bool place_by_sign = true; - // The watch for a warp's fade starts with the hold onto the warp - // (Pokemon::WatchAlong), not when it ends. Without it a fade over - // before the hold ended was missed, and the walk stopped on "no fade in - // and out after walking onto the warp" though it had warped (console B, - // 2026-11-09 01:41, 07.02, the warp to CeruleanCity: the watch started - // about 1.3 s into the hold). - bool watch_fade_along_hold = true; - // A warp's fade is taken as the warp only once the screen after it - // shows the player off the map they held from (warp_left_scene()). - // Without it a black that cleared with the player where they were was - // taken as the warp (console B, 2026-11-10 01:44, 09.01 run 4). - bool confirm_warp_destination = true; - // A warp whose fade was over before the watch for it began is taken by - // the screen after it: another scene than before the hold, held still - // (OverworldWalkSteps::arrived_without_fade()). Without it the walker - // tapped twice into the Department Store lift's back wall and failed - // on "no fade in and out after walking onto the warp" with the player - // inside the lift (console B, 2026-11-12 00:39, 10.01 lift_to_1f): the - // lift room is mostly black, so a watch started after the fade never - // sees black end. - bool scene_confirms_missed_fade = true; - // A turn tap is checked by the facing on screen, and tapped again - // while the player faces another way (OverworldWalkSteps::turn_to()). - // Without it a dropped tap left a one-tile leg turning the player - // only, taken as walked (console B, 2026-11-09, 08.01 run 2). - bool confirm_turn = true; - // The speed the walker goes at: its turn taps - // (OverworldWalkSteps::turns_first()) and its holds' tile time. - MoveSpeed speed = MoveSpeed::WALK; - // An open leg on the Bicycle is counted out a tap at a time, each a - // tile (count_bike_taps()), and one that doesn't move finds the player - // ahead of a block. Without it the leg is one hold, and a start off - // along the leg ends it off with nothing to show it (console B, - // 2026-11-09, 08.03: three runs 3 tiles east after Route 8's legs). - bool count_bike_taps = true; - // How far apart, start to start, the counted taps are - // (MovementMechanics::BIKE_TAP_PERIOD). - Milliseconds bike_tap_period = MovementMechanics::BIKE_TAP_PERIOD; - // After a warp, which takes the player off the Bicycle, the next leg - // where it may be ridden gets on again with SELECT. Without it the - // walker held on-foot legs at the Bicycle's pace. - bool get_back_on_bike = true; - // A dark cave's overworld isn't a battle on its way - // (OverworldWalkSteps::dark_cave_screen()). Without it the check - // before each step watched for a battle on it (console B, 2026-11-09, - // 08.01: "running from a wild Pokemon", then "not a battle"). - bool dark_cave_not_battle = true; - // A stop on an open leg that started in a dark cave may be anywhere on - // the leg (whole_leg()). Without it the stop is placed by the dark - // screen's black, read as the battle at the hold's start: a battle at - // the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 tiles in, - // and the player was found again at a wall 5 tiles off (console B, - // 2026-11-09, 08.01). - bool whole_leg_in_dark = true; - // The end of a trainer's battle the walker fought, as the story's - // battle loop takes it on the screen the sim shows after it: its - // failure, or empty. By default the battle just ends. - std::function trainer_battle_end = [](const OverworldSim&){ - return std::string(); - }; -}; - -// OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the -// overworld only; with `confirm` false, the one tap before it. -void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm = SimWalkerRules{}.confirm_turn); - -// AutoStory's step_once() on `sim`: turns the player if they face another -// way, then one step tap. -void sim_step_once(OverworldSim& sim, Direction direction); - -// The console side of run_route() on an OverworldSim, as -// walk_overworld_route_with_recovery() does it, with the story's -// interrupts: a wild battle (flashes, or seen late) is fought or run from, -// a message is closed and a trainer's battle after it fought. -class OverworldSimWalker{ -public: - // `interrupts`: whose detection delays place a stopped leg, the - // walker's own or a caller's (story_interrupts()). Each set lists a - // wild battle, one seen late and a message for `wild`, and a message - // for `other`, in that order. - OverworldSimWalker( - OverworldSim& sim, SimWalkerRules rules = {}, - const OverworldInterruptSet& interrupts = default_overworld_interrupts() - ); - - // RouteCalls whose `fail` throws OperationFailedException, as the - // console's does. - RouteCalls calls(); - - // run_route() from the sim's facing, planned with `planning`. Returns - // the failure's message, or empty if the route was walked. - std::string run(const std::vector& route, const RoutePlanning& planning); - - const std::vector& log() const{ return m_log; } - -private: - // One of the story's interrupts (story_interrupts()), with the - // walker's detection delay for it. - struct Interrupt{ - std::string name; - SimWatcher watcher; - Milliseconds delay; - bool battle; - }; - StepOutcome walk(const RouteStep& step, std::optional facing); - StepOutcome walk_ridden(const RouteStep& step, std::optional facing); - // count_bike_taps() on the sim. - StepOutcome walk_bike_taps(const RouteStep& step); - BikeTap bike_tap(const RouteStep& step); - // count_bike_taps() on foot (counts_step_taps()). - StepOutcome walk_step_taps(const RouteStep& step); - BikeTap step_tap(const RouteStep& step, int tap); - std::optional late_stop(const RouteStep& step); - // stop_tiles(); without SimWalkerRules::whole_leg_in_dark, the dark - // screen places the stop at the hold's start. - WalkedTiles dark_stop(const RouteStep& step, WalkedTiles timed) const{ - if (m_leg_dark && !m_rules.whole_leg_in_dark){ - return walked_near(step, 0, MovementMechanics::TILE_TIME); - } - return stop_tiles(step, timed, m_leg_dark); - } - std::optional walk_step(const RouteStep& step, std::optional facing); - // start_surf(): turned to the water, A, YES, and the jump onto it. - // Nothing: a Surf is never stopped part-way. - // (PokemonFRLG_OverworldSimField.cpp) - std::optional surf(const RouteStep& step); - bool after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); - bool fade_over_since(Milliseconds from) const; - // after_warp() on a fade seen with no warp: fails, or with - // SimWalkerRules::confirm_warp_destination off, takes it as the warp. - bool black_without_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); - [[noreturn]] void fail_off_route(const RouteStep& step); - std::optional hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts); - size_t clear_late(const std::vector& interrupts, Milliseconds watch, size_t max); - size_t clear_unseen_battle(const RouteStep& step); - bool battle_on_its_way() const; - void clear(const Interrupt& interrupt); - void hold_to_warp(const RouteStep& step); - StepEnd watch_for_trainer(const RouteStep& step, int approach_tiles); - bool moved_past_wall(const RouteStep& step); - void check_overworld(const RouteStep& step); - // After a leg onto a spinner: the slide's time. - void wait_out_slide(const RouteStep& step); - const std::vector& interrupts(const RouteStep& step) const; - std::vector watchers(const std::vector& interrupts) const; - [[noreturn]] void fail(const std::string& message); - - OverworldSim& m_sim; - SimWalkerRules m_rules; - std::vector m_wild; - std::vector m_other; - std::vector m_log; - // When the last WALK leg's first hold started, on the sim's clock, - // and whether its map was dark then. - Milliseconds m_leg_start{0}; - bool m_leg_dark = false; - // Whether the walker takes the player to ride the Bicycle, and the - // speed of the step under way. - bool m_riding = false; - MoveSpeed m_speed = MoveSpeed::WALK; -}; - - -// Register overworld simulation unit tests. -void add_tests_OverworldSim(UnitTestDatabase& database); -// Register the tests of a warp's fade over before the hold onto it ends. -void add_tests_OverworldWarpFade(UnitTestDatabase& database); -// Register the tests of the way a warp leaves the player facing. -void add_tests_OverworldStairs(UnitTestDatabase& database); - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif +/* Overworld Sim + * + * From: https://github.com/PokemonAutomation/ + * + * A whole-tile model of FireRed's overworld, for running the walker + * (run_route(), Pokemon::walk_leg_with()) without a console. The player + * moves a tile per 16 frames while the D-pad is held, by the maps' step + * rules (classify_step()), and also hops ledges the way they face, takes + * warps with a fade, reads signs walked into moving north or south, and is + * seen by trainers along their sight. Wild battles start on the steps a + * test chooses. Each of these shows a screen at a time after the step's + * press, which the walker's watchers see or miss as the console's do. + * + * Every console failure of the walker becomes a test here (red first). + * OverworldSimWalker is the console side of run_route() (RouteCalls) on + * the sim, step for step as walk_overworld_route_with_recovery() does it, + * with the walker's rules as switches, so a test can show a failure with + * the rule that was missing and its absence with the rule. + * + * A step onto a connected map waits a tile first, as the console does + * while the game loads the map. + * + * Not modelled: running, HP and status, and wild battles on the water. + * Surf and Fly are (SimField::SURF, SimField::FLY). Wandering people stand on + * their tile. The Bicycle is: its pace, its taps (each a tile, some + * dropped when they come too fast), SELECT and doors taking the player + * off it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldSim_H +#define PokemonAutomation_PokemonFRLG_OverworldSim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "PokemonFRLG_MovementMechanics.h" +#include "PokemonFRLG_BikeSpinPresses.h" +#include "PokemonFRLG_BikeSpinMechanics.h" +#include "PokemonFRLG_OverworldBikeTaps.h" +#include "PokemonFRLG_OverworldRecovery.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldSimField.h" +#include "PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_OverworldSpin.h" +#include "PokemonFRLG_OverworldSimState.h" +#include "PokemonFRLG_OverworldSimScreens.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Simulates overworld movement, encounters and dialogs. +class OverworldSim{ +public: + OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script = {}); + + const SimState& state() const{ return m_state; } + + // Whether the walker's screen check reads its last step tap as a + // step: one that moved the player from `before`, but for + // SimScript::unseen_step_taps, or a turn tap since `turn_taps_before` + // (SimState::turn_taps) that SimScript::seen_turn_taps names. + bool reads_step_tap_as_step(const MapPosition& before, int turn_taps_before); + + // Holds `direction` for `duration` then lets go for `release`, while + // `watchers` watch until `watch` (at least the hold and release) from + // the start. Returns the first that saw its screen, as run_until(). + std::optional hold( + Direction direction, Milliseconds duration, Milliseconds release, Milliseconds watch, + const std::vector& watchers + ); + + // A press of `direction` for `duration` (at most MovementMechanics:: + // LONGEST_TAP), then `release`, as the console measured it: a player + // facing another way only turns; one facing that way steps once, + // unless the tap starts inside the lockout after the last step tap + // (STEP_TAP_LOCKOUT), which the game ignores, as it does any tap + // inside the lockout after a battle (BATTLE_EXIT_LOCKOUT); holds + // aren't held up by that lockout yet. A tap that starts as + // the last one ends, with no release between, holds it on. A turn may + // be dropped by fault injection (SimScript::dropped_turn_taps). + void tap( + Direction direction, + Milliseconds duration = MovementMechanics::TURN_TAP, + Milliseconds release = MovementMechanics::TURN_SETTLE + ); + + // Watches `watchers` for `duration`, as wait_until(). + std::optional watch(const std::vector& watchers, Milliseconds duration); + + // Runs from or fights the battle on screen, back to the overworld. A + // trainer's battle can't be run from; a battle that isn't there is + // waited out (the story's battle loop gives up after 15 s). + SimBattleEnd handle_battle(SimBattleChoice choice); + + // Closes the message on screen with B. Returns whether a trainer's + // battle follows it. + bool close_message(); + + // A on what the player faces, as `field` says (`floor`: the lift's). + // Returns whether it was there. (PokemonFRLG_OverworldSimField.cpp) + bool use_field(SimField field, size_t floor = 0); + +private: + // A screen that shows at `at`; `unfreeze`: the player can move again. + struct Pending{ + Milliseconds at; + SimScreen screen; + bool unfreeze; + }; + // Where one press of the D-pad takes the player. + struct Step{ + int map = 0; + PlayerState player; + bool warped = false; + // The way the warp left the player facing (arrival_facing()), if + // not the way they moved. + std::optional facing = std::nullopt; + bool ledge = false; + // The step landed on a spinner, which slid the player to `player`. + std::optional spin = {}; + }; + + void advance_to(Milliseconds time); + void show(SimScreen screen, Milliseconds at); + void schedule(Milliseconds at, SimScreen screen, bool unfreeze); + bool sees(SimWatcher watcher, SimScreen screen) const; + std::optional first_seen(SimWatcher watcher, Milliseconds from, Milliseconds to) const; + std::optional watch_until(const std::vector& watchers, Milliseconds from, Milliseconds to); + // A tap, for the next one's lockout and to hold on: when it started + // and ended, the player's facing before it and the steps it took. + struct TapPress{ + Direction direction = Direction::NORTH; + Milliseconds start{0}; + Milliseconds end{0}; + Direction facing_before = Direction::NORTH; + int steps = 0; + }; + void walk_hold(Direction direction, Milliseconds duration, int short_by); + void take_steps(Direction direction, Milliseconds pressed, Milliseconds end, int left); + void step_tap(Direction direction, Milliseconds duration); + void hold_on(Direction direction, Milliseconds end); + void stuck_hold(Direction direction); + void bump(Direction direction, Milliseconds pressed); + std::optional press(Direction direction) const; + std::optional take_warp(int map_index, const TilePos& tile) const; + std::optional cross_edge(Direction direction) const; + // The lift's door to the floor picked, if `map_index` is a lift and + // one was picked. + std::optional lift_warp(int map_index) const; + // A step that landed on a spinner slides on to the slide's end; false + // if the slide never stops. + bool slide_on(Step& step) const; + // The slide's time after `step`, and its facing; 0 for no slide. + Milliseconds after_slide(const Step& step); + // What the maps can't say, from code (add_coded_objects()). + void add_coded_field(); + bool cut_tree(); + bool choose_lift_floor(size_t floor); + bool push_poster_switch(); + bool start_surf(); + bool fly_to_town(size_t town); + // The trees cut come back, as after a warp. + void regrow_cut_trees(); + bool after_step(const Step& step, Milliseconds pressed); + bool wild_battle(Milliseconds pressed); + std::optional next_encounter(); + bool rolls_encounter(int rate); + bool drops_turn_tap(); + bool press_select(); + // Whether the Bicycle tap starting at `start` is dropped, too soon + // after the last one. + bool drops_bike_tap(Milliseconds start); + // How long a tile takes: on the water, on the Bicycle or on foot. + Milliseconds tile_time() const{ + if (m_player.surfing){ + return m_script.timing.surf_tile; + } + return m_state.on_bike ? m_script.timing.bike_tile : m_script.timing.tile; + } + bool trainer_sees(Milliseconds pressed); + void update_view(); + void note(const std::string& line); + void violation(const std::string& line); + const MapData& map() const{ return m_maps[m_map]; } + + std::vector m_maps; + SimScript m_script; + int m_map = 0; + PlayerState m_player; + Milliseconds m_now{0}; + std::vector m_pending; // in time order + // The game has stopped the player: a battle, a message, a warp. + bool m_frozen = false; + // A battle is on screen or about to show. + bool m_battle_pending = false; + // The trainer (an object of the player's map) whose message is up or + // about to show, and whose battle follows it. + std::optional m_trainer_speaking; + // The trainer whose battle is on screen or about to show. + std::optional m_trainer; + // The trees cut since the last warp, and their maps. + std::vector> m_cut_trees; + // The floor picked on the lift's panel, if any. + std::optional m_lift_floor; + int m_grass_steps = 0; + // The game's wild encounter state (SimScript::encounter_rates). + std::mt19937 m_encounter_rng; + int m_steps_since_encounter = 0; + int m_encounter_rate_buff = 0; + // The turn taps so far, for SimScript::dropped_turn_taps. + // Steps onto a warp so far, and the fault on one + // (SimScript::black_without_warp): its black without the warp. + int m_warp_steps = 0; + bool black_without_warp(Milliseconds pressed); + // The last tap, until a hold. + std::optional m_last_tap; + // When the last Bicycle tap started, and how many came too soon. + std::optional m_last_bike_tap; + int m_fast_bike_taps = 0; + // A hold of `direction` for `duration`: counts the leg a tap on the + // Bicycle starts (SimState::bike_legs), and takes the player off the + // Bicycle if SimScript::off_bike_at_legs names it. + void count_bike_leg(Direction direction, Milliseconds duration); + // The way of the last Bicycle tap, unless another press came since. + std::optional m_bike_leg_direction; + // When the last tap that stepped started. + std::optional m_last_step_tap; + // The end of the lockout after the last battle. + Milliseconds m_battle_lockout_end{0}; + Milliseconds m_wild_battle_from{0}; + int m_holds = 0; + SimState m_state; +}; + + +// The walker's rules that console failures added, each on unless a test +// turns it off to show the failure it fixed. +struct SimWalkerRules{ + // Fail before a step unless the overworld is up (START menu left open, + // console B, 2026-11-01, Viridian Forest). + bool check_overworld = true; + // A battle needs an HP box or the battle menu: black below a small room + // isn't one (console B, 2026-11-01, Viridian Forest's north gate). + bool battle_needs_hp_box = true; + // A trainer's battle after their message is fought, not taken for a + // wild one and run from (console B, 2026-11-01, Viridian Forest). + bool fight_trainer_after_message = true; + // How long the walker watches after a leg through grass for a battle + // whose flashes it missed. It watched 500 ms, and walked the next leg + // into the battle (console B, 2026-11-01, Route 1, run 7 and r14). + Milliseconds after_wild_leg_watch = OverworldWalkSteps::AFTER_WILD_LEG_WATCH; + // A leg to a wall held again after an interrupt stops when it is + // interrupted again right away: by a sign it is held into. Without it + // the walker read the sign 6 times (console B, 2026-11-01, r16). + bool stop_if_blocked = true; + // How long a hold's watch goes on past the hold and its release. 0 as + // now; the tile-at-a-time build watched each step for 900 ms, and saw + // the warp's fade on the step onto the forest's north gate as a battle. + Milliseconds watch_past_hold{0}; + // A leg onto a warp whose fade was a wild battle's (its wipe passes for + // the fade) stops before the warp, and the player is found again on it. + // Without it the walker stopped as off the route (console B, + // 2026-11-03, Mt. Moon 1F, row 04.05). + bool find_player_after_warp_battle = true; + // After a leg's watch saw nothing, a battle's text box on screen (its + // HP boxes still to come) is watched on for, and the leg taken as + // stopped part-way. Without it the walker took "south 15 (to wall)" + // as walked and the next leg into the battle (console B, 2026-11-03, + // Mt. Moon B1F, row 04.05). + bool watch_on_for_unseen_battle = true; + // The same after a leg the maps see no wild tiles on (RouteStep::wild), + // which the leg and its watch don't watch for battles: on Mt. Moon + // B2F's tiles closed on one side, which the maps don't mark as wild, a + // battle on "east 7 (to wall)" left black after the leg, the leg was + // taken as walked and the next one held from where the battle was + // (console B, 2026-11-03, row 04.05). + bool watch_on_after_unmarked_leg = true; + // Before a step, a battle on its way (its text box or wipe) is watched + // on for, and the step before it taken as stopped part-way, not the + // step held from where the battle left the player. + bool battle_before_step = true; + // A hold over a step onto a connected map is a tile longer for it + // (RouteStep::connection_steps). Without it the open leg north from + // Cerulean City onto Nugget Bridge ended a tile short (console B, + // 2026-11-03, rows 05.05 and 05.09). + bool hold_over_connections = true; + // An open leg after whose hold a wild battle was seen is placed by the + // battle's first timed screen event (place_late_stop()). Without it the + // player may be anywhere on the leg: on Route 10, "east 11" was found + // again from all 12 of its tiles (console B, 2026-11-09, 07.02 run 2). + bool place_late_battle = true; + // A message after the hold of an open leg that ends below a sign + // (RouteStep::sign_ahead) places the player on its end. Without it + // the walker found the player at walls and held the same leg into the + // sign 9 times (console B, 2026-11-12, 11.03, Safari Zone West). + bool place_by_sign = true; + // The watch for a warp's fade starts with the hold onto the warp + // (Pokemon::WatchAlong), not when it ends. Without it a fade over + // before the hold ended was missed, and the walk stopped on "no fade in + // and out after walking onto the warp" though it had warped (console B, + // 2026-11-09 01:41, 07.02, the warp to CeruleanCity: the watch started + // about 1.3 s into the hold). + bool watch_fade_along_hold = true; + // A warp's fade is taken as the warp only once the screen after it + // shows the player off the map they held from (warp_left_scene()). + // Without it a black that cleared with the player where they were was + // taken as the warp (console B, 2026-11-10 01:44, 09.01 run 4). + bool confirm_warp_destination = true; + // A warp whose fade was over before the watch for it began is taken by + // the screen after it: another scene than before the hold, held still + // (OverworldWalkSteps::arrived_without_fade()). Without it the walker + // tapped twice into the Department Store lift's back wall and failed + // on "no fade in and out after walking onto the warp" with the player + // inside the lift (console B, 2026-11-12 00:39, 10.01 lift_to_1f): the + // lift room is mostly black, so a watch started after the fade never + // sees black end. + bool scene_confirms_missed_fade = true; + // A turn tap is checked by the facing on screen, and tapped again + // while the player faces another way (OverworldWalkSteps::turn_to()). + // Without it a dropped tap left a one-tile leg turning the player + // only, taken as walked (console B, 2026-11-09, 08.01 run 2). + bool confirm_turn = true; + // The speed the walker goes at: its turn taps + // (OverworldWalkSteps::turns_first()) and its holds' tile time. + MoveSpeed speed = MoveSpeed::WALK; + // An open leg on the Bicycle is counted out a tap at a time, each a + // tile (count_bike_taps()), and one that doesn't move finds the player + // ahead of a block. Without it the leg is one hold, and a start off + // along the leg ends it off with nothing to show it (console B, + // 2026-11-09, 08.03: three runs 3 tiles east after Route 8's legs). + bool count_bike_taps = true; + // How far apart, start to start, the counted taps are + // (MovementMechanics::BIKE_TAP_PERIOD). + Milliseconds bike_tap_period = MovementMechanics::BIKE_TAP_PERIOD; + // After a warp, which takes the player off the Bicycle, the next leg + // where it may be ridden gets on again with SELECT. Without it the + // walker held on-foot legs at the Bicycle's pace. + bool get_back_on_bike = true; + // A dark cave's overworld isn't a battle on its way + // (OverworldWalkSteps::dark_cave_screen()). Without it the check + // before each step watched for a battle on it (console B, 2026-11-09, + // 08.01: "running from a wild Pokemon", then "not a battle"). + bool dark_cave_not_battle = true; + // A stop on an open leg that started in a dark cave may be anywhere on + // the leg (whole_leg()). Without it the stop is placed by the dark + // screen's black, read as the battle at the hold's start: a battle at + // the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 tiles in, + // and the player was found again at a wall 5 tiles off (console B, + // 2026-11-09, 08.01). + bool whole_leg_in_dark = true; + // The end of a trainer's battle the walker fought, as the story's + // battle loop takes it on the screen the sim shows after it: its + // failure, or empty. By default the battle just ends. + std::function trainer_battle_end = [](const OverworldSim&){ + return std::string(); + }; +}; + +// OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the +// overworld only; with `confirm` false, the one tap before it. +void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm = SimWalkerRules{}.confirm_turn); + +// AutoStory's step_once() on `sim`: turns the player if they face another +// way, then one step tap. +void sim_step_once(OverworldSim& sim, Direction direction); + +// The console side of run_route() on an OverworldSim, as +// walk_overworld_route_with_recovery() does it, with the story's +// interrupts: a wild battle (flashes, or seen late) is fought or run from, +// a message is closed and a trainer's battle after it fought. +class OverworldSimWalker{ +public: + // `interrupts`: whose detection delays place a stopped leg, the + // walker's own or a caller's (story_interrupts()). Each set lists a + // wild battle, one seen late and a message for `wild`, and a message + // for `other`, in that order. + OverworldSimWalker( + OverworldSim& sim, SimWalkerRules rules = {}, + const OverworldInterruptSet& interrupts = default_overworld_interrupts() + ); + + // RouteCalls whose `fail` throws OperationFailedException, as the + // console's does. + RouteCalls calls(); + + // run_route() from the sim's facing, planned with `planning`. Returns + // the failure's message, or empty if the route was walked. + std::string run(const std::vector& route, const RoutePlanning& planning); + + const std::vector& log() const{ return m_log; } + +private: + // One of the story's interrupts (story_interrupts()), with the + // walker's detection delay for it. + struct Interrupt{ + std::string name; + SimWatcher watcher; + Milliseconds delay; + bool battle; + }; + StepOutcome walk(const RouteStep& step, std::optional facing); + StepOutcome walk_ridden(const RouteStep& step, std::optional facing); + // count_bike_taps() on the sim. + StepOutcome walk_bike_taps(const RouteStep& step); + BikeTap bike_tap(const RouteStep& step); + // count_bike_taps() on foot (counts_step_taps()). + StepOutcome walk_step_taps(const RouteStep& step); + BikeTap step_tap(const RouteStep& step, int tap); + std::optional late_stop(const RouteStep& step); + // stop_tiles(); without SimWalkerRules::whole_leg_in_dark, the dark + // screen places the stop at the hold's start. + WalkedTiles dark_stop(const RouteStep& step, WalkedTiles timed) const{ + if (m_leg_dark && !m_rules.whole_leg_in_dark){ + return walked_near(step, 0, MovementMechanics::TILE_TIME); + } + return stop_tiles(step, timed, m_leg_dark); + } + std::optional walk_step(const RouteStep& step, std::optional facing); + // start_surf(): turned to the water, A, YES, and the jump onto it. + // Nothing: a Surf is never stopped part-way. + // (PokemonFRLG_OverworldSimField.cpp) + std::optional surf(const RouteStep& step); + bool after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); + bool fade_over_since(Milliseconds from) const; + // after_warp() on a fade seen with no warp: fails, or with + // SimWalkerRules::confirm_warp_destination off, takes it as the warp. + bool black_without_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); + [[noreturn]] void fail_off_route(const RouteStep& step); + std::optional hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts); + size_t clear_late(const std::vector& interrupts, Milliseconds watch, size_t max); + size_t clear_unseen_battle(const RouteStep& step); + bool battle_on_its_way() const; + void clear(const Interrupt& interrupt); + void hold_to_warp(const RouteStep& step); + StepEnd watch_for_trainer(const RouteStep& step, int approach_tiles); + bool moved_past_wall(const RouteStep& step); + void check_overworld(const RouteStep& step); + // After a leg onto a spinner: the slide's time. + void wait_out_slide(const RouteStep& step); + const std::vector& interrupts(const RouteStep& step) const; + std::vector watchers(const std::vector& interrupts) const; + [[noreturn]] void fail(const std::string& message); + + OverworldSim& m_sim; + SimWalkerRules m_rules; + std::vector m_wild; + std::vector m_other; + std::vector m_log; + // When the last WALK leg's first hold started, on the sim's clock, + // and whether its map was dark then. + Milliseconds m_leg_start{0}; + bool m_leg_dark = false; + // Whether the walker takes the player to ride the Bicycle, and the + // speed of the step under way. + bool m_riding = false; + MoveSpeed m_speed = MoveSpeed::WALK; +}; + + +// Register overworld simulation unit tests. +void add_tests_OverworldSim(UnitTestDatabase& database); +// Register the tests of a warp's fade over before the hold onto it ends. +void add_tests_OverworldWarpFade(UnitTestDatabase& database); +// Register the tests of the way a warp leaves the player facing. +void add_tests_OverworldStairs(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h index 5c05786a6a..e985f46736 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h @@ -20,7 +20,6 @@ #include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" #include "PokemonFRLG_OverworldRoute.h" #include "PokemonFRLG_OverworldSimScreens.h" -#include "PokemonFRLG_OverworldSimTrainerTurns.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -43,9 +42,6 @@ struct SimScript{ // don't mark as grass: Mt. Moon B2F's tiles closed on one side ('8') // are cave floor too (console B, 2026-11-03). std::set wild_floor_maps; - // Trainers who turn on a timer, by the tile they stand on - // (to_string(MapPosition)); the others see every way they look. - std::map trainer_turns; // Whether the game holds the player up a tile on a step onto a // connected map. It did north onto Nugget Bridge (console B, // 2026-11-03, rows 05.05 and 05.09), not south from Route 6 into diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainerTurns.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainerTurns.h deleted file mode 100644 index 186a4508bd..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainerTurns.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Overworld Sim Trainer Turns - * - * From: https://github.com/PokemonAutomation/ - * - * The sim's trainers who turn on a timer, and the way one faces at a time. - * - */ - -#ifndef PokemonAutomation_PokemonFRLG_OverworldSimTrainerTurns_H -#define PokemonAutomation_PokemonFRLG_OverworldSimTrainerTurns_H - -#include -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Pokemon/Navigation/Pokemon_Grid.h" -#include "PokemonFRLG_OverworldRouteSteps.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -// A trainer who turns on a timer (pokefirered MovementType_FaceDownAndRight -// and its kin): `ways[0]` at first, then after 32, 48, 64 or 80 frames -// (gMovementDelaysShort) one of `ways` at random, from `seed`, and again. -// They turn to the player only when the player runs -// (TryGetTrainerEncounterDirection()), which the sim's player doesn't, and -// see only the way they face. -struct SimTrainerTurns{ - std::vector ways; - uint32_t seed = 0; -}; - -// The way the trainer standing on `home` faces at `when` on the sim's -// clock, if `turns` (by to_string(MapPosition)) has them. -std::optional trainer_turns_facing( - const std::map& turns, const MapPosition& home, Milliseconds when -); - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainers.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainers.cpp deleted file mode 100644 index a28ecbf994..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimTrainers.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* Overworld Sim Trainers - * - * From: https://github.com/PokemonAutomation/ - * - * The sim's trainers: who sees the player, and who turns on a timer. - * - */ - -#include -#include -#include -#include "PokemonFRLG_OverworldObjects.h" -#include "PokemonFRLG_OverworldSim.h" -#include "PokemonFRLG_OverworldSimTrainerTurns.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -std::optional trainer_turns_facing( - const std::map& turns, const MapPosition& home, Milliseconds when -){ - const auto found = turns.find(to_string(home)); - if (found == turns.end() || found->second.ways.empty()){ - return std::nullopt; - } - const SimTrainerTurns& trainer = found->second; - static constexpr int64_t DELAY_FRAMES[] = {32, 48, 64, 80}; - std::mt19937 rng(trainer.seed); - Direction facing = trainer.ways[0]; - // Each turn: the delay, then a frame for the turn itself; 60 frames a - // second. - int64_t frame = 0; - while (true){ - frame += DELAY_FRAMES[rng() & 3] + 1; - if (frame * 1000 / 60 > when.count()){ - return facing; - } - facing = trainer.ways[rng() % trainer.ways.size()]; - } -} - -std::optional trainer_facing(const OverworldSim& sim, const MapPosition& home){ - return trainer_turns_facing(sim.m_script.trainer_turns, home, sim.m_now); -} - -namespace{ - -// The tile next to `player` a trainer standing on `box` walks up to. -TilePos trainer_stop(const Pokemon::TileBox& box, const TilePos& player){ - if (box.x0 <= player.x && player.x <= box.x1){ - return TilePos{player.x, box.y0 > player.y ? player.y + 1 : player.y - 1}; - } - return TilePos{box.x0 > player.x ? player.x + 1 : player.x - 1, player.y}; -} - -} // namespace - -// A trainer on the player's map who sees them now walks up and speaks. -bool OverworldSim::trainer_sees(Milliseconds pressed){ - std::vector& objects = m_maps[m_map].objects; - for (size_t c = 0; c < objects.size(); c++){ - MapObject& trainer = objects[c]; - if (!trainer.trainer){ - continue; - } - // One who turns on a timer sees only the way they face as the step - // ends. - MapObject looking = trainer; - if (const std::optional facing = trainer_turns_facing(m_script.trainer_turns, MapPosition{map().name, {trainer.x, trainer.y}}, pressed + tile_time())){ - looking.trainer->looks = {*facing}; - } - if (!trainer_may_see(map(), looking, m_player.position)){ - continue; - } - const Pokemon::TileBox box = trainer.wander.value_or(Pokemon::TileBox{trainer.x, trainer.y, trainer.x, trainer.y}); - const TilePos stop = trainer_stop(box, m_player.position); - const int approach = std::abs(stop.x - trainer.x) + std::abs(stop.y - trainer.y); - trainer.x = stop.x; - trainer.y = stop.y; - trainer.wander.reset(); - // The player turns to face the trainer. - for (Direction direction : {Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST}){ - m_state.facing = m_player.position.next(direction) == stop ? direction : m_state.facing; - } - m_trainer_speaking = c; - m_frozen = true; - schedule(pressed + m_script.timing.tile * (1 + approach) + m_script.timing.trainer_notice, SimScreen::MESSAGE, false); - note(std::format("{} on {} sees the player, walks up {} tile(s) to {}.", trainer.name, map().name, approach, to_string(stop))); - return true; - } - return false; -} - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp index 390c96315d..407420bac7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp @@ -39,14 +39,10 @@ constexpr int SHEET_FIRST_ROW = 12; constexpr int SPRITE_WIDTH = 16; constexpr int SPRITE_ROWS = 19; -// Where the player's 16x32 frame sits on the GBA's 240x160 screen while -// the camera follows the player (its first drawn row 12 lower). Measured -// on the console. An object a tile away sits a tile (16 pixels) away. -constexpr int FRAME_X = 112; -constexpr int FRAME_Y = 56; -constexpr int TILE_PIXELS = 16; -constexpr int SPRITE_X = FRAME_X; -constexpr int SPRITE_Y = FRAME_Y + SHEET_FIRST_ROW; +// Where the sprite's first drawn row sits on the GBA's 240x160 screen while +// the camera follows the player. Measured on the console. +constexpr int SPRITE_X = 112; +constexpr int SPRITE_Y = 56 + 12; constexpr int GBA_WIDTH = 240; constexpr int GBA_HEIGHT = 160; @@ -60,22 +56,20 @@ ImageRGB32 sheet_frame(const ImageViewRGB32& sheet, int frame){ return sheet.sub_image(frame * SHEET_FRAME_WIDTH, SHEET_FIRST_ROW, SPRITE_WIDTH, SPRITE_ROWS).copy(); } -// How far the screen differs from `sprite`, its first row drawn at GBA -// pixel (`x0`, `y0`). -double difference(const ImageViewRGB32& game, const ImageViewRGB32& sprite, bool mirror, int x0, int y0){ +// How far the screen differs from `sprite`, drawn `dy` GBA pixels lower. +double difference(const ImageViewRGB32& game, const ImageViewRGB32& sprite, bool mirror, int dy){ const double scale_x = (double)game.width() / GBA_WIDTH; const double scale_y = (double)game.height() / GBA_HEIGHT; - const int width = (int)sprite.width(); long total = 0; int pixels = 0; - for (int row = 0; row < (int)sprite.height(); row++){ - for (int col = 0; col < width; col++){ - const Color expected(sprite.pixel(mirror ? width - 1 - col : col, row)); + for (int row = 0; row < SPRITE_ROWS; row++){ + for (int col = 0; col < SPRITE_WIDTH; col++){ + const Color expected(sprite.pixel(mirror ? SPRITE_WIDTH - 1 - col : col, row)); if (expected.alpha() == 0){ continue; } - const size_t x = (size_t)((x0 + col + 0.5) * scale_x); - const size_t y = (size_t)((y0 + row + 0.5) * scale_y); + const size_t x = (size_t)((SPRITE_X + col + 0.5) * scale_x); + const size_t y = (size_t)((SPRITE_Y + dy + row + 0.5) * scale_y); if (x >= game.width() || y >= game.height()){ return std::numeric_limits::max(); } @@ -135,12 +129,6 @@ std::optional read_player_facing(const ImageViewRGB32& screen){ } std::optional match_player_facing(const ImageViewRGB32& game, const PlayerSprites& sprites){ - return match_facing_at(game, sprites, SHEET_FIRST_ROW, 0, 0); -} - -std::optional match_facing_at(const ImageViewRGB32& game, const PlayerSprites& sprites, int first_row, int dx_tiles, int dy_tiles){ - const int x0 = FRAME_X + TILE_PIXELS * dx_tiles; - const int y0 = FRAME_Y + TILE_PIXELS * dy_tiles + first_row; struct Candidate{ Direction direction; const ImageViewRGB32& sprite; @@ -160,7 +148,7 @@ std::optional match_facing_at(const ImageViewRGB32& game, const Playe // A pixel either way, for a box that is slightly off. double score = std::numeric_limits::max(); for (int dy = -1; dy <= 1; dy++){ - score = std::min(score, difference(game, candidate.sprite, candidate.mirror, x0, y0 + dy)); + score = std::min(score, difference(game, candidate.sprite, candidate.mirror, dy)); } if (score < best){ second = best; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h index bc1043da5d..4ad7021011 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h @@ -34,9 +34,8 @@ enum class PlayerGender{ GIRL, }; -// The standing player's frames (or another person's, match_facing_at()), -// as the game draws them, with transparent pixels at alpha 0. Facing east -// is facing west mirrored. +// The standing player's frames, as the game draws them, with transparent +// pixels at alpha 0. Facing east is facing west mirrored. struct PlayerSprites{ ImageRGB32 south; ImageRGB32 north; @@ -59,12 +58,6 @@ std::optional read_player_facing(const ImageViewRGB32& screen); std::optional match_player_facing(const ImageViewRGB32& game, const PlayerSprites& sprites); -// The way a standing person faces whose `sprites` are drawn from row -// `first_row` of their 16x32 frames, `dx_tiles` east and `dy_tiles` south -// of the player, on `game` (as match_player_facing(), which is this at the -// player's own tile). Nothing if no frame matches clearly. -std::optional match_facing_at(const ImageViewRGB32& game, const PlayerSprites& sprites, int first_row, int dx_tiles, int dy_tiles); - // Registers player facing reader unit tests. void add_tests_PlayerFacingReader(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.cpp deleted file mode 100644 index 646d593e64..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* Trainer Facing Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/TestRunners/UnitTest.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" -#include "PokemonFRLG_TrainerFacingReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - -namespace{ - -// rocker.png's standing frames 0 (south), 1 (north) and 2 (west), rows 11 -// to 30 of each 16x32 frame (the rest is empty), as palette indices; 0 is -// transparent. -constexpr int ROCKER_FIRST_ROW = 11; -constexpr int ROCKER_ROWS = 20; -constexpr int SPRITE_WIDTH = 16; -const char* const ROCKER_SOUTH[ROCKER_ROWS] = { - "0000007777000000", - "0000776666770000", - "0007665555667000", - "0007655665567000", - "0076656556566700", - "0076775555776700", - "0f272167761272f0", - "0f272111111272f0", - "00f32f1111f23f00", - "000f22422422f000", - "000f32222223f000", - "0042f433334f2400", - "04222dffffd22240", - "0422dc6cc6cd2240", - "0433dcc55ccd3340", - "00ddfcbbbbcfdd00", - "000d7ffeeff7d000", - "000fd77dd77df000", - "000f66f00f66f000", - "0000ff0000ff0000", -}; -const char* const ROCKER_NORTH[ROCKER_ROWS] = { - "0000007777000000", - "0000776556770000", - "0007655555567000", - "0007655555567000", - "0076655555566700", - "0076665555666700", - "0f276666666672f0", - "0f276666666672f0", - "00f7766666677f00", - "000f77777777f000", - "000f77777777f000", - "0042fd7777df2400", - "04223dffffd32240", - "0422dccccccd2240", - "043fdcbbbbcdf340", - "00ddffbbbbffdd00", - "000d7ffffff7d000", - "000fd77dd77df000", - "000f66f00f66f000", - "0000ff0000ff0000", -}; -const char* const ROCKER_WEST[ROCKER_ROWS] = { - "0000007777000000", - "0000775555770000", - "0007555555567000", - "0776555555557000", - "0755655555666700", - "0075566666666700", - "00f7711766667f00", - "00f1111277777f00", - "004111f27237f000", - "004224227237f000", - "00042222337f0000", - "0000433334f00000", - "0000df744bd00000", - "000075411dbd0000", - "0000db411dbd0000", - "0000df433dfd0000", - "0000d7f44fd00000", - "00000d7777d00000", - "00000d667d000000", - "000000fff0000000", -}; - -// graphics/object_events/palettes/npc_blue.pal. -constexpr uint32_t NPC_BLUE[16] = { - 0xff73c5a4, 0xffffd5b4, 0xfff6bd94, 0xffde9473, 0xff7b4141, 0xffffde4a, 0xffd5ac20, 0xff836200, - 0xffa48bee, 0xff6a52bd, 0xff413962, 0xffee7341, 0xffac4139, 0xff4a3131, 0xffffffff, 0xff000000, -}; - -ImageRGB32 frame_of(const char* const rows[ROCKER_ROWS]){ - ImageRGB32 frame(SPRITE_WIDTH, ROCKER_ROWS); - for (int row = 0; row < ROCKER_ROWS; row++){ - for (int col = 0; col < SPRITE_WIDTH; col++){ - const char digit = rows[row][col]; - const int index = digit <= '9' ? digit - '0' : digit - 'a' + 10; - frame.pixel(col, row) = index == 0 ? 0x00000000 : NPC_BLUE[index]; - } - } - return frame; -} - -} // namespace - - -const PlayerSprites* trainer_sprites(std::string_view sprite){ - static const PlayerSprites ROCKER{frame_of(ROCKER_SOUTH), frame_of(ROCKER_NORTH), frame_of(ROCKER_WEST)}; - return sprite == "rocker" ? &ROCKER : nullptr; -} - -std::optional read_trainer_facing( - const ImageViewRGB32& screen, const PlayerSprites& sprites, int dx_tiles, int dy_tiles -){ - const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); - return match_facing_at(game, sprites, ROCKER_FIRST_ROW, dx_tiles, dy_tiles); -} - - -namespace{ - -constexpr int GBA_WIDTH = 240; -constexpr int GBA_HEIGHT = 160; -constexpr int SCALE = 4; -// Kayden from the tile the pass waits on: two west, one north. -constexpr int KAYDEN_DX = -2; -constexpr int KAYDEN_DY = -1; - -// A GBA screen at SCALE times its size, the gym's floor grey, with -// `sprite` (mirrored if `mirror`) drawn `dx`, `dy` tiles from the -// player's frame (112, 56), and the player's spot left empty. -ImageRGB32 synthetic_game(const ImageViewRGB32* sprite, bool mirror, int dx, int dy){ - ImageRGB32 game(SCALE * GBA_WIDTH, SCALE * GBA_HEIGHT); - game.fill(0xff9c9c94); - const int x0 = 112 + 16 * dx; - const int y0 = 56 + 16 * dy + ROCKER_FIRST_ROW; - for (int row = 0; sprite != nullptr && row < ROCKER_ROWS; row++){ - for (int col = 0; col < SPRITE_WIDTH; col++){ - const uint32_t pixel = sprite->pixel(mirror ? SPRITE_WIDTH - 1 - col : col, row); - if (Color(pixel).alpha() == 0){ - continue; - } - for (int y = 0; y < SCALE; y++){ - for (int x = 0; x < SCALE; x++){ - game.pixel(SCALE * (x0 + col) + x, SCALE * (y0 + row) + y) = pixel; - } - } - } - } - return game; -} - -std::string facing_text(const std::optional& facing){ - return facing ? std::string(direction_name(*facing)) : std::string("nothing"); -} - -// Kayden's frames drawn where he stands from the pass's tile read as the -// way they face; nothing there, or Kayden a tile off, reads as nothing. -class Test_TrainerFacingSynthetic : public UnitTest{ -public: - Test_TrainerFacingSynthetic() - : UnitTest("PokemonFRLG::TrainerFacingReader - rocker frames on a synthetic gym floor") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const PlayerSprites& rocker = *trainer_sprites("rocker"); - struct Case{ - const ImageViewRGB32* sprite; - bool mirror; - int dx; - std::optional expected; - }; - const Case cases[] = { - {&rocker.south, false, KAYDEN_DX, Direction::SOUTH}, - {&rocker.north, false, KAYDEN_DX, Direction::NORTH}, - {&rocker.west, false, KAYDEN_DX, Direction::WEST}, - {&rocker.west, true, KAYDEN_DX, Direction::EAST}, - {nullptr, false, KAYDEN_DX, std::nullopt}, - {&rocker.south, false, KAYDEN_DX + 1, std::nullopt}, - }; - for (const Case& test : cases){ - const ImageRGB32 game = synthetic_game(test.sprite, test.mirror, test.dx, KAYDEN_DY); - const std::optional facing = match_facing_at(game, rocker, ROCKER_FIRST_ROW, KAYDEN_DX, KAYDEN_DY); - if (facing != test.expected){ - return std::format("Read {} instead of {}.", facing_text(facing), facing_text(test.expected)); - } - } - return trainer_sprites("hiker") == nullptr ? UnitTestResult(true) : UnitTestResult("A hiker's frames that aren't there."); - } -}; - -} // namespace - -void add_tests_TrainerFacingReader(UnitTestDatabase& database){ - database.add(); -} - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h deleted file mode 100644 index fe0f3b1a8d..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h +++ /dev/null @@ -1,49 +0,0 @@ -/* Trainer Facing Reader - * - * From: https://github.com/PokemonAutomation/ - * - * Which way a trainer standing near the player faces, read from the - * overworld with match_facing_at() against their standing frames. The - * frames are pret/pokefirered's: a rocker (OBJ_EVENT_GFX_ROCKER, Juggler - * Kayden in Fuchsia Gym) from graphics/object_events/pics/people/rocker.png - * in the colours the game gives it, graphics/object_events/palettes/ - * npc_blue.pal (gObjectEventGraphicsInfo_Rocker: OBJ_EVENT_PAL_TAG_NPC_BLUE). - * They are kept here, not in Resources, until a Packages change carries - * the sheet. - * - */ - -#ifndef PokemonAutomation_PokemonFRLG_TrainerFacingReader_H -#define PokemonAutomation_PokemonFRLG_TrainerFacingReader_H - -#include -#include -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "PokemonFRLG_PlayerFacingReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -// The standing frames of the trainer sprite `sprite` ("rocker"), or null -// for one this reader hasn't got. -const PlayerSprites* trainer_sprites(std::string_view sprite); - -// The way the trainer drawn with `sprites`, standing `dx_tiles` east and -// `dy_tiles` south of the player, faces on the console's `screen`; nothing -// if no frame matches clearly (another person there, mid-turn, a menu). -std::optional read_trainer_facing( - const ImageViewRGB32& screen, const PlayerSprites& sprites, int dx_tiles, int dy_tiles -); - -// Registers the trainer facing reader's tests. -void add_tests_TrainerFacingReader(UnitTestDatabase& database); - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 0d606cff86..80ba736ea8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -44,7 +44,6 @@ #include "Overworld/PokemonFRLG_OverworldSim.h" #include "Overworld/PokemonFRLG_OverworldWalk.h" #include "Overworld/PokemonFRLG_PlayerFacingReader.h" -#include "Overworld/PokemonFRLG_TrainerFacingReader.h" #include "Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h" #include "PokemonFRLG_Navigation.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h" @@ -335,12 +334,6 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& database){ add_tests_AutoStoryFuchsiaGym(database); } -// Which way the player, and a trainer near them, faces on the overworld. -static void add_tests_FacingReaders(UnitTestDatabase& database){ - add_tests_PlayerFacingReader(database); - add_tests_TrainerFacingReader(database); -} - void add_tests(UnitTestDatabase& database){ add_tests_AdvanceWhiteDialogDetector(database); add_tests_AdvanceBattleDialogDetector(database); @@ -376,7 +369,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_OverworldReanchor(database); add_tests_OverworldRecovery(database); add_tests_OverworldSim(database); - add_tests_FacingReaders(database); + add_tests_PlayerFacingReader(database); add_tests_AutoStory(database); add_tests_AutoStoryJson(database); add_tests_AutoStorySimulation(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 6d4a109468..9345eb5aac 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -31,7 +31,6 @@ #include "PokemonFRLG_AutoStorySlopeRun.h" #include "PokemonFRLG_AutoStorySummary.h" #include "PokemonFRLG_AutoStoryTable.h" -#include "PokemonFRLG_AutoStoryTrainerPass.h" #include "PokemonFRLG_AutoStoryTeachScreens.h" #include "PokemonFRLG_AutoStoryTrashCans.h" #include "PokemonFRLG_AutoStoryViridianMart.h" @@ -214,8 +213,6 @@ Outcome take_warp_step(StoryEnv& env, const RunState& state, const RouteStep& wa return Pokemon::outcome_ok(); } -Outcome battle(StoryEnv& env, const StoryStep& step); - Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ const Direction direction = arg(step, "direction"); int tiles_stepped = 1; @@ -226,10 +223,6 @@ Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ } env.console.log(std::format("Story: {}: a trainer saw the player after {} tile(s).", step.name, *stepped)); tiles_stepped = *stepped; - }else if (step.action == TRAINER_PASS_VARIANT){ - return pass_trainer(env, state, step, [&env](const StoryStep& fight){ - return battle(env, fight); - }); }else if (step.action == TRAINER_WAIT_VARIANT){ if (!step_into_line(env.console, env.context, direction, facing_of(state.pose), 1, TRAINER_WAIT_WATCH)){ return Pokemon::outcome_failed("no_trainer", std::format("{} s on the tile {}", TRAINER_WAIT_WATCH.count() / 1000, direction_name(direction))); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp index e707d93cbb..c032768c81 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp @@ -11,7 +11,6 @@ */ #include -#include #include #include #include @@ -85,16 +84,14 @@ const StoryCheckpoint& checkpoint(std::string_view id){ // across sims: the trainers fought. struct GymWalk{ StoryPose at; - SimScript script; std::optional sim; std::vector fought; // Koga is beaten: so is every trainer of the gym // (FuchsiaCity_Gym_EventScript_DefeatedKoga, set_gym_trainers 5). bool gym_beaten = false; - GymWalk(StoryPose start, SimScript sim_script) + explicit GymWalk(StoryPose start) : at(std::move(start)) - , script(std::move(sim_script)) { place(); } @@ -113,7 +110,7 @@ struct GymWalk{ object.trainer.reset(); } } - sim.emplace(std::move(maps), MapPosition{at.map, at.tile}, *at.facing, script); + sim.emplace(std::move(maps), MapPosition{at.map, at.tile}, *at.facing); } std::vector all_fought() const{ std::vector all = fought; @@ -152,33 +149,14 @@ std::string row_on_sim(std::string_view id, GymWalk& walk){ return ""; } -// Juggler Kayden (12, 16) turns south or east on a timer -// (MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT), from `seed`; or, for the fallback, -// never turns from east. -SimScript kayden_turns(uint32_t seed, bool only_east){ - SimScript script; - std::vector ways{Direction::SOUTH, Direction::EAST}; - if (only_east){ - ways = {Direction::EAST}; - } - script.trainer_turns[to_string(MapPosition{GYM, {12, 16}})] = SimTrainerTurns{.ways = ways, .seed = seed}; - return script; -} - -// The gym's trainers by sprite: Kayden and Kirk are both rockers, Edgar -// a man. -const std::vector KIRK_AND_EDGAR{"rocker", "man"}; -const std::vector KAYDEN_KIRK_AND_EDGAR{"rocker", "rocker", "man"}; - -// 12.01 from the nurse with `script`: the gym, past Kayden's east line -// (13..14, 16) on his turn south, Kirk fought from (14, 11), round the top -// edge to west of Koga, where 12.02 starts, fighting `expected`; then +// 12.01 from the nurse: the gym, Kayden fought from (14, 16) and Kirk from +// (14, 11), round the top edge to west of Koga, where 12.02 starts; then // 12.02 from there to the Warden and the nurse, meeting no one else. The -// sim's other lookers see every way at once, so Edgar, whose lines the -// legs to the walls cross, always stops the walk there: the worst case, -// which the console meets only when he looks that way. -UnitTestResult test_gym_rows(const SimScript& script, const std::vector& expected){ - GymWalk walk(*story_pose(Pokemon::pose_of(*checkpoint("12.01").start)), script); +// sim's lookers see every way at once, so Edgar, whose lines the legs to +// the walls cross, always stops the walk there: the worst case, which +// the console meets only when he looks that way. +UnitTestResult test_gym_rows(){ + GymWalk walk(*story_pose(Pokemon::pose_of(*checkpoint("12.01").start))); if (const std::string failure = row_on_sim("12.01", walk); !failure.empty()){ return failure; } @@ -186,8 +164,8 @@ UnitTestResult test_gym_rows(const SimScript& script, const std::vectorstate().position == west_of_koga) || walk.sim->state().facing != Direction::EAST){ return std::format("12.01: ended on {}, not west of Koga {} facing east.", to_string(walk.sim->state().position), to_string(west_of_koga)); } - if (walk.all_fought() != expected){ - return std::format("12.01: fought {} trainers, expected {}.", walk.all_fought().size(), expected.size()); + if (walk.all_fought() != std::vector{"rocker", "rocker", "man"}){ + return std::format("12.01: fought {} trainers, not Kayden, Kirk and Edgar.", walk.all_fought().size()); } const StoryPose next = *story_pose(Pokemon::pose_of(*checkpoint("12.02").start)); if (next.map != GYM || !(next.tile == west_of_koga.point)){ @@ -196,7 +174,7 @@ UnitTestResult test_gym_rows(const SimScript& script, const std::vector(step.args, "direction"); const MapData* map = map_named(at->map); - if (step.action == TRAINER_PASS_VARIANT){ - TilePos onto = at->tile; - for (int64_t c = 0; c < Pokemon::story_arg(step.args, "tiles"); c++){ - onto = onto.next(direction); - } - return Pokemon::outcome_ok(to_pose(StoryPose{at->map, onto, direction})); - } if (step.action != TRAINER_LINE_VARIANT || map == nullptr){ return Pokemon::outcome_ok(to_pose(StoryPose{at->map, at->tile.next(direction), direction})); } @@ -476,50 +468,6 @@ void sim_wait_out_battle_exit(OverworldSim& sim){ } // namespace -namespace{ - -// pass_trainer() on the sim, with the trainer's facing read from the sim: -// wait_for_turn_away(), the crossing, and the trainer's battle if they -// see the player. -std::string sim_pass_trainer(OverworldSim& sim, StoryPose& at, const StoryStep& step){ - const Direction direction = Pokemon::story_arg(step.args, "direction"); - const int tiles = (int)Pokemon::story_arg(step.args, "tiles"); - const Direction away = Pokemon::story_arg(step.args, "away"); - const MapPosition trainer{at.map, { - at.tile.x + (int)Pokemon::story_arg(step.args, "trainer_dx"), - at.tile.y + (int)Pokemon::story_arg(step.args, "trainer_dy"), - }}; - wait_for_turn_away( - (int)(TRAINER_PASS_WATCH / TRAINER_PASS_POLL), away, - [&]{ return trainer_facing(sim, trainer); }, - [&]{ sim.watch({}, TRAINER_PASS_POLL); } - ); - for (int c = 1; c < tiles; c++){ - sim_step_once(sim, direction); - } - sim_step_once(sim, direction); - if (sim.watch({SimWatcher::MESSAGE}, TRAINER_LINE_WATCH)){ - if (!sim.close_message() || sim.handle_battle(SimBattleChoice::FIGHT) != SimBattleEnd::ENDED){ - return "no battle after the trainer's message."; - } - if (const std::string failure = battle_end_on_sim(sim); !failure.empty()){ - return failure; - } - sim_wait_out_battle_exit(sim); - for (int c = 1; c < tiles; c++){ - sim_step_once(sim, direction); - } - } - TilePos onto = at.tile; - for (int c = 0; c < tiles; c++){ - onto = onto.next(direction); - } - at = StoryPose{at.map, onto, direction}; - return sim.state().position == MapPosition{at.map, at.tile} ? "" : "expected to end on " + to_string(MapPosition{at.map, at.tile}) + "."; -} - -} // namespace - // A ROUTE or LEGS by the sim's walker, fighting a trainer who sees the // player on the way. std::string OverworldStepSim::walk(const StoryStep& step){ @@ -556,9 +504,6 @@ std::string OverworldStepSim::step_ahead(const StoryStep& step){ return step_onto_warp(*warp); } } - if (step.action == TRAINER_PASS_VARIANT){ - return sim_pass_trainer(m_sim, m_at, step); - } const auto tap = [this, direction]{ sim_step_once(m_sim, direction); }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index 29ffa82fd9..9402a4f78c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -21,7 +21,6 @@ #include "PokemonFRLG_AutoStorySlopeRun.h" #include "PokemonFRLG_AutoStoryTeach.h" #include "PokemonFRLG_AutoStoryStepTable.h" -#include "PokemonFRLG_AutoStoryTrainerPass.h" #include "PokemonFRLG_AutoStoryTrashCans.h" namespace PokemonAutomation{ @@ -61,7 +60,6 @@ const std::vector& story_action_rows(){ {StoryStepKind::ROUTE, "", StoryActionId::ROUTE}, {StoryStepKind::LEGS, "", StoryActionId::LEGS}, {StoryStepKind::STEP, "", StoryActionId::STEP}, - {StoryStepKind::STEP, TRAINER_PASS_VARIANT, StoryActionId::STEP}, {StoryStepKind::TALK, "", StoryActionId::TALK}, {StoryStepKind::ANSWER, "", StoryActionId::ANSWER}, {StoryStepKind::MASH, "", StoryActionId::MASH}, @@ -174,18 +172,6 @@ std::vector movement_variant_specs(std::span -#include -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_TrainerFacingReader.h" -#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" -#include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "PokemonFRLG_AutoStoryPoses.h" -#include "PokemonFRLG_AutoStoryTrainerLine.h" -#include "PokemonFRLG_AutoStoryTrainerPass.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - -using Pokemon::Direction; -using Pokemon::Outcome; - - -bool wait_for_turn_away( - int polls, Direction away, - const std::function()>& read, const std::function& wait -){ - bool other_way = false; - for (int poll = 0; poll < polls; poll++){ - if (poll > 0){ - wait(); - } - const std::optional facing = read(); - if (facing && *facing == away && other_way){ - return true; - } - other_way = other_way || (facing && *facing != away); - } - return false; -} - -namespace{ - -template -const Type& arg(const StoryStep& step, std::string_view key){ - return Pokemon::story_arg(step.args, key); -} - -// The battle of a TRAINER_PASS_VARIANT step's trainer, as a BATTLE step. -StoryStep pass_fallback_battle(const StoryStep& step){ - StoryStep fight; - fight.kind = StoryStepKind::BATTLE; - fight.name = std::format("{} (fallback battle)", step.name); - fight.args = { - {"trainer", arg(step, "trainer")}, - {"foes", arg>(step, "foes")}, - {"use_items", std::vector()}, - {"may_lose", false}, - {"run", false}, - }; - return fight; -} - -// Waits for the trainer's turn away (wait_for_turn_away()), reading their -// facing on screen, if the reader has the step's "sprite"; else, or with -// no turn seen in TRAINER_PASS_WATCH, logs that the crossing is blind. -void wait_for_trainer(StoryEnv& env, const StoryStep& step){ - const PlayerSprites* sprites = trainer_sprites(arg(step, "sprite")); - if (sprites == nullptr){ - env.console.log(std::format("Story: {}: no frames of the trainer's sprite to read their facing; crossing blind.", step.name), COLOR_ORANGE); - return; - } - const int dx = (int)arg(step, "trainer_dx"); - const int dy = (int)arg(step, "trainer_dy"); - const Direction away = arg(step, "away"); - const bool turned = wait_for_turn_away( - (int)(TRAINER_PASS_WATCH / TRAINER_PASS_POLL), away, - [&]() -> std::optional{ - env.context.wait_for_all_requests(); - const VideoSnapshot screen = env.console.video().snapshot(); - return screen ? read_trainer_facing(screen, *sprites, dx, dy) : std::nullopt; - }, - [&]{ pbf_wait(env.context, TRAINER_PASS_POLL); } - ); - if (turned){ - env.console.log(std::format("Story: {}: the trainer turned {}; crossing.", step.name, direction_name(away))); - }else{ - env.console.log(std::format("Story: {}: no turn {} seen in {} s; crossing blind.", step.name, direction_name(away), TRAINER_PASS_WATCH.count() / 1000), COLOR_ORANGE); - } -} - -// The tiles crossed without a stop on the line, the last step watched for -// the trainer's message. Returns whether the trainer saw the player. -bool cross_line(StoryEnv& env, std::optional facing, Direction direction, int tiles){ - for (int c = 1; c < tiles; c++){ - step_once(env.console, env.context, direction, facing); - facing = direction; - } - return step_into_line(env.console, env.context, direction, facing, 1).has_value(); -} - -} // namespace - -Outcome pass_trainer( - StoryEnv& env, const Pokemon::RunState& state, const StoryStep& step, - const std::function& fight -){ - const Direction direction = arg(step, "direction"); - const int tiles = (int)arg(step, "tiles"); - wait_for_trainer(env, step); - if (cross_line(env, Pokemon::facing_of(state.pose), direction, tiles)){ - // Seen on the line's tile, the crossing's first: the steps after - // it were lost to the trainer's "!". - env.console.log(std::format("Story: {}: the trainer saw the player; fighting them (fallback).", step.name), COLOR_ORANGE); - const Outcome fought = fight(pass_fallback_battle(step)); - if (!fought.succeeded()){ - return fought; - } - for (int c = 1; c < tiles; c++){ - step_once(env.console, env.context, direction, direction); - } - } - const std::vector at = Pokemon::tiles_of(state.pose); - if (at.size() != 1){ - return Pokemon::outcome_ok(); - } - TilePos onto = at[0]; - for (int c = 0; c < tiles; c++){ - onto = onto.next(direction); - } - return Pokemon::outcome_ok(to_pose(StoryPose{state.pose.map, onto, direction})); -} - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h deleted file mode 100644 index 0dfac43064..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerPass.h +++ /dev/null @@ -1,67 +0,0 @@ -/* AutoStory Trainer Pass - * - * From: https://github.com/PokemonAutomation/ - * - * A step across the line of a trainer who turns on a timer, on the turn - * away, as pokeguy passes Juggler Kayden in Fuchsia Gym. - * - */ - -#ifndef PokemonAutomation_PokemonFRLG_AutoStoryTrainerPass_H -#define PokemonAutomation_PokemonFRLG_AutoStoryTrainerPass_H - -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Pokemon/Navigation/Pokemon_Grid.h" -#include "PokemonFRLG_AutoStoryEvents.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -// The variant of a STEP across the line of a trainer who turns on a timer -// (MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT and its kin), as pokeguy passes -// Juggler Kayden in Fuchsia Gym (1:15:14): from outside their sight, the -// trainer (at "trainer_dx", "trainer_dy" tiles from the player, drawn with -// "sprite") is watched, -// up to TRAINER_PASS_WATCH, until they turn "away", and then the player -// steps "tiles" tiles `direction` across the line. They hold a way at least -// 32 frames (pokefirered gMovementDelaysShort), longer than the step onto -// the line takes, so the crossing starts on a turn seen -// (wait_for_turn_away()), not on a facing that has lasted. If they see the -// player anyway (no turn seen in time, or the facing misread), their -// battle ("trainer", "foes") is fought there and the crossing goes on. -inline const std::string TRAINER_PASS_VARIANT = "trainer_pass"; -// The longest wait for the trainer's turn away. -inline constexpr Milliseconds TRAINER_PASS_WATCH(20000); -// How often the trainer's facing is read while waiting. -inline constexpr Milliseconds TRAINER_PASS_POLL(50); - -// Reads `read` (the trainer's facing, or nothing if it can't be read), -// then `wait` and again, at most `polls` times, until it reads `away` -// after reading another way. Returns whether it did. -bool wait_for_turn_away( - int polls, Pokemon::Direction away, - const std::function()>& read, const std::function& wait -); - -// A TRAINER_PASS_VARIANT `step` on the console, from `state`'s pose; -// `fight` fights the trainer's battle (a BATTLE step) if they see the -// player. The line is one tile deep where the crossing meets it, its -// first tile. The trainer's facing is read on screen with the frames of -// the step's "sprite" (read_trainer_facing()); without them the crossing -// is blind, logged. -Pokemon::Outcome pass_trainer( - StoryEnv& env, const Pokemon::RunState& state, const StoryStep& step, - const std::function& fight -); - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index 387e877a6e..3f232448e2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -41,7 +41,6 @@ #include "PokemonFRLG_AutoStoryMoveData.h" #include "PokemonFRLG_AutoStoryStepTable.h" #include "PokemonFRLG_AutoStoryTable.h" -#include "PokemonFRLG_AutoStoryTrainerPass.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -493,18 +492,10 @@ const MapObject* trainer_seeing(const MapData& map, const TilePos& tile, const s // The tile a STEP from `pose` ends on: the next one; for a step into a // trainer's line, the first within TRAINER_LINE_TILES that a trainer // other than the `beaten` sees, where step_until_seen() stops, else the -// last; for a pass across a trainer's line (TRAINER_PASS_VARIANT), its -// last tile. +// last. TilePos step_end(const StoryPose& pose, const StoryStep& step, const std::set& beaten){ const MapData* map = find_map_named(pose.map); const Direction direction = Pokemon::story_arg(step.args, "direction"); - if (step.action == TRAINER_PASS_VARIANT){ - TilePos tile = pose.tile; - for (int64_t c = 0; c < Pokemon::story_arg(step.args, "tiles"); c++){ - tile = tile.next(direction); - } - return tile; - } if (step.action != TRAINER_LINE_VARIANT || map == nullptr){ return pose.tile.next(direction); } @@ -712,9 +703,8 @@ UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::set Date: Thu, 12 Nov 2026 11:05:47 -0800 Subject: [PATCH 08/39] FRLG 12.01: heal to full HP before Koga, Fuchsia Mart buys the shortfall The lead's HP between battles is tracked from the last measured battle HP bar plus the Potions and Super Potions used since. heal_to_full after Kayden's and Kirk's fights uses bag items until no HP is missing; check_full_hp west of Koga fails loudly if HP is missing or unmeasured. 12.01 counts Potions and Super Potions at the start and the Fuchsia Mart buys Super Potions only for what the bag lacks to heal 122 HP. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldMaps.cpp | 2 + .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../AutoStory/PokemonFRLG_AutoStoryBattle.cpp | 32 +-- .../PokemonFRLG_AutoStoryBattleDecisions.cpp | 3 + .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 10 +- .../PokemonFRLG_AutoStoryHealing.cpp | 232 ++++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryHealing.h | 66 +++++ .../PokemonFRLG_AutoStoryHealingSteps.cpp | 100 ++++++++ .../PokemonFRLG_AutoStoryHealingSteps.h | 65 +++++ .../PokemonFRLG_AutoStoryItemsPocket.cpp | 5 + .../AutoStory/PokemonFRLG_AutoStoryMart.cpp | 2 + .../PokemonFRLG_AutoStorySlopeRun.cpp | 5 + .../PokemonFRLG_AutoStoryStepTable.cpp | 6 +- .../AutoStory/PokemonFRLG_AutoStorySupplies.h | 7 + .../AutoStory/StoryData/frlg-12.01.plan.json | 78 +++++- SerialPrograms/cmake/SourceFiles.cmake | 4 + 16 files changed, 600 insertions(+), 19 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp index a08ef364d2..b7839f7106 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp @@ -128,6 +128,8 @@ constexpr std::string_view MAP_NAMES[] = { "Route18", "Route18_EastEntrance_1F", "FuchsiaCity", + // Fuchsia's Mart: Super Potions before Koga's gym (12.01). + "FuchsiaCity_Mart", // The Safari Zone, pokeguy's way through it: its entrance, the // center, east, north and west areas, and the Secret House (HM03). "FuchsiaCity_SafariZone_Entrance", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 80ba736ea8..3b8734d4d9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -53,6 +53,7 @@ #include "Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.h" @@ -332,6 +333,7 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& database){ add_tests_AutoStorySlope(database); add_tests_AutoStorySafari(database); add_tests_AutoStoryFuchsiaGym(database); + add_tests_AutoStoryHealing(database); } void add_tests(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index 01cdc9797a..f069abd40b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -29,6 +29,8 @@ #include "PokemonFRLG_AutoStoryBattleData.h" #include "PokemonFRLG_AutoStoryBattleDecisions.h" #include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryHealing.h" +#include "PokemonFRLG_AutoStoryHealingSteps.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -567,6 +569,7 @@ class BattleLoop{ m_supplies.hurt = status.hp_red || status.hp_yellow; m_supplies.hp_red = status.hp_red; m_supplies.hp_fill = status.hp_fill; + measured_hp(m_supplies, status.hp_fill); } m_supplies.status = status.status; } @@ -895,26 +898,25 @@ std::vector read_items_pocket(ConsoleHandle& console, ProControllerConte return rows; } +bool use_recovery_item( + ConsoleHandle& console, ProControllerContext& context, + const std::string& item, Pokemon::StoryCheckLevel checks, Language language, Supplies& supplies +){ + // The row before the count drops: a counted item with none left takes + // no row. + if (!use_item_on_overworld(console, context, supplies, item, checks, language)){ + return false; + } + took_recovery_item(supplies, item); + return true; +} + void recover_after_battle( ConsoleHandle& console, ProControllerContext& context, Supplies& supplies, Pokemon::StoryCheckLevel checks, Language language ){ for (const std::string& item : recovery_items(supplies)){ - // The row before the count drops: a counted item with none left - // takes no row. - if (!use_item_on_overworld(console, context, supplies, item, checks, language)){ - continue; - } - spend_item(supplies, item); - if (item == "potion"){ - // One Potion (20 HP) takes a starter of these levels from red - // to green; the bar can't be read again on the overworld. - supplies.hurt = false; - supplies.hp_red = false; - supplies.hp_fill = 1.0; - }else{ - supplies.status = StatusCondition::NONE; - } + use_recovery_item(console, context, item, checks, language, supplies); } if (supplies.status != StatusCondition::NONE){ console.log(std::format( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp index 246f7c3d72..6b4fed137b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp @@ -10,6 +10,7 @@ #include #include #include "PokemonFRLG_AutoStoryBattleDecisions.h" +#include "PokemonFRLG_AutoStoryHealing.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -118,6 +119,7 @@ void healed_by_nurse(Supplies& supplies){ supplies.hurt = false; supplies.hp_red = false; supplies.hp_fill = 1.0; + measured_hp(supplies, 1.0); supplies.status = StatusCondition::NONE; restore_pp(supplies.lead); } @@ -185,6 +187,7 @@ TurnAction BattleDecisions::lead_turn(const PartyStatus& status){ m_supplies.hurt = hurt; if (status.hp_seen){ m_supplies.hp_fill = status.hp_fill; + measured_hp(m_supplies, status.hp_fill); } m_supplies.status = status.status; m_psn_reads = status.status == StatusCondition::POISON ? m_psn_reads + 1 : 0; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 9345eb5aac..23c169657f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -25,6 +25,7 @@ #include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryGrind.h" #include "PokemonFRLG_AutoStoryGameArgs.h" +#include "PokemonFRLG_AutoStoryHealingSteps.h" #include "PokemonFRLG_AutoStoryHideout.h" #include "PokemonFRLG_AutoStoryLegs.h" #include "PokemonFRLG_AutoStoryScreenEvents.h" @@ -578,7 +579,11 @@ std::optional run_abilities(StoryEnv& env, RunState& state, const Story } return Pokemon::outcome_unchanged(); } - return run_ability_game_step(env.console.logger(), &env.console, step, abilities); + StoryStep covered = step; + if (const std::optional nothing_to_buy = cover_hp_in_mart(env.console.logger(), env.supplies, covered)){ + return nothing_to_buy; + } + return run_ability_game_step(env.console.logger(), &env.console, covered, abilities); } // CUT_TREE_VARIANT: the tree in the step's direction, cut, and a step @@ -666,6 +671,9 @@ Outcome other_game_step(StoryEnv& env, RunState& state, const StoryStep& step){ if (!done){ done = run_storage_game_step(env.console.logger(), &env.console, step, capture, pc); } + if (!done){ + done = run_healing_step(env, step); + } if (!done){ done = run_abilities(env, state, step); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.cpp new file mode 100644 index 0000000000..cdf2470061 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.cpp @@ -0,0 +1,232 @@ +/* AutoStory Healing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryHealing.h" +#include "PokemonFRLG_AutoStoryItemsPocket.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +namespace{ + +constexpr int POTION_HP = 20; +constexpr int SUPER_POTION_HP = 50; +// The player's HP bar's width in pixels: its fill is read to one. +constexpr int HP_BAR_PIXELS = 48; +// The most items heal_to_full() uses: more than a full bar takes. +constexpr int MAX_HEAL_ITEMS = 12; + +} // namespace + + +int healing_hp(const std::string& item){ + if (item == "potion"){ + return POTION_HP; + } + if (item == "super-potion"){ + return SUPER_POTION_HP; + } + return 0; +} + +void measured_hp(Supplies& supplies, double fill){ + supplies.measured_fill = fill; + supplies.healed_since_measured = 0; +} + +void took_recovery_item(Supplies& supplies, const std::string& item){ + spend_item(supplies, item); + if (const int healed = healing_hp(item); healed > 0){ + // One Potion (20 HP) takes a starter of the early levels from red + // to green; the bar can't be read again on the overworld. The HP + // is counted against the last measured bar (missing_hp()). + supplies.hurt = false; + supplies.hp_red = false; + supplies.hp_fill = 1.0; + supplies.healed_since_measured += healed; + }else{ + supplies.status = StatusCondition::NONE; + } +} + +std::optional missing_hp(const Supplies& supplies, int fallback_max_hp){ + if (!supplies.measured_fill){ + return std::nullopt; + } + const int max_hp = supplies.lead.stats && supplies.lead.stats->hp > 0 ? supplies.lead.stats->hp : fallback_max_hp; + const double fill = *supplies.measured_fill; + const int missing = fill >= 1.0 ? 0 : (int)std::ceil((1.0 - fill) * max_hp + (double)max_hp / HP_BAR_PIXELS); + return missing - supplies.healed_since_measured; +} + +std::optional heal_to_full( + Supplies& supplies, int fallback_max_hp, const std::function& use +){ + for (int c = 0; c < MAX_HEAL_ITEMS; c++){ + const std::optional missing = missing_hp(supplies, fallback_max_hp); + if (!missing || *missing <= 0){ + return missing; + } + std::string item; + if (*missing > POTION_HP && supplies.super_potions > 0){ + item = "super-potion"; + }else if (supplies.potions > 0){ + item = "potion"; + }else if (supplies.super_potions > 0){ + item = "super-potion"; + }else{ + return missing; + } + if (!use(item)){ + break; + } + } + return missing_hp(supplies, fallback_max_hp); +} + +int hp_cover_shortfall(const Supplies& supplies, int cover_hp, const std::string& item){ + const int held = supplies.potions * POTION_HP + supplies.super_potions * SUPER_POTION_HP; + const int each = healing_hp(item); + if (each <= 0 || held >= cover_hp){ + return 0; + } + return (cover_hp - held + each - 1) / each; +} + + +namespace{ + +// Blastoise at Lv39 (pokeguy's lead into Koga), its maximum HP known. +constexpr int LEAD_MAX_HP = 122; + +Supplies bag(int potions, int super_potions){ + Supplies supplies; + supplies.potions = potions; + supplies.super_potions = super_potions; + supplies.pocket = {"potion", "super-potion"}; + return supplies; +} + +// The fake bag use: every item is used, as the console's +// use_recovery_item() takes it into the supplies. +bool use_from_bag(Supplies& supplies, const std::string& item){ + took_recovery_item(supplies, item); + return true; +} + +struct HealingCase{ + std::string name; + std::function body; +}; + +class Test_AutoStoryHealing : public UnitTest{ +public: + explicit Test_AutoStoryHealing(HealingCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStoryHealing - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.body(); + } + +private: + HealingCase m_case; +}; + +// Kayden's Hypno leaves the bar at 3/10: Super Potions and a Potion heal +// it to full (with a bar pixel over), and the check before Koga passes. +UnitTestResult test_hard_hit_healed(){ + Supplies supplies = bag(2, 3); + measured_hp(supplies, 0.30); + const std::optional before = missing_hp(supplies, LEAD_MAX_HP); + if (before != 88){ + return std::format("Missing {} HP at 3/10 of 122, expected 88 (85.4 and a bar pixel).", before.value_or(-1)); + } + const std::optional after = heal_to_full(supplies, LEAD_MAX_HP, [&](const std::string& item){ + return use_from_bag(supplies, item); + }); + if (!after || *after > 0){ + return std::format("Still missing {} HP after healing.", after.value_or(-1)); + } + if (supplies.super_potions != 1 || supplies.potions != 2){ + return std::format("Used {} Super Potions and {} Potions, expected 2 and none.", 3 - supplies.super_potions, 2 - supplies.potions); + } + return true; +} + +// Out of Potions and Super Potions: the HP stays missing, which the check +// before Koga fails on. +UnitTestResult test_out_of_potions(){ + Supplies supplies = bag(1, 0); + measured_hp(supplies, 0.50); + const std::optional after = heal_to_full(supplies, LEAD_MAX_HP, [&](const std::string& item){ + return use_from_bag(supplies, item); + }); + if (!after || *after <= 0){ + return "Healed to full with one Potion from half of 122 HP."; + } + return supplies.potions == 0 ? UnitTestResult(true) : UnitTestResult("The Potion wasn't used."); +} + +// A full bar needs nothing; no measurement since the load is unknown; the +// summary's maximum HP wins over the plan's. +UnitTestResult test_missing_hp_edges(){ + Supplies supplies = bag(0, 0); + if (missing_hp(supplies, LEAD_MAX_HP)){ + return "A bar never measured gave a missing HP."; + } + measured_hp(supplies, 1.0); + if (missing_hp(supplies, LEAD_MAX_HP) != 0){ + return "A full bar misses HP."; + } + measured_hp(supplies, 0.5); + supplies.lead.stats = Stats{.hp = 100}; + if (missing_hp(supplies, LEAD_MAX_HP) != 53){ + return std::format("Half of a 100 HP bar: {} missing, expected 53.", missing_hp(supplies, LEAD_MAX_HP).value_or(-1)); + } + return true; +} + +// The Fuchsia Mart buys Super Potions so the bag covers a full bar. +UnitTestResult test_cover_shortfall(){ + struct Case{ + int potions; + int super_potions; + int expected; + }; + const Case cases[] = { + {0, 0, 3}, + {2, 0, 2}, + {5, 1, 0}, + {0, 3, 0}, + }; + for (const Case& test : cases){ + const int buy = hp_cover_shortfall(bag(test.potions, test.super_potions), LEAD_MAX_HP, "super-potion"); + if (buy != test.expected){ + return std::format("{} Potions, {} Super Potions: buy {}, expected {}.", test.potions, test.super_potions, buy, test.expected); + } + } + return true; +} + +} // namespace + +void add_tests_AutoStoryHealing(UnitTestDatabase& database){ + database.add(HealingCase{"Kayden hits hard: healed to full before Koga", test_hard_hit_healed}); + database.add(HealingCase{"out of Potions: the HP stays missing", test_out_of_potions}); + database.add(HealingCase{"missing HP: unknown, full, the summary's maximum", test_missing_hp_edges}); + database.add(HealingCase{"the Mart buys the shortfall for a full bar", test_cover_shortfall}); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h new file mode 100644 index 0000000000..e516127b4e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h @@ -0,0 +1,66 @@ +/* AutoStory Healing + * + * From: https://github.com/PokemonAutomation/ + * + * The lead's HP between battles, as far as the story can know it: the HP + * bar's share as last measured on a battle screen, the lead's maximum HP, + * and the HP of the items used since. From them, the HP to heal before a + * battle that wants full HP (Koga, 12.02), the items that heal it, and the + * items to buy so the bag covers a worst case. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryHealing_H +#define PokemonAutomation_PokemonFRLG_AutoStoryHealing_H + +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_AutoStorySupplies.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The HP `item` (a bag slug) heals: a Potion 20, a Super Potion 50 +// (pokefirered items.json); 0 for another item. +int healing_hp(const std::string& item); + +// The lead's HP bar showed `fill` (1 after the nurse): the measurement +// missing_hp() counts from, with no item used since. +void measured_hp(Supplies& supplies, double fill); + +// One of `item` was used on the lead: its count spent, and its HP +// (healing_hp()) or, for another item, its cure taken into `supplies`. +void took_recovery_item(Supplies& supplies, const std::string& item); + +// The HP the lead misses: the bar's empty share of its maximum HP (the +// summary's, else `fallback_max_hp`), rounded up by a bar pixel (the bar +// is 48 pixels) unless the bar was full, less the HP healed since. +// Nothing if no bar was measured since the checkpoint loaded. +std::optional missing_hp(const Supplies& supplies, int fallback_max_hp); + +// Uses healing items with `use` (which returns whether the item was used, +// having called took_recovery_item()) until missing_hp() is 0 or less: +// a Super Potion while more than a Potion's HP is missing, else a Potion, +// else a Super Potion. Stops when none is left or one couldn't be used. +// Returns missing_hp() at the end. +std::optional heal_to_full( + Supplies& supplies, int fallback_max_hp, const std::function& use +); + +// How many of `item` to buy so the bag's Potions and Super Potions, with +// them, heal at least `cover_hp`: 0 if they already do. +int hp_cover_shortfall(const Supplies& supplies, int cover_hp, const std::string& item); + +// Registers the healing tests. +void add_tests_AutoStoryHealing(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.cpp new file mode 100644 index 0000000000..00a3f19336 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.cpp @@ -0,0 +1,100 @@ +/* AutoStory Healing Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Color.h" +#include "PokemonFRLG_AutoStoryGameArgs.h" +#include "PokemonFRLG_AutoStoryHealing.h" +#include "PokemonFRLG_AutoStoryHealingSteps.h" +#include "PokemonFRLG_AutoStoryItemsPocket.h" +#include "PokemonFRLG_AutoStoryMartPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::Outcome; +using Pokemon::StoryStep; + +namespace{ + +std::string hp_text(const std::optional& missing){ + return missing ? std::format("{} HP missing", *missing) : std::string("HP unknown (no bar measured since the load)"); +} + +Outcome heal(StoryEnv& env, const StoryStep& step, int max_hp){ + const std::optional before = missing_hp(env.supplies, max_hp); + const std::optional after = heal_to_full(env.supplies, max_hp, [&](const std::string& item){ + return use_recovery_item(env.console, env.context, item, env.checks, env.language, env.supplies); + }); + const bool full = after && *after <= 0; + env.console.log(std::format( + "Story: {}: {} before, {} after; {} Potions, {} Super Potions left.", + step.name, hp_text(before), hp_text(after), env.supplies.potions, env.supplies.super_potions + ), full ? COLOR_BLACK : COLOR_RED); + return Pokemon::outcome_ok(); +} + +Outcome check(StoryEnv& env, const StoryStep& step, int max_hp){ + const std::optional missing = missing_hp(env.supplies, max_hp); + if (!missing){ + return Pokemon::outcome_failed("hp_unknown", step.name); + } + if (*missing > 0){ + return Pokemon::outcome_failed("hp_not_full", std::format("{}: {} HP missing", step.name, *missing)); + } + env.console.log(std::format("Story: {}: the lead's HP is full.", step.name)); + return Pokemon::outcome_ok(); +} + +} // namespace + + +std::vector healing_action_specs(){ + const Pokemon::StoryArgSpec max_hp = required_arg("max_hp", Pokemon::StoryArgType::INTEGER, "the lead's maximum HP when its summary wasn't read"); + return { + {.kind = Pokemon::StoryStepKind::GAME, .name = HEAL_TO_FULL_ACTION, .args = {max_hp}}, + {.kind = Pokemon::StoryStepKind::GAME, .name = CHECK_FULL_HP_ACTION, .args = {max_hp}}, + }; +} + +std::optional run_healing_step(StoryEnv& env, const StoryStep& step){ + if (step.action != HEAL_TO_FULL_ACTION && step.action != CHECK_FULL_HP_ACTION){ + return std::nullopt; + } + const int64_t* max_hp = game_arg(step.args, "max_hp"); + if (max_hp == nullptr){ + return Pokemon::outcome_failed("bad_args", step.action); + } + return step.action == HEAL_TO_FULL_ACTION ? heal(env, step, (int)*max_hp) : check(env, step, (int)*max_hp); +} + +std::optional cover_hp_in_mart(Logger& logger, const Supplies& supplies, StoryStep& step){ + const int64_t* cover = step.action == MART_ACTION ? game_arg(step.args, "cover_hp") : nullptr; + const std::vector* items = game_arg>(step.args, "items"); + if (cover == nullptr || items == nullptr || items->empty()){ + return std::nullopt; + } + std::vector lines = *items; + const int shortfall = hp_cover_shortfall(supplies, (int)*cover, lines[0].item); + logger.log(std::format( + "Story: {}: {} Potions and {} Super Potions against {} HP: {} {} short.", + step.name, supplies.potions, supplies.super_potions, *cover, shortfall, lines[0].item + )); + if (shortfall <= 0){ + return Pokemon::outcome_unchanged(); + } + lines[0].quantity = std::min(lines[0].quantity, (size_t)shortfall); + step.args["items"] = lines; + return std::nullopt; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.h new file mode 100644 index 0000000000..fcf5a52cde --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.h @@ -0,0 +1,65 @@ +/* AutoStory Healing Steps + * + * From: https://github.com/PokemonAutomation/ + * + * The story's steps for full HP into a battle (PokemonFRLG_AutoStoryHealing.h) + * on the console: heal to full with the bag's Potions and Super Potions, + * check the HP is full, and a Mart step's buy cut to what the bag lacks. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryHealingSteps_H +#define PokemonAutomation_PokemonFRLG_AutoStoryHealingSteps_H + +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" +#include "PokemonFRLG_AutoStoryEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The GAME step that heals the lead to full with the bag (heal_to_full()): +// max_hp INTEGER, the lead's maximum HP when the summary wasn't read. HP +// still missing when the bag runs out is logged; the check fails on it. +inline const std::string HEAL_TO_FULL_ACTION = "heal_to_full"; +// The GAME step that fails unless the lead's HP is known full +// (missing_hp() measured and 0 or less): max_hp INTEGER, as above. +inline const std::string CHECK_FULL_HP_ACTION = "check_full_hp"; + +// From the overworld: `item` from the bag on the lead, if one is left: +// its count spent, and its HP (healing_hp()) or its cure taken into +// `supplies`. Returns whether it was used. Defined with the bag's other +// overworld use, in PokemonFRLG_AutoStoryBattle.cpp. +bool use_recovery_item( + ConsoleHandle& console, ProControllerContext& context, + const std::string& item, Pokemon::StoryCheckLevel checks, Language language, Supplies& supplies +); + +// HEAL_TO_FULL_ACTION's and CHECK_FULL_HP_ACTION's specs. +std::vector healing_action_specs(); + +// On the console, a HEAL_TO_FULL_ACTION or CHECK_FULL_HP_ACTION step; +// nothing for another. +std::optional run_healing_step(StoryEnv& env, const Pokemon::StoryStep& step); + +// A MART_ACTION step with "cover_hp": its first line cut to the +// hp_cover_shortfall() of `supplies` (at most the plan's quantity), in +// `step`. Nothing to buy: the step's Outcome, unchanged, logged. Nothing +// for another step, left as it was. +std::optional cover_hp_in_mart(Logger& logger, const Supplies& supplies, Pokemon::StoryStep& step); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.cpp index 21045a47b2..d7b284fe50 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.cpp @@ -19,6 +19,9 @@ static int Supplies::* count_member(const std::string& item){ if (item == "potion"){ return &Supplies::potions; } + if (item == "super-potion"){ + return &Supplies::super_potions; + } if (item == "antidote"){ return &Supplies::antidotes; } @@ -86,6 +89,7 @@ int item_shown_row(const Supplies& supplies, int row){ std::vector set_from_bag(Supplies& supplies, const std::vector& rows){ const Supplies before = supplies; supplies.potions = 0; + supplies.super_potions = 0; supplies.antidotes = 0; supplies.parlyz_heals = 0; supplies.awakenings = 0; @@ -120,6 +124,7 @@ std::vector set_from_loaded_bag(Supplies& supplies, Supplies& saved } std::vector unread = set_from_bag(supplies, rows); saved.potions = supplies.potions; + saved.super_potions = supplies.super_potions; saved.antidotes = supplies.antidotes; saved.parlyz_heals = supplies.parlyz_heals; saved.awakenings = supplies.awakenings; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp index e88eb36921..0e1fddbebf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp @@ -496,6 +496,8 @@ void count_supplies(Supplies& supplies, std::string_view item, size_t quantity){ int Supplies::* count = nullptr; if (item == "potion"){ count = &Supplies::potions; + }else if (item == "super-potion"){ + count = &Supplies::super_potions; }else if (item == "antidote"){ count = &Supplies::antidotes; }else if (item == "parlyz-heal"){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySlopeRun.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySlopeRun.cpp index 00161d8a05..f1d0a6ca98 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySlopeRun.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySlopeRun.cpp @@ -144,6 +144,11 @@ Pokemon::Outcome count_items(SlopeEnv& env, const StoryStep& step){ return Pokemon::unsupported_step(step); } const std::vector rows = read_items_pocket(env.console, env.context, env.language); + // The counts the story keeps (Potions, Super Potions, ...) from the bag + // too: a Mart step's cover_hp buys against them. + if (!rows.empty()){ + set_from_bag(env.supplies, rows); + } for (const std::string& item : *items){ const int count = read_count(rows, item); env.console.log(std::format("Bag: {} x{}.", item, count)); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index 9402a4f78c..fcede59be6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -11,6 +11,7 @@ #include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryGameArgs.h" #include "PokemonFRLG_AutoStoryGrind.h" +#include "PokemonFRLG_AutoStoryHealingSteps.h" #include "PokemonFRLG_AutoStoryHideout.h" #include "PokemonFRLG_AutoStoryItemUse.h" #include "PokemonFRLG_AutoStoryLegs.h" @@ -122,6 +123,7 @@ Pokemon::StoryActionSpec mart_action_spec(){ required_arg("budget", StoryArgType::INTEGER, "the most the step spends"), absent_arg("floor", StoryArgType::INTEGER, "the least money the player has here, when the money box can't be read"), required_arg("items", StoryArgType::ITEMS, "what to buy, in priority order"), + absent_arg("cover_hp", StoryArgType::INTEGER, "buy only the first line's shortfall for the bag's Potions and Super Potions to heal this much HP"), }}; } @@ -220,8 +222,8 @@ std::span story_action_specs(){ }){ specs.push_back(std::move(spec)); } - for (Pokemon::StoryActionSpec spec : field_action_specs()){ - specs.push_back(std::move(spec)); + for (const std::vector& more : {field_action_specs(), healing_action_specs()}){ + specs.insert(specs.end(), more.begin(), more.end()); } return specs; }(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h index 58d122e50f..78e1743350 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h @@ -47,6 +47,7 @@ std::string_view status_name(StatusCondition status); // Potions, Antidotes, then Parlyz Heals; Awakenings from Cerulean's Mart. struct Supplies{ int potions = 0; + int super_potions = 0; int antidotes = 0; int parlyz_heals = 0; int awakenings = 0; @@ -71,6 +72,12 @@ struct Supplies{ // The starter's HP bar's filled share at the last battle screen that // showed it, 1 after the nurse or a Potion on the overworld. double hp_fill = 1.0; + // The bar's filled share as last measured on a battle screen (1 after + // the nurse), unlike hp_fill not raised by a Potion's guess; nothing + // while none was (a checkpoint loaded from a save). And the HP the + // items used on the lead since then heal. + std::optional measured_fill = std::nullopt; + int healed_since_measured = 0; // The starter's moves and their PP, as far as the story knows them: // a new game's Squirtle unless a checkpoint's row says otherwise. PartyMember lead = new_member("squirtle", 5); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json index 7608e24666..635bb8afdb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json @@ -6,6 +6,15 @@ "title": "Fuchsia: heal, HM03 Surf over Water Gun, the gym past Jugglers Kayden and Kirk and round the top edge to west of Koga", "start": {"map": "FuchsiaCity", "tiles": [[25, 32]], "facing": "south"}, "events": [ + { + "id": "count_healing_items", + "kind": "game_action", + "action": "count_items", + "args": { + "items": ["potion", "super-potion"] + }, + "why": "the Items pocket's Potions and Super Potions: the Fuchsia Mart buys only what they lack to heal a full HP bar before Koga" + }, { "id": "face_center_door", "kind": "route", @@ -48,6 +57,45 @@ }, "why": "from the nurse to the Center's wall west (0, 4) and up to the wall (0, 2): legs to walls, so the walk out starts from a known tile even if the Center script left the player a tile off the nurse" }, + { + "id": "fuchsia_mart_wall", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "FuchsiaCity_Mart", "tiles": [[4, 2]], "facing": "north"} + }, + "why": "out of the Center, in at the Mart's door (11, 15) and up column 4 to the wall (4, 1)" + }, + { + "id": "fuchsia_mart_clerk", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "FuchsiaCity_Mart", "tiles": [[4, 3]], "facing": "west"} + }, + "why": "a tile back down, facing the clerk (2, 3) over the counter (3, 3)" + }, + { + "id": "buy_super_potions", + "kind": "game_action", + "action": "mart", + "args": { + "map": "FuchsiaCity_Mart", + "budget": 2100, + "items": [{"item": "super-potion", "quantity": 3}], + "cover_hp": 122 + }, + "why": "Super Potions for what the bag's Potions and Super Potions lack to heal 122 HP, the lead's whole bar at Lv39 (3 with none): Kayden's and Kirk's damage is healed to full before Koga. Skipped when the bag covers it" + }, + { + "id": "out_of_fuchsia_mart", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "FuchsiaCity", "tiles": [[11, 16]], "facing": "south"} + }, + "why": "down to the mat and out of the door (11, 15)" + }, { "id": "gym_east_wall", "kind": "route", @@ -85,6 +133,15 @@ "declared_after": {"map": "FuchsiaCity_Gym", "tiles": [[14, 16]], "facing": "north"}, "why": "Juggler Kayden (TRAINER_JUGGLER_KAYDEN): Hypno Lv38" }, + { + "id": "heal_after_kayden", + "kind": "game_action", + "action": "heal_to_full", + "args": { + "max_hp": 122 + }, + "why": "Super Potions and Potions until the HP Kayden's fight left missing (from the battle's last HP bar) is healed: full HP into Koga" + }, { "id": "east_column_to_kirk", "kind": "legs", @@ -113,6 +170,15 @@ "declared_after": {"map": "FuchsiaCity_Gym", "tiles": [[14, 11]], "facing": "north"}, "why": "Juggler Kirk (TRAINER_JUGGLER_KIRK): Drowzee, Drowzee, Kadabra, Drowzee, all Lv31 (pokeguy: one Surf each, 1:15:14 to 1:16:17)" }, + { + "id": "heal_after_kirk", + "kind": "game_action", + "action": "heal_to_full", + "args": { + "max_hp": 122 + }, + "why": "Super Potions and Potions until the HP Kirk's fight left missing (from the battle's last HP bar) is healed: full HP into Koga" + }, { "id": "east_column_to_wall", "kind": "legs", @@ -148,6 +214,15 @@ "target": {"map": "FuchsiaCity_Gym", "tiles": [[6, 13]], "facing": "east"} }, "why": "turn to Koga (7, 13): pokeguy approaches him from the west (1:16:33)" + }, + { + "id": "check_full_hp", + "kind": "game_action", + "action": "check_full_hp", + "args": { + "max_hp": 122 + }, + "why": "Koga wants full HP (88.0% from full, 70.1% from pokeguy's 34/122): stop here, before 12.02's save, if any HP is missing or no battle measured the bar since the checkpoint loaded" } ] }, @@ -156,7 +231,8 @@ "notes": { "checkpoint": [ "Starts where 11.03's Fly lands, below Fuchsia's Center facing south, and goes in to the nurse (pokeguy bikes straight into the gym from there, 1:14:38; the Center heal is ours).", - "PokeGuy's way (1:14:38 to 1:16:33): into the gym, Surf taught over Water Gun, Juggler Kirk fought (forced), round the top edge, Koga from the west. He fights nobody else; this row also fights Juggler Kayden (Hypno Lv38), whose east line every way north crosses with no wall to end a leg on: the user's call (2026-11-12) is to fight him with the normal battle code rather than wait for him to face away. The battle's own recovery uses a Potion if his fight leaves the HP bar yellow or red.", + "PokeGuy's way (1:14:38 to 1:16:33): into the gym, Surf taught over Water Gun, Juggler Kirk fought (forced), round the top edge, Koga from the west. He fights nobody else; this row also fights Juggler Kayden (Hypno Lv38), whose east line every way north crosses with no wall to end a leg on: the user's call (2026-11-12) is to fight him with the normal battle code rather than wait for him to face away. After each of Kayden's and Kirk's fights, heal_to_full uses Super Potions and Potions until the HP missing from the battle's last HP bar (of 122 at Lv39, or the summary's maximum) is healed; check_full_hp stops the row west of Koga if any is missing.", + "The Fuchsia Mart (not in pokeguy's run: our healing for Kayden) buys Super Potions for what the bag's Potions and Super Potions, counted at the start, lack to heal 122 HP; it is skipped when they cover it.", "The gym (FuchsiaCity_Gym map.json), 15 x 23, no running, its invisible walls in the map: Koga (7, 13) in the middle box, entered only from row 12 on the west. Its trainers and lines: Kayden (12, 16) south and east 4, Shawn (2, 9) west 1, Kirk (11, 11) east 3, Edgar (13, 4) every way 2, Phil (4, 6) every way 2, Nate (2, 16) south 4. Every way north crosses Kirk's line and one of Kayden's and Edgar's; the legs across a looker's line end on walls.", "Ends west of Koga and saves there: his own pre-battle checkpoint (battle-checkpoint-retry), 12.02. Koga is a D7 fight: pokeguy entered at 34/122 HP and the PokemonSimulation benchmark wins 70.1% (64.5%-75.2%, 1700 trials) from that. Entered at full HP and PP it wins 88.0% (82.4%-92.3%, 840 trials; same C2 policy df4fece, seed 4), which holds for this row only if Kayden's damage is healed to full before Koga." ] diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index e343df04ad..5e0830817c 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2083,6 +2083,10 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGameArgs.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrindRun.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrindStep.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp From 137916a2742356a5d00b591acd0fdad830e55ea7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 11:09:33 -0800 Subject: [PATCH 09/39] FRLG 12.01: golden plan lines for the Fuchsia Mart detour Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryPlanGolden12.h | 38 +++++++++++++++++-- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h index 8544908867..171f328f19 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h @@ -21,13 +21,43 @@ namespace PokemonFRLG{ inline constexpr std::string_view FRLG_PLAN_GOLDEN_12[] = { "12.01 face_center_door from FuchsiaCity (25, 32) facing south to FuchsiaCity (25, 32) facing north", "12.01 face north -> FuchsiaCity (25, 32)", - "12.01 gym_east_wall from FuchsiaCity_PokemonCenter_1F (0, 2) facing north to FuchsiaCity_Gym (14, 21) facing north", + "12.01 fuchsia_mart_wall from FuchsiaCity_PokemonCenter_1F (0, 2) facing north to FuchsiaCity_Mart (4, 2) facing north", "12.01 walk south 3 (to wall) -> FuchsiaCity_PokemonCenter_1F (0, 5) [walk only]", "12.01 walk east 7 -> FuchsiaCity_PokemonCenter_1F (7, 5) [walk only]", "12.01 walk south 4 (warp) -> FuchsiaCity (25, 32) [walk only]", - "12.01 walk south 1 -> FuchsiaCity (25, 33)", - "12.01 walk west 16 -> FuchsiaCity (9, 33)", - "12.01 walk north 1 (warp) -> FuchsiaCity_Gym (7, 21)", + "12.01 walk west 14 (to wall) -> FuchsiaCity (11, 32)", + "12.01 walk south 5 (to wall) -> FuchsiaCity (11, 37)", + "12.01 walk west 9 (to wall) -> FuchsiaCity (2, 37)", + "12.01 walk north 14 -> FuchsiaCity (2, 23)", + "12.01 walk east 27 -> FuchsiaCity (29, 23)", + "12.01 walk north 6 (to wall) -> FuchsiaCity (29, 17)", + "12.01 walk east 7 -> FuchsiaCity (36, 17)", + "12.01 walk south 1 (to wall) -> FuchsiaCity (36, 18)", + "12.01 walk east 9 (to wall) -> FuchsiaCity (45, 18)", + "12.01 walk north 6 -> FuchsiaCity (45, 12)", + "12.01 walk west 22 (to wall) -> FuchsiaCity (23, 12)", + "12.01 walk south 4 -> FuchsiaCity (23, 16)", + "12.01 walk west 12 -> FuchsiaCity (11, 16)", + "12.01 walk north 1 (warp) -> FuchsiaCity_Mart (4, 7)", + "12.01 walk north 5 (to wall) -> FuchsiaCity_Mart (4, 2) [walk only]", + "12.01 fuchsia_mart_clerk from FuchsiaCity_Mart (4, 2) facing north to FuchsiaCity_Mart (4, 3) facing west", + "12.01 walk south 1 -> FuchsiaCity_Mart (4, 3) [walk only]", + "12.01 face west -> FuchsiaCity_Mart (4, 3) [walk only]", + "12.01 out_of_fuchsia_mart from FuchsiaCity_Mart (4, 3) facing west to FuchsiaCity (11, 16) facing south", + "12.01 walk south 5 (warp) -> FuchsiaCity (11, 16) [walk only]", + "12.01 gym_east_wall from FuchsiaCity (11, 16) facing south to FuchsiaCity_Gym (14, 21) facing north", + "12.01 walk east 13 (to wall) -> FuchsiaCity (24, 16)", + "12.01 walk north 4 -> FuchsiaCity (24, 12)", + "12.01 walk east 21 (to wall) -> FuchsiaCity (45, 12)", + "12.01 walk south 6 (to wall) -> FuchsiaCity (45, 18)", + "12.01 walk west 13 (to wall) -> FuchsiaCity (32, 18)", + "12.01 walk north 1 -> FuchsiaCity (32, 17)", + "12.01 walk west 5 -> FuchsiaCity (27, 17)", + "12.01 walk south 8 (to wall) -> FuchsiaCity (27, 25)", + "12.01 walk west 25 (to wall) -> FuchsiaCity (2, 25)", + "12.01 walk south 12 (to wall) -> FuchsiaCity (2, 37)", + "12.01 walk east 7 -> FuchsiaCity (9, 37)", + "12.01 walk north 5 (warp) -> FuchsiaCity_Gym (7, 21)", "12.01 walk east 7 (to wall) -> FuchsiaCity_Gym (14, 21) [walk only]", "12.01 face north -> FuchsiaCity_Gym (14, 21) [walk only]", "12.01 west_of_koga from FuchsiaCity_Gym (6, 13) facing south to FuchsiaCity_Gym (6, 13) facing east", From 209a482d3b1d4a732e2628a0f23bc3c3cf99b3a6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 13:41:59 -0800 Subject: [PATCH 10/39] FRLG 12.01: Fuchsia Mart via the east ledge and the Cut tree; nurse heal from Navigation The Mart detour went round the city (about 150 tiles there, 110 back): planned routes never hop a ledge, and the Cut tree (24, 22) is the only gap between row 23 and the Mart's road. Hop the ledge (28, 32) and cut the tree both ways. AutoStory's blind heal_at_center is replaced by upstream's heal_at_pokecenter, which waits for the nurse's dialog and retries. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryActions.cpp | 16 ------ .../AutoStory/PokemonFRLG_AutoStoryActions.h | 2 - .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 7 ++- .../AutoStory/StoryData/frlg-12.01.plan.json | 55 +++++++++++++++++-- 4 files changed, 55 insertions(+), 25 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 850068b884..47a9e786af 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -58,9 +58,6 @@ constexpr Milliseconds INTRO_A_EVERY = 1500ms; constexpr Milliseconds INTRO_QUIET = 3000ms; constexpr Milliseconds INTRO_STUCK = 15000ms; constexpr Milliseconds INTRO_TIMEOUT = 600000ms; -// "Wait about 8 s" after YES at the nurse (console B, 2026-11-01): 1.5 s -// between presses did not heal. -constexpr Milliseconds HEAL_TIME = 8000ms; DpadPosition dpad(Direction direction){ switch (direction){ @@ -880,19 +877,6 @@ void set_options(ConsoleHandle& console, ProControllerContext& context, StartMen mash_until_overworld(console, context, 20000ms); } -void heal_at_center(ConsoleHandle& console, ProControllerContext& context){ - console.log("Healing at the Pokemon Center."); - // The nurse's YES/NO isn't seen by the selection detector (console B, - // 2026-11-01); YES is the default, so A after her lines is YES. - // "Welcome ... We heal your POKEMON ... Shall we heal?" is 3 lines. - press(context, BUTTON_A, 1500ms); - press(context, BUTTON_A, 1500ms); - press(context, BUTTON_A, 2500ms); - press(context, BUTTON_A, 1000ms); - pbf_wait(context, HEAL_TIME); - mash_until_overworld(console, context, 30000ms); -} - // A picture of the Mart screen for the run's record: the list with the // cursor, the quantity, the bag after. static void mart_shot(ConsoleHandle& console, ProControllerContext& context, const std::string& label){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h index 4b813e3f77..79034b19fb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h @@ -52,8 +52,6 @@ std::optional option_right_presses( // presses, fails with a screenshot and leaves the menu open. void set_options(ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language); -// Facing the nurse: A, YES, the heal, and the text to its end. -void heal_at_center(ConsoleHandle& console, ProControllerContext& context); // One line of a Mart's BUY list: the row (from 0) and how many. struct MartOrder{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 23c169657f..0e12a840de 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -19,6 +19,7 @@ #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "PokemonFRLG_AutoStoryAbilities.h" #include "PokemonFRLG_AutoStoryBattleData.h" #include "PokemonFRLG_AutoStoryCapture.h" @@ -302,7 +303,7 @@ Outcome get_ready(StoryEnv& env, RunState& state, const StoryStep& step){ if (!walked.succeeded()){ return walked; } - heal_at_center(env.console, env.context); + heal_at_pokecenter(env.console, env.context); healed_by_nurse(supplies); return walked; } @@ -528,7 +529,7 @@ bool grind_heal_trip(StoryEnv& env, RunState& state, const StoryStep& step, cons if (!walked(env, state, walk)){ return false; } - heal_at_center(env.console, env.context); + heal_at_pokecenter(env.console, env.context); // PP too: a grind's battles spend more than its attacks have. healed_by_nurse(env.supplies); walk.name = step.name + "_back_to_patch"; @@ -755,7 +756,7 @@ ConsoleAction console_action_of(StoryActionId id){ return [](StoryEnv& env, RunState&, const StoryStep& step){ return battle(env, step); }; case StoryActionId::HEAL: return [](StoryEnv& env, RunState&, const StoryStep&){ - heal_at_center(env.console, env.context); + heal_at_pokecenter(env.console, env.context); healed_by_nurse(env.supplies); return Pokemon::outcome_ok(); }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json index 635bb8afdb..a33177bcd2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json @@ -57,6 +57,43 @@ }, "why": "from the nurse to the Center's wall west (0, 4) and up to the wall (0, 2): legs to walls, so the walk out starts from a known tile even if the Center script left the player a tile off the nurse" }, + { + "id": "west_of_east_ledge", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "FuchsiaCity", "tiles": [[27, 32]], "facing": "east"} + }, + "why": "out of the Center and east along row 32 to the ledge column (28, 30..34)" + }, + { + "id": "east_ledge_hop", + "kind": "step", + "args": { + "direction": "east" + }, + "declared_after": {"map": "FuchsiaCity", "tiles": [[29, 32]], "facing": "east"}, + "why": "over the ledge (28, 32): planned routes never hop a ledge, and without it the way north goes round the city's west edge" + }, + { + "id": "below_mart_tree", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "FuchsiaCity", "tiles": [[24, 23]], "facing": "north"} + }, + "why": "up columns 29..30 to row 23 and west to below the Cut tree (24, 22), the one gap between row 23 and the Mart's road" + }, + { + "id": "cut_mart_tree", + "kind": "game_action", + "action": "cut_tree", + "args": { + "direction": "north" + }, + "declared_after": {"map": "FuchsiaCity", "tiles": [[24, 22]], "facing": "north"}, + "why": "the tree (FuchsiaCity map.json object 13, EventScript_CutTree); a step onto its tile. Without it the way to the Mart goes round the city's east side, about 150 tiles" + }, { "id": "fuchsia_mart_wall", "kind": "route", @@ -64,7 +101,7 @@ "args": { "target": {"map": "FuchsiaCity_Mart", "tiles": [[4, 2]], "facing": "north"} }, - "why": "out of the Center, in at the Mart's door (11, 15) and up column 4 to the wall (4, 1)" + "why": "up column 24 to row 17, west to the Mart's door (11, 15) and in, up column 4 to the wall (4, 1)" }, { "id": "fuchsia_mart_clerk", @@ -88,13 +125,23 @@ "why": "Super Potions for what the bag's Potions and Super Potions lack to heal 122 HP, the lead's whole bar at Lv39 (3 with none): Kayden's and Kirk's damage is healed to full before Koga. Skipped when the bag covers it" }, { - "id": "out_of_fuchsia_mart", + "id": "above_mart_tree", "kind": "route", "action": "run", "args": { - "target": {"map": "FuchsiaCity", "tiles": [[11, 16]], "facing": "south"} + "target": {"map": "FuchsiaCity", "tiles": [[24, 21]], "facing": "south"} + }, + "why": "out of the Mart's door (11, 15), east along row 17 and down column 24 to above the Cut tree (24, 22), grown back when the city loaded" + }, + { + "id": "cut_mart_tree_back", + "kind": "game_action", + "action": "cut_tree", + "args": { + "direction": "south" }, - "why": "down to the mat and out of the door (11, 15)" + "declared_after": {"map": "FuchsiaCity", "tiles": [[24, 22]], "facing": "south"}, + "why": "the tree again; a step onto its tile" }, { "id": "gym_east_wall", From 22152361bcd4692a585cc4245df1ac9de193b464 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 13:44:06 -0800 Subject: [PATCH 11/39] FRLG 12.01: golden plan lines and notes for the ledge and Cut tree way Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryPlanGolden12.h | 41 ++++++++----------- .../AutoStory/StoryData/frlg-12.01.plan.json | 4 +- 2 files changed, 18 insertions(+), 27 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h index 171f328f19..31dccb5e45 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden12.h @@ -21,40 +21,31 @@ namespace PokemonFRLG{ inline constexpr std::string_view FRLG_PLAN_GOLDEN_12[] = { "12.01 face_center_door from FuchsiaCity (25, 32) facing south to FuchsiaCity (25, 32) facing north", "12.01 face north -> FuchsiaCity (25, 32)", - "12.01 fuchsia_mart_wall from FuchsiaCity_PokemonCenter_1F (0, 2) facing north to FuchsiaCity_Mart (4, 2) facing north", + "12.01 west_of_east_ledge from FuchsiaCity_PokemonCenter_1F (0, 2) facing north to FuchsiaCity (27, 32) facing east", "12.01 walk south 3 (to wall) -> FuchsiaCity_PokemonCenter_1F (0, 5) [walk only]", "12.01 walk east 7 -> FuchsiaCity_PokemonCenter_1F (7, 5) [walk only]", "12.01 walk south 4 (warp) -> FuchsiaCity (25, 32) [walk only]", - "12.01 walk west 14 (to wall) -> FuchsiaCity (11, 32)", - "12.01 walk south 5 (to wall) -> FuchsiaCity (11, 37)", - "12.01 walk west 9 (to wall) -> FuchsiaCity (2, 37)", - "12.01 walk north 14 -> FuchsiaCity (2, 23)", - "12.01 walk east 27 -> FuchsiaCity (29, 23)", - "12.01 walk north 6 (to wall) -> FuchsiaCity (29, 17)", - "12.01 walk east 7 -> FuchsiaCity (36, 17)", - "12.01 walk south 1 (to wall) -> FuchsiaCity (36, 18)", - "12.01 walk east 9 (to wall) -> FuchsiaCity (45, 18)", - "12.01 walk north 6 -> FuchsiaCity (45, 12)", - "12.01 walk west 22 (to wall) -> FuchsiaCity (23, 12)", - "12.01 walk south 4 -> FuchsiaCity (23, 16)", - "12.01 walk west 12 -> FuchsiaCity (11, 16)", + "12.01 walk east 2 -> FuchsiaCity (27, 32)", + "12.01 below_mart_tree from FuchsiaCity (29, 32) facing east to FuchsiaCity (24, 23) facing north", + "12.01 walk north 9 -> FuchsiaCity (29, 23)", + "12.01 walk west 5 -> FuchsiaCity (24, 23)", + "12.01 face north -> FuchsiaCity (24, 23)", + "12.01 fuchsia_mart_wall from FuchsiaCity (24, 22) facing north to FuchsiaCity_Mart (4, 2) facing north", + "12.01 walk north 6 -> FuchsiaCity (24, 16)", + "12.01 walk west 13 -> FuchsiaCity (11, 16)", "12.01 walk north 1 (warp) -> FuchsiaCity_Mart (4, 7)", "12.01 walk north 5 (to wall) -> FuchsiaCity_Mart (4, 2) [walk only]", "12.01 fuchsia_mart_clerk from FuchsiaCity_Mart (4, 2) facing north to FuchsiaCity_Mart (4, 3) facing west", "12.01 walk south 1 -> FuchsiaCity_Mart (4, 3) [walk only]", "12.01 face west -> FuchsiaCity_Mart (4, 3) [walk only]", - "12.01 out_of_fuchsia_mart from FuchsiaCity_Mart (4, 3) facing west to FuchsiaCity (11, 16) facing south", + "12.01 above_mart_tree from FuchsiaCity_Mart (4, 3) facing west to FuchsiaCity (24, 21) facing south", "12.01 walk south 5 (warp) -> FuchsiaCity (11, 16) [walk only]", - "12.01 gym_east_wall from FuchsiaCity (11, 16) facing south to FuchsiaCity_Gym (14, 21) facing north", - "12.01 walk east 13 (to wall) -> FuchsiaCity (24, 16)", - "12.01 walk north 4 -> FuchsiaCity (24, 12)", - "12.01 walk east 21 (to wall) -> FuchsiaCity (45, 12)", - "12.01 walk south 6 (to wall) -> FuchsiaCity (45, 18)", - "12.01 walk west 13 (to wall) -> FuchsiaCity (32, 18)", - "12.01 walk north 1 -> FuchsiaCity (32, 17)", - "12.01 walk west 5 -> FuchsiaCity (27, 17)", - "12.01 walk south 8 (to wall) -> FuchsiaCity (27, 25)", - "12.01 walk west 25 (to wall) -> FuchsiaCity (2, 25)", + "12.01 walk south 1 (to wall) -> FuchsiaCity (11, 17)", + "12.01 walk east 13 (to wall) -> FuchsiaCity (24, 17)", + "12.01 walk south 4 -> FuchsiaCity (24, 21)", + "12.01 gym_east_wall from FuchsiaCity (24, 22) facing south to FuchsiaCity_Gym (14, 21) facing north", + "12.01 walk south 3 (to wall) -> FuchsiaCity (24, 25)", + "12.01 walk west 22 (to wall) -> FuchsiaCity (2, 25)", "12.01 walk south 12 (to wall) -> FuchsiaCity (2, 37)", "12.01 walk east 7 -> FuchsiaCity (9, 37)", "12.01 walk north 5 (warp) -> FuchsiaCity_Gym (7, 21)", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json index a33177bcd2..b0f95ef78e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json @@ -150,7 +150,7 @@ "args": { "target": {"map": "FuchsiaCity_Gym", "tiles": [[14, 21]], "facing": "north"} }, - "why": "out of the Center (its ground floor coded), west along row 32 to the gym's door (9, 32), and in the gym (no running) from the mat (7, 21) east along row 21 to the east wall: below Juggler Kayden's south line (12, 17..20) and Nate's (2, 17..20)" + "why": "from the Cut tree down to row 25, west to the city's west edge, down it to row 37 and up into the gym's door (9, 32) (the ledges (4, 30..34) and (28, 30..34) close the gym's road from row 23 elsewhere), and in the gym (no running) from the mat (7, 21) east along row 21 to the east wall: below Juggler Kayden's south line (12, 17..20) and Nate's (2, 17..20)" }, { "id": "below_kayden_line", @@ -279,7 +279,7 @@ "checkpoint": [ "Starts where 11.03's Fly lands, below Fuchsia's Center facing south, and goes in to the nurse (pokeguy bikes straight into the gym from there, 1:14:38; the Center heal is ours).", "PokeGuy's way (1:14:38 to 1:16:33): into the gym, Surf taught over Water Gun, Juggler Kirk fought (forced), round the top edge, Koga from the west. He fights nobody else; this row also fights Juggler Kayden (Hypno Lv38), whose east line every way north crosses with no wall to end a leg on: the user's call (2026-11-12) is to fight him with the normal battle code rather than wait for him to face away. After each of Kayden's and Kirk's fights, heal_to_full uses Super Potions and Potions until the HP missing from the battle's last HP bar (of 122 at Lv39, or the summary's maximum) is healed; check_full_hp stops the row west of Koga if any is missing.", - "The Fuchsia Mart (not in pokeguy's run: our healing for Kayden) buys Super Potions for what the bag's Potions and Super Potions, counted at the start, lack to heal 122 HP; it is skipped when they cover it.", + "The Fuchsia Mart (not in pokeguy's run: our healing for Kayden) buys Super Potions for what the bag's Potions and Super Potions, counted at the start, lack to heal 122 HP; it is skipped when they cover it. The way there hops the ledge (28, 32) east and cuts the tree (24, 22) both ways (about 37 tiles in, 68 on to the gym); without them the planned routes went round the city (about 150 and 110).", "The gym (FuchsiaCity_Gym map.json), 15 x 23, no running, its invisible walls in the map: Koga (7, 13) in the middle box, entered only from row 12 on the west. Its trainers and lines: Kayden (12, 16) south and east 4, Shawn (2, 9) west 1, Kirk (11, 11) east 3, Edgar (13, 4) every way 2, Phil (4, 6) every way 2, Nate (2, 16) south 4. Every way north crosses Kirk's line and one of Kayden's and Edgar's; the legs across a looker's line end on walls.", "Ends west of Koga and saves there: his own pre-battle checkpoint (battle-checkpoint-retry), 12.02. Koga is a D7 fight: pokeguy entered at 34/122 HP and the PokemonSimulation benchmark wins 70.1% (64.5%-75.2%, 1700 trials) from that. Entered at full HP and PP it wins 88.0% (82.4%-92.3%, 840 trials; same C2 policy df4fece, seed 4), which holds for this row only if Kayden's damage is healed to full before Koga." ] From c99f7f4c37dc5a4f12ee3c069308819e95ae0848 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 13:53:11 -0800 Subject: [PATCH 12/39] FRLG AutoStory: note where our helpers overlap upstream Navigation Comment on each AutoStory helper that overlaps a PokemonFRLG_Navigation or StartMenuNavigation helper: which one, how ours differs or that it wraps it, and that the two could be unified if needed. Comments only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStoryActions.cpp | 10 ++++++++++ .../Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp | 7 +++++++ .../Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h | 3 +++ .../AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp | 8 ++++++++ .../AutoStory/PokemonFRLG_AutoStoryFieldSteps.h | 8 ++++++++ .../AutoStory/PokemonFRLG_AutoStoryPcStorage.h | 4 ++++ .../Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h | 4 ++++ .../Programs/AutoStory/PokemonFRLG_AutoStorySave.h | 4 ++++ .../AutoStory/PokemonFRLG_AutoStoryStartMenu.h | 4 ++++ 9 files changed, 52 insertions(+) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 47a9e786af..28e6499962 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -113,6 +113,10 @@ std::optional start_cursor_row(ConsoleHandle& console, ProControllerContext // The START menu's cursor onto `row`, read from the arrow. As // move_cursor_to_position(), for a menu of any length. +// Overlaps move_cursor_to_position() in PokemonFRLG_StartMenuNavigation.h. +// Upstream only has fixed-menu overloads (Start, Safari, NoDex); ours takes a row count, +// so it also fits the 5-row menu before the starter. +// Could be unified with upstream if needed. bool move_start_cursor(ConsoleHandle& console, ProControllerContext& context, int rows, int row){ const std::optional current = start_cursor_row(console, context, rows); if (!current){ @@ -131,6 +135,9 @@ bool move_start_cursor(ConsoleHandle& console, ProControllerContext& context, in // The START menu's cursor onto SAVE, in a menu of any length: up past the // top wraps to EXIT, the last row, whose place gives the length; SAVE is // two above it. +// Overlaps move_cursor_to_position(SelectionArrowPositionStartMenu::SAVE) in PokemonFRLG_StartMenuNavigation.h. +// Upstream's SAVE position only fits the full menu; ours finds the menu length first, so it fits any menu. +// Could be unified with upstream if needed. bool move_start_cursor_to_save(ConsoleHandle& console, ProControllerContext& context){ const int most = start_menu_rows(StartMenu::FULL); const std::optional current = start_cursor_row(console, context, most); @@ -151,6 +158,9 @@ bool move_start_cursor_to_save(ConsoleHandle& console, ProControllerContext& con return true; } +// Overlaps open_start_menu() and move_cursor_to_position() in PokemonFRLG_StartMenuNavigation.h. +// Ours wraps open_start_menu() and then moves the cursor by row for any START menu variant. +// Could be unified with upstream if needed. void open_start_menu_row(ConsoleHandle& console, ProControllerContext& context, StartMenu menu, int row){ open_start_menu(console, context); if (!move_start_cursor(console, context, start_menu_rows(menu), row)){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index f069abd40b..67a2015b72 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -211,6 +211,10 @@ bool use_item( } // RUN, bottom right of the battle menu. +// Overlaps flee_battle() in PokemonFRLG_Navigation.h. +// Ours is one blind turn that resets the cursor first, since the battle loop reads the result itself; +// upstream needs the cursor on FIGHT and assumes the run always works. +// Could be unified with upstream if needed. void run_away(ProControllerContext& context){ tap(context, DPAD_LEFT); tap(context, DPAD_UP); @@ -676,6 +680,9 @@ class BattleLoop{ // From the overworld: the bag open on the Items pocket, cursor on its top. +// Overlaps open_bag_from_overworld() in PokemonFRLG_Navigation.h. +// Ours wraps it, then waits for the bag to slide in and moves the cursor to the top of the Items pocket. +// Could be unified with upstream if needed. void open_items_pocket(ConsoleHandle& console, ProControllerContext& context){ open_bag_from_overworld(console, context); // The bag ignores presses while it slides in. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h index e5ed4a3543..e28373b9bf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h @@ -143,6 +143,9 @@ class ConsoleCaptureActions : public CaptureActions{ virtual bool find_encounter(Pokemon::Direction pace) override; virtual EncounterSeen read_encounter() override; + // Overlaps flee_battle() in PokemonFRLG_Navigation.h. + // Ours wraps it, then waits out the battle exit and turns a thrown failure into false. + // Could be unified with upstream if needed. virtual bool flee() override; virtual FoeHp read_foe_hp() override; virtual TurnEnd attack(size_t move) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp index 304f69404e..acd43830b3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp @@ -131,6 +131,10 @@ void tap_dpad(ProControllerContext& context, DpadPosition dpad, size_t count, Mi // From the overworld to the fly map: the party, the Fly user, FLY. // Returns the failure, or empty. +// Overlaps open_fly_map_from_overworld() in PokemonFRLG_Navigation.h. +// Ours picks the Fly user by slot or species and FLY's menu row, and returns a failure code instead of +// throwing; upstream assumes the last party slot and the second menu row. +// Could be unified with upstream if needed. std::string open_fly_map(ConsoleHandle& console, ProControllerContext& context, const FlyPlan& plan){ open_party_menu_from_overworld(console, context, start_menu_context(plan.start_menu)); tap_dpad(context, DPAD_DOWN, plan.slot, MENU_TAP, MENU_TAP_RELEASE); @@ -154,6 +158,10 @@ std::string open_fly_map(ConsoleHandle& console, ProControllerContext& context, // On the fly map: the cursor to the corner, then to the town, and A. // Returns the failure, or empty once the overworld is at rest after the // landing. +// Overlaps fly_from_kanto_map() in PokemonFRLG_Navigation.h. +// Ours moves the cursor by map cell from a town table and waits for a quiet overworld after landing; +// upstream uses timed stick holds per KantoFlyLocation and a blind wait. +// Could be unified with upstream if needed. std::string fly_to_town(ConsoleHandle& console, ProControllerContext& context, const FlyTown& town){ pbf_press_dpad(context, DPAD_UP_LEFT, CURSOR_TO_CORNER, CURSOR_TAP_RELEASE); tap_dpad(context, DPAD_RIGHT, (size_t)town.cell.x, CURSOR_TAP, CURSOR_TAP_RELEASE); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldSteps.h index 27b7cc5d1b..53470bfc5b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldSteps.h @@ -35,10 +35,18 @@ Pokemon::StoryStep lift_floor_step(std::string name, std::string_view from, std: // Into the Pokemon Center `center` (a map name) from below its door, // facing north, to below the nurse's counter (CENTER_ENTER_VARIANT). +// Overlaps enter_pokecenter() in PokemonFRLG_Navigation.h. +// Ours walks one tap per tile and ends on the nurse's front tile with a declared pose; +// upstream holds the stick until the screen goes black and leaves the position unknown. +// Could be unified with upstream if needed. Pokemon::StoryStep center_enter_step(std::string name, std::string_view center); // Out of the Center from below the nurse's counter (CENTER_EXIT_VARIANT) // to `below_door`, the tile below its door outside, facing south. +// Overlaps leave_pokecenter() in PokemonFRLG_Navigation.h. +// Ours starts below the nurse's counter and ends on the tile below the door with a declared pose; +// upstream starts north of the exit and holds the stick until the screen goes black. +// Could be unified with upstream if needed. Pokemon::StoryStep center_exit_step(std::string name, Pokemon::GridPose below_door); // Uses `item` from the bag on the overworld (USE_ITEM_VARIANT): a diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h index a5134f6b7e..9f8c54906a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h @@ -68,6 +68,10 @@ PcResult run_pc_transfer(Logger& logger, PcStorageActions& actions, const PcTran // From the overworld: the party's size, read from the party menu, which is // closed again. +// Overlaps detect_last_occupied_party_slot() in PokemonFRLG_Navigation.h. +// Ours wraps it with open_party_menu_from_overworld() before and mash_until_overworld() after, +// and returns a count; upstream only reads the party menu that is already open. +// Could be unified with upstream if needed. size_t read_party_size(ConsoleHandle& console, ProControllerContext& context); // The console's PC steps. Party members are read by count only: none is diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h index 67d4cc7133..8ae2ddbb04 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h @@ -43,6 +43,10 @@ enum class TextEnd{ TextEnd advance_text(ConsoleHandle& console, ProControllerContext& context, Milliseconds timeout, bool stop_at_battle); // advance_text() to the overworld. +// Overlaps in_overworld() in PokemonFRLG_Navigation.h. +// Ours watches the screen while pressing B; upstream opens START to check, +// which ours avoids during text and prompts. +// Could be unified with upstream if needed. void mash_until_overworld(ConsoleHandle& console, ProControllerContext& context, Milliseconds timeout); // From the overworld, facing something that answers A with a message (a diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h index 784ad4579d..cf5af79645 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h @@ -75,6 +75,10 @@ class SaveDialog{ // (see SaveDialog). The menu's cursor is read, since the game remembers it // and the menu grows. Returns to the overworld; throws // OperationFailedException if the save wasn't made. +// Overlaps save_game_to_overworld() in PokemonFRLG_Navigation.h. +// Ours reads the cursor for any START menu length (the menu grows during the +// story) and checks the overworld is back; upstream assumes the full menu. +// Could be unified with upstream if needed. void save_game(ConsoleHandle& console, ProControllerContext& context, StartMenu menu); // From the overworld: the place the START menu's SAVE card names (see diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h index 689eb1a3b6..9f7f5e8a23 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h @@ -69,6 +69,10 @@ StartMenu step_start_menu(const Pokemon::StoryActionArgs& args); // Whether the overworld is up: START opens the menu only there, with no // scene running. If it opened, it is closed again. +// Overlaps in_overworld() in PokemonFRLG_Navigation.h. +// Ours presses START once and takes one snapshot, with no B presses before the menu shows; +// upstream mashes B and retries START up to 3 times, which is unsafe in the intro and move prompts. +// Could be unified with upstream if needed. bool overworld_shows(ConsoleHandle& console, ProControllerContext& context); From 7c2e36a9524b927d084518a53d3b308b06616e3e Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:12:56 -0800 Subject: [PATCH 13/39] CI: link Pokemon_Direction.cpp into runtime-map tests; ItemListReader test loop over const char* Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp | 2 +- devtools/runtime-map-tests/CMakeLists.txt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp index e09313cee1..2ec4647ef6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp @@ -241,7 +241,7 @@ class Test_Route17ItemNames : public UnitTest{ virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const ItemNameMatcher& matcher = ItemNameMatcher::instance(); - for (const std::string& text : {"FARE CANCY", "RARE CANOY", "RARE CANDY"}){ + for (const char* text : {"FARE CANCY", "RARE CANOY", "RARE CANDY"}){ const std::string item = matcher.match(Language::English, text); if (item != "rare-candy"){ return std::format("Expected \"{}\" read as rare-candy, got \"{}\".", text, item); diff --git a/devtools/runtime-map-tests/CMakeLists.txt b/devtools/runtime-map-tests/CMakeLists.txt index 8a91248664..eb200ef5cc 100644 --- a/devtools/runtime-map-tests/CMakeLists.txt +++ b/devtools/runtime-map-tests/CMakeLists.txt @@ -11,6 +11,7 @@ add_library(RuntimeMapDecoder STATIC "${NAV}/Pokemon_RuntimeMap.cpp" "${NAV}/Pokemon_MapData.cpp" "${NAV}/Pokemon_Grid.cpp" + "${NAV}/Pokemon_Direction.cpp" "${ROOT}/Common/Cpp/Exceptions.cpp" "${ROOT}/Common/Cpp/Json/JsonValue.cpp" "${ROOT}/Common/Cpp/Json/JsonObject.cpp" From 13fc72d2faeec0be156c06637d048e68f9e76e92 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:57:24 -0800 Subject: [PATCH 14/39] FRLG teach: keep lists instead of one move to forget A TEACH step may list the moves to keep: the one known move outside the list is forgotten, and none or several outside it is an error that logs the moveset. 12.01's Surf named Water Gun, which console B's Blastoise (Bite, Water Pulse, Bubble, Dig) doesn't know. The 04.06, 05.02-05.04, 06.02 and 12.01 teach steps now carry keep lists; 10.01's Fly keeps its ordered forget/or_forget, which a keep list can't express. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryRunPlan_Tests.cpp | 12 ++++-- .../PokemonFRLG_AutoStoryStepTable.cpp | 1 + .../AutoStory/PokemonFRLG_AutoStoryTeach.cpp | 37 +++++++++++++++++++ .../PokemonFRLG_AutoStoryTeachPlan.h | 8 +++- .../PokemonFRLG_AutoStoryTeach_Tests.cpp | 27 ++++++++++++++ .../AutoStory/StoryData/frlg-04.06.plan.json | 4 +- .../AutoStory/StoryData/frlg-05.02.plan.json | 4 +- .../AutoStory/StoryData/frlg-05.03.plan.json | 4 +- .../AutoStory/StoryData/frlg-05.04.plan.json | 4 +- .../AutoStory/StoryData/frlg-06.02.plan.json | 4 +- .../AutoStory/StoryData/frlg-12.01.plan.json | 4 +- 11 files changed, 93 insertions(+), 16 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp index d94dd1cedd..05aa4a2aa3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp @@ -31,6 +31,12 @@ namespace PokemonFRLG{ namespace{ +// Whether a Water Pulse teach step forgets Tail Whip: its keep list holds +// other moves and not Tail Whip. +bool forgets_tail_whip(const TeachPlan& plan){ + return !plan.keep.empty() && std::find(plan.keep.begin(), plan.keep.end(), "tail-whip") == plan.keep.end(); +} + struct AutoStoryInput{ std::string name; std::function body; @@ -422,7 +428,7 @@ UnitTestResult test_cerulean_mart_and_grind(){ return "05.03: expected it to start in Cerulean's Center."; } const std::optional teach = steps.empty() ? std::nullopt : teach_of(steps[0]); - if (!teach || teach->item != "tm03" || teach->move != "water-pulse" || teach->member != 0 || teach->forget_move != "tail-whip"){ + if (!teach || teach->item != "tm03" || teach->move != "water-pulse" || teach->member != 0 || !forgets_tail_whip(*teach)){ return "05.03: expected it to start with TM03 Water Pulse over the lead's Tail Whip."; } const size_t mart = find_step(steps, 0, [](const StoryStep& step){ @@ -487,7 +493,7 @@ UnitTestResult test_cerulean_rival_row(){ } const std::optional teach = teach_of(rival.steps[0]); if (rival.steps[0].kind != StoryStepKind::GAME || !teach || teach->item != "tm03" || teach->move != "water-pulse" - || teach->member != 0 || teach->forget_move != "tail-whip" + || teach->member != 0 || !forgets_tail_whip(*teach) ){ return "05.04: expected it to start with TM03 Water Pulse over the lead's Tail Whip."; } @@ -553,7 +559,7 @@ UnitTestResult test_misty_rows(){ } const size_t teach = find_step(misty.steps, 0, [](const StoryStep& step){ const std::optional plan = teach_of(step); - return plan && plan->item == "tm03" && plan->move == "water-pulse" && plan->member == 0 && plan->forget_move == "tail-whip"; + return plan && plan->item == "tm03" && plan->move == "water-pulse" && plan->member == 0 && forgets_tail_whip(*plan); }); if (teach == misty.steps.size()){ return "05.02: expected TM03 Water Pulse taught to the lead in place of Tail Whip."; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index fcede59be6..5fd497df5b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -135,6 +135,7 @@ Pokemon::StoryActionSpec teach_action_spec(){ absent_arg("species", StoryArgType::WORD, "the member by its species, e.g. \"pidgey\": the first slot whose summary reads it"), absent_arg("forget", StoryArgType::WORD, "the move to forget when it knows four"), absent_arg("or_forget", StoryArgType::WORDS, "the moves to forget, in order, when it doesn't know `forget`"), + absent_arg("keep", StoryArgType::WORDS, "the moves to keep when it knows four: the one known move outside them is forgotten"), absent_arg("forget_slot", StoryArgType::INTEGER, "the move slot to forget, from 1, when no move is named"), }}; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp index 02cc1455f5..a3eb82c424 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp @@ -66,6 +66,34 @@ std::string forget_names(const TeachPlan& plan){ return names; } +// "bite, water-pulse". +std::string joined(const std::vector& moves){ + std::string names; + for (const std::string& move : moves){ + names += names.empty() ? move : ", " + move; + } + return names; +} + +// The decision for a plan with a keep list: forget the one known move +// outside it. +TeachDecision decide_keep(const TeachPlan& plan, const std::vector& moves){ + std::vector outside; + for (size_t slot = 0; slot < moves.size(); slot++){ + const bool kept = std::find(plan.keep.begin(), plan.keep.end(), moves[slot]) != plan.keep.end(); + if (!kept && !is_hm_move(moves[slot])){ + outside.push_back(slot); + } + } + if (outside.size() != 1){ + return {.error = std::format( + "it knows {} and the keep list ({}) leaves {} moves to forget, not one", + joined(moves), joined(plan.keep), outside.size() + )}; + } + return {.forget = outside[0]}; +} + } // namespace Pokemon::StoryActionArgs teach_args(const TeachPlan& plan){ @@ -75,6 +103,9 @@ Pokemon::StoryActionArgs teach_args(const TeachPlan& plan){ }else{ args.emplace("species", plan.species); } + if (!plan.keep.empty()){ + args.emplace("keep", plan.keep); + } if (!plan.forget_move.empty()){ args.emplace("forget", plan.forget_move); if (!plan.forget_else.empty()){ @@ -99,6 +130,9 @@ std::optional teach_plan_of(const Pokemon::StoryActionArgs& args){ if (species != nullptr){ plan.species = *species; } + if (const std::vector* keep = game_arg>(args, "keep")){ + plan.keep = *keep; + } if (const std::string* forget = game_arg(args, "forget")){ if (forget->empty()){ return std::nullopt; @@ -139,6 +173,9 @@ TeachDecision decide_teach(const TeachPlan& plan, const std::vector if (moves.size() < MOVE_SLOTS){ return {}; } + if (!plan.keep.empty()){ + return decide_keep(plan, moves); + } std::optional slot = plan.forget_slot; if (!plan.forget_move.empty()){ const std::optional known = first_known(moves, plan); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachPlan.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachPlan.h index 84e98f69a3..4281b71a3b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachPlan.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachPlan.h @@ -45,6 +45,11 @@ struct TeachPlan{ // The moves to forget, in order, when it doesn't know `forget_move`. std::vector forget_else = {}; std::optional forget_slot = std::nullopt; + // The moves to keep when it knows four: the one known move outside + // this list (HM moves count as kept) is forgotten; none or several + // outside is an error. When not empty, it replaces forget_move, + // forget_else and forget_slot. + std::vector keep = {}; }; // Whether `move` is an HM's, which the game won't let a Pokemon forget. @@ -55,7 +60,8 @@ bool is_hm_move(std::string_view move); // or species WORD (one of them required); forget WORD or forget_slot // INTEGER (from 1) (optional): the move to forget when it knows four. // or_forget WORDS (optional): the moves to forget, in order, when it -// doesn't know `forget`'s. +// doesn't know `forget`'s. keep WORDS (optional): the moves to keep; the +// one known move outside them is forgotten. inline const std::string TEACH_ACTION = "teach"; // `plan` as its action's args. Pokemon::StoryActionArgs teach_args(const TeachPlan& plan); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp index 293ceb2f2e..2ec976748d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp @@ -227,6 +227,28 @@ std::vector teach_cases_1(){ .plan = {.item = "hm03", .move = "surf", .member = 0, .forget_move = "tail-whip"}, .moves = {"water-gun", "surf", "bubble", "withdraw"}, }, + { + .name = "Surf over the one move outside the keep list (BUBBLE, as console B's Blastoise)", + .plan = {.item = "hm03", .move = "surf", .member = 0, .keep = {"bite", "water-pulse", "dig"}}, + .setup = [](FakeTeachGame& game){ game.party[0].moves = {"bite", "water-pulse", "bubble", "dig"}; }, + .moves = {"bite", "water-pulse", "surf", "dig"}, + }, + { + .name = "a keep list with two moves outside it forgets none", + .plan = {.item = "hm03", .move = "surf", .member = 0, .keep = {"bite", "dig"}}, + .setup = [](FakeTeachGame& game){ game.party[0].moves = {"bite", "water-pulse", "bubble", "dig"}; }, + .end = TeachEnd::REFUSED, + .moves = {"bite", "water-pulse", "bubble", "dig"}, + .opened = false, + }, + { + .name = "a keep list that holds all four moves forgets none", + .plan = {.item = "hm03", .move = "surf", .member = 0, .keep = {"bite", "water-pulse", "bubble", "dig"}}, + .setup = [](FakeTeachGame& game){ game.party[0].moves = {"bite", "water-pulse", "bubble", "dig"}; }, + .end = TeachEnd::REFUSED, + .moves = {"bite", "water-pulse", "bubble", "dig"}, + .opened = false, + }, { .name = "Strength over the fourth slot by number", .plan = {.item = "hm04", .move = "strength", .member = 0, .forget_slot = 3}, @@ -405,6 +427,11 @@ UnitTestResult test_teach_by_species(){ if (fallback.end != TeachEnd::LEARNED || fallback.forgot != "sand-attack" || game.party[3].moves != pokeguys){ return std::format("Fly, no Whirlwind: ended {} ({}), forgot \"{}\".", teach_end_name(fallback.end), fallback.detail, fallback.forgot); } + const TeachPlan kept{.item = "hm03", .move = "surf", .member = 0, .keep = {"bite", "dig"}}; + const std::optional kept_back = teach_plan_of(teach_args(kept)); + if (!kept_back || kept_back->keep != kept.keep){ + return "keep didn't read back from its args."; + } const std::optional back = teach_plan_of(teach_args(or_else)); if (!back || back->forget_else != or_else.forget_else){ return "or_forget didn't read back from its args."; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-04.06.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-04.06.plan.json index 3d1ef9ad07..e1aa178af0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-04.06.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-04.06.plan.json @@ -23,9 +23,9 @@ "item": "tutor", "move": "mega-kick", "slot": 1, - "forget": "withdraw" + "keep": ["tackle", "tail-whip", "water-gun", "bubble", "bite", "water-pulse", "dig", "surf"] }, - "why": "the tutor's Mega Kick in place of Withdraw, unless the lead knows it" + "why": "the tutor's Mega Kick in place of Withdraw, unless the lead knows it; keep list: every move the lead can know but Withdraw, which goes; fails if it knows none or several outside the list" }, { "id": "above_ledge", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.02.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.02.plan.json index e0430b4ebf..ca1c30c6a4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.02.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.02.plan.json @@ -61,9 +61,9 @@ "item": "tm03", "move": "water-pulse", "slot": 1, - "forget": "tail-whip" + "keep": ["tackle", "withdraw", "water-gun", "bubble", "bite", "mega-kick", "dig", "surf"] }, - "why": "TM03 Water Pulse in place of Tail Whip" + "why": "TM03 Water Pulse in place of Tail Whip; keep list: the damaging moves, Bite, Withdraw and Mega Kick, so the one other move (Tail Whip) goes; fails if none or several are outside the list" } ] }, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.03.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.03.plan.json index 5ddbd5224f..9c18d5f56c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.03.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.03.plan.json @@ -14,9 +14,9 @@ "item": "tm03", "move": "water-pulse", "slot": 1, - "forget": "tail-whip" + "keep": ["tackle", "withdraw", "water-gun", "bubble", "bite", "mega-kick", "dig", "surf"] }, - "why": "TM03 Water Pulse in place of Tail Whip, unless the lead knows it or there is no TM03" + "why": "TM03 Water Pulse in place of Tail Whip, unless the lead knows it or there is no TM03; keep list: the damaging moves, Bite, Withdraw and Mega Kick, so the one other move (Tail Whip) goes; fails if none or several are outside the list" }, { "id": "mart_clerk", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.04.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.04.plan.json index fbfa4e03fc..27f931a076 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.04.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-05.04.plan.json @@ -14,9 +14,9 @@ "item": "tm03", "move": "water-pulse", "slot": 1, - "forget": "tail-whip" + "keep": ["tackle", "withdraw", "water-gun", "bubble", "bite", "mega-kick", "dig", "surf"] }, - "why": "TM03 Water Pulse in place of Tail Whip, unless the lead knows it" + "why": "TM03 Water Pulse in place of Tail Whip, unless the lead knows it; keep list: the damaging moves, Bite, Withdraw and Mega Kick, so the one other move (Tail Whip) goes; fails if none or several are outside the list" }, { "id": "rival_trigger", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-06.02.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-06.02.plan.json index cb8b4e4cd3..ee1b5c8b06 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-06.02.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-06.02.plan.json @@ -25,9 +25,9 @@ "item": "tm28", "move": "dig", "slot": 1, - "forget": "withdraw" + "keep": ["tackle", "water-gun", "bubble", "bite", "water-pulse", "mega-kick", "surf"] }, - "why": "TM28 Dig in place of Withdraw, for Lt. Surge, unless the lead knows it or there is no TM28" + "why": "TM28 Dig in place of Withdraw, for Lt. Surge, unless the lead knows it or there is no TM28; keep list: the damaging moves, Bite, Mega Kick and Surf, so the one other move (Withdraw) goes; fails if none or several are outside the list" }, { "id": "above_gym_tree", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json index b0f95ef78e..6c86a2c872 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json @@ -44,9 +44,9 @@ "item": "hm03", "move": "surf", "slot": 1, - "forget": "water-gun" + "keep": ["bite", "water-pulse", "dig", "mega-kick"] }, - "why": "HM03 Surf in place of Water Gun, as pokeguy (1:14:55 to 1:15:13: Surf, Water Pulse, Bite, Mega Kick after it), unless the lead knows it; an HM, so not a one-shot TM" + "why": "HM03 Surf in place of Water Gun, as pokeguy (1:14:55 to 1:15:13: Surf, Water Pulse, Bite, Mega Kick after it), unless the lead knows it; an HM, so not a one-shot TM; keep list: Bite, Water Pulse, Dig and Mega Kick stay and the one other move (Bubble or Water Gun) goes; fails if none or several are outside the list" }, { "id": "center_northwest_corner", From ef1d107362ab46931d9cb46a1dbbf10f690280d7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 16:19:04 -0800 Subject: [PATCH 15/39] FRLG 12.01: floor 3762 for buy_super_potions; every Mart step needs a floor read_money() reads nothing yet, so a Mart step with no floor buys nothing (console failure 2026-11-12 16:13). 3762 = 10.01's floor 19862 less its 15600 of X items and the Safari Zone's 500, prize money not counted. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryMart_Tests.cpp | 23 +++++++++++++++++++ .../AutoStory/StoryData/frlg-12.01.plan.json | 3 ++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp index e88dae4d58..71c8d553ef 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp @@ -19,6 +19,8 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "PokemonFRLG_AutoStoryMart.h" +#include "PokemonFRLG_AutoStoryMartPlan.h" +#include "PokemonFRLG_AutoStoryTable.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -455,6 +457,23 @@ UnitTestResult test_count_supplies(){ return true; } +// ConsoleMartActions::read_money() reads nothing yet, so a Mart step with no +// "floor" buys nothing (MartEnd::NO_MONEY_READ): every one carries a floor. +UnitTestResult test_mart_steps_have_floor(){ + std::string missing; + for (const StoryCheckpoint& data : story_checkpoints()){ + for (const StoryStep& step : data.steps){ + if (step.kind == Pokemon::StoryStepKind::GAME && step.action == MART_ACTION && !step.args.contains("floor")){ + missing += " " + data.id + "/" + step.name; + } + } + } + if (!missing.empty()){ + return "Mart steps with no floor:" + missing; + } + return true; +} + } // namespace @@ -479,6 +498,10 @@ const AutoStoryMartCase AUTO_STORY_MART_CASES[] = { .input = {"bought supplies counted", test_count_supplies}, .expectation = {}, }, + { + .input = {"every Mart step has a floor", test_mart_steps_have_floor}, + .expectation = {}, + }, }; void add_tests_AutoStoryMart(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json index 6c86a2c872..647a870407 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json @@ -119,10 +119,11 @@ "args": { "map": "FuchsiaCity_Mart", "budget": 2100, + "floor": 3762, "items": [{"item": "super-potion", "quantity": 3}], "cover_hp": 122 }, - "why": "Super Potions for what the bag's Potions and Super Potions lack to heal 122 HP, the lead's whole bar at Lv39 (3 with none): Kayden's and Kirk's damage is healed to full before Koga. Skipped when the bag covers it" + "why": "Super Potions for what the bag's Potions and Super Potions lack to heal 122 HP, the lead's whole bar at Lv39 (3 with none): Kayden's and Kirk's damage is healed to full before Koga. Skipped when the bag covers it. The floor is 10.01's 19,862 less its 15,600 of X items and the Safari Zone's 500 (11.03), 3,762, prize money not counted: a lower bound while the money box is unread" }, { "id": "above_mart_tree", From 66baa7e56cc2ebdb85da199d5083fa63c0211313 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 16:32:16 -0800 Subject: [PATCH 16/39] FRLG Mart: the item list reader names every item the Marts sell The Fuchsia Mart's ULTRA BALL row read as PARLYZ HEAL, the nearest name in a dictionary without Ultra Ball, and 12.01 bought nothing (console B, 2026-11-12). The Bag-layout name box reads the Mart's rows correctly. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Menus/PokemonFRLG_ItemListReader.cpp | 17 +++++++++++ .../PokemonFRLG_AutoStoryMart_Tests.cpp | 28 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp index 2ec4647ef6..a3b3b05999 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp @@ -70,6 +70,20 @@ constexpr std::pair ENGLISH_ITEM_NAMES[] = { // Mt. Moon's, which top the pocket above the story's items. {"moon-stone", "Moon Stone"}, {"nugget", "Nugget"}, + // The rest of the Marts' stock. The Fuchsia Mart's ULTRA BALL row read + // as PARLYZ HEAL, the nearest name there was, and 12.01 bought + // nothing (console B, 2026-11-12). + {"great-ball", "Great Ball"}, + {"ultra-ball", "Ultra Ball"}, + {"hyper-potion", "Hyper Potion"}, + {"max-potion", "Max Potion"}, + {"revive", "Revive"}, + {"burn-heal", "Burn Heal"}, + {"ice-heal", "Ice Heal"}, + {"full-heal", "Full Heal"}, + {"x-attack", "X Attack"}, + {"x-defend", "X Defend"}, + {"dire-hit", "Dire Hit"}, {"cancel", "Cancel"}, }; @@ -337,6 +351,9 @@ void add_tests_ItemListReader(UnitTestDatabase& database){ database.add("PokemonFRLG/ItemListReader/ItemsPocketMoonStone_eng.png"); // The Viridian Mart's BUY list, the same day, the cursor on POTION. database.add("PokemonFRLG/ItemListReader/MartBuyList_eng.png"); + // The Fuchsia Mart's, the cursor on ULTRA BALL (console B, 2026-11-12): six + // rows, none of them in the reader's dictionary yet. + database.add("PokemonFRLG/ItemListReader/FuchsiaMartBuyList_eng.png"); database.add(); database.add(); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp index 71c8d553ef..e2349b78b0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp @@ -18,6 +18,7 @@ #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h" #include "PokemonFRLG_AutoStoryMart.h" #include "PokemonFRLG_AutoStoryMartPlan.h" #include "PokemonFRLG_AutoStoryTable.h" @@ -438,6 +439,29 @@ UnitTestResult test_mart_stock(){ } +// 12.01's Fuchsia Mart read its ULTRA BALL row as PARLYZ HEAL and bought +// nothing (console B, 2026-11-12): the item list reader had no name for it. +// Every item any Mart sells has one. +UnitTestResult test_mart_stock_readable(){ + std::string missing; + for (const char* map : { + "ViridianCity_Mart", "PewterCity_Mart", "CeruleanCity_Mart", "VermilionCity_Mart", + "LavenderTown_Mart", "FuchsiaCity_Mart", "SaffronCity_Mart", "CinnabarIsland_Mart", + "CeladonCity_DepartmentStore_5F", + }){ + for (const MartStockItem& stock : mart_stock(map)){ + if (!item_list_reader_knows(stock.item)){ + missing += std::format("\n {}: {}", map, stock.item); + } + } + } + if (!missing.empty()){ + return std::format("The item list reader has no name for:{}", missing); + } + return true; +} + + // Potions, Antidotes, Parlyz Heals and Awakenings bought go into the // battles' supplies. UnitTestResult test_count_supplies(){ @@ -494,6 +518,10 @@ const AutoStoryMartCase AUTO_STORY_MART_CASES[] = { .input = {"Mart stocks", test_mart_stock}, .expectation = {}, }, + { + .input = {"every Mart item has a reader name", test_mart_stock_readable}, + .expectation = {}, + }, { .input = {"bought supplies counted", test_count_supplies}, .expectation = {}, From c269877a0b1380b181b8c67228858e573b75eca3 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 16:34:34 -0800 Subject: [PATCH 17/39] CI: CommandLineTests with the Fuchsia Mart BUY list image Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .github/workflows/cpp-ci-serial-programs-base.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index 83d7054074..8eefdf4f37 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -385,7 +385,7 @@ jobs: with: # Complete fork fixtures include pending FRLG image submissions. repository: 'dayfine/CommandLineTests' - ref: 'd150a6c547434110a920f95ba7857b93d5bb9222' + ref: 'fc303e1c9edcc98bd6d1171276a306cf2a6280d9' path: 'CommandLineTests' # The unit tests assume the downloadable resources they need are already downloaded From 5551f771eb8fce7fad4740c7939cdb149248a22c Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 16:34:51 -0800 Subject: [PATCH 18/39] FRLG Mart tests: string_view for the Mart maps Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp index e2349b78b0..69f0e28efc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" @@ -444,7 +445,7 @@ UnitTestResult test_mart_stock(){ // Every item any Mart sells has one. UnitTestResult test_mart_stock_readable(){ std::string missing; - for (const char* map : { + for (const std::string_view map : { "ViridianCity_Mart", "PewterCity_Mart", "CeruleanCity_Mart", "VermilionCity_Mart", "LavenderTown_Mart", "FuchsiaCity_Mart", "SaffronCity_Mart", "CinnabarIsland_Mart", "CeladonCity_DepartmentStore_5F", From a63973d43ec02876f53e427f88754bfbd2b8abb7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 16:55:00 -0800 Subject: [PATCH 19/39] FRLG 12.01: the Fuchsia Mart fills the bag to 5 Super Potions The step's cover_hp 122 bought one Super Potion with 6 Potions in the bag. PokeGuy's bag at Koga holds 5 (PokemonSimulation docs/battles/ pokeguy-conditions.md, ### koga), so the step takes a new "fill_to" argument: it buys what the bag lacks of the first line's item to hold that many. The budget is raised to 3,500 (5 x 700); the floor stays 3,762. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp | 48 +++++++++++++++++++ .../PokemonFRLG_AutoStoryHealing.cpp | 5 ++ .../AutoStory/PokemonFRLG_AutoStoryHealing.h | 4 ++ .../PokemonFRLG_AutoStoryHealingSteps.cpp | 25 +++++++--- .../PokemonFRLG_AutoStoryHealingSteps.h | 4 +- .../PokemonFRLG_AutoStoryStepTable.cpp | 1 + .../AutoStory/StoryData/frlg-12.01.plan.json | 8 ++-- 7 files changed, 82 insertions(+), 13 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp index c032768c81..77d47e9e6a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFuchsiaGym_Tests.cpp @@ -10,6 +10,7 @@ * */ +#include #include #include #include @@ -23,6 +24,8 @@ #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryGameArgs.h" +#include "PokemonFRLG_AutoStoryHealingSteps.h" #include "PokemonFRLG_AutoStoryParty.h" #include "PokemonFRLG_AutoStoryRooms.h" #include "PokemonFRLG_AutoStoryMember.h" @@ -248,7 +251,52 @@ UnitTestResult check_lead_level_precondition(Logger& logger, std::string_view id return true; } +// pokeguy's bag at Koga holds 5 Super Potions (PokemonSimulation +// docs/battles/pokeguy-conditions.md, ### koga): 12.01's Mart step buys up +// to 5, whatever the Potions cover, within its budget. +UnitTestResult test_mart_fills_super_potions(){ + const std::optional row = checkpoint("12.01"); + if (!row){ + return "12.01 is missing."; + } + const auto step_it = std::find_if(row->steps.begin(), row->steps.end(), [](const Pokemon::StoryStep& step){ + return step.name == "buy_super_potions"; + }); + if (step_it == row->steps.end()){ + return "12.01 has no buy_super_potions step."; + } + struct Case{ + int potions; + int super_potions; + size_t expected; + }; + const Case cases[] = {{6, 0, 5}, {0, 0, 5}, {6, 2, 3}, {6, 5, 0}, {0, 7, 0}}; + QuietLogger logger; + for (const Case& test : cases){ + Supplies supplies; + supplies.potions = test.potions; + supplies.super_potions = test.super_potions; + Pokemon::StoryStep step = *step_it; + const std::optional done = cover_hp_in_mart(logger, supplies, step); + const std::vector* items = game_arg>(step.args, "items"); + const size_t buys = done ? 0 : (items == nullptr || items->empty() ? 0 : items->at(0).quantity); + if (buys != test.expected){ + return std::format("{} Potions, {} Super Potions: buys {}, expected {}.", test.potions, test.super_potions, buys, test.expected); + } + } + const int64_t* budget = game_arg(step_it->args, "budget"); + const int64_t* floor = game_arg(step_it->args, "floor"); + if (budget == nullptr || *budget < 5 * 700 || floor == nullptr || *floor != 3762){ + return "The step's budget doesn't cover 5 Super Potions, or its floor moved off 3762."; + } + return true; +} + const AutoStoryFuchsiaGymCase AUTO_STORY_FUCHSIA_GYM_CASES[] = { + { + .input = {.name = "12.01's Mart fills the bag to pokeguy's 5 Super Potions", .body = test_mart_fills_super_potions}, + .expectation = {.description = "5 bought with 6 Potions and none, fewer or none when the bag holds some"}, + }, { .input = {.name = "12.01 past Kayden and Kirk to west of Koga and 12.02 to the Warden and the nurse", .body = test_gym_rows}, .expectation = {.description = "Kayden and Kirk fought where the table steps into their lines, no one else; ends at Fuchsia's nurse"}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.cpp index cdf2470061..0993662951 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.cpp @@ -100,6 +100,11 @@ int hp_cover_shortfall(const Supplies& supplies, int cover_hp, const std::string return (cover_hp - held + each - 1) / each; } +int fill_shortfall(const Supplies& supplies, int target, const std::string& item){ + const int held = item == "potion" ? supplies.potions : item == "super-potion" ? supplies.super_potions : 0; + return std::max(0, target - held); +} + namespace{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h index e516127b4e..d50d26cf6f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h @@ -55,6 +55,10 @@ std::optional heal_to_full( // them, heal at least `cover_hp`: 0 if they already do. int hp_cover_shortfall(const Supplies& supplies, int cover_hp, const std::string& item); +// How many more of `item` (a Potion or Super Potion) the bag needs to hold +// `target` of it: 0 if it already does. +int fill_shortfall(const Supplies& supplies, int target, const std::string& item); + // Registers the healing tests. void add_tests_AutoStoryHealing(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.cpp index 00a3f19336..4c3ca84f41 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.cpp @@ -74,17 +74,28 @@ std::optional run_healing_step(StoryEnv& env, const StoryStep& step){ } std::optional cover_hp_in_mart(Logger& logger, const Supplies& supplies, StoryStep& step){ - const int64_t* cover = step.action == MART_ACTION ? game_arg(step.args, "cover_hp") : nullptr; + const bool mart = step.action == MART_ACTION; + const int64_t* cover = mart ? game_arg(step.args, "cover_hp") : nullptr; + const int64_t* fill = mart ? game_arg(step.args, "fill_to") : nullptr; const std::vector* items = game_arg>(step.args, "items"); - if (cover == nullptr || items == nullptr || items->empty()){ + if ((cover == nullptr && fill == nullptr) || items == nullptr || items->empty()){ return std::nullopt; } std::vector lines = *items; - const int shortfall = hp_cover_shortfall(supplies, (int)*cover, lines[0].item); - logger.log(std::format( - "Story: {}: {} Potions and {} Super Potions against {} HP: {} {} short.", - step.name, supplies.potions, supplies.super_potions, *cover, shortfall, lines[0].item - )); + int shortfall; + if (fill != nullptr){ + shortfall = fill_shortfall(supplies, (int)*fill, lines[0].item); + logger.log(std::format( + "Story: {}: {} Potions and {} Super Potions against {} {}: {} short.", + step.name, supplies.potions, supplies.super_potions, *fill, lines[0].item, shortfall + )); + }else{ + shortfall = hp_cover_shortfall(supplies, (int)*cover, lines[0].item); + logger.log(std::format( + "Story: {}: {} Potions and {} Super Potions against {} HP: {} {} short.", + step.name, supplies.potions, supplies.super_potions, *cover, shortfall, lines[0].item + )); + } if (shortfall <= 0){ return Pokemon::outcome_unchanged(); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.h index fcf5a52cde..3dab8193c0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHealingSteps.h @@ -51,8 +51,8 @@ std::vector healing_action_specs(); // nothing for another. std::optional run_healing_step(StoryEnv& env, const Pokemon::StoryStep& step); -// A MART_ACTION step with "cover_hp": its first line cut to the -// hp_cover_shortfall() of `supplies` (at most the plan's quantity), in +// A MART_ACTION step with "cover_hp" or "fill_to": its first line cut to the +// hp_cover_shortfall() or fill_shortfall() of `supplies` (at most the plan's quantity), in // `step`. Nothing to buy: the step's Outcome, unchanged, logged. Nothing // for another step, left as it was. std::optional cover_hp_in_mart(Logger& logger, const Supplies& supplies, Pokemon::StoryStep& step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index 5fd497df5b..91afb042a8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -124,6 +124,7 @@ Pokemon::StoryActionSpec mart_action_spec(){ absent_arg("floor", StoryArgType::INTEGER, "the least money the player has here, when the money box can't be read"), required_arg("items", StoryArgType::ITEMS, "what to buy, in priority order"), absent_arg("cover_hp", StoryArgType::INTEGER, "buy only the first line's shortfall for the bag's Potions and Super Potions to heal this much HP"), + absent_arg("fill_to", StoryArgType::INTEGER, "buy only what the bag lacks of the first line's item to hold this many"), }}; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json index 647a870407..d853cec30e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-12.01.plan.json @@ -118,12 +118,12 @@ "action": "mart", "args": { "map": "FuchsiaCity_Mart", - "budget": 2100, + "budget": 3500, "floor": 3762, - "items": [{"item": "super-potion", "quantity": 3}], - "cover_hp": 122 + "items": [{"item": "super-potion", "quantity": 5}], + "fill_to": 5 }, - "why": "Super Potions for what the bag's Potions and Super Potions lack to heal 122 HP, the lead's whole bar at Lv39 (3 with none): Kayden's and Kirk's damage is healed to full before Koga. Skipped when the bag covers it. The floor is 10.01's 19,862 less its 15,600 of X items and the Safari Zone's 500 (11.03), 3,762, prize money not counted: a lower bound while the money box is unread" + "why": "Super Potions up to 5 in the bag, as in PokeGuy's bag at Koga (potion x5, superpotion x5, fullrestore x1, xspecial x19, xspeed x6, xaccuracy x5; PokemonSimulation docs/battles/pokeguy-conditions.md): Kayden's and Kirk's damage is healed to full before Koga. Buys 5 less what the bag holds, skipped at 5. The floor is 10.01's 19,862 less its 15,600 of X items and the Safari Zone's 500 (11.03), 3,762, prize money not counted: a lower bound while the money box is unread" }, { "id": "above_mart_tree", From da549f4ca3a2dd68f67dd51430a6010238fe2930 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:15:13 -0800 Subject: [PATCH 20/39] FRLG battle policy: PokeGuy's C2 goal-based setup at Koga and the Tower rival Koga ended console B's run in 6 turns with no Antidote and no X item used: a trainer battle only used its step's use_items. A step now names a "policy" (solo-recovery or goal-based-setup), the doc's setup goals and the foes' threat rows; the pure BattlePolicy module chooses a cure, a heal, or an X item / Guard Spec before the lead attacks, tracks the stages and Mist, and counts the foes left for X Speed. 12.02 koga and 10.03 rival_tower carry them; Lavender buys 1 Antidote and 1 Parlyz Heal and Cerulean 3 Awakenings, PokeGuy's bag at Koga. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStoryBattle.cpp | 23 +- .../PokemonFRLG_AutoStoryBattleDecisions.cpp | 93 +++- .../PokemonFRLG_AutoStoryBattleDecisions.h | 17 +- .../PokemonFRLG_AutoStoryBattlePolicy.cpp | 363 ++++++++++++++ .../PokemonFRLG_AutoStoryBattlePolicy.h | 131 +++++ .../PokemonFRLG_AutoStoryBattlePolicyData.h | 87 ++++ ...okemonFRLG_AutoStoryBattlePolicy_Tests.cpp | 463 ++++++++++++++++++ .../PokemonFRLG_AutoStoryBattleTurns.h | 3 + .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 3 + .../PokemonFRLG_AutoStoryItems_Tests.cpp | 2 + .../PokemonFRLG_AutoStoryStepTable.cpp | 79 ++- .../AutoStory/PokemonFRLG_AutoStorySupplies.h | 4 + .../AutoStory/StoryData/frlg-05.03.plan.json | 184 +++---- .../AutoStory/StoryData/frlg-08.03.plan.json | 432 ++++++++-------- .../AutoStory/StoryData/frlg-10.03.plan.json | 16 +- .../AutoStory/StoryData/frlg-12.02.plan.json | 15 +- SerialPrograms/cmake/SourceFiles.cmake | 4 + 17 files changed, 1566 insertions(+), 353 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicyData.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy_Tests.cpp diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index 67a2015b72..4541571a9c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -593,6 +593,17 @@ class BattleLoop{ m_last_press = now; } + void log_turn(const PartyStatus& status, const TurnAction& action){ + m_console.log(std::format( + "Battle: turn {}, HP {} ({:.0f}% of the bar), {}, {} Potions, {} Antidotes, {} Parlyz Heals, {} Awakenings.", + m_decisions.turns(), status.hp_red ? "red" : status.hp_yellow ? "yellow" : "green", 100 * status.hp_fill, + status_name(status.status), m_supplies.potions, m_supplies.antidotes, m_supplies.parlyz_heals, m_supplies.awakenings + )); + if (!action.heal_reason.empty()){ + m_console.log("Battle: " + action.heal_reason + "."); + } + } + void take_turn(const ImageViewRGB32& screen){ m_faint_polls = 0; if (m_kind != BattleKind::TRAINER && m_decisions.turns() == 0){ @@ -608,14 +619,7 @@ class BattleLoop{ const PartyStatus status = read_party_status(screen); const TurnAction action = m_decisions.turn(status); m_evolution.turn_taken(action.choice); - m_console.log(std::format( - "Battle: turn {}, HP {} ({:.0f}% of the bar), {}, {} Potions, {} Antidotes, {} Parlyz Heals, {} Awakenings.", - m_decisions.turns(), status.hp_red ? "red" : status.hp_yellow ? "yellow" : "green", 100 * status.hp_fill, - status_name(status.status), m_supplies.potions, m_supplies.antidotes, m_supplies.parlyz_heals, m_supplies.awakenings - )); - if (!action.heal_reason.empty()){ - m_console.log("Battle: " + action.heal_reason + "."); - } + log_turn(status, action); dump_debug_image(m_console, "AutoStory/battle", std::format("turn{}-menu", m_decisions.turns()), screen); switch (action.choice){ case TurnChoice::RUN: @@ -631,6 +635,9 @@ class BattleLoop{ case TurnChoice::AWAKENING: m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, m_supplies, "awakening", ItemTarget::PARTY_MEMBER, m_checks, m_language))); return; + case TurnChoice::MEDICINE: + m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, m_supplies, action.item, ItemTarget::PARTY_MEMBER, m_checks, m_language))); + return; case TurnChoice::BATTLE_ITEM: m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, m_supplies, action.item, ItemTarget::POKEMON_OUT, m_checks, m_language))); return; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp index 6b4fed137b..a503ed7ee1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp @@ -11,6 +11,7 @@ #include #include "PokemonFRLG_AutoStoryBattleDecisions.h" #include "PokemonFRLG_AutoStoryHealing.h" +#include "PokemonFRLG_AutoStoryItemsPocket.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -61,6 +62,24 @@ constexpr uint8_t MAX_LEVELS_IN_BATTLE = 3; // The HP a Potion heals (pret src/data/items.h). constexpr double POTION_HP = 20; +// An item used: the story's count of it goes down, and an item it doesn't +// count takes its row with the last one. +void spend_bag_item(Supplies& supplies, const std::string& item){ + const auto count = supplies.other_counts.find(item); + if (count == supplies.other_counts.end()){ + spend_item(supplies, item); + return; + } + if (--count->second > 0){ + return; + } + supplies.other_counts.erase(count); + const auto row = std::find(supplies.pocket.begin(), supplies.pocket.end(), item); + if (row != supplies.pocket.end()){ + supplies.pocket.erase(row); + } +} + // A trainer's battle: the plan's attack, else the best type matchup // (attack_slot_against()) against the foe out as read at the battle // menu, else against the whole party its plan lists. @@ -162,6 +181,10 @@ BattleDecisions::BattleDecisions(Supplies& supplies, BattleKind kind) if (supplies.lead.level > 0){ m_level_cap = static_cast(std::min(battle_level(supplies.lead) + MAX_LEVELS_IN_BATTLE, 255)); } + // The policy needs the lead's HP and Speed, which its stats give. + if (kind == BattleKind::TRAINER && supplies.policy.kind != BattlePolicyKind::NONE && supplies.lead.stats){ + m_policy.emplace(supplies.policy); + } } TurnAction BattleDecisions::turn(const PartyStatus& status){ @@ -201,6 +224,9 @@ TurnAction BattleDecisions::lead_turn(const PartyStatus& status){ return TurnAction{.choice = TurnChoice::RUN}; } see_hit(status); + if (m_policy){ + return policy_turn(status, {}); + } // Awakenings are kept for trainers: a wild battle with a status is run from. const int awakenings = m_kind == BattleKind::TRAINER ? m_supplies.awakenings : 0; const ItemTurn items = m_items_off ? ItemTurn{} : item_turn(m_supplies, status, m_seen_hit, awakenings); @@ -220,6 +246,40 @@ TurnAction BattleDecisions::lead_turn(const PartyStatus& status){ return action; } +size_t BattleDecisions::track_foe(){ + const std::vector& foes = m_supplies.foes; + for (size_t index = m_foe_index; index < foes.size() && !m_supplies.foe_out.empty(); index++){ + if (foes[index] == m_supplies.foe_out){ + m_foe_index = index; + break; + } + } + return m_foe_index; +} + +TurnAction BattleDecisions::policy_turn(const PartyStatus& status, std::string heal_reason){ + const std::optional hp = lead_hp(m_supplies, status); + const PolicyView view{ + .hp = hp.value_or(static_cast(m_supplies.lead.stats->hp)), + .max_hp = static_cast(m_supplies.lead.stats->hp), + .status = status.status, + .speed = m_supplies.lead.stats->speed, + .foe_index = track_foe(), + }; + std::optional item = m_items_off ? std::nullopt : m_policy->choose(m_supplies, view); + if (!item){ + TurnAction action = move_turn(); + action.heal_reason = std::move(heal_reason); + return action; + } + m_planned_item = item->item; + return TurnAction{ + .choice = item->party_member ? TurnChoice::MEDICINE : TurnChoice::BATTLE_ITEM, + .heal_reason = "policy: " + item->why, + .item = std::move(item->item), + }; +} + void BattleDecisions::see_hit(const PartyStatus& status){ if (m_supplies.foe_out != m_hit_by){ m_seen_hit = 0; @@ -227,13 +287,13 @@ void BattleDecisions::see_hit(const PartyStatus& status){ } const std::optional hp = lead_hp(m_supplies, status); if (hp && m_last_hp){ - const double taken = *m_last_hp + (m_healed ? POTION_HP : 0) - *hp; + const double taken = *m_last_hp + m_healed_hp - *hp; if (taken > 0){ m_seen_hit = taken; } } m_last_hp = hp; - m_healed = false; + m_healed_hp = 0; } // The plan's attack with PP left, or against known foes (a trainer's @@ -278,15 +338,15 @@ void BattleDecisions::planned_item_used(){ break; } } - const auto count = m_supplies.other_counts.find(m_planned_item); - if (count == m_supplies.other_counts.end() || --count->second > 0){ - return; - } - m_supplies.other_counts.erase(count); - const auto row = std::find(m_supplies.pocket.begin(), m_supplies.pocket.end(), m_planned_item); - if (row != m_supplies.pocket.end()){ - m_supplies.pocket.erase(row); - } + spend_bag_item(m_supplies, m_planned_item); +} + +void BattleDecisions::policy_item_used(){ + spend_bag_item(m_supplies, m_planned_item); + m_policy->item_used(m_planned_item); + // A medicine heals up to the bar's end. + const double room = static_cast(m_supplies.lead.stats->hp) - m_last_hp.value_or(0); + m_healed_hp = std::min(medicine_hp(m_planned_item), std::max(0.0, room)); } void BattleDecisions::count_down_refused(){ @@ -328,7 +388,7 @@ void BattleDecisions::turn_done(TurnChoice choice, TurnResult result){ } switch (choice){ case TurnChoice::POTION: - m_healed = true; + m_healed_hp = POTION_HP; m_supplies.potions--; m_supplies.hurt = false; m_supplies.hp_red = false; @@ -340,8 +400,15 @@ void BattleDecisions::turn_done(TurnChoice choice, TurnResult result){ m_supplies.awakenings--; m_supplies.status = StatusCondition::NONE; return; + case TurnChoice::MEDICINE: + policy_item_used(); + return; case TurnChoice::BATTLE_ITEM: - planned_item_used(); + if (m_policy){ + policy_item_used(); + }else{ + planned_item_used(); + } return; case TurnChoice::RUN: case TurnChoice::MOVE: diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h index 167dd3c9ab..e0949c3b13 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h @@ -28,6 +28,7 @@ #include "Common/Cpp/Time.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryBattlePolicy.h" #include "PokemonFRLG_AutoStoryParty.h" #include "PokemonFRLG_AutoStoryBattleTurns.h" @@ -79,6 +80,13 @@ class BattleDecisions{ // The plan's battle item chosen last was used: its quantity and count // go down, and its pocket row goes with the last one the bag had. void planned_item_used(); + // The policy's item chosen last was used. + void policy_item_used(); + // The battle policy's turn, with the lead's HP and speed known: its + // item, or an attack. + TurnAction policy_turn(const PartyStatus& status, std::string heal_reason); + // The foe out, as an index into the step's foes. + size_t track_foe(); // The HP the lead lost since the last turn, from the bar. void see_hit(const PartyStatus& status); void count_down_refused(); @@ -94,6 +102,9 @@ class BattleDecisions{ bool m_items_off = false; // The plan's battle item chosen last. std::string m_planned_item; + // The step's battle policy, if it has one and the lead's stats are read. + std::optional m_policy; + size_t m_foe_index = 0; bool m_lost = false; // NO was answered to "Delete a move?": "Stop learning?" comes next. bool m_declined_delete = false; @@ -103,10 +114,10 @@ class BattleDecisions{ // A YES/NO before the next turn means nothing was forgotten. std::optional m_before_forget; std::optional m_last_move_slot; - // The lead's HP at the last turn, from the bar, and whether a Potion - // was used on it since. + // The lead's HP at the last turn, from the bar, and the HP the + // medicine used on it since heals. std::optional m_last_hp; - bool m_healed = false; + double m_healed_hp = 0; // The HP the last hit seen took, from the foe out `m_hit_by`; 0 if none // was seen. double m_seen_hit = 0; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp new file mode 100644 index 0000000000..a0b1248756 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp @@ -0,0 +1,363 @@ +/* AutoStory Battle Policy + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "PokemonFRLG_AutoStoryBattlePolicy.h" +#include "PokemonFRLG_AutoStoryItemsPocket.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// Thunder Badge: Speed x1.1. Every fight a policy is written for is after Lt. Surge. +constexpr double THUNDER_BADGE = 1.1; +// Guard Spec's Mist lasts this many turns, the one it is used on included. +constexpr int MIST_TURNS = 5; +constexpr int MAX_STAGE = 6; +constexpr double WHOLE_HP = std::numeric_limits::infinity(); + +// The HP medicines, smallest first (the doc's HEALS table). +struct Medicine{ + std::string_view item; + double hp; +}; +constexpr Medicine MEDICINES[] = { + {"potion", 20}, {"super-potion", 50}, {"hyper-potion", 200}, {"max-potion", WHOLE_HP}, {"full-restore", WHOLE_HP}, +}; + +// The cure for a status, by the doc's CURES table; "" for none. +std::string_view cure_of(StatusCondition status){ + switch (status){ + case StatusCondition::SLEEP: + return "awakening"; + case StatusCondition::POISON: + return "antidote"; + case StatusCondition::PARALYSIS: + return "parlyz-heal"; + case StatusCondition::NONE: + case StatusCondition::OTHER: + return ""; + } + return ""; +} + +double stage_multiplier(int stage){ + return stage >= 0 ? (2.0 + stage) / 2.0 : 2.0 / (2.0 - stage); +} + +PolicyItem medicine_item(const std::string& item, std::string why){ + return PolicyItem{.item = item, .party_member = true, .why = std::move(why)}; +} + +PolicyItem setup_item_of(const std::string& item, std::string why){ + return PolicyItem{.item = item, .party_member = false, .why = std::move(why)}; +} + +} // namespace + + +std::optional battle_policy_kind(std::string_view word){ + if (word == "solo-recovery"){ + return BattlePolicyKind::SOLO_RECOVERY; + } + if (word == "goal-based-setup"){ + return BattlePolicyKind::GOAL_BASED_SETUP; + } + return std::nullopt; +} + +std::optional> foe_threats_of(const std::vector>& rows){ + constexpr size_t COLUMNS = 7; + std::vector foes; + for (const std::vector& row : rows){ + if (row.size() != COLUMNS){ + return std::nullopt; + } + foes.push_back(FoeThreat{ + .speed = static_cast(row[0]), + .likely = static_cast(row[1]), + .mean = static_cast(row[2]), + .max = static_cast(row[3]), + .normal_max = static_cast(row[4]), + .lowers_accuracy = row[5] != 0, + .explodes = row[6] != 0, + }); + } + return foes; +} + +BattlePolicy battle_policy_of(const Pokemon::StoryActionArgs& args){ + const std::optional kind = battle_policy_kind(Pokemon::story_arg(args, "policy")); + if (!kind){ + return {}; + } + BattlePolicy policy; + policy.kind = *kind; + policy.goals = SetupGoals{ + .spa = static_cast(Pokemon::story_arg(args, "setup_spa")), + .accuracy = static_cast(Pokemon::story_arg(args, "setup_accuracy")), + .outspeed = Pokemon::story_arg(args, "setup_outspeed"), + .guard_accuracy = Pokemon::story_arg(args, "setup_guard_accuracy"), + .torrent_power = Pokemon::story_arg(args, "setup_torrent_power"), + }; + if (std::optional> foes = foe_threats_of(Pokemon::story_arg>>(args, "foe_threats"))){ + policy.foes = std::move(*foes); + } + return policy; +} + +int bag_count(const Supplies& supplies, std::string_view item){ + const std::string name(item); + const auto other = supplies.other_counts.find(name); + return other != supplies.other_counts.end() ? other->second : item_count(supplies, name); +} + +double medicine_hp(std::string_view item){ + for (const Medicine& medicine : MEDICINES){ + if (medicine.item == item){ + return medicine.hp; + } + } + return 0; +} + + +PolicyState::PolicyState(const BattlePolicy& policy) + : m_policy(policy) +{} + +const FoeThreat* PolicyState::foe(const PolicyView& view) const{ + return view.foe_index < m_policy.foes.size() ? &m_policy.foes[view.foe_index] : nullptr; +} + +PolicyState::Danger PolicyState::danger(const PolicyView& view) const{ + // A poisoned lead also loses 1/8 of its HP to the poison each turn. + const double residual = view.status == StatusCondition::POISON ? std::floor(view.max_hp / 8) : 0; + const FoeThreat* threat = foe(view); + if (threat == nullptr){ + return {residual, residual, residual, residual}; + } + return { + residual + threat->likely, residual + threat->mean, residual + threat->max, residual + threat->normal_max, + }; +} + +int PolicyState::own_speed(const PolicyView& view) const{ + const int badged = static_cast(std::floor(view.speed * THUNDER_BADGE)); + return static_cast(std::floor(badged * stage_multiplier(m_speed))); +} + +bool PolicyState::outsped(const PolicyView& view) const{ + const int own = own_speed(view); + for (size_t index = view.foe_index; index < m_policy.foes.size(); index++){ + if (m_policy.foes[index].speed >= own){ + return false; + } + } + return true; +} + +int PolicyState::spa_goal(const PolicyView& view) const{ + const int target = m_policy.goals.spa; + const bool torrent = view.hp * 3 <= view.max_hp; + if (!m_policy.goals.torrent_power || torrent){ + return target; + } + // The stage whose multiplier makes up for Torrent's 1.5. + const double wanted = 1.5 * (2.0 + target) / 2.0; + for (int stage = target; stage <= MAX_STAGE; stage++){ + if ((2.0 + stage) / 2.0 >= wanted){ + return stage; + } + } + return MAX_STAGE; +} + +int PolicyState::accuracy_goal() const{ + return std::min(MAX_STAGE, m_policy.goals.accuracy + std::max(0, m_foe_evasion)); +} + +std::optional PolicyState::cure(const Supplies& supplies, const PolicyView& view, const Danger& danger) const{ + if (view.hp <= danger.likely){ + return std::nullopt; + } + const std::string_view own_cure = cure_of(view.status); + std::vector candidates; + if (!own_cure.empty()){ + candidates = {own_cure, "full-heal", "full-restore"}; + }else if (view.status == StatusCondition::OTHER){ + candidates = {"full-heal", "full-restore"}; + } + for (const std::string_view item : candidates){ + if (bag_count(supplies, item) > 0){ + return medicine_item(std::string(item), std::format("{} for {}", item, status_name(view.status))); + } + } + return std::nullopt; +} + +std::optional PolicyState::heal(const Supplies& supplies, const PolicyView& view, const Danger& danger) const{ + if (view.hp > std::max(view.max_hp / 2, danger.max)){ + return std::nullopt; + } + const double missing = view.max_hp - view.hp; + for (const Medicine& medicine : MEDICINES){ + const double gained = std::min(medicine.hp, missing); + if (bag_count(supplies, medicine.item) > 0 && gained > danger.likely && gained > 0){ + return medicine_item(std::string(medicine.item), std::format( + "{}: HP {:.0f}/{:.0f}, a turn's loss up to {:.0f}", medicine.item, view.hp, view.max_hp, danger.max + )); + } + } + return std::nullopt; +} + +int PolicyState::setup_turns(const Supplies& supplies, const PolicyView& view, bool guard) const{ + int count = std::min(bag_count(supplies, "x-special"), std::max(0, spa_goal(view) - m_spa)); + count += std::min(bag_count(supplies, "x-accuracy"), std::max(0, accuracy_goal() - m_accuracy)); + if (m_policy.goals.outspeed && !outsped(view) && bag_count(supplies, "x-speed") > 0){ + count++; + } + if (guard){ + count++; + } + return std::max(1, count); +} + +std::optional PolicyState::setup(const Supplies& supplies, const PolicyView& view) const{ + const bool special = m_spa < spa_goal(view) && bag_count(supplies, "x-special") > 0; + const bool speed = m_policy.goals.outspeed && bag_count(supplies, "x-speed") > 0 + && m_speed < MAX_STAGE && !outsped(view); + const bool accuracy = m_accuracy < accuracy_goal() && bag_count(supplies, "x-accuracy") > 0; + if (!special && !speed && !accuracy){ + return std::nullopt; + } + const FoeThreat* threat = foe(view); + if (m_policy.goals.guard_accuracy && bag_count(supplies, "guard-spec") > 0 && m_mist_turns <= 0 + && threat != nullptr && threat->lowers_accuracy + ){ + return setup_item_of("guard-spec", "Guard Spec: the foe lowers accuracy and setup is pending"); + } + if (special){ + return setup_item_of("x-special", std::format("X Special: Sp. Atk +{} of +{}", m_spa, spa_goal(view))); + } + if (speed){ + return setup_item_of("x-speed", std::format("X Speed: Speed {} against the foes left", own_speed(view))); + } + return setup_item_of("x-accuracy", std::format("X Accuracy: accuracy {:+} of {:+}", m_accuracy, accuracy_goal())); +} + +std::optional PolicyState::planning_heal( + const Supplies& supplies, const PolicyView& view, const Danger& danger, int turns +) const{ + // An HP reserve for the setup turns ahead. + const double reserve = std::min(view.max_hp * 0.75, danger.normal_max + std::max(0, turns - 1) * danger.mean); + if (view.hp > danger.normal_max && view.hp >= reserve){ + return std::nullopt; + } + struct Option{ + bool sufficient; + double expected; + double restored; + std::string_view item; + }; + std::vector