From e0906586f34d4e76a1f269888742b11383e08d91 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 23:38:36 -0800 Subject: [PATCH 01/12] FRLG AutoStory: Fly by species opens the party once, party read cached A Fly naming a species read every slot with its own open/close of the start menu, then opened the menu again to fly. A PartyRoster scan now opens the party once, enters slot 1's summary, pages with D-pad down until the species matches, and backs out to that member's menu to pick FLY. The species read are cached in StoryEnv (cleared on a save load and on PC deposit/withdraw), so a later Fly or species TEACH reads no summary. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../AutoStory/PokemonFRLG_AutoStory.cpp | 2 + .../PokemonFRLG_AutoStoryAbilities.cpp | 2 +- .../PokemonFRLG_AutoStoryAbilities.h | 2 + .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 15 +- .../AutoStory/PokemonFRLG_AutoStoryEvents.h | 6 + .../PokemonFRLG_AutoStoryFieldMoves.cpp | 46 ++-- .../PokemonFRLG_AutoStoryFieldMoves.h | 8 +- .../PokemonFRLG_AutoStoryHideout.cpp | 4 +- .../AutoStory/PokemonFRLG_AutoStoryHideout.h | 3 +- .../PokemonFRLG_AutoStoryPartyRoster.cpp | 109 ++++++++ .../PokemonFRLG_AutoStoryPartyRoster.h | 97 +++++++ ...PokemonFRLG_AutoStoryPartyRoster_Tests.cpp | 246 ++++++++++++++++++ .../PokemonFRLG_AutoStorySummary.cpp | 116 ++++++++- .../AutoStory/PokemonFRLG_AutoStorySummary.h | 18 ++ .../AutoStory/PokemonFRLG_AutoStoryTeach.cpp | 7 +- .../AutoStory/PokemonFRLG_AutoStoryTeach.h | 11 +- SerialPrograms/cmake/SourceFiles.cmake | 3 + 18 files changed, 660 insertions(+), 37 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index b96f9aeff5..0bb2198d75 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -52,6 +52,7 @@ #include "Programs/AutoStory/PokemonFRLG_AutoStoryPaceSim.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h" @@ -336,6 +337,7 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& database){ add_tests_AutoStoryVermilionGym(database); add_tests_AutoStoryCeladon(database); add_tests_AutoStorySnorlax(database); + add_tests_AutoStoryPartyRoster(database); add_tests_AutoStorySlope(database); add_tests_AutoStorySafari(database); add_tests_AutoStoryFuchsiaGym(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index dc0d21bdcc..929d1a6244 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -228,6 +228,8 @@ Pokemon::StoryGameHooks story_game(SingleSwitchProgramEnvironment& env, StoryEnv }; game.after_load = [&story](Pokemon::RunState&){ story.supplies = story.saved_supplies; + // The save's party, which a catch or a gift since then changed. + story.party.invalidate(); // Until read in full, so each verify run starts from the bag as // the save holds it, not from a count once read wrong or not at // all (console B, 2026-11-03: 0 Potions in all 3 runs). Once diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp index 6219a617b1..270a1ce9b9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp @@ -25,7 +25,7 @@ Outcome mart(Logger& logger, const MartPlan& plan, StoryAbilities& abilities){ } Outcome teach(Logger& logger, const TeachPlan& plan, StoryAbilities& abilities){ - const TeachResult result = run_teach(logger, abilities.teach, abilities.members, plan); + const TeachResult result = run_teach(logger, abilities.teach, abilities.members, plan, abilities.species); if (result.end == TeachEnd::LEARNED){ return Pokemon::outcome_ok(); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h index add8e48eff..4a8ae431fe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h @@ -36,6 +36,8 @@ struct StoryAbilities{ TeachActions& teach; GrindActions& grind; ChoiceActions& choice; + // Where a TEACH naming a species finds it; empty reads the members in turn. + SpeciesFinder species = {}; }; // A MART, TEACH, LEVEL, GRIND or fossil step with `abilities`: nothing for diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 0100ed32bf..0045a4f642 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -575,12 +575,10 @@ std::optional run_abilities(StoryEnv& env, RunState& state, const Story [&](const GrindSpot& spot){ return grind_heal_trip(env, state, step, patch, spot); }, - [&]{ - pace_trainer_battle(env, state, step, patch); - } + [&]{ pace_trainer_battle(env, state, step, patch); } ); ConsoleChoiceActions choice(env.console, env.context); - StoryAbilities abilities{console_member_reader(env.console, env.context, env.language, StartMenu::FULL), mart, teach, grind, choice}; + StoryAbilities abilities{console_member_reader(env.console, env.context, env.language, StartMenu::FULL), mart, teach, grind, choice, console_species_finder(env.console, env.context, env.language, env.party)}; if (const std::optional plan = step.action == GRIND_CHECK_ACTION ? grind_plan_of(step.args) : std::nullopt){ if (grind_reached_already(env.console.logger(), grind, abilities.members, *plan)){ state.flags.insert(step.name); @@ -698,13 +696,14 @@ Outcome open_gym_door(StoryEnv& env, RunState& state, const StoryStep& step){ // withdrawal, a MART, TEACH, LEVEL, GRIND or fossil CHOICE. Outcome other_game_step(StoryEnv& env, RunState& state, const StoryStep& step){ const Pokemon::Pose patch = state.pose; - ConsoleCaptureActions capture(env.console, env.context, env.language, env.player_gender, [&]{ - pace_trainer_battle(env, state, step, patch); - }); + ConsoleCaptureActions capture(env.console, env.context, env.language, env.player_gender, [&]{ pace_trainer_battle(env, state, step, patch); }); ConsolePcStorageActions pc(env.console, env.context); - std::optional done = run_field_game_step(env.console, env.context, env.language, env.player_gender, step); + std::optional done = run_field_game_step(env.console, env.context, env.language, env.player_gender, step, env.party); if (!done){ done = run_storage_game_step(env.console.logger(), &env.console, step, capture, pc); + if (done){ + env.party.invalidate(); + } } if (!done){ done = run_healing_step(env, state, step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index d03e617838..c9eec936d4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -42,6 +42,7 @@ #include "PokemonFRLG_AutoStoryStepTable.h" #include "PokemonFRLG_AutoStoryCheckpoints.h" #include "PokemonFRLG_AutoStoryPacedRoute.h" +#include "PokemonFRLG_AutoStoryPartyRoster.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -93,6 +94,11 @@ struct StoryEnv{ // The Items pocket's counts a count_items step kept // (PokemonFRLG_AutoStorySlopeRun.h), for the next to compare. std::map counted_items = {}; + // The species the party's summaries were read as, for a Fly or a TEACH + // that names one. Emptied when a save is loaded and when a PC deposit + // or withdrawal moves members; a catch or a gift adds one at the end, + // so the slots read stay right. + PartyCache party = {}; }; // After a save is loaded for a checkpoint that starts on `start_map`: the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp index acd43830b3..75f78b86b0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp @@ -5,6 +5,7 @@ */ #include +#include #include "CommonTools/Async/InferenceRoutines.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "Pokemon/AutoStory/Pokemon_StoryInterrupts.h" @@ -20,6 +21,7 @@ #include "PokemonFRLG_AutoStoryGameArgs.h" #include "PokemonFRLG_AutoStoryQuietOverworld.h" #include "PokemonFRLG_AutoStoryStepInterrupts.h" +#include "PokemonFRLG_AutoStorySummary.h" #include "PokemonFRLG_AutoStoryTeach.h" namespace PokemonAutomation{ @@ -129,6 +131,19 @@ void tap_dpad(ProControllerContext& context, DpadPosition dpad, size_t count, Mi } } +// From the Fly user's menu: FLY, to the fly map. Returns the failure, or empty. +std::string fly_from_member_menu(ConsoleHandle& console, ProControllerContext& context, const FlyPlan& plan){ + tap_dpad(context, DPAD_DOWN, plan.menu_row, MENU_TAP, MENU_TAP_RELEASE); + KantoMapWatcher fly_map(COLOR_RED); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_A, 160ms, 0ms); + if (wait_until(console, context, FLY_MAP_TIMEOUT, {fly_map}) < 0){ + return "fly_no_map"; + } + pbf_wait(context, FLY_MAP_SETTLE); + return ""; +} + // 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. @@ -144,15 +159,7 @@ std::string open_fly_map(ConsoleHandle& console, ProControllerContext& context, if (wait_until(console, context, MON_MENU_TIMEOUT, {mon_menu}) < 0){ return "fly_no_menu"; } - tap_dpad(context, DPAD_DOWN, plan.menu_row, MENU_TAP, MENU_TAP_RELEASE); - KantoMapWatcher fly_map(COLOR_RED); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_A, 160ms, 0ms); - if (wait_until(console, context, FLY_MAP_TIMEOUT, {fly_map}) < 0){ - return "fly_no_map"; - } - pbf_wait(context, FLY_MAP_SETTLE); - return ""; + return fly_from_member_menu(console, context, plan); } // On the fly map: the cursor to the corner, then to the town, and A. @@ -185,7 +192,7 @@ std::string fly_to_town(ConsoleHandle& console, ProControllerContext& context, c } // namespace std::optional run_field_move_step( - ConsoleHandle& console, ProControllerContext& context, Language language, const StoryStep& step + ConsoleHandle& console, ProControllerContext& context, Language language, const StoryStep& step, PartyCache& party ){ const auto done = [&step]{ return step.pose_after ? Pokemon::outcome_ok(Pokemon::pose_of(*step.pose_after)) : Pokemon::outcome_ok(); @@ -200,17 +207,24 @@ std::optional run_field_move_step( return std::nullopt; } const FlyTown& town = kanto_fly_towns()[plan->town]; - const std::optional slot = plan->party_slot(console_member_reader(console, context, language, plan->start_menu)); - if (!slot){ - console.log(std::format("Story: no {} read in the party to Fly with.", plan->species), COLOR_RED); - return Pokemon::outcome_failed("fly_no_member", plan->species); + // With a species, the party is opened once: the scan (or the cache) + // leaves the Fly user's menu open. + bool menu_open = false; + if (!plan->species.empty()){ + const std::unique_ptr screens = console_party_screens(console, context, plan->start_menu, language); + const std::optional slot = open_member_menu_of(console.logger(), *screens, party, plan->species, true); + if (!slot){ + console.log(std::format("Story: no {} read in the party to Fly with.", plan->species), COLOR_RED); + return Pokemon::outcome_failed("fly_no_member", plan->species); + } + plan->slot = *slot; + menu_open = true; } - plan->slot = *slot; console.log(std::format( "Story: Fly with slot {}, menu row {}, to {} (cell {}, {}).", plan->slot + 1, plan->menu_row + 1, town.name, town.cell.x, town.cell.y )); - std::string failure = open_fly_map(console, context, *plan); + std::string failure = menu_open ? fly_from_member_menu(console, context, *plan) : open_fly_map(console, context, *plan); if (failure.empty()){ failure = fly_to_town(console, context, town); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.h index 6a7bb54af5..366b691d83 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.h @@ -25,6 +25,7 @@ #include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" #include "PokemonFRLG_AutoStoryMemberInfo.h" +#include "PokemonFRLG_AutoStoryPartyRoster.h" #include "PokemonFRLG_AutoStoryStartMenu.h" namespace PokemonAutomation{ @@ -73,9 +74,12 @@ bool is_field_move_step(const Pokemon::StoryStep& step); std::vector field_move_specs(); // On the console, a step of this file's; nothing for another step. The -// step ends on its pose_after, if it has one. +// step ends on its pose_after, if it has one. A Fly naming a species opens +// the party once and goes to the Fly user's menu from there; `party` +// keeps the species read, so a later Fly reads no summary. std::optional run_field_move_step( - ConsoleHandle& console, ProControllerContext& context, Language language, const Pokemon::StoryStep& step + ConsoleHandle& console, ProControllerContext& context, Language language, const Pokemon::StoryStep& step, + PartyCache& party ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHideout.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHideout.cpp index bbcb4bf697..5440a7a789 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHideout.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHideout.cpp @@ -183,7 +183,7 @@ void push_poster_switch(ConsoleHandle& console, ProControllerContext& context){ std::optional run_field_game_step( ConsoleHandle& console, ProControllerContext& context, Language language, PlayerGender player, - const Pokemon::StoryStep& step + const Pokemon::StoryStep& step, PartyCache& party ){ const auto done = [&step]{ return step.pose_after ? Pokemon::outcome_ok(Pokemon::pose_of(*step.pose_after)) : Pokemon::outcome_ok(); @@ -192,7 +192,7 @@ std::optional run_field_game_step( ride_lift(console, context, *ride, player); return done(); } - if (std::optional moved = run_field_move_step(console, context, language, step)){ + if (std::optional moved = run_field_move_step(console, context, language, step, party)){ return moved; } if (is_center_variant(step.action)){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHideout.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHideout.h index 780f652d4d..5e1b50afc1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHideout.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryHideout.h @@ -26,6 +26,7 @@ #include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" #include "Pokemon/Navigation/Pokemon_Grid.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h" +#include "PokemonFRLG_AutoStoryPartyRoster.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -66,7 +67,7 @@ void push_poster_switch(ConsoleHandle& console, ProControllerContext& context); // has one (an Escape Rope's, a lift ride's, a Center's). std::optional run_field_game_step( ConsoleHandle& console, ProControllerContext& context, Language language, PlayerGender player, - const Pokemon::StoryStep& step + const Pokemon::StoryStep& step, PartyCache& party ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp new file mode 100644 index 0000000000..cef08a00a6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp @@ -0,0 +1,109 @@ +/* AutoStory Party Roster + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Color.h" +#include "PokemonFRLG_AutoStoryPartyRoster.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void PartyCache::invalidate(){ + m_species.clear(); +} + +void PartyCache::store(std::vector species){ + m_species = std::move(species); +} + +std::optional PartyCache::find(std::string_view species) const{ + for (size_t slot = 0; slot < m_species.size(); slot++){ + if (m_species[slot] == species){ + return slot; + } + } + return std::nullopt; +} + + +namespace{ + +// With the party open: the summaries paged through until one reads as +// `species`, left on its summary. The species read are in `read`. +std::optional scan_summaries( + PartyScreens& screens, size_t members, std::string_view species, std::vector& read +){ + if (!screens.enter_summary()){ + return std::nullopt; + } + for (size_t slot = 0; slot < members; slot++){ + if (slot > 0 && !screens.next_member()){ + return std::nullopt; + } + const std::string seen = screens.read_species(); + if (seen.empty()){ + return std::nullopt; + } + read.push_back(seen); + if (seen == species){ + return slot; + } + } + return std::nullopt; +} + +} // namespace + + +std::optional open_member_menu_of( + Logger& logger, PartyScreens& screens, PartyCache& cache, std::string_view species, bool keep_menu +){ + const std::optional known = cache.find(species); + if (known && !keep_menu){ + logger.log(std::format("Party: the {} is slot {} (read earlier in this checkpoint).", species, *known + 1)); + return known; + } + size_t members = 0; + if (!screens.open_party(members)){ + logger.log("Party: the menu didn't open.", COLOR_RED); + return std::nullopt; + } + if (known){ + logger.log(std::format("Party: the {} is slot {} (read earlier in this checkpoint).", species, *known + 1)); + if (screens.open_member_menu(*known)){ + return known; + } + logger.log("Party: the member's menu didn't open.", COLOR_RED); + screens.close(); + return std::nullopt; + } + std::vector read; + const std::optional slot = scan_summaries(screens, members, species, read); + if (!slot){ + logger.log(std::format("Party: no {} among the {} read.", species, read.size()), COLOR_RED); + screens.close(); + return std::nullopt; + } + cache.store(std::move(read)); + logger.log(std::format("Party: the {} is slot {}.", species, *slot + 1)); + if (!screens.leave_summary()){ + logger.log("Party: the summary didn't close to the member's menu.", COLOR_RED); + screens.close(); + return std::nullopt; + } + if (!keep_menu){ + screens.close(); + } + return slot; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h new file mode 100644 index 0000000000..8e9ac8d03a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h @@ -0,0 +1,97 @@ +/* AutoStory Party Roster + * + * From: https://github.com/PokemonAutomation/ + * + * Which party slot holds a species, found with the party opened once. + * The scan opens the party, enters slot 1's summary and pages down with + * the D-pad, reading each member's species until one matches. In the + * summary's first page (pokefirered pokemon_summary_screen.c, + * SeekToNextMonInSingleParty()), DOWN goes to the next party member, eggs + * included, and does nothing on the last one: it never wraps, so the + * party's size bounds the scan. Leaving the summary returns to the party + * menu with the cursor on the last viewed member and that member's menu + * open again (CB2_ReturnToPartyMenuFromSummaryScreen(): slotId = + * GetLastViewedMonIndex(), Task_TryCreateSelectionWindow), so a field + * move is picked from there without closing anything. + * + * The species read are kept in a PartyCache for the checkpoint: the next + * lookup of a species in it opens the party once and goes straight to the + * slot, with no summary read. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryPartyRoster_H +#define PokemonAutomation_PokemonFRLG_AutoStoryPartyRoster_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The species of the first party slots as the last scan read them. +class PartyCache{ +public: + // Forget the party: it changed (a catch, a gift, a deposit or + // withdrawal) or a new checkpoint starts. + void invalidate(); + // Keep `species` as slots 0, 1, ... + void store(std::vector species); + // The first slot read as `species`; nothing if none, or no scan yet. + std::optional find(std::string_view species) const; + +private: + std::vector m_species; +}; + + +// The screens a scan goes through, from the overworld. +class PartyScreens{ +public: + virtual ~PartyScreens() = default; + // Open the party menu with the cursor on the lead. Gives the number + // of members; false if it didn't open. + virtual bool open_party(size_t& members) = 0; + // Slot 1's summary, first page; false if it didn't show. + virtual bool enter_summary() = 0; + // The species slug on the summary now shown; empty if not read. + virtual std::string read_species() = 0; + // D-pad down to the next member's summary; false if it didn't change. + virtual bool next_member() = 0; + // Back out of the summary to the party menu: the member's menu is + // open. False if it didn't show. + virtual bool leave_summary() = 0; + // From the party menu on the lead: slot `slot`'s menu opened. + virtual bool open_member_menu(size_t slot) = 0; + // Back to the overworld from wherever the party menu is. + virtual void close() = 0; +}; + + +// The party opened once and left on the menu of the first member read as +// `species`, whose slot is given; from the cache, with no summary read, if +// it knows the species. With `keep_menu` false the slot is only found: from +// the cache, nothing is opened; otherwise the party is closed again before +// it returns. If no member reads as `species`, or a screen didn't show, the +// party is closed and the result is nothing; a failed scan leaves the cache +// as it was. +std::optional open_member_menu_of( + Logger& logger, PartyScreens& screens, PartyCache& cache, std::string_view species, bool keep_menu +); + + +// Registers this file's tests (PokemonFRLG_AutoStoryPartyRoster_Tests.cpp). +void add_tests_AutoStoryPartyRoster(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp new file mode 100644 index 0000000000..0fd96945b4 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp @@ -0,0 +1,246 @@ +/* AutoStory Party Roster Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Counts the screens a species lookup goes through, on a fake party. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryPartyRoster.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// A party that counts what is opened and read. +class FakeParty : public PartyScreens{ +public: + explicit FakeParty(std::vector species) + : m_species(std::move(species)) + {} + + virtual bool open_party(size_t& members) override{ + members = m_species.size(); + m_party_opens++; + return true; + } + virtual bool enter_summary() override{ + m_summary_opens++; + m_shown = 0; + return true; + } + virtual std::string read_species() override{ + m_reads++; + return m_species[m_shown]; + } + virtual bool next_member() override{ + // The game's DOWN does nothing on the last member. + if (m_shown + 1 < m_species.size()){ + m_shown++; + } + return true; + } + virtual bool leave_summary() override{ + m_menu_slot = m_shown; + return true; + } + virtual bool open_member_menu(size_t slot) override{ + m_menu_slot = slot; + return true; + } + virtual void close() override{ + m_closes++; + m_menu_slot = SIZE_MAX; + } + + std::vector m_species; + size_t m_shown = 0; + size_t m_menu_slot = SIZE_MAX; + size_t m_party_opens = 0; + size_t m_summary_opens = 0; + size_t m_reads = 0; + size_t m_closes = 0; +}; + +UnitTestResult check_counts( + const std::string& what, const FakeParty& party, + size_t party_opens, size_t summary_opens, size_t reads, size_t closes +){ + if (party.m_party_opens != party_opens || party.m_summary_opens != summary_opens + || party.m_reads != reads || party.m_closes != closes + ){ + return std::format( + "{}: {} party opens, {} summary entries, {} summary reads, {} closes; expected {}, {}, {}, {}.", + what, party.m_party_opens, party.m_summary_opens, party.m_reads, party.m_closes, + party_opens, summary_opens, reads, closes + ); + } + return true; +} + +// A Fly naming the Pidgey: one party open, the summaries up to the +// Pidgey read once, the member's menu left open for FLY. +UnitTestResult test_first_lookup_opens_party_once(Logger& logger){ + FakeParty party({"blastoise", "oddish", "pidgey", "eevee"}); + PartyCache cache; + const std::optional slot = open_member_menu_of(logger, party, cache, "pidgey", true); + if (slot != size_t(2) || party.m_menu_slot != 2){ + return "the Pidgey isn't found at slot 3 with its menu open."; + } + return check_counts("first lookup", party, 1, 1, 3, 0); +} + +// The second Fly in the checkpoint: one party open and no summary read. +UnitTestResult test_second_lookup_reads_nothing(Logger& logger){ + FakeParty party({"blastoise", "oddish", "pidgey", "eevee"}); + PartyCache cache; + open_member_menu_of(logger, party, cache, "pidgey", true); + FakeParty again({"blastoise", "oddish", "pidgey", "eevee"}); + const std::optional slot = open_member_menu_of(logger, again, cache, "pidgey", true); + if (slot != size_t(2) || again.m_menu_slot != 2){ + return "the cached Pidgey isn't found at slot 3 with its menu open."; + } + return check_counts("second lookup", again, 1, 0, 0, 0); +} + +// A member the scan passed is cached too; one it never reached is read for. +UnitTestResult test_cache_holds_what_was_read(Logger& logger){ + FakeParty party({"blastoise", "oddish", "pidgey", "eevee"}); + PartyCache cache; + open_member_menu_of(logger, party, cache, "pidgey", true); + FakeParty second({"blastoise", "oddish", "pidgey", "eevee"}); + if (open_member_menu_of(logger, second, cache, "oddish", true) != size_t(1)){ + return "the Oddish, read on the way to the Pidgey, isn't found."; + } + if (UnitTestResult result = check_counts("cached passed-by member", second, 1, 0, 0, 0); result.result != UnitTestResult::PASSED){ + return result; + } + FakeParty third({"blastoise", "oddish", "pidgey", "eevee"}); + if (open_member_menu_of(logger, third, cache, "eevee", true) != size_t(3)){ + return "the Eevee, past the cache, isn't found."; + } + return check_counts("species past the cache", third, 1, 1, 4, 0); +} + +// A changed party: invalidate() makes the next lookup read again. +UnitTestResult test_invalidate_reads_again(Logger& logger){ + FakeParty party({"blastoise", "oddish", "pidgey"}); + PartyCache cache; + open_member_menu_of(logger, party, cache, "pidgey", true); + cache.invalidate(); + FakeParty caught({"blastoise", "pidgey", "oddish"}); + if (open_member_menu_of(logger, caught, cache, "pidgey", true) != size_t(1)){ + return "after invalidate(), the Pidgey isn't found at its new slot 2."; + } + return check_counts("after invalidate", caught, 1, 1, 2, 0); +} + +// No such member: the scan stops at the party's size (DOWN doesn't wrap) +// and the party is closed. +UnitTestResult test_missing_species_closes(Logger& logger){ + FakeParty party({"blastoise", "oddish"}); + PartyCache cache; + if (open_member_menu_of(logger, party, cache, "pidgey", true).has_value()){ + return "found a Pidgey in a party without one."; + } + return check_counts("missing species", party, 1, 1, 2, 1); +} + +// The first of two of a species wins, and the scan stops there. +UnitTestResult test_first_duplicate_wins(Logger& logger){ + FakeParty party({"pidgey", "oddish", "pidgey"}); + PartyCache cache; + if (open_member_menu_of(logger, party, cache, "pidgey", true) != size_t(0)){ + return "the first Pidgey isn't the one found."; + } + return check_counts("duplicates", party, 1, 1, 1, 0); +} + +// Teach and the like want the overworld back: the menu is closed after. +UnitTestResult test_closes_when_not_kept(Logger& logger){ + FakeParty party({"blastoise", "pidgey"}); + PartyCache cache; + if (open_member_menu_of(logger, party, cache, "pidgey", false) != size_t(1)){ + return "the Pidgey isn't found."; + } + return check_counts("closing lookup", party, 1, 1, 2, 1); +} + +// The slot alone, for a TEACH, from the cache: nothing opened at all. +UnitTestResult test_cached_slot_opens_nothing(Logger& logger){ + FakeParty party({"blastoise", "pidgey"}); + PartyCache cache; + open_member_menu_of(logger, party, cache, "pidgey", true); + FakeParty again({"blastoise", "pidgey"}); + if (open_member_menu_of(logger, again, cache, "pidgey", false) != size_t(1)){ + return "the cached Pidgey isn't found."; + } + return check_counts("cached slot only", again, 0, 0, 0, 0); +} + +struct AutoStoryPartyRosterInput{ + std::string name; + std::function body; +}; + +struct AutoStoryPartyRosterExpectation{ +}; + +struct AutoStoryPartyRosterCase{ + AutoStoryPartyRosterInput input; + AutoStoryPartyRosterExpectation expectation; +}; + +class Test_AutoStoryPartyRoster : public UnitTest{ +public: + explicit Test_AutoStoryPartyRoster(AutoStoryPartyRosterCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStory - Party roster: {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + } + } + +private: + AutoStoryPartyRosterCase m_case; +}; + +const AutoStoryPartyRosterCase AUTO_STORY_PARTY_ROSTER_CASES[] = { + {.input = {"a Fly by species opens the party once", test_first_lookup_opens_party_once}, .expectation = {}}, + {.input = {"the second Fly reads no summary", test_second_lookup_reads_nothing}, .expectation = {}}, + {.input = {"the cache holds the members read on the way", test_cache_holds_what_was_read}, .expectation = {}}, + {.input = {"invalidate() reads the party again", test_invalidate_reads_again}, .expectation = {}}, + {.input = {"a missing species closes the party", test_missing_species_closes}, .expectation = {}}, + {.input = {"the first of two of a species wins", test_first_duplicate_wins}, .expectation = {}}, + {.input = {"a lookup that doesn't keep the menu closes it", test_closes_when_not_kept}, .expectation = {}}, + {.input = {"a cached slot for a TEACH opens nothing", test_cached_slot_opens_nothing}, .expectation = {}}, +}; + +} // namespace + + +void add_tests_AutoStoryPartyRoster(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_PARTY_ROSTER_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp index 4ba5e94cf7..4f0bbb79b0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp @@ -58,19 +58,28 @@ std::optional skills_stats(ConsoleHandle& console, Language language, con }; } -// From the party menu with the cursor on the member: its summary, read. -std::optional read_open_summary(ConsoleHandle& console, ProControllerContext& context, Language language){ +// From the party menu with the cursor on the member: its summary's first +// page shown. +bool open_summary(ConsoleHandle& console, ProControllerContext& context){ PartySelectionWatcher submenu(COLOR_RED); press(context, BUTTON_A); if (!wait_drawn(console, context, submenu, 5000ms)){ console.log("Summary: the party member's menu didn't show.", COLOR_ORANGE); - return std::nullopt; + return false; } // SUMMARY, the menu's top row. SummaryWatcher info(COLOR_RED); press(context, BUTTON_A); if (!wait_drawn(console, context, info, 5000ms)){ console.log("Summary: the summary's first page didn't show.", COLOR_ORANGE); + return false; + } + return true; +} + +// From the party menu with the cursor on the member: its summary, read. +std::optional read_open_summary(ConsoleHandle& console, ProControllerContext& context, Language language){ + if (!open_summary(console, context)){ return std::nullopt; } SummaryRead read; @@ -108,8 +117,109 @@ std::optional read_open_summary(ConsoleHandle& console, ProControll return read; } + +// The member switch (DOWN on the summary's first page): the sprite and +// text are redrawn over a few frames. +constexpr Milliseconds MEMBER_SWITCH_SETTLE = 900ms; +constexpr size_t SPECIES_READ_TRIES = 3; + +class ConsolePartyScreens : public PartyScreens{ +public: + ConsolePartyScreens(ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language) + : m_console(console) + , m_context(context) + , m_menu(menu) + , m_language(language) + {} + + virtual bool open_party(size_t& members) override{ + if (m_menu == StartMenu::BEFORE_POKEMON){ + return false; + } + open_party_menu_from_overworld(m_console, m_context, start_menu_context(m_menu)); + m_context.wait_for_all_requests(); + // The cursor on the lead, as read_party_summary() does. + tap(m_context, DPAD_LEFT); + m_context.wait_for_all_requests(); + members = size_t(detect_last_occupied_party_slot(m_console)) + 1; + return true; + } + + virtual bool enter_summary() override{ + return open_summary(m_console, m_context); + } + + virtual std::string read_species() override{ + for (size_t c = 0; c < SPECIES_READ_TRIES; c++){ + if (VideoSnapshot screen = m_console.video().snapshot()){ + PokemonFRLG_Stats stats; + StatsReader().read_page1(m_console, m_language, screen, stats); + if (!stats.name.empty()){ + return stats.name; + } + } + pbf_wait(m_context, 400ms); + m_context.wait_for_all_requests(); + } + return ""; + } + + virtual bool next_member() override{ + tap(m_context, DPAD_DOWN, 0ms); + pbf_wait(m_context, MEMBER_SWITCH_SETTLE); + m_context.wait_for_all_requests(); + return true; + } + + virtual bool leave_summary() override{ + PartySelectionWatcher menu(COLOR_RED); + // The party menu comes back with the member's menu open + // (pokefirered party_menu.c, CB2_ReturnToPartyMenuFromSummaryScreen()). + press(m_context, BUTTON_B); + return wait_drawn(m_console, m_context, menu, 5000ms); + } + + virtual bool open_member_menu(size_t slot) override{ + for (size_t c = 0; c < slot; c++){ + tap(m_context, DPAD_DOWN); + } + return open_menu_on_cursor(); + } + + virtual void close() override{ + mash_until_overworld(m_console, m_context, 20000ms); + } + +private: + bool open_menu_on_cursor(){ + PartySelectionWatcher menu(COLOR_RED); + press(m_context, BUTTON_A); + return wait_drawn(m_console, m_context, menu, 5000ms); + } + + ConsoleHandle& m_console; + ProControllerContext& m_context; + StartMenu m_menu; + Language m_language; +}; + } // namespace +std::unique_ptr console_party_screens( + ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language +){ + return std::make_unique(console, context, menu, language); +} + +SpeciesFinder console_species_finder( + ConsoleHandle& console, ProControllerContext& context, Language language, PartyCache& party +){ + return [&console, &context, language, &party](std::string_view species){ + const std::unique_ptr screens = console_party_screens(console, context, StartMenu::FULL, language); + return open_member_menu_of(console.logger(), *screens, party, species, false); + }; +} + std::optional read_party_summary( ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language, size_t slot ){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h index 0fd32999f7..6a8d0e3d90 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h @@ -12,6 +12,7 @@ #define PokemonAutomation_PokemonFRLG_AutoStorySummary_H #include +#include #include #include #include @@ -20,6 +21,8 @@ #include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.h" #include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryPartyRoster.h" +#include "PokemonFRLG_AutoStoryTeach.h" #include "PokemonFRLG_AutoStoryStats.h" namespace PokemonAutomation{ @@ -50,6 +53,21 @@ std::optional read_party_summary( ); +// The console's screens for a PartyRoster scan, from the overworld with +// START menu `menu`: the party opened once, the summaries paged with DOWN, +// the member's menu left open (see PokemonFRLG_AutoStoryPartyRoster.h). +// The summary's member switch (DOWN) is waited out with a fixed settle, +// not measured on the console. +std::unique_ptr console_party_screens( + ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language +); + +// Where a TEACH finds a species' slot from the full START menu: from +// `party` if it knows it; else a scan, with the party closed after. +SpeciesFinder console_species_finder( + ConsoleHandle& console, ProControllerContext& context, Language language, PartyCache& party +); + } // namespace PokemonFRLG } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp index a3eb82c424..0c1add818c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp @@ -336,10 +336,13 @@ std::optional find_party_species(const MemberReader& reader, std::string return std::nullopt; } -TeachResult run_teach(Logger& logger, TeachActions& actions, const MemberReader& reader, const TeachPlan& plan){ +TeachResult run_teach( + Logger& logger, TeachActions& actions, const MemberReader& reader, const TeachPlan& plan, + const SpeciesFinder& find_species +){ TeachPlan found = plan; if (!plan.species.empty()){ - const std::optional slot = find_party_species(reader, plan.species); + const std::optional slot = find_species ? find_species(plan.species) : find_party_species(reader, plan.species); if (!slot){ const TeachResult result{.end = TeachEnd::UNREAD, .detail = std::format("no {} read in the party", plan.species)}; logger.log(std::format("Teach {} ({}) to the {}: {}.", plan.move, plan.item, plan.species, result.detail), COLOR_RED); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h index 08d418d90e..ca8322811f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h @@ -49,6 +49,7 @@ #define PokemonAutomation_PokemonFRLG_AutoStoryTeach_H #include +#include #include #include #include @@ -94,9 +95,15 @@ struct TeachResult{ // party). std::optional find_party_species(const MemberReader& reader, std::string_view species); +// Finds the party slot of a species; nothing if none reads as it. +using SpeciesFinder = std::function(std::string_view species)>; + // From the overworld: reads the member, teaches as `plan` says, back to -// the overworld, and reads the member again to confirm. -TeachResult run_teach(Logger& logger, TeachActions& actions, const MemberReader& reader, const TeachPlan& plan); +// the overworld, and reads the member again to confirm. A plan naming a +// species finds its slot with `find_species` if given (the console's opens the +// party once, or not at all from its cache), else by reading the members in turn +// (find_party_species()). +TeachResult run_teach(Logger& logger, TeachActions& actions, const MemberReader& reader, const TeachPlan& plan, const SpeciesFinder& find_species = {}); // Formats a log message summarizing the move teaching result. std::string teach_message(const TeachPlan& plan, const TeachResult& result); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index f737b94097..8447335c6e 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2154,6 +2154,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTower_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySnorlax_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySlope.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySlope.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySlopeMessage.h @@ -2232,6 +2233,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameStore.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.cpp From d3e6fea34f41f28cb42aa4d4fa334d2c80a312ee Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 00:08:23 -0800 Subject: [PATCH 02/12] FRLG AutoStory: remember who uses each field move, Fly goes to that slot A TEACH of an HM or field move (Fly, Surf, Strength, Cut, Flash, Rock Smash, Dig...) records the move's user, slot and species, in the story state next to the saved supplies: a save keeps a copy, a load restores it, a PC deposit or withdrawal clears it. A Fly naming a species opens the party, picks the recorded slot and the FLY row, and reads no summary. If that menu does not give Fly, the party is closed, the record dropped, and the #453 scan finds the member and records it again; a scan records what it finds for the next Fly. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStory.cpp | 3 +- .../PokemonFRLG_AutoStoryAbilities.cpp | 5 + .../PokemonFRLG_AutoStoryAbilities.h | 3 + .../PokemonFRLG_AutoStoryAbilities_Tests.cpp | 60 ++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 3 +- .../AutoStory/PokemonFRLG_AutoStoryEvents.h | 10 +- .../PokemonFRLG_AutoStoryFieldMoveUsers.cpp | 41 ++++++++ .../PokemonFRLG_AutoStoryFieldMoveUsers.h | 50 ++++++++++ .../PokemonFRLG_AutoStoryFieldMoves.cpp | 31 +++--- .../PokemonFRLG_AutoStoryPartyRoster.cpp | 61 ++++++++++++ .../PokemonFRLG_AutoStoryPartyRoster.h | 32 ++++++- ...PokemonFRLG_AutoStoryPartyRoster_Tests.cpp | 95 +++++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryTeach.cpp | 11 +++ .../AutoStory/PokemonFRLG_AutoStoryTeach.h | 8 ++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 15 files changed, 396 insertions(+), 19 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 929d1a6244..d29bf04586 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -229,7 +229,8 @@ Pokemon::StoryGameHooks story_game(SingleSwitchProgramEnvironment& env, StoryEnv game.after_load = [&story](Pokemon::RunState&){ story.supplies = story.saved_supplies; // The save's party, which a catch or a gift since then changed. - story.party.invalidate(); + story.party.invalidate_species(); + story.party.users() = story.saved_field_moves; // Until read in full, so each verify run starts from the bag as // the save holds it, not from a count once read wrong or not at // all (console B, 2026-11-03: 0 Potions in all 3 runs). Once diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp index 270a1ce9b9..a8584ae77b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp @@ -26,6 +26,11 @@ Outcome mart(Logger& logger, const MartPlan& plan, StoryAbilities& abilities){ Outcome teach(Logger& logger, const TeachPlan& plan, StoryAbilities& abilities){ const TeachResult result = run_teach(logger, abilities.teach, abilities.members, plan, abilities.species); + if ((result.end == TeachEnd::LEARNED || result.end == TeachEnd::ALREADY_KNOWN) && abilities.party != nullptr && is_field_move(plan.move)){ + const std::string& species = result.species.empty() ? plan.species : result.species; + logger.log(std::format("Party: {} is used by slot {} ({}).", plan.move, result.member + 1, species.empty() ? "species unread" : species)); + abilities.party->users().record(plan.move, result.member, species); + } if (result.end == TeachEnd::LEARNED){ return Pokemon::outcome_ok(); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h index 4a8ae431fe..df10a48840 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h @@ -22,6 +22,7 @@ #include "PokemonFRLG_AutoStoryGrind.h" #include "PokemonFRLG_AutoStoryMart.h" #include "PokemonFRLG_AutoStoryMember.h" +#include "PokemonFRLG_AutoStoryPartyRoster.h" #include "PokemonFRLG_AutoStoryTeach.h" namespace PokemonAutomation{ @@ -38,6 +39,8 @@ struct StoryAbilities{ ChoiceActions& choice; // Where a TEACH naming a species finds it; empty reads the members in turn. SpeciesFinder species = {}; + // Where a TEACH of a field move records who learned it; none records nothing. + PartyCache* party = nullptr; }; // A MART, TEACH, LEVEL, GRIND or fossil step with `abilities`: nothing for diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp index 5763b66376..310b846e29 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -199,6 +199,62 @@ UnitTestResult test_once_per_save_steps(){ } +// A party whose screens count the summaries read. +class CountingScreens : public PartyScreens{ +public: + virtual bool open_party(size_t& members) override{ members = 2; m_opens++; return true; } + virtual bool enter_summary() override{ m_summaries++; return true; } + virtual std::string read_species() override{ m_summaries++; return "squirtle"; } + virtual bool next_member() override{ return true; } + virtual bool leave_summary() override{ return true; } + virtual bool open_member_menu(size_t slot) override{ m_menu = slot; return true; } + virtual void close() override{} + + size_t m_opens = 0; + size_t m_summaries = 0; + size_t m_menu = SIZE_MAX; +}; + +// A TEACH of a field move records its user; the Fly after it opens the +// party once, at that slot, and reads no summary, though the species +// cache was emptied by a reload. A TEACH of a plain TM records nothing. +UnitTestResult test_teach_records_fly_user(){ + StubGame game; + QuietLogger logger; + const MemberReader members = [](size_t slot) -> std::optional{ + if (slot != 0){ + return std::nullopt; + } + return MemberInfo{.species = "squirtle", .level = 16, .moves = {"water-gun", "surf"}}; + }; + PartyCache party; + StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils, {}, &party}; + run_ability_game_step(logger, nullptr, teach_step("teach_surf", "", {.item = "hm03", .move = "surf", .member = 0}), abilities); + run_ability_game_step(logger, nullptr, teach_step("teach_tm", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), abilities); + const std::optional user = party.users().find("surf"); + if (!user || user->slot != 0 || user->species != "squirtle"){ + return "the Surf user isn't recorded as slot 1, squirtle."; + } + if (party.users().find("water-pulse")){ + return "a TM move was recorded as a field move."; + } + party.invalidate_species(); + CountingScreens screens; + size_t flights = 0; + const std::string failure = use_field_move(logger, screens, party, "surf", "squirtle", [&flights]{ + flights++; + return std::string(); + }); + if (!failure.empty() || flights != 1 || screens.m_menu != 0 || screens.m_opens != 1 || screens.m_summaries != 0){ + return std::format( + "Fly after TEACH: failure '{}', {} flights, menu {}, {} party opens, {} summary reads.", + failure, flights, screens.m_menu, screens.m_opens, screens.m_summaries + ); + } + return true; +} + + // A shiny in a GRIND stops the program, not the checkpoint: a reload // would lose it. UnitTestResult test_grind_shiny_stops(){ @@ -246,6 +302,10 @@ const AutoStoryAbilitiesCase AUTO_STORY_ABILITIES_CASES[] = { .input = {"a shiny in a GRIND stops the program", test_grind_shiny_stops}, .expectation = {}, }, + { + .input = {"a Fly after a TEACH reads no summary", test_teach_records_fly_user}, + .expectation = {}, + }, { .input = {"the LEVEL step's args", test_level_args}, .expectation = {}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 0045a4f642..365155b133 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -578,7 +578,7 @@ std::optional run_abilities(StoryEnv& env, RunState& state, const Story [&]{ pace_trainer_battle(env, state, step, patch); } ); ConsoleChoiceActions choice(env.console, env.context); - StoryAbilities abilities{console_member_reader(env.console, env.context, env.language, StartMenu::FULL), mart, teach, grind, choice, console_species_finder(env.console, env.context, env.language, env.party)}; + StoryAbilities abilities{console_member_reader(env.console, env.context, env.language, StartMenu::FULL), mart, teach, grind, choice, console_species_finder(env.console, env.context, env.language, env.party), &env.party}; if (const std::optional plan = step.action == GRIND_CHECK_ACTION ? grind_plan_of(step.args) : std::nullopt){ if (grind_reached_already(env.console.logger(), grind, abilities.members, *plan)){ state.flags.insert(step.name); @@ -1002,6 +1002,7 @@ Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryExecutor& keep_next_start_frame(env, id); env.has_save = true; env.saved_supplies = env.supplies; + env.saved_field_moves = env.party.users(); env.prepared.clear(); env.bag_read = false; return Pokemon::outcome_ok(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index c9eec936d4..cf29d409f7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -95,10 +95,14 @@ struct StoryEnv{ // (PokemonFRLG_AutoStorySlopeRun.h), for the next to compare. std::map counted_items = {}; // The species the party's summaries were read as, for a Fly or a TEACH - // that names one. Emptied when a save is loaded and when a PC deposit - // or withdrawal moves members; a catch or a gift adds one at the end, - // so the slots read stay right. + // that names one, and who uses each field move (`party.users`, set by a + // TEACH of one or a Fly's scan). The species are emptied when a save is + // loaded; both when a PC deposit or withdrawal moves members. A catch + // or a gift adds a member at the end, so the slots stay right. PartyCache party = {}; + // Who uses the field moves as the last save holds it, which a load + // restores into `party.users`. + FieldMoveUsers saved_field_moves = {}; }; // After a save is loaded for a checkpoint that starts on `start_map`: the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp new file mode 100644 index 0000000000..b01941a880 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp @@ -0,0 +1,41 @@ +/* AutoStory Field Move Users + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonFRLG_AutoStoryFieldMoveUsers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void FieldMoveUsers::record(std::string move, size_t slot, std::string species){ + m_users[std::move(move)] = FieldMoveUser{.slot = slot, .species = std::move(species)}; +} + +std::optional FieldMoveUsers::find(std::string_view move) const{ + const auto found = m_users.find(move); + if (found == m_users.end()){ + return std::nullopt; + } + return found->second; +} + +void FieldMoveUsers::forget(std::string_view move){ + const auto found = m_users.find(move); + if (found != m_users.end()){ + m_users.erase(found); + } +} + +void FieldMoveUsers::clear(){ + m_users.clear(); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h new file mode 100644 index 0000000000..f3cd721999 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h @@ -0,0 +1,50 @@ +/* AutoStory Field Move Users + * + * From: https://github.com/PokemonAutomation/ + * + * Who in the party uses which field move (Fly, Surf, Strength, ...), as + * a TEACH of it, or a scan that found the user, learned it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryFieldMoveUsers_H +#define PokemonAutomation_PokemonFRLG_AutoStoryFieldMoveUsers_H + +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Who in the party uses a field move: the slot and species it was taught +// to. Kept with the run like the saved supplies (a save keeps a copy, a +// load restores it), so a Fly after the TEACH opens the party once and +// reads no summary, in a later checkpoint too. +struct FieldMoveUser{ + size_t slot = 0; + // Empty if the TEACH named a slot and the summary didn't read. + std::string species = {}; +}; + +class FieldMoveUsers{ +public: + void record(std::string move, size_t slot, std::string species); + std::optional find(std::string_view move) const; + void forget(std::string_view move); + // The party order changed (a deposit or withdrawal): nobody is known. + void clear(); + +private: + std::map> m_users; +}; + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp index 75f78b86b0..2d2a7d56fd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp @@ -39,6 +39,8 @@ namespace{ // A Pokemon's menu has at most SUMMARY, four field moves, SWITCH, ITEM // and CANCEL (the party's six slots are PARTY_SLOTS). constexpr size_t MON_MENU_ROWS = 8; +// The move a Fly step's user is recorded under. +const std::string FLY_MOVE = "fly"; } // namespace @@ -207,24 +209,29 @@ std::optional run_field_move_step( return std::nullopt; } const FlyTown& town = kanto_fly_towns()[plan->town]; - // With a species, the party is opened once: the scan (or the cache) - // leaves the Fly user's menu open. - bool menu_open = false; + std::string failure; if (!plan->species.empty()){ + // The party is opened once, at the recorded Fly user's slot if the + // TEACH or an earlier Fly left one, else at the scan's find. + console.log(std::format( + "Story: Fly with the {}, menu row {}, to {} (cell {}, {}).", + plan->species, plan->menu_row + 1, town.name, town.cell.x, town.cell.y + )); const std::unique_ptr screens = console_party_screens(console, context, plan->start_menu, language); - const std::optional slot = open_member_menu_of(console.logger(), *screens, party, plan->species, true); - if (!slot){ + failure = use_field_move(console.logger(), *screens, party, FLY_MOVE, plan->species, [&]{ + return fly_from_member_menu(console, context, *plan); + }); + if (failure == FIELD_MOVE_NO_MEMBER){ console.log(std::format("Story: no {} read in the party to Fly with.", plan->species), COLOR_RED); return Pokemon::outcome_failed("fly_no_member", plan->species); } - plan->slot = *slot; - menu_open = true; + }else{ + console.log(std::format( + "Story: Fly with slot {}, menu row {}, to {} (cell {}, {}).", + plan->slot + 1, plan->menu_row + 1, town.name, town.cell.x, town.cell.y + )); + failure = open_fly_map(console, context, *plan); } - console.log(std::format( - "Story: Fly with slot {}, menu row {}, to {} (cell {}, {}).", - plan->slot + 1, plan->menu_row + 1, town.name, town.cell.x, town.cell.y - )); - std::string failure = menu_open ? fly_from_member_menu(console, context, *plan) : open_fly_map(console, context, *plan); if (failure.empty()){ failure = fly_to_town(console, context, town); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp index cef08a00a6..9b11d3c3ae 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp @@ -15,6 +15,19 @@ namespace PokemonFRLG{ void PartyCache::invalidate(){ m_species.clear(); + m_users.clear(); +} + +FieldMoveUsers& PartyCache::users(){ + return m_users; +} + +const FieldMoveUsers& PartyCache::users() const{ + return m_users; +} + +void PartyCache::invalidate_species(){ + m_species.clear(); } void PartyCache::store(std::vector species){ @@ -103,6 +116,54 @@ std::optional open_member_menu_of( } +namespace{ + +// The recorded user's menu from the overworld, and `from_menu` from it: +// the failure, or nothing if the record didn't give the move (the screens +// are closed then). A party that doesn't open is no fault of the record. +std::optional use_recorded_member( + Logger& logger, PartyScreens& screens, const FieldMoveUser& user, std::string_view move, + const FieldMoveFromMenu& from_menu +){ + size_t members = 0; + if (!screens.open_party(members)){ + logger.log("Party: the menu didn't open.", COLOR_RED); + return FIELD_MOVE_NO_MEMBER; + } + logger.log(std::format("Party: the {} uses {} from slot {} (recorded).", user.species, move, user.slot + 1)); + if (user.slot < members && screens.open_member_menu(user.slot)){ + std::string failure = from_menu(); + if (failure.empty()){ + return failure; + } + } + logger.log(std::format("Party: slot {} didn't give {}; reading the party.", user.slot + 1, move), COLOR_RED); + screens.close(); + return std::nullopt; +} + +} // namespace + +std::string use_field_move( + Logger& logger, PartyScreens& screens, PartyCache& cache, + std::string_view move, std::string_view species, const FieldMoveFromMenu& from_menu +){ + if (const std::optional user = cache.users().find(move); user && user->species == species){ + if (const std::optional done = use_recorded_member(logger, screens, *user, move, from_menu)){ + return *done; + } + cache.users().forget(move); + cache.invalidate_species(); + } + const std::optional slot = open_member_menu_of(logger, screens, cache, species, true); + if (!slot){ + return FIELD_MOVE_NO_MEMBER; + } + cache.users().record(std::string(move), *slot, std::string(species)); + return from_menu(); +} + + } // namespace PokemonFRLG } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h index 8e9ac8d03a..0a4fc2f282 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h @@ -24,12 +24,14 @@ #define PokemonAutomation_PokemonFRLG_AutoStoryPartyRoster_H #include +#include #include #include #include #include #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_AutoStoryFieldMoveUsers.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -39,16 +41,24 @@ namespace PokemonFRLG{ // The species of the first party slots as the last scan read them. class PartyCache{ public: - // Forget the party: it changed (a catch, a gift, a deposit or - // withdrawal) or a new checkpoint starts. + // Forget the party: a deposit or withdrawal changed its order, or a + // save is loaded. Drops the field move users too. void invalidate(); + // Forget only the species read. + void invalidate_species(); // Keep `species` as slots 0, 1, ... void store(std::vector species); // The first slot read as `species`; nothing if none, or no scan yet. std::optional find(std::string_view species) const; + // Who uses which field move. A load restores them from the save's + // copy (StoryEnv::saved_field_moves), not from nothing. + FieldMoveUsers& users(); + const FieldMoveUsers& users() const; + private: std::vector m_species; + FieldMoveUsers m_users; }; @@ -87,6 +97,24 @@ std::optional open_member_menu_of( ); +// What use_field_move() returns when no member reads as the species. +inline const std::string FIELD_MOVE_NO_MEMBER = "no_member"; +// Runs the move from the member's menu; its failure, or empty. +using FieldMoveFromMenu = std::function; +// The field move `move` used by the first member read as `species`: the +// party is opened, the member's menu is chosen, and `from_menu` (the +// console's FLY row and map) runs from it. Returns its failure, empty on +// success, or FIELD_MOVE_NO_MEMBER if no member reads as `species`. With a +// record in the cache's users for `move` and `species`, the slot is chosen +// without reading a summary; if the menu there fails (no such row, a +// different member), the party is closed, the record dropped, and the scan +// finds the member and records it again. A scan records what it finds. +std::string use_field_move( + Logger& logger, PartyScreens& screens, PartyCache& cache, + std::string_view move, std::string_view species, const FieldMoveFromMenu& from_menu +); + + // Registers this file's tests (PokemonFRLG_AutoStoryPartyRoster_Tests.cpp). void add_tests_AutoStoryPartyRoster(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp index 0fd96945b4..0174f89be8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp @@ -188,6 +188,95 @@ UnitTestResult test_cached_slot_opens_nothing(Logger& logger){ return check_counts("cached slot only", again, 0, 0, 0, 0); } +// A Fly from the member's menu: it works on the slot that holds `holder`. +FieldMoveFromMenu fly_from(const FakeParty& party, size_t holder, size_t& calls){ + return [&party, holder, &calls]() -> std::string{ + calls++; + return party.m_menu_slot == holder ? "" : "fly_no_map"; + }; +} + +// A recorded Fly user: the party opens once and no summary is read. +UnitTestResult test_recorded_user_reads_no_summary(Logger& logger){ + FakeParty party({"blastoise", "pidgey", "oddish"}); + PartyCache cache; + cache.users().record("fly", 1, "pidgey"); + size_t calls = 0; + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, calls)); + if (!failure.empty() || calls != 1){ + return std::format("a recorded Fly: failure '{}', {} menu uses.", failure, calls); + } + return check_counts("recorded user", party, 1, 0, 0, 0); +} + +// The record names a slot another member holds now: the menu fails, the +// party is closed, the scan finds the right slot and the record is updated. +UnitTestResult test_stale_record_scans_and_updates(Logger& logger){ + FakeParty party({"blastoise", "oddish", "pidgey"}); + PartyCache cache; + cache.users().record("fly", 0, "pidgey"); + size_t calls = 0; + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 2, calls)); + if (!failure.empty() || calls != 2){ + return std::format("a stale Fly record: failure '{}', {} menu uses.", failure, calls); + } + const std::optional user = cache.users().find("fly"); + if (!user || user->slot != 2){ + return "the stale record isn't replaced by the slot the scan found."; + } + return check_counts("stale record", party, 2, 1, 3, 1); +} + +// A record for another species isn't trusted: the scan runs. +UnitTestResult test_other_species_record_scans(Logger& logger){ + FakeParty party({"blastoise", "pidgeot"}); + PartyCache cache; + cache.users().record("fly", 0, "pidgey"); + size_t calls = 0; + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgeot", fly_from(party, 1, calls)); + if (!failure.empty() || calls != 1){ + return std::format("a record of another species: failure '{}', {} menu uses.", failure, calls); + } + return check_counts("other species", party, 1, 1, 2, 0); +} + +// No record: the scan runs once and records, so the next Fly reads nothing. +UnitTestResult test_scan_records_for_next_fly(Logger& logger){ + FakeParty party({"blastoise", "pidgey"}); + PartyCache cache; + size_t calls = 0; + use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, calls)); + FakeParty again({"blastoise", "pidgey"}); + cache.invalidate_species(); + const std::string failure = use_field_move(logger, again, cache, "fly", "pidgey", fly_from(again, 1, calls)); + if (!failure.empty()){ + return std::format("the second Fly: {}", failure); + } + return check_counts("second fly", again, 1, 0, 0, 0); +} + +// A deposit or withdrawal moves members: nothing is recorded after it. +UnitTestResult test_invalidate_drops_records(Logger&){ + PartyCache cache; + cache.users().record("fly", 1, "pidgey"); + cache.invalidate(); + if (cache.users().find("fly")){ + return "invalidate() kept a field move user."; + } + return true; +} + +// No member of the species: its failure, the party closed. +UnitTestResult test_no_member_failure(Logger& logger){ + FakeParty party({"blastoise"}); + PartyCache cache; + size_t calls = 0; + if (use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 0, calls)) != FIELD_MOVE_NO_MEMBER || calls != 0){ + return "a party without the species should fail with no member and not fly."; + } + return check_counts("no member", party, 1, 1, 1, 1); +} + struct AutoStoryPartyRosterInput{ std::string name; std::function body; @@ -228,6 +317,12 @@ const AutoStoryPartyRosterCase AUTO_STORY_PARTY_ROSTER_CASES[] = { {.input = {"the first of two of a species wins", test_first_duplicate_wins}, .expectation = {}}, {.input = {"a lookup that doesn't keep the menu closes it", test_closes_when_not_kept}, .expectation = {}}, {.input = {"a cached slot for a TEACH opens nothing", test_cached_slot_opens_nothing}, .expectation = {}}, + {.input = {"a recorded field move user reads no summary", test_recorded_user_reads_no_summary}, .expectation = {}}, + {.input = {"a stale record falls back to the scan and is updated", test_stale_record_scans_and_updates}, .expectation = {}}, + {.input = {"a record of another species is not trusted", test_other_species_record_scans}, .expectation = {}}, + {.input = {"a scan records the user for the next Fly", test_scan_records_for_next_fly}, .expectation = {}}, + {.input = {"invalidate() drops the field move users", test_invalidate_drops_records}, .expectation = {}}, + {.input = {"no member of the species fails without flying", test_no_member_failure}, .expectation = {}}, }; } // namespace diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp index 0c1add818c..84e7b3463e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp @@ -24,6 +24,15 @@ bool is_hm_move(std::string_view move){ return false; } +bool is_field_move(std::string_view move){ + for (std::string_view other : {"dig", "teleport", "sweet-scent", "softboiled", "milk-drink"}){ + if (move == other){ + return true; + } + } + return is_hm_move(move); +} + std::string_view teach_end_name(TeachEnd end){ switch (end){ case TeachEnd::LEARNED: return "learned"; @@ -210,6 +219,8 @@ class TeachRun{ if (!member || member->moves.empty()){ return end(TeachEnd::UNREAD, "couldn't read the member's moves"); } + m_result.member = m_plan.member; + m_result.species = member->species; const TeachDecision decision = decide_teach(m_plan, member->moves); if (decision.already_known){ return end(TeachEnd::ALREADY_KNOWN, ""); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h index ca8322811f..14ebef4ad6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h @@ -88,8 +88,16 @@ struct TeachResult{ // The move forgotten, if any. std::string forgot = {}; std::string detail = {}; + // The party slot taught and the species its summary read as (empty if + // not read), for the field move users record; set once the member is read. + size_t member = 0; + std::string species = {}; }; +// Whether `move` is one the overworld uses (an HM's, Dig, Teleport, Sweet +// Scent, Softboiled, Milk Drink): its user is worth remembering. +bool is_field_move(std::string_view move); + // The first party slot whose member `reader` reads as `species`; nothing // if none does. Stops at the first slot not read (an empty slot ends the // party). diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 8447335c6e..5ccc2db90a 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2233,6 +2233,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameStore.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp From 2a66fc0cf62da81559dba9cf4e295ab739cffd88 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 00:17:36 -0800 Subject: [PATCH 03/12] FRLG AutoStory: document FieldMoveUsers Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h | 1 + 1 file changed, 1 insertion(+) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h index f3cd721999..54f51fec57 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h @@ -31,6 +31,7 @@ struct FieldMoveUser{ std::string species = {}; }; +// The user of each field move, by the move's slug ("fly", "surf"). class FieldMoveUsers{ public: void record(std::string move, size_t slot, std::string species); From 995cf838517a6a37855a9ce265464d8f539dd8bf Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 03:22:16 -0800 Subject: [PATCH 04/12] FRLG AutoStory: tests for the field move users' settings text (red) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryFieldMoveUsers.cpp | 8 +++ .../PokemonFRLG_AutoStoryFieldMoveUsers.h | 19 ++++++ ...PokemonFRLG_AutoStoryPartyRoster_Tests.cpp | 58 +++++++++++++++++++ 3 files changed, 85 insertions(+) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp index b01941a880..64758d669d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp @@ -34,6 +34,14 @@ void FieldMoveUsers::clear(){ m_users.clear(); } +std::string FieldMoveUsers::to_text() const{ + return ""; +} + +ParsedFieldMoveUsers parse_field_move_users(std::string_view){ + return {}; +} + } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h index 54f51fec57..1d06bc4295 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h @@ -15,6 +15,7 @@ #include #include #include +#include namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -29,6 +30,8 @@ struct FieldMoveUser{ size_t slot = 0; // Empty if the TEACH named a slot and the summary didn't read. std::string species = {}; + + friend bool operator==(const FieldMoveUser&, const FieldMoveUser&) = default; }; // The user of each field move, by the move's slug ("fly", "surf"). @@ -40,10 +43,26 @@ class FieldMoveUsers{ // The party order changed (a deposit or withdrawal): nobody is known. void clear(); + // The users as text, "fly=3:pidgey,cut=2:", slots from 1, in move + // order: AutoStory keeps it in its settings, as it keeps the SID, so a + // restart of the program knows them too. + std::string to_text() const; + + friend bool operator==(const FieldMoveUsers&, const FieldMoveUsers&) = default; + private: std::map> m_users; }; +// The users read back from to_text()'s text, and the entries that weren't +// readable (a slot outside 1-6, a move or species that isn't a slug, no +// "="): those are dropped, so their moves are found by a party scan. +struct ParsedFieldMoveUsers{ + FieldMoveUsers users = {}; + std::vector rejected = {}; +}; +ParsedFieldMoveUsers parse_field_move_users(std::string_view text); + } // namespace PokemonFRLG } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp index 0174f89be8..5d41ce610a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp @@ -277,6 +277,61 @@ UnitTestResult test_no_member_failure(Logger& logger){ return check_counts("no member", party, 1, 1, 1, 1); } +// The users as the settings keep them read back the same, slots from 1. +UnitTestResult test_users_text_round_trip(Logger&){ + FieldMoveUsers users; + users.record("fly", 2, "pidgey"); + users.record("cut", 1, ""); + const std::string text = users.to_text(); + if (text != "cut=2:,fly=3:pidgey"){ + return std::format("the users' text is '{}', expected 'cut=2:,fly=3:pidgey'.", text); + } + const ParsedFieldMoveUsers parsed = parse_field_move_users(text); + if (!(parsed.users == users) || !parsed.rejected.empty()){ + return std::format("'{}' doesn't read back as the users it came from.", text); + } + return true; +} + +// Text that isn't readable is dropped entry by entry, never thrown on: +// those moves are found by a scan. Empty text is no users. +UnitTestResult test_unreadable_users_text_dropped(Logger&){ + const ParsedFieldMoveUsers parsed = parse_field_move_users( + " strength = 1 : blastoise ,fly=x:pidgey,surf=7:lapras,=2:oddish,junk,cut=0:oddish,flash=2:Bad Name,," + ); + const std::optional strength = parsed.users.find("strength"); + if (!strength || strength->slot != 0 || strength->species != "blastoise"){ + return "the readable entry, strength=1:blastoise, isn't kept."; + } + if (parsed.users.find("fly") || parsed.users.find("surf") || parsed.users.find("cut") || parsed.users.find("flash")){ + return "an unreadable entry was kept."; + } + if (parsed.rejected.size() != 6){ + return std::format("{} entries rejected, expected 6.", parsed.rejected.size()); + } + const ParsedFieldMoveUsers empty = parse_field_move_users(""); + if (!(empty.users == FieldMoveUsers{}) || !empty.rejected.empty()){ + return "empty text isn't empty users."; + } + return true; +} + +// After a restart, the users read from the settings: the first Fly opens +// the party once and reads no summary. +UnitTestResult test_restart_fly_reads_no_summary(Logger& logger){ + FieldMoveUsers before; + before.record("fly", 2, "pidgey"); + PartyCache cache; + cache.users() = parse_field_move_users(before.to_text()).users; + FakeParty party({"blastoise", "oddish", "pidgey"}); + size_t calls = 0; + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 2, calls)); + if (!failure.empty() || calls != 1){ + return std::format("the Fly after a restart: failure '{}', {} menu uses.", failure, calls); + } + return check_counts("restart", party, 1, 0, 0, 0); +} + struct AutoStoryPartyRosterInput{ std::string name; std::function body; @@ -323,6 +378,9 @@ const AutoStoryPartyRosterCase AUTO_STORY_PARTY_ROSTER_CASES[] = { {.input = {"a scan records the user for the next Fly", test_scan_records_for_next_fly}, .expectation = {}}, {.input = {"invalidate() drops the field move users", test_invalidate_drops_records}, .expectation = {}}, {.input = {"no member of the species fails without flying", test_no_member_failure}, .expectation = {}}, + {.input = {"the field move users' text reads back the same", test_users_text_round_trip}, .expectation = {}}, + {.input = {"unreadable field move users' text is dropped", test_unreadable_users_text_dropped}, .expectation = {}}, + {.input = {"a Fly after a restart reads no summary", test_restart_fly_reads_no_summary}, .expectation = {}}, }; } // namespace From ce033cb933e9448a11cf910d1fc0b1df2bc0f1c8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 03:31:15 -0800 Subject: [PATCH 05/12] FRLG AutoStory: keep the field move users in the settings, as the SID Who uses each field move (slot and species, "fly=3:pidgey") is written to AutoStory's Field move users option after each save and read at the start, so a Fly after the program restarts goes to the slot without a party scan. An unreadable entry is dropped and logged; a record of another species or a slot that doesn't give the move falls back to the scan, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStory.cpp | 30 +++++++ .../AutoStory/PokemonFRLG_AutoStory.h | 3 + .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 3 + .../AutoStory/PokemonFRLG_AutoStoryEvents.h | 5 +- .../PokemonFRLG_AutoStoryFieldMoveUsers.cpp | 79 ++++++++++++++++++- 5 files changed, 116 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index d29bf04586..f0ee999eef 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -142,6 +142,15 @@ AutoStory::AutoStory() ) , RUN_STARTER_RNG(RUN_STARTER_RNG_TEXT, LockMode::LOCK_WHILE_RUNNING, false) , RUN_GIFT_RNG(RUN_GIFT_RNG_TEXT, LockMode::LOCK_WHILE_RUNNING, false) + , FIELD_MOVE_USERS( + false, + "Field move users:
Set by the run at each save: the party slot and species that use each field move " + "(e.g. fly=3:pidgey), so a Fly after the program restarts goes to that slot without reading the party's summaries. " + "A slot that holds another member now, or an entry that can't be read, only costs a party scan. " + "Clear it when loading a different save.", + LockMode::LOCK_WHILE_RUNNING, + "", "fly=3:pidgey" + ) , NOTIFICATION_SHINY("Shiny found", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) , KEEP_START_FRAME(KEEP_START_FRAME_TEXT, LockMode::LOCK_WHILE_RUNNING, false) @@ -157,6 +166,7 @@ AutoStory::AutoStory() PA_ADD_OPTION(RUN_STARTER_RNG); PA_ADD_OPTION(RUN_GIFT_RNG); PA_ADD_OPTION(RNG_PLAN); + PA_ADD_OPTION(FIELD_MOVE_USERS); PA_ADD_OPTION(NOTIFICATIONS); } @@ -187,6 +197,25 @@ StoryEnv story_env( return story; } +// Who uses the field moves, from `setting` (FieldMoveUsers' text) into +// `story`, and back into it after each save. An entry that can't be read +// is dropped and logged: its move is found by a party scan. +void keep_field_move_users(ConsoleHandle& console, StoryEnv& story, StringOption& setting){ + const ParsedFieldMoveUsers parsed = parse_field_move_users(static_cast(setting)); + for (const std::string& entry : parsed.rejected){ + console.log(std::format("AutoStory: Field move users: can't read \"{}\"; the party is scanned for it.", entry), COLOR_ORANGE); + } + story.saved_field_moves = parsed.users; + story.party.users() = parsed.users; + story.keep_saved_field_moves = [&console, &setting](const FieldMoveUsers& users){ + const std::string text = users.to_text(); + if (static_cast(setting) != text){ + setting.set(text); + console.log(std::format("AutoStory: Field move users set to \"{}\".", text), COLOR_BLUE); + } + }; +} + // The start gate's preflight failed: the console's setup, nothing pressed. void throw_if_not_started(ConsoleHandle& console, const Pokemon::Outcome& outcome){ if (outcome.failure == Pokemon::StoryPreflight::FAILURE){ @@ -712,6 +741,7 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex plan = plan_story_run(checkpoints, first, last, handoffs); } StoryEnv story = story_env(env, context, checkpoints[first], RUN.check_level(), KEEP_START_FRAME); + keep_field_move_users(env.console, story, FIELD_MOVE_USERS); story.player_gender = PLAYER_GENDER; story.player_name = player_name; const bool at_gift_rng = plan.stop == StoryHandoff::GIFT_RNG && plan.rows.empty(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h index da0bf2d6e5..646cb1abbc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h @@ -98,6 +98,9 @@ class AutoStory : public SingleSwitchProgramInstance{ // and 09.03 (the Eevee). BooleanCheckBoxOption RUN_GIFT_RNG; StarterRngPlanOptions RNG_PLAN; + // Who uses each field move as the last save holds it (FieldMoveUsers' + // text), kept as the SID is, so a restart skips the party scan. + StringOption FIELD_MOVE_USERS; EventNotificationOption NOTIFICATION_SHINY; EventNotificationOption NOTIFICATION_STATUS_UPDATE; // The save loaded was made by hand: keep the screen as its start frame. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 365155b133..dc9278aa5a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -1003,6 +1003,9 @@ Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryExecutor& env.has_save = true; env.saved_supplies = env.supplies; env.saved_field_moves = env.party.users(); + if (env.keep_saved_field_moves){ + env.keep_saved_field_moves(env.saved_field_moves); + } env.prepared.clear(); env.bag_read = false; return Pokemon::outcome_ok(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index cf29d409f7..26d194b97c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -101,8 +101,11 @@ struct StoryEnv{ // or a gift adds a member at the end, so the slots stay right. PartyCache party = {}; // Who uses the field moves as the last save holds it, which a load - // restores into `party.users`. + // restores into `party.users`. The program starts it from its settings. FieldMoveUsers saved_field_moves = {}; + // Called with `saved_field_moves` after each save, to keep them in the + // program's settings for the next run; empty: nothing kept. + std::function keep_saved_field_moves = {}; }; // After a save is loaded for a checkpoint that starts on `start_map`: the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp index 64758d669d..c6c6a86014 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp @@ -4,6 +4,10 @@ * */ +#include +#include +#include +#include #include "PokemonFRLG_AutoStoryFieldMoveUsers.h" namespace PokemonAutomation{ @@ -35,11 +39,80 @@ void FieldMoveUsers::clear(){ } std::string FieldMoveUsers::to_text() const{ - return ""; + std::string text; + for (const auto& [move, user] : m_users){ + if (!text.empty()){ + text += ","; + } + text += std::format("{}={}:{}", move, user.slot + 1, user.species); + } + return text; +} + + +namespace{ + +// The game's party: slots 1 to 6 in the text. +constexpr size_t PARTY_SLOTS = 6; + +std::string_view trimmed(std::string_view text){ + while (!text.empty() && text.front() == ' '){ + text.remove_prefix(1); + } + while (!text.empty() && text.back() == ' '){ + text.remove_suffix(1); + } + return text; } -ParsedFieldMoveUsers parse_field_move_users(std::string_view){ - return {}; +// A move or species slug: lower-case letters, digits and '-'. +bool is_slug(std::string_view text){ + for (char c : text){ + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')){ + return false; + } + } + return true; +} + +// "move=slot:species" as its move and user; nothing if it isn't readable. +std::optional> parse_entry(std::string_view entry){ + const size_t equals = entry.find('='); + const size_t colon = entry.find(':', equals == std::string_view::npos ? 0 : equals); + if (equals == std::string_view::npos || colon == std::string_view::npos){ + return std::nullopt; + } + const std::string_view move = trimmed(entry.substr(0, equals)); + const std::string_view slot_text = trimmed(entry.substr(equals + 1, colon - equals - 1)); + const std::string_view species = trimmed(entry.substr(colon + 1)); + size_t slot = 0; + const auto [end, error] = std::from_chars(slot_text.data(), slot_text.data() + slot_text.size(), slot); + if (move.empty() || !is_slug(move) || !is_slug(species) + || error != std::errc{} || end != slot_text.data() + slot_text.size() || slot < 1 || slot > PARTY_SLOTS + ){ + return std::nullopt; + } + return std::pair{std::string(move), FieldMoveUser{.slot = slot - 1, .species = std::string(species)}}; +} + +} // namespace + +ParsedFieldMoveUsers parse_field_move_users(std::string_view text){ + ParsedFieldMoveUsers parsed; + while (!text.empty()){ + const size_t comma = text.find(','); + const std::string_view entry = trimmed(text.substr(0, comma)); + text = comma == std::string_view::npos ? std::string_view{} : text.substr(comma + 1); + if (entry.empty()){ + continue; + } + if (std::optional> user = parse_entry(entry)){ + parsed.users.record(std::move(user->first), user->second.slot, std::move(user->second.species)); + }else{ + parsed.rejected.emplace_back(entry); + } + } + return parsed; } From 1ce9a85f7ef646674d4a0772fe168f7ea3487dd2 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 03:33:39 -0800 Subject: [PATCH 06/12] FRLG AutoStory: the saved field move users keep themselves (SavedFieldMoveUsers); option text as constants Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStory.cpp | 37 +++++++++---------- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 5 +-- .../AutoStory/PokemonFRLG_AutoStoryEvents.h | 8 ++-- .../PokemonFRLG_AutoStoryFieldMoveUsers.cpp | 16 ++++++++ .../PokemonFRLG_AutoStoryFieldMoveUsers.h | 19 ++++++++++ 5 files changed, 56 insertions(+), 29 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index f0ee999eef..73bcc49b92 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -74,6 +74,18 @@ const StringSelectDatabase& checkpoint_database(){ return database; } +const std::string PLAYER_NAME_TEXT = + "Player name:
Typed on the new game's keyboard (01.01). Empty keeps the game's default name. " + "The rival always keeps the default name."; + +// Kept by the run as the SID is: who uses each field move as the last save +// holds it (FieldMoveUsers' text). +const std::string FIELD_MOVE_USERS_TEXT = + "Field move users:
Set by the run at each save: the party slot and species that use each field move " + "(e.g. fly=3:pidgey), so a Fly after the program restarts goes to that slot without reading the party's summaries. " + "A slot that holds another member now, or an entry that can't be read, only costs a party scan. " + "Clear it when loading a different save."; + const std::string KEEP_START_FRAME_TEXT = "Keep the start frame:
Off by default. The save loaded was made by hand where the start checkpoint " "begins: keep the screen after loading it as that checkpoint's start frame, which later runs compare their " @@ -116,13 +128,7 @@ AutoStory::AutoStory() LockMode::LOCK_WHILE_RUNNING, PlayerGender::BOY ) - , PLAYER_NAME( - false, - "Player name:
Typed on the new game's keyboard (01.01). Empty keeps the game's default name. " - "The rival always keeps the default name.", - LockMode::LOCK_WHILE_RUNNING, - "Kosmos", "" - ) + , PLAYER_NAME(false, PLAYER_NAME_TEXT, LockMode::LOCK_WHILE_RUNNING, "Kosmos", "") , STOP_FOR_SID_HELPER( "Stop for SID Helper:
Off by default. At 01.01, stop on the player's keyboard with the name typed and OK not pressed, " "where the SID Helper program starts. After SID Helper, start AutoStory at 01.02, with the game as SID Helper left it " @@ -142,15 +148,7 @@ AutoStory::AutoStory() ) , RUN_STARTER_RNG(RUN_STARTER_RNG_TEXT, LockMode::LOCK_WHILE_RUNNING, false) , RUN_GIFT_RNG(RUN_GIFT_RNG_TEXT, LockMode::LOCK_WHILE_RUNNING, false) - , FIELD_MOVE_USERS( - false, - "Field move users:
Set by the run at each save: the party slot and species that use each field move " - "(e.g. fly=3:pidgey), so a Fly after the program restarts goes to that slot without reading the party's summaries. " - "A slot that holds another member now, or an entry that can't be read, only costs a party scan. " - "Clear it when loading a different save.", - LockMode::LOCK_WHILE_RUNNING, - "", "fly=3:pidgey" - ) + , FIELD_MOVE_USERS(false, FIELD_MOVE_USERS_TEXT, LockMode::LOCK_WHILE_RUNNING, "", "fly=3:pidgey") , NOTIFICATION_SHINY("Shiny found", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) , KEEP_START_FRAME(KEEP_START_FRAME_TEXT, LockMode::LOCK_WHILE_RUNNING, false) @@ -205,15 +203,14 @@ void keep_field_move_users(ConsoleHandle& console, StoryEnv& story, StringOption for (const std::string& entry : parsed.rejected){ console.log(std::format("AutoStory: Field move users: can't read \"{}\"; the party is scanned for it.", entry), COLOR_ORANGE); } - story.saved_field_moves = parsed.users; story.party.users() = parsed.users; - story.keep_saved_field_moves = [&console, &setting](const FieldMoveUsers& users){ + story.saved_field_moves = SavedFieldMoveUsers(parsed.users, [&console, &setting](const FieldMoveUsers& users){ const std::string text = users.to_text(); if (static_cast(setting) != text){ setting.set(text); console.log(std::format("AutoStory: Field move users set to \"{}\".", text), COLOR_BLUE); } - }; + }); } // The start gate's preflight failed: the console's setup, nothing pressed. @@ -259,7 +256,7 @@ Pokemon::StoryGameHooks story_game(SingleSwitchProgramEnvironment& env, StoryEnv story.supplies = story.saved_supplies; // The save's party, which a catch or a gift since then changed. story.party.invalidate_species(); - story.party.users() = story.saved_field_moves; + story.party.users() = story.saved_field_moves.users(); // Until read in full, so each verify run starts from the bag as // the save holds it, not from a count once read wrong or not at // all (console B, 2026-11-03: 0 Potions in all 3 runs). Once diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index dc9278aa5a..a63f1ef158 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -1002,10 +1002,7 @@ Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryExecutor& keep_next_start_frame(env, id); env.has_save = true; env.saved_supplies = env.supplies; - env.saved_field_moves = env.party.users(); - if (env.keep_saved_field_moves){ - env.keep_saved_field_moves(env.saved_field_moves); - } + env.saved_field_moves.save(env.party.users()); env.prepared.clear(); env.bag_read = false; return Pokemon::outcome_ok(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index 26d194b97c..9c2b895782 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -101,11 +101,9 @@ struct StoryEnv{ // or a gift adds a member at the end, so the slots stay right. PartyCache party = {}; // Who uses the field moves as the last save holds it, which a load - // restores into `party.users`. The program starts it from its settings. - FieldMoveUsers saved_field_moves = {}; - // Called with `saved_field_moves` after each save, to keep them in the - // program's settings for the next run; empty: nothing kept. - std::function keep_saved_field_moves = {}; + // restores into `party.users`. The program starts it from its settings + // and keeps it there. + SavedFieldMoveUsers saved_field_moves = {}; }; // After a save is loaded for a checkpoint that starts on `start_map`: the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp index c6c6a86014..27fd346444 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp @@ -49,6 +49,22 @@ std::string FieldMoveUsers::to_text() const{ return text; } +SavedFieldMoveUsers::SavedFieldMoveUsers(FieldMoveUsers users, Keep keep) + : m_users(std::move(users)) + , m_keep(std::move(keep)) +{} + +void SavedFieldMoveUsers::save(const FieldMoveUsers& users){ + m_users = users; + if (m_keep){ + m_keep(users); + } +} + +const FieldMoveUsers& SavedFieldMoveUsers::users() const{ + return m_users; +} + namespace{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h index 1d06bc4295..aa96a97a2e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h @@ -11,6 +11,7 @@ #define PokemonAutomation_PokemonFRLG_AutoStoryFieldMoveUsers_H #include +#include #include #include #include @@ -54,6 +55,23 @@ class FieldMoveUsers{ std::map> m_users; }; +// The users as the last save holds them, and where they are kept beyond +// the program (AutoStory's settings), called at each save. +class SavedFieldMoveUsers{ +public: + using Keep = std::function; + SavedFieldMoveUsers() = default; + SavedFieldMoveUsers(FieldMoveUsers users, Keep keep); + + // A save holds `users`: kept here, and by `keep` if there is one. + void save(const FieldMoveUsers& users); + const FieldMoveUsers& users() const; + +private: + FieldMoveUsers m_users; + Keep m_keep; +}; + // The users read back from to_text()'s text, and the entries that weren't // readable (a slot outside 1-6, a move or species that isn't a slug, no // "="): those are dropped, so their moves are found by a party scan. @@ -61,6 +79,7 @@ struct ParsedFieldMoveUsers{ FieldMoveUsers users = {}; std::vector rejected = {}; }; +// `text` read as ParsedFieldMoveUsers says; never throws. ParsedFieldMoveUsers parse_field_move_users(std::string_view text); From f34c9c087dcf3aaa2b01cbf0f87968a030f0cb5d Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 07:04:11 -0800 Subject: [PATCH 07/12] FRLG: PartyMemberMenuReader reads a party member's menu and its blue field moves --- .../PokemonFRLG_PartyMemberMenuReader.cpp | 282 ++++++++++++++++++ .../Menus/PokemonFRLG_PartyMemberMenuReader.h | 60 ++++ .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + SerialPrograms/cmake/SourceFiles.cmake | 2 + 4 files changed, 346 insertions(+) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp new file mode 100644 index 0000000000..3b0234f7a6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp @@ -0,0 +1,282 @@ +/* Party Member Menu Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" +#include "Tests/ImageUnitTest.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_OcrPreprocessing.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "PokemonFRLG_PartyMemberMenuReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// Measured on a capture of the menu (console B, 2026-11-13, a Pidgey's +// SUMMARY / FLY / SWITCH / ITEM / CANCEL), in the game's 240x160 pixels: +// CANCEL's text from y 140 to 150, each row above it 16 higher; the names +// from x 160, the cursor to their left. +constexpr double ROW_STEP = 16; +constexpr double BOTTOM_ROW_TOP = 140; +constexpr double ROW_HEIGHT = 10; +constexpr double TEXT_LEFT = 160; +constexpr double TEXT_WIDTH = 70; +// SUMMARY, four field moves, SWITCH, ITEM and CANCEL. +constexpr size_t MAX_ROWS = 8; +// SWITCH and CANCEL at least, under the field moves (an egg has no ITEM). +constexpr size_t MIN_PLAIN_ROWS_BELOW = 2; + +// The field moves (pokefirered party_menu.c, sFieldMoves), as the menu +// writes them (src/data/text/move_names.h, in capitals). +constexpr std::pair FIELD_MOVE_NAMES[] = { + {"flash", "FLASH"}, + {"cut", "CUT"}, + {"fly", "FLY"}, + {"strength", "STRENGTH"}, + {"surf", "SURF"}, + {"rock-smash", "ROCK SMASH"}, + {"waterfall", "WATERFALL"}, + {"teleport", "TELEPORT"}, + {"dig", "DIG"}, + {"milk-drink", "MILK DRINK"}, + {"soft-boiled", "SOFTBOILED"}, + {"sweet-scent", "SWEET SCENT"}, +}; + +// The blue of a field move's name: (32, 80, 224) and its darker edges; +// its shadow, (160, 192, 240), is left out. +const std::vector& BLUE_TEXT_FILTERS(){ + static const std::vector filters{ + {combine_rgb(0, 0, 160), combine_rgb(80, 120, 255)}, + {combine_rgb(0, 0, 128), combine_rgb(112, 152, 255)}, + {combine_rgb(0, 0, 112), combine_rgb(136, 168, 255)}, + }; + return filters; +} + +class FieldMoveNameMatcher : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + + static const FieldMoveNameMatcher& instance(){ + static const FieldMoveNameMatcher matcher; + return matcher; + } + + std::string read(Logger& logger, Language language, const ImageViewRGB32& image) const{ + if (!languages()[language]){ + return ""; + } + const ImageRGB32 ready = preprocess_for_ocr(image); + const OCR::StringMatchResult result = match_substring_from_image_multifiltered( + &logger, language, ready, BLUE_TEXT_FILTERS(), + MAX_LOG10P, MAX_LOG10P_SPREAD, 0.01, 0.50 + ); + return result.results.empty() ? "" : result.results.begin()->second.token; + } + +private: + FieldMoveNameMatcher() + : SmallDictionaryMatcher(dictionary()) + {} + + static JsonObject dictionary(){ + JsonObject english; + for (const auto& [slug, name] : FIELD_MOVE_NAMES){ + JsonArray names; + names.push_back(std::string(name)); + english[std::string(slug)] = std::move(names); + } + JsonObject json; + json["eng"] = std::move(english); + return json; + } +}; + +enum class RowKind{ + NONE, // not a row of the menu's white window + PLAIN, // dark gray text: SUMMARY, SWITCH, ITEM, CANCEL + FIELD, // blue text: a field move +}; + +// Row `row`, counted up from CANCEL's row 0, as a box of the game screen. +ImageFloatBox row_box(size_t row){ + return ImageFloatBox( + TEXT_LEFT / 240, (BOTTOM_ROW_TOP - ROW_STEP * double(row)) / 160, TEXT_WIDTH / 240, ROW_HEIGHT / 160 + ); +} + +bool is_white(uint32_t pixel){ + return ((pixel >> 16) & 0xff) > 192 && ((pixel >> 8) & 0xff) > 192 && (pixel & 0xff) > 176; +} +bool is_gray_text(uint32_t pixel){ + const int r = (pixel >> 16) & 0xff; + const int g = (pixel >> 8) & 0xff; + const int b = pixel & 0xff; + return r < 136 && g < 136 && b < 136 && std::abs(r - b) < 32 && std::abs(g - b) < 32; +} +bool is_blue_text(uint32_t pixel){ + const int r = (pixel >> 16) & 0xff; + const int g = (pixel >> 8) & 0xff; + const int b = pixel & 0xff; + return b > 176 && r < 96 && g < 136; +} + +RowKind classify_row(const ImageViewRGB32& row){ + const size_t area = row.width() * row.height(); + if (area == 0){ + return RowKind::NONE; + } + size_t white = 0; + size_t gray = 0; + size_t blue = 0; + for (size_t y = 0; y < row.height(); y++){ + for (size_t x = 0; x < row.width(); x++){ + const uint32_t pixel = row.pixel(x, y); + white += is_white(pixel) ? 1 : 0; + gray += is_gray_text(pixel) ? 1 : 0; + blue += is_blue_text(pixel) ? 1 : 0; + } + } + // Measured: a name covers 5% to 25% of its row, the window's white + // the most of the rest; the party's slots behind the window are teal + // and blue. + if (white * 2 < area){ + return RowKind::NONE; + } + if (blue * 50 >= area && gray * 4 < blue){ + return RowKind::FIELD; + } + if (gray * 50 >= area && blue * 4 < gray){ + return RowKind::PLAIN; + } + return RowKind::NONE; +} + +} // namespace + + +std::optional PartyMemberMenu::row_of(std::string_view move) const{ + for (size_t c = 0; c < field_moves.size(); c++){ + if (field_moves[c] == move){ + return c + 1; + } + } + return std::nullopt; +} + +bool PartyMemberMenu::all_read() const{ + for (const std::string& move : field_moves){ + if (move.empty()){ + return false; + } + } + return true; +} + +std::optional read_party_member_menu(Logger& logger, Language language, const ImageViewRGB32& screen){ + const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); + // The rows from CANCEL up, to the first that isn't one. + std::vector kinds; + for (size_t row = 0; row < MAX_ROWS; row++){ + const RowKind kind = classify_row(extract_box_reference(game, row_box(row))); + if (kind == RowKind::NONE){ + break; + } + kinds.push_back(kind); + } + // Plain rows (CANCEL, ITEM, SWITCH), the field moves, then SUMMARY. + size_t plain_below = 0; + while (plain_below < kinds.size() && kinds[plain_below] == RowKind::PLAIN){ + plain_below++; + } + size_t fields = 0; + while (plain_below + fields < kinds.size() && kinds[plain_below + fields] == RowKind::FIELD){ + fields++; + } + const size_t summary_row = plain_below + fields; + const bool shape = fields == 0 + ? plain_below >= MIN_PLAIN_ROWS_BELOW + 1 && plain_below == kinds.size() + : plain_below >= MIN_PLAIN_ROWS_BELOW && summary_row + 1 == kinds.size() + && kinds[summary_row] == RowKind::PLAIN; + if (!shape){ + return std::nullopt; + } + PartyMemberMenu menu; + // From the top: the field move under SUMMARY first. + for (size_t c = 0; c < fields; c++){ + const size_t row = summary_row - 1 - c; + menu.field_moves.push_back( + FieldMoveNameMatcher::instance().read(logger, language, extract_box_reference(game, row_box(row))) + ); + } + return menu; +} + + +namespace{ + +// A capture, named _.png, and what it shows: +// no member's menu, or one listing `field_moves`. +class Test_PartyMemberMenuReader : public ImageUnitTest{ +public: + Test_PartyMemberMenuReader(const std::string& image, std::optional> field_moves) + : ImageUnitTest(std::format("PokemonFRLG::PartyMemberMenuReader - {}", image), {image}) + , m_field_moves(std::move(field_moves)) + {} + + virtual UnitTestResult run_on_images( + Logger& logger, CancellableScope&, const std::vector& images + ) const override{ + const std::optional menu = read_party_member_menu(logger, Language::English, images[0]); + if (!m_field_moves){ + return menu ? UnitTestResult("read a member's menu where none shows.") : UnitTestResult(true); + } + if (!menu){ + return "the member's menu isn't read."; + } + if (menu->field_moves != *m_field_moves){ + std::string read; + for (const std::string& move : menu->field_moves){ + read += std::format("{}'{}'", read.empty() ? "" : ", ", move); + } + return std::format("field moves read: [{}].", read); + } + return true; + } + +private: + std::optional> m_field_moves; +}; + +} // namespace + +void add_tests_PartyMemberMenuReader(UnitTestDatabase& database){ + // FireRed on console B, 2026-11-13: the Pidgey's menu, the cursor on + // SUMMARY, FLY in blue under it. + database.add( + "PokemonFRLG/PartyMemberMenuReader/PidgeyFly_eng.png", std::vector{"fly"} + ); + // The party menu before A: no member's menu. + database.add( + "PokemonFRLG/PartyMemberMenuReader/PartyList_eng.png", std::nullopt + ); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.h new file mode 100644 index 0000000000..e94a29768f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.h @@ -0,0 +1,60 @@ +/* Party Member Menu Reader + * + * From: https://github.com/PokemonAutomation/ + * + * Reads the menu A opens on a member in the party menu: SUMMARY, the + * member's field moves in blue (FLY, CUT, ...), then SWITCH, ITEM and + * CANCEL (pokefirered party_menu.c, SetPartyMonFieldSelectionActions()). + * The window grows upwards from the bottom right corner, one row of + * 16 pixels per action, so its rows are found from CANCEL up. + * + * It knows the field moves' names in English only so far: in another + * language a blue row is never read. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_PartyMemberMenuReader_H +#define PokemonAutomation_PokemonFRLG_PartyMemberMenuReader_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// A member's menu as read. +struct PartyMemberMenu{ + // The field moves' slugs ("fly", "rock-smash"), from the top; empty + // for a blue row whose name wasn't read. + std::vector field_moves = {}; + + // The row of `move`, counted from SUMMARY's row 0; nothing if the + // menu doesn't list it. + std::optional row_of(std::string_view move) const; + // Whether every blue row's name was read. + bool all_read() const; +}; + +// The member's menu on `screen`; nothing if the screen doesn't show one +// (no CANCEL at the bottom right, or rows that don't make SUMMARY, field +// moves, then two or more plain rows). +std::optional read_party_member_menu(Logger& logger, Language language, const ImageViewRGB32& screen); + + +// Registers this reader's tests. +void add_tests_PartyMemberMenuReader(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 0bb2198d75..83d2829610 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -26,6 +26,7 @@ #include "Inference/Menus/PokemonFRLG_PartyHeldItemDetector.h" #include "Inference/Menus/PokemonFRLG_PartyMenuDetector.h" #include "Inference/Menus/PokemonFRLG_SaveCardReader.h" +#include "Inference/Menus/PokemonFRLG_PartyMemberMenuReader.h" #include "Inference/Menus/PokemonFRLG_SummaryMovesReader.h" #include "Inference/Menus/PokemonFRLG_TeachScreenReader.h" #include "Inference/PokemonFRLG_BattleLevelUpReader.h" @@ -314,6 +315,7 @@ static void add_tests_AutoStoryReaders(UnitTestDatabase& database){ add_tests_ItemListReader(database); add_tests_OptionMenuReader(database); add_tests_SaveCardReader(database); + add_tests_PartyMemberMenuReader(database); add_tests_SummaryMovesReader(database); add_tests_TeachScreenReader(database); add_tests_AutoStoryScreenEvents(database); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 5ccc2db90a..2b104d5e2e 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1933,6 +1933,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyEmptySlotDetector.h Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyHeldItemDetector.cpp Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyHeldItemDetector.h + Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp + Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.h Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMenuDetector.cpp Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMenuDetector.h Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartySlot.h From bb61c0e45c57c564d38a8bfb5b77bfee3cc3eb14 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 07:10:36 -0800 Subject: [PATCH 08/12] FRLG AutoStory: tests for a Fly user found by its party menu (red) --- .../PokemonFRLG_AutoStoryAbilities_Tests.cpp | 670 +++++++++--------- .../PokemonFRLG_AutoStoryFieldMoves.cpp | 28 +- .../PokemonFRLG_AutoStoryPartyRoster.cpp | 4 +- .../PokemonFRLG_AutoStoryPartyRoster.h | 42 +- ...PokemonFRLG_AutoStoryPartyRoster_Tests.cpp | 205 ++++-- .../PokemonFRLG_AutoStorySummary.cpp | 47 +- 6 files changed, 588 insertions(+), 408 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp index 310b846e29..0668f6343c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -1,333 +1,337 @@ -/* AutoStory Abilities Tests - * - * From: https://github.com/PokemonAutomation/ - * - * The LEVEL step, and which ends of the MART, TEACH, GRIND and fossil - * steps the story takes as success, failure or a stop. - * - */ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/TestRunners/UnitTest.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "PokemonFRLG_AutoStoryAbilities.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -namespace{ - -class QuietLogger : public Logger{ -public: - using Logger::log; - virtual void log(const std::string&, Color) override{} -}; - -// A game where nothing happens: a lead whose level is set, a patch whose one battle is shiny if set. -class StubMart : public MartActions{ -public: - virtual bool open_buy_list() override{ return true; } - virtual void press_cursor(bool) override{} - virtual std::string read_row(size_t) override{ return ""; } - virtual void dump_screen(std::string_view) override{} - virtual PurchaseEnd buy(const MartBuy&) override{ return PurchaseEnd::FAILED; } - virtual bool leave() override{ return true; } -}; - -class StubTeach : public TeachActions{ -public: - // Its TM Case is empty. - virtual ItemOpen open_item(std::string_view, std::string_view) override{ return ItemOpen::NOT_IN_CASE; } - virtual TeachPrompt choose_member(size_t) override{ return TeachPrompt::FAILED; } - virtual ForgetEnd forget(size_t) override{ return ForgetEnd::FAILED; } - virtual void stop_teaching() override{} - virtual bool leave() override{ return true; } - virtual void dump_screen(std::string_view) override{} -}; - -class StubPatch : public GrindActions{ -public: - bool shiny = false; - - virtual bool find_encounter(Pokemon::Direction) override{ return true; } - virtual EncounterSeen read_encounter() override{ return {.species = "pidgey", .shiny = shiny}; } - virtual GrindFight fight() override{ return GrindFight::FAILED; } - virtual bool needs_heal() override{ return false; } - virtual bool heal_trip() override{ return true; } -}; - -class StubFossils : public ChoiceActions{ -public: - virtual bool talk() override{ return false; } - virtual std::optional read_offer() override{ return std::nullopt; } - virtual void answer(bool) override{} - virtual bool finish() override{ return true; } - virtual std::optional fossil_in_bag() override{ return std::nullopt; } -}; - -struct StubGame{ - std::optional level = 16; - StubMart mart; - StubTeach teach; - StubPatch patch; - StubFossils fossils; -}; - - -struct AutoStoryAbilitiesInput{ - std::string name; - std::function body; -}; - -struct AutoStoryAbilitiesExpectation{ -}; - -struct AutoStoryAbilitiesCase{ - AutoStoryAbilitiesInput input; - AutoStoryAbilitiesExpectation expectation; -}; - -class Test_AutoStoryAbilities : public UnitTest{ -public: - explicit Test_AutoStoryAbilities(AutoStoryAbilitiesCase test_case) - : UnitTest("PokemonFRLG::AutoStoryAbilities - " + 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::string(e.name()) + ": " + e.message(); - } - } - -private: - AutoStoryAbilitiesCase m_case; -}; - - -Pokemon::StoryStep game_step(std::string action, Pokemon::StoryActionArgs args){ - Pokemon::StoryStep step; - step.kind = Pokemon::StoryStepKind::GAME; - step.name = "test"; - step.action = std::move(action); - step.args = std::move(args); - return step; -} - -// The failure name the step ends with ("" for success, "unchanged" for -// one that changed nothing in the game); "none" if it isn't one of these -// steps. -std::string run_step(StubGame& game, const Pokemon::StoryStep& step){ - QuietLogger logger; - const MemberReader members = [&game](size_t slot) -> std::optional{ - if (slot != 0 || !game.level){ - return std::nullopt; - } - return MemberInfo{.species = "squirtle", .level = game.level, .moves = {"water-gun", "surf"}}; - }; - StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils}; - const std::optional outcome = run_ability_game_step(logger, nullptr, step, abilities); - if (!outcome){ - return "none"; - } - return outcome->changed_nothing ? "unchanged" : outcome->failure; -} - -struct StepCase{ - std::string name; - std::function setup; - Pokemon::StoryStep step; - std::string failure; -}; - -std::vector step_cases(){ - const auto none = [](StubGame&){}; - const Pokemon::StoryStep mart = mart_step("mart", "", {.map = "PewterCity_Mart", .lines = {{"potion", 5}}}); - const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); - return { - {"level reached", none, level_step("check", "", {.slot = 0, .level = 16}), "unchanged"}, - {"level below", none, level_step("check", "", {.slot = 0, .level = 17}), "level_below"}, - {"level unread", [](StubGame& game){ game.level.reset(); }, level_step("check", "", {.slot = 0, .level = 16}), "level_unread"}, - {"a Mart purchase that fails", none, mart, "mart_failed"}, - {"a move it knows already succeeds", none, teach_step("teach", "", {.item = "hm03", .move = "surf", .member = 0}), "unchanged"}, - {"a TM not in the TM Case is skipped", none, teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), "unchanged"}, - {"a level that can't be read stops a GRIND", [](StubGame& game){ game.level.reset(); }, grind, "grind_unread"}, - {"a GRIND without a nurse", none, game_step(GRIND_ACTION, {{"slot", int64_t(1)}, {"level", int64_t(20)}}), "bad_args"}, - {"no YES/NO at the fossil", none, fossil_step("fossil", "", Fossil::HELIX), "fossil_failed"}, - {"bad args", none, game_step(MART_ACTION, {{"map", std::string("PewterCity_Mart")}}), "bad_args"}, - {"another game step", none, capture_step("capture", "", {.species = "rattata"}), "none"}, - }; -} - -UnitTestResult test_ability_steps(){ - for (const StepCase& item : step_cases()){ - StubGame game; - item.setup(game); - const std::string failure = run_step(game, item.step); - if (failure != item.failure){ - return std::format("{}: \"{}\", expected \"{}\".", item.name, failure, item.failure); - } - } - return true; -} - - -// TEACH and MART steps are preparation, once per save: a retry from the -// same save skips one that changed nothing. A LEVEL check, which follows -// a GRIND, and the GRIND run every attempt. -UnitTestResult test_once_per_save_steps(){ - const std::vector once{ - teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}), - mart_step("mart", "", {.map = "CeruleanCity_Mart", .lines = {{.item = "potion", .quantity = 3}}}), - }; - for (const Pokemon::StoryStep& step : once){ - if (!step.once_per_save){ - return step.name + ": expected once per save."; - } - } - const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); - if (grind.once_per_save || level_step("level", "", {.slot = 0, .level = 16}).once_per_save){ - return "GRIND and LEVEL: expected every attempt."; - } - return true; -} - - -// A party whose screens count the summaries read. -class CountingScreens : public PartyScreens{ -public: - virtual bool open_party(size_t& members) override{ members = 2; m_opens++; return true; } - virtual bool enter_summary() override{ m_summaries++; return true; } - virtual std::string read_species() override{ m_summaries++; return "squirtle"; } - virtual bool next_member() override{ return true; } - virtual bool leave_summary() override{ return true; } - virtual bool open_member_menu(size_t slot) override{ m_menu = slot; return true; } - virtual void close() override{} - - size_t m_opens = 0; - size_t m_summaries = 0; - size_t m_menu = SIZE_MAX; -}; - -// A TEACH of a field move records its user; the Fly after it opens the -// party once, at that slot, and reads no summary, though the species -// cache was emptied by a reload. A TEACH of a plain TM records nothing. -UnitTestResult test_teach_records_fly_user(){ - StubGame game; - QuietLogger logger; - const MemberReader members = [](size_t slot) -> std::optional{ - if (slot != 0){ - return std::nullopt; - } - return MemberInfo{.species = "squirtle", .level = 16, .moves = {"water-gun", "surf"}}; - }; - PartyCache party; - StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils, {}, &party}; - run_ability_game_step(logger, nullptr, teach_step("teach_surf", "", {.item = "hm03", .move = "surf", .member = 0}), abilities); - run_ability_game_step(logger, nullptr, teach_step("teach_tm", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), abilities); - const std::optional user = party.users().find("surf"); - if (!user || user->slot != 0 || user->species != "squirtle"){ - return "the Surf user isn't recorded as slot 1, squirtle."; - } - if (party.users().find("water-pulse")){ - return "a TM move was recorded as a field move."; - } - party.invalidate_species(); - CountingScreens screens; - size_t flights = 0; - const std::string failure = use_field_move(logger, screens, party, "surf", "squirtle", [&flights]{ - flights++; - return std::string(); - }); - if (!failure.empty() || flights != 1 || screens.m_menu != 0 || screens.m_opens != 1 || screens.m_summaries != 0){ - return std::format( - "Fly after TEACH: failure '{}', {} flights, menu {}, {} party opens, {} summary reads.", - failure, flights, screens.m_menu, screens.m_opens, screens.m_summaries - ); - } - return true; -} - - -// A shiny in a GRIND stops the program, not the checkpoint: a reload -// would lose it. -UnitTestResult test_grind_shiny_stops(){ - StubGame game; - game.patch.shiny = true; - Pokemon::StoryStep step = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); - try{ - run_step(game, step); - }catch (ProgramFinishedException&){ - return true; - } - return "Expected the program to stop on a shiny."; -} - - -UnitTestResult test_level_args(){ - const std::optional back = level_check_of(level_args({.slot = 1, .level = 23})); - if (!back || back->slot != 1 || back->level != 23){ - return "Expected slot 2, level 23 to read back."; - } - const std::vector bad_args{ - {}, - {{"slot", int64_t(1)}}, - {{"min", int64_t(5)}}, - {{"slot", int64_t(0)}, {"min", int64_t(5)}}, - {{"slot", int64_t(1)}, {"min", int64_t(101)}}, - }; - for (const Pokemon::StoryActionArgs& bad : bad_args){ - if (level_check_of(bad)){ - return "Expected args with a missing or out-of-range value refused."; - } - } - return true; -} - -} // namespace - - -const AutoStoryAbilitiesCase AUTO_STORY_ABILITIES_CASES[] = { - { - .input = {"the steps' ends as outcomes", test_ability_steps}, - .expectation = {}, - }, - { - .input = {"a shiny in a GRIND stops the program", test_grind_shiny_stops}, - .expectation = {}, - }, - { - .input = {"a Fly after a TEACH reads no summary", test_teach_records_fly_user}, - .expectation = {}, - }, - { - .input = {"the LEVEL step's args", test_level_args}, - .expectation = {}, - }, - { - .input = {"TEACH and MART run once per save", test_once_per_save_steps}, - .expectation = {}, - }, -}; - -void add_tests_AutoStoryAbilities(UnitTestDatabase& database){ - for (const auto& item : AUTO_STORY_ABILITIES_CASES){ - database.add(item); - } - add_tests_AutoStoryMart(database); - add_tests_AutoStoryTeach(database); - add_tests_AutoStoryGrind(database); - add_tests_AutoStoryChoice(database); -} - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation +/* AutoStory Abilities Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The LEVEL step, and which ends of the MART, TEACH, GRIND and fossil + * steps the story takes as success, failure or a stop. + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "PokemonFRLG_AutoStoryAbilities.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +// A game where nothing happens: a lead whose level is set, a patch whose one battle is shiny if set. +class StubMart : public MartActions{ +public: + virtual bool open_buy_list() override{ return true; } + virtual void press_cursor(bool) override{} + virtual std::string read_row(size_t) override{ return ""; } + virtual void dump_screen(std::string_view) override{} + virtual PurchaseEnd buy(const MartBuy&) override{ return PurchaseEnd::FAILED; } + virtual bool leave() override{ return true; } +}; + +class StubTeach : public TeachActions{ +public: + // Its TM Case is empty. + virtual ItemOpen open_item(std::string_view, std::string_view) override{ return ItemOpen::NOT_IN_CASE; } + virtual TeachPrompt choose_member(size_t) override{ return TeachPrompt::FAILED; } + virtual ForgetEnd forget(size_t) override{ return ForgetEnd::FAILED; } + virtual void stop_teaching() override{} + virtual bool leave() override{ return true; } + virtual void dump_screen(std::string_view) override{} +}; + +class StubPatch : public GrindActions{ +public: + bool shiny = false; + + virtual bool find_encounter(Pokemon::Direction) override{ return true; } + virtual EncounterSeen read_encounter() override{ return {.species = "pidgey", .shiny = shiny}; } + virtual GrindFight fight() override{ return GrindFight::FAILED; } + virtual bool needs_heal() override{ return false; } + virtual bool heal_trip() override{ return true; } +}; + +class StubFossils : public ChoiceActions{ +public: + virtual bool talk() override{ return false; } + virtual std::optional read_offer() override{ return std::nullopt; } + virtual void answer(bool) override{} + virtual bool finish() override{ return true; } + virtual std::optional fossil_in_bag() override{ return std::nullopt; } +}; + +struct StubGame{ + std::optional level = 16; + StubMart mart; + StubTeach teach; + StubPatch patch; + StubFossils fossils; +}; + + +struct AutoStoryAbilitiesInput{ + std::string name; + std::function body; +}; + +struct AutoStoryAbilitiesExpectation{ +}; + +struct AutoStoryAbilitiesCase{ + AutoStoryAbilitiesInput input; + AutoStoryAbilitiesExpectation expectation; +}; + +class Test_AutoStoryAbilities : public UnitTest{ +public: + explicit Test_AutoStoryAbilities(AutoStoryAbilitiesCase test_case) + : UnitTest("PokemonFRLG::AutoStoryAbilities - " + 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::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryAbilitiesCase m_case; +}; + + +Pokemon::StoryStep game_step(std::string action, Pokemon::StoryActionArgs args){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = "test"; + step.action = std::move(action); + step.args = std::move(args); + return step; +} + +// The failure name the step ends with ("" for success, "unchanged" for +// one that changed nothing in the game); "none" if it isn't one of these +// steps. +std::string run_step(StubGame& game, const Pokemon::StoryStep& step){ + QuietLogger logger; + const MemberReader members = [&game](size_t slot) -> std::optional{ + if (slot != 0 || !game.level){ + return std::nullopt; + } + return MemberInfo{.species = "squirtle", .level = game.level, .moves = {"water-gun", "surf"}}; + }; + StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils}; + const std::optional outcome = run_ability_game_step(logger, nullptr, step, abilities); + if (!outcome){ + return "none"; + } + return outcome->changed_nothing ? "unchanged" : outcome->failure; +} + +struct StepCase{ + std::string name; + std::function setup; + Pokemon::StoryStep step; + std::string failure; +}; + +std::vector step_cases(){ + const auto none = [](StubGame&){}; + const Pokemon::StoryStep mart = mart_step("mart", "", {.map = "PewterCity_Mart", .lines = {{"potion", 5}}}); + const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); + return { + {"level reached", none, level_step("check", "", {.slot = 0, .level = 16}), "unchanged"}, + {"level below", none, level_step("check", "", {.slot = 0, .level = 17}), "level_below"}, + {"level unread", [](StubGame& game){ game.level.reset(); }, level_step("check", "", {.slot = 0, .level = 16}), "level_unread"}, + {"a Mart purchase that fails", none, mart, "mart_failed"}, + {"a move it knows already succeeds", none, teach_step("teach", "", {.item = "hm03", .move = "surf", .member = 0}), "unchanged"}, + {"a TM not in the TM Case is skipped", none, teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), "unchanged"}, + {"a level that can't be read stops a GRIND", [](StubGame& game){ game.level.reset(); }, grind, "grind_unread"}, + {"a GRIND without a nurse", none, game_step(GRIND_ACTION, {{"slot", int64_t(1)}, {"level", int64_t(20)}}), "bad_args"}, + {"no YES/NO at the fossil", none, fossil_step("fossil", "", Fossil::HELIX), "fossil_failed"}, + {"bad args", none, game_step(MART_ACTION, {{"map", std::string("PewterCity_Mart")}}), "bad_args"}, + {"another game step", none, capture_step("capture", "", {.species = "rattata"}), "none"}, + }; +} + +UnitTestResult test_ability_steps(){ + for (const StepCase& item : step_cases()){ + StubGame game; + item.setup(game); + const std::string failure = run_step(game, item.step); + if (failure != item.failure){ + return std::format("{}: \"{}\", expected \"{}\".", item.name, failure, item.failure); + } + } + return true; +} + + +// TEACH and MART steps are preparation, once per save: a retry from the +// same save skips one that changed nothing. A LEVEL check, which follows +// a GRIND, and the GRIND run every attempt. +UnitTestResult test_once_per_save_steps(){ + const std::vector once{ + teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}), + mart_step("mart", "", {.map = "CeruleanCity_Mart", .lines = {{.item = "potion", .quantity = 3}}}), + }; + for (const Pokemon::StoryStep& step : once){ + if (!step.once_per_save){ + return step.name + ": expected once per save."; + } + } + const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); + if (grind.once_per_save || level_step("level", "", {.slot = 0, .level = 16}).once_per_save){ + return "GRIND and LEVEL: expected every attempt."; + } + return true; +} + + +// A party whose screens count the summaries read. +class CountingScreens : public PartyScreens{ +public: + virtual bool open_party(size_t& members) override{ members = 2; m_opens++; return true; } + virtual bool enter_summary() override{ m_summaries++; return true; } + virtual std::string read_species() override{ m_summaries++; return "squirtle"; } + virtual bool next_member() override{ return true; } + virtual bool leave_summary() override{ return true; } + virtual bool open_member_menu(size_t slot) override{ m_menu = slot; return true; } + virtual std::optional read_member_menu() override{ + return PartyMemberMenu{.field_moves = {"surf"}}; + } + virtual bool close_member_menu() override{ return true; } + virtual void close() override{} + + size_t m_opens = 0; + size_t m_summaries = 0; + size_t m_menu = SIZE_MAX; +}; + +// A TEACH of a field move records its user; the Fly after it opens the +// party once, at that slot, and reads no summary, though the species +// cache was emptied by a reload. A TEACH of a plain TM records nothing. +UnitTestResult test_teach_records_fly_user(){ + StubGame game; + QuietLogger logger; + const MemberReader members = [](size_t slot) -> std::optional{ + if (slot != 0){ + return std::nullopt; + } + return MemberInfo{.species = "squirtle", .level = 16, .moves = {"water-gun", "surf"}}; + }; + PartyCache party; + StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils, {}, &party}; + run_ability_game_step(logger, nullptr, teach_step("teach_surf", "", {.item = "hm03", .move = "surf", .member = 0}), abilities); + run_ability_game_step(logger, nullptr, teach_step("teach_tm", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), abilities); + const std::optional user = party.users().find("surf"); + if (!user || user->slot != 0 || user->species != "squirtle"){ + return "the Surf user isn't recorded as slot 1, squirtle."; + } + if (party.users().find("water-pulse")){ + return "a TM move was recorded as a field move."; + } + party.invalidate_species(); + CountingScreens screens; + size_t flights = 0; + const std::string failure = use_field_move(logger, screens, party, "surf", "squirtle", [&flights](size_t){ + flights++; + return std::string(); + }); + if (!failure.empty() || flights != 1 || screens.m_menu != 0 || screens.m_opens != 1 || screens.m_summaries != 0){ + return std::format( + "Fly after TEACH: failure '{}', {} flights, menu {}, {} party opens, {} summary reads.", + failure, flights, screens.m_menu, screens.m_opens, screens.m_summaries + ); + } + return true; +} + + +// A shiny in a GRIND stops the program, not the checkpoint: a reload +// would lose it. +UnitTestResult test_grind_shiny_stops(){ + StubGame game; + game.patch.shiny = true; + Pokemon::StoryStep step = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); + try{ + run_step(game, step); + }catch (ProgramFinishedException&){ + return true; + } + return "Expected the program to stop on a shiny."; +} + + +UnitTestResult test_level_args(){ + const std::optional back = level_check_of(level_args({.slot = 1, .level = 23})); + if (!back || back->slot != 1 || back->level != 23){ + return "Expected slot 2, level 23 to read back."; + } + const std::vector bad_args{ + {}, + {{"slot", int64_t(1)}}, + {{"min", int64_t(5)}}, + {{"slot", int64_t(0)}, {"min", int64_t(5)}}, + {{"slot", int64_t(1)}, {"min", int64_t(101)}}, + }; + for (const Pokemon::StoryActionArgs& bad : bad_args){ + if (level_check_of(bad)){ + return "Expected args with a missing or out-of-range value refused."; + } + } + return true; +} + +} // namespace + + +const AutoStoryAbilitiesCase AUTO_STORY_ABILITIES_CASES[] = { + { + .input = {"the steps' ends as outcomes", test_ability_steps}, + .expectation = {}, + }, + { + .input = {"a shiny in a GRIND stops the program", test_grind_shiny_stops}, + .expectation = {}, + }, + { + .input = {"a Fly after a TEACH reads no summary", test_teach_records_fly_user}, + .expectation = {}, + }, + { + .input = {"the LEVEL step's args", test_level_args}, + .expectation = {}, + }, + { + .input = {"TEACH and MART run once per save", test_once_per_save_steps}, + .expectation = {}, + }, +}; + +void add_tests_AutoStoryAbilities(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_ABILITIES_CASES){ + database.add(item); + } + add_tests_AutoStoryMart(database); + add_tests_AutoStoryTeach(database); + add_tests_AutoStoryGrind(database); + add_tests_AutoStoryChoice(database); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp index 2d2a7d56fd..1f810c0478 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.cpp @@ -93,7 +93,7 @@ std::vector field_move_specs(){ {.kind = StoryStepKind::GAME, .name = FLY_VARIANT, .args = { required_arg("town", StoryArgType::WORD, "the town's map, as kanto_fly_towns() names it (CeladonCity, Route4)"), absent_arg("slot", StoryArgType::INTEGER, "the Fly user's party slot, from 1, when no species is named"), - absent_arg("species", StoryArgType::WORD, "the Fly user by its species, e.g. \"pidgey\": the first slot whose summary reads it"), + absent_arg("species", StoryArgType::WORD, "the Fly user by its species, e.g. \"pidgey\": the first member whose menu lists FLY flies, recorded under this name"), optional_arg("menu_row", StoryArgType::INTEGER, int64_t(2), "FLY's row on its menu, from 1: SUMMARY, then field moves in move order"), optional_arg("safari", StoryArgType::BOOLEAN, false, "in the Safari Zone, whose START menu has RETIRE on top"), }}, @@ -133,9 +133,10 @@ void tap_dpad(ProControllerContext& context, DpadPosition dpad, size_t count, Mi } } -// From the Fly user's menu: FLY, to the fly map. Returns the failure, or empty. -std::string fly_from_member_menu(ConsoleHandle& console, ProControllerContext& context, const FlyPlan& plan){ - tap_dpad(context, DPAD_DOWN, plan.menu_row, MENU_TAP, MENU_TAP_RELEASE); +// From the Fly user's menu, the cursor on SUMMARY: FLY on row `row`, to +// the fly map. Returns the failure, or empty. +std::string fly_from_member_menu(ConsoleHandle& console, ProControllerContext& context, size_t row){ + tap_dpad(context, DPAD_DOWN, row, MENU_TAP, MENU_TAP_RELEASE); KantoMapWatcher fly_map(COLOR_RED); context.wait_for_all_requests(); pbf_press_button(context, BUTTON_A, 160ms, 0ms); @@ -161,7 +162,7 @@ std::string open_fly_map(ConsoleHandle& console, ProControllerContext& context, if (wait_until(console, context, MON_MENU_TIMEOUT, {mon_menu}) < 0){ return "fly_no_menu"; } - return fly_from_member_menu(console, context, plan); + return fly_from_member_menu(console, context, plan.menu_row); } // On the fly map: the cursor to the corner, then to the town, and A. @@ -211,20 +212,23 @@ std::optional run_field_move_step( const FlyTown& town = kanto_fly_towns()[plan->town]; std::string failure; if (!plan->species.empty()){ - // The party is opened once, at the recorded Fly user's slot if the - // TEACH or an earlier Fly left one, else at the scan's find. + // The party is opened once: the recorded Fly user's menu if the + // TEACH or an earlier Fly left one, else the members' menus down + // the party to the first that lists FLY. console.log(std::format( - "Story: Fly with the {}, menu row {}, to {} (cell {}, {}).", - plan->species, plan->menu_row + 1, town.name, town.cell.x, town.cell.y + "Story: Fly with the {}, to {} (cell {}, {}).", plan->species, town.name, town.cell.x, town.cell.y )); const std::unique_ptr screens = console_party_screens(console, context, plan->start_menu, language); - failure = use_field_move(console.logger(), *screens, party, FLY_MOVE, plan->species, [&]{ - return fly_from_member_menu(console, context, *plan); + failure = use_field_move(console.logger(), *screens, party, FLY_MOVE, plan->species, [&](size_t row){ + return fly_from_member_menu(console, context, row); }); if (failure == FIELD_MOVE_NO_MEMBER){ - console.log(std::format("Story: no {} read in the party to Fly with.", plan->species), COLOR_RED); + console.log("Story: no member's menu lists FLY.", COLOR_RED); return Pokemon::outcome_failed("fly_no_member", plan->species); } + if (failure == FIELD_MOVE_MENU_UNREAD){ + return Pokemon::outcome_failed("fly_menu_unread", plan->species); + } }else{ console.log(std::format( "Story: Fly with slot {}, menu row {}, to {} (cell {}, {}).", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp index 9b11d3c3ae..b17eb0cf4d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp @@ -132,7 +132,7 @@ std::optional use_recorded_member( } logger.log(std::format("Party: the {} uses {} from slot {} (recorded).", user.species, move, user.slot + 1)); if (user.slot < members && screens.open_member_menu(user.slot)){ - std::string failure = from_menu(); + std::string failure = from_menu(1); if (failure.empty()){ return failure; } @@ -160,7 +160,7 @@ std::string use_field_move( return FIELD_MOVE_NO_MEMBER; } cache.users().record(std::string(move), *slot, std::string(species)); - return from_menu(); + return from_menu(1); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h index 0a4fc2f282..494c37e805 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h @@ -18,6 +18,12 @@ * lookup of a species in it opens the party once and goes straight to the * slot, with no summary read. * + * A field move's user is found without a summary: A on a member opens its + * menu, which lists its field moves in blue under SUMMARY + * (PartyMemberMenuReader). The scan opens the party once, walks the cursor + * down it, and stops at the first member whose menu lists the move; that + * menu is where the move is picked. + * */ #ifndef PokemonAutomation_PokemonFRLG_AutoStoryPartyRoster_H @@ -31,6 +37,7 @@ #include #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.h" #include "PokemonFRLG_AutoStoryFieldMoveUsers.h" namespace PokemonAutomation{ @@ -78,8 +85,14 @@ class PartyScreens{ // Back out of the summary to the party menu: the member's menu is // open. False if it didn't show. virtual bool leave_summary() = 0; - // From the party menu on the lead: slot `slot`'s menu opened. + // From the party menu, the cursor where open_party(), the summary or + // the last member's menu left it: slot `slot`'s menu opened. virtual bool open_member_menu(size_t slot) = 0; + // The member's menu now open, as read; nothing if it isn't read. + virtual std::optional read_member_menu() = 0; + // B on the member's menu: back to the party menu, the cursor on the + // member. False if the menu didn't close. + virtual bool close_member_menu() = 0; // Back to the overworld from wherever the party menu is. virtual void close() = 0; }; @@ -97,18 +110,23 @@ std::optional open_member_menu_of( ); -// What use_field_move() returns when no member reads as the species. +// What use_field_move() returns when no member's menu lists the move. inline const std::string FIELD_MOVE_NO_MEMBER = "no_member"; -// Runs the move from the member's menu; its failure, or empty. -using FieldMoveFromMenu = std::function; -// The field move `move` used by the first member read as `species`: the -// party is opened, the member's menu is chosen, and `from_menu` (the -// console's FLY row and map) runs from it. Returns its failure, empty on -// success, or FIELD_MOVE_NO_MEMBER if no member reads as `species`. With a -// record in the cache's users for `move` and `species`, the slot is chosen -// without reading a summary; if the menu there fails (no such row, a -// different member), the party is closed, the record dropped, and the scan -// finds the member and records it again. A scan records what it finds. +// What it returns when a member's menu isn't read, or lists a field move +// whose name isn't read: the move may be there, so nothing is picked. +inline const std::string FIELD_MOVE_MENU_UNREAD = "menu_unread"; +// Runs the move from the member's menu, its row there (SUMMARY is 0) +// given; its failure, or empty. +using FieldMoveFromMenu = std::function; +// The field move `move` (a slug, "fly") used by the first member whose +// menu lists it: the party is opened once, the members' menus are opened +// down the party until one lists `move`, and `from_menu` (the console's +// FLY row and map) runs from that menu. No summary is read. Returns its +// failure, empty on success, FIELD_MOVE_NO_MEMBER if no menu lists the +// move, or FIELD_MOVE_MENU_UNREAD. With a record in the cache's users for +// `move`, that slot's menu is opened first and the scan runs only if it +// doesn't list the move (the record is dropped then). What is found is +// recorded, with `species` (the step's name for the user) as its species. std::string use_field_move( Logger& logger, PartyScreens& screens, PartyCache& cache, std::string_view move, std::string_view species, const FieldMoveFromMenu& from_menu diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp index 5d41ce610a..7e90706977 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp @@ -2,11 +2,13 @@ * * From: https://github.com/PokemonAutomation/ * - * Counts the screens a species lookup goes through, on a fake party. + * Counts the screens a species lookup and a field move's user scan go + * through, on a fake party. * */ #include +#include #include #include #include @@ -27,6 +29,12 @@ class FakeParty : public PartyScreens{ public: explicit FakeParty(std::vector species) : m_species(std::move(species)) + , m_menus(m_species.size()) + {} + // Each member's menu: the field moves it lists, nothing if unread. + FakeParty(std::vector species, std::vector> menus) + : m_species(std::move(species)) + , m_menus(std::move(menus)) {} virtual bool open_party(size_t& members) override{ @@ -56,6 +64,15 @@ class FakeParty : public PartyScreens{ } virtual bool open_member_menu(size_t slot) override{ m_menu_slot = slot; + m_menu_opens++; + return true; + } + virtual std::optional read_member_menu() override{ + m_menu_reads++; + return m_menu_slot < m_menus.size() ? m_menus[m_menu_slot] : std::nullopt; + } + virtual bool close_member_menu() override{ + m_menu_closes++; return true; } virtual void close() override{ @@ -70,8 +87,44 @@ class FakeParty : public PartyScreens{ size_t m_summary_opens = 0; size_t m_reads = 0; size_t m_closes = 0; + std::vector> m_menus; + size_t m_menu_opens = 0; + size_t m_menu_reads = 0; + size_t m_menu_closes = 0; }; +// A menu listing `moves` in blue. +PartyMemberMenu menu_with(std::vector moves){ + return PartyMemberMenu{.field_moves = std::move(moves)}; +} +const PartyMemberMenu NO_FIELD_MOVES = {}; + +// The story's party: the Pidgey third, with Fly; the Oddish with Cut. +FakeParty fly_party(){ + return FakeParty( + {"blastoise", "oddish", "pidgey", "eevee"}, + {NO_FIELD_MOVES, menu_with({"cut", "flash"}), menu_with({"fly"}), NO_FIELD_MOVES} + ); +} + +// Party opens, members' menus opened and closed (B), summaries entered. +UnitTestResult check_menus( + const std::string& what, const FakeParty& party, + size_t party_opens, size_t menu_opens, size_t menu_closes, size_t closes +){ + if (party.m_party_opens != party_opens || party.m_menu_opens != menu_opens + || party.m_menu_closes != menu_closes || party.m_closes != closes || party.m_summary_opens != 0 + ){ + return std::format( + "{}: {} party opens, {} member menus opened, {} closed with B, {} party closes, {} summaries; " + "expected {}, {}, {}, {}, 0.", + what, party.m_party_opens, party.m_menu_opens, party.m_menu_closes, party.m_closes, + party.m_summary_opens, party_opens, menu_opens, menu_closes, closes + ); + } + return true; +} + UnitTestResult check_counts( const std::string& what, const FakeParty& party, size_t party_opens, size_t summary_opens, size_t reads, size_t closes @@ -188,71 +241,134 @@ UnitTestResult test_cached_slot_opens_nothing(Logger& logger){ return check_counts("cached slot only", again, 0, 0, 0, 0); } -// A Fly from the member's menu: it works on the slot that holds `holder`. -FieldMoveFromMenu fly_from(const FakeParty& party, size_t holder, size_t& calls){ - return [&party, holder, &calls]() -> std::string{ +// A Fly from the member's menu: it works on the slot that holds `holder`, +// from FLY's row `row`. +FieldMoveFromMenu fly_from(const FakeParty& party, size_t holder, size_t row, size_t& calls){ + return [&party, holder, row, &calls](size_t picked) -> std::string{ calls++; - return party.m_menu_slot == holder ? "" : "fly_no_map"; + return party.m_menu_slot == holder && picked == row ? "" : "fly_no_map"; }; } -// A recorded Fly user: the party opens once and no summary is read. +// The first Fly: the party opened once, the menus down to the Pidgey's, +// FLY picked there; no summary. +UnitTestResult test_scan_stops_at_first_user(Logger& logger){ + FakeParty party = fly_party(); + PartyCache cache; + size_t calls = 0; + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 2, 1, calls)); + if (!failure.empty() || calls != 1){ + return std::format("the first Fly: failure '{}', {} menu uses.", failure, calls); + } + const std::optional user = cache.users().find("fly"); + if (!user || user->slot != 2 || user->species != "pidgey"){ + return "the scan didn't record the Pidgey at slot 3."; + } + return check_menus("first fly", party, 1, 3, 2, 0); +} + +// FLY under another field move is picked from its own row. +UnitTestResult test_fly_row_from_menu(Logger& logger){ + FakeParty party({"pidgeot"}, {menu_with({"teleport", "fly"})}); + PartyCache cache; + size_t calls = 0; + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgeot", fly_from(party, 0, 2, calls)); + if (!failure.empty() || calls != 1){ + return std::format("FLY on the menu's third row: failure '{}', {} menu uses.", failure, calls); + } + return true; +} + +// A recorded Fly user: one party open, its menu only. UnitTestResult test_recorded_user_reads_no_summary(Logger& logger){ - FakeParty party({"blastoise", "pidgey", "oddish"}); + FakeParty party = fly_party(); PartyCache cache; - cache.users().record("fly", 1, "pidgey"); + cache.users().record("fly", 2, "pidgey"); size_t calls = 0; - const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, calls)); + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 2, 1, calls)); if (!failure.empty() || calls != 1){ return std::format("a recorded Fly: failure '{}', {} menu uses.", failure, calls); } - return check_counts("recorded user", party, 1, 0, 0, 0); + return check_menus("recorded user", party, 1, 1, 0, 0); } -// The record names a slot another member holds now: the menu fails, the -// party is closed, the scan finds the right slot and the record is updated. +// The record names a slot whose menu has no FLY now: B, and the scan runs +// in the same party menu; the record is updated. UnitTestResult test_stale_record_scans_and_updates(Logger& logger){ - FakeParty party({"blastoise", "oddish", "pidgey"}); + FakeParty party = fly_party(); PartyCache cache; cache.users().record("fly", 0, "pidgey"); size_t calls = 0; - const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 2, calls)); - if (!failure.empty() || calls != 2){ + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 2, 1, calls)); + if (!failure.empty() || calls != 1){ return std::format("a stale Fly record: failure '{}', {} menu uses.", failure, calls); } const std::optional user = cache.users().find("fly"); if (!user || user->slot != 2){ return "the stale record isn't replaced by the slot the scan found."; } - return check_counts("stale record", party, 2, 1, 3, 1); + // Slot 1 (the record), then 2 and 3; slot 1 isn't opened twice. + return check_menus("stale record", party, 1, 3, 2, 0); } -// A record for another species isn't trusted: the scan runs. -UnitTestResult test_other_species_record_scans(Logger& logger){ - FakeParty party({"blastoise", "pidgeot"}); +// A record of another species (the Pidgey evolved) is checked by its menu. +UnitTestResult test_other_species_record_checked_by_menu(Logger& logger){ + FakeParty party({"blastoise", "pidgeot"}, {NO_FIELD_MOVES, menu_with({"fly"})}); PartyCache cache; - cache.users().record("fly", 0, "pidgey"); + cache.users().record("fly", 1, "pidgey"); size_t calls = 0; - const std::string failure = use_field_move(logger, party, cache, "fly", "pidgeot", fly_from(party, 1, calls)); + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgeot", fly_from(party, 1, 1, calls)); if (!failure.empty() || calls != 1){ return std::format("a record of another species: failure '{}', {} menu uses.", failure, calls); } - return check_counts("other species", party, 1, 1, 2, 0); + return check_menus("other species", party, 1, 1, 0, 0); } -// No record: the scan runs once and records, so the next Fly reads nothing. +// No record: the scan runs once and records, so the next Fly opens one menu. UnitTestResult test_scan_records_for_next_fly(Logger& logger){ - FakeParty party({"blastoise", "pidgey"}); + FakeParty party = fly_party(); PartyCache cache; size_t calls = 0; - use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, calls)); - FakeParty again({"blastoise", "pidgey"}); - cache.invalidate_species(); - const std::string failure = use_field_move(logger, again, cache, "fly", "pidgey", fly_from(again, 1, calls)); + use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 2, 1, calls)); + FakeParty again = fly_party(); + const std::string failure = use_field_move(logger, again, cache, "fly", "pidgey", fly_from(again, 2, 1, calls)); if (!failure.empty()){ return std::format("the second Fly: {}", failure); } - return check_counts("second fly", again, 1, 0, 0, 0); + return check_menus("second fly", again, 1, 1, 0, 0); +} + +// No menu lists FLY: every member's menu opened once, the party closed. +UnitTestResult test_no_member_failure(Logger& logger){ + FakeParty party({"blastoise", "oddish"}, {NO_FIELD_MOVES, menu_with({"cut"})}); + PartyCache cache; + size_t calls = 0; + if (use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 0, 1, calls)) != FIELD_MOVE_NO_MEMBER || calls != 0){ + return "a party without a Fly user should fail with no member and not fly."; + } + return check_menus("no member", party, 1, 2, 2, 1); +} + +// A menu not read stops the scan: the party is closed, nothing picked. +UnitTestResult test_unread_menu_fails(Logger& logger){ + FakeParty party({"blastoise", "pidgey"}, {std::nullopt, menu_with({"fly"})}); + PartyCache cache; + size_t calls = 0; + if (use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, 1, calls)) != FIELD_MOVE_MENU_UNREAD || calls != 0){ + return "an unread menu should fail as unread and not fly."; + } + return check_menus("unread menu", party, 1, 1, 0, 1); +} + +// A blue row whose name isn't read may be FLY: the scan stops. +UnitTestResult test_unread_field_move_fails(Logger& logger){ + FakeParty party({"oddish", "pidgey"}, {menu_with({"cut", ""}), menu_with({"fly"})}); + PartyCache cache; + size_t calls = 0; + if (use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, 1, calls)) != FIELD_MOVE_MENU_UNREAD || calls != 0){ + return "an unread field move name should fail as unread and not fly."; + } + return check_menus("unread field move", party, 1, 1, 0, 1); } // A deposit or withdrawal moves members: nothing is recorded after it. @@ -266,17 +382,6 @@ UnitTestResult test_invalidate_drops_records(Logger&){ return true; } -// No member of the species: its failure, the party closed. -UnitTestResult test_no_member_failure(Logger& logger){ - FakeParty party({"blastoise"}); - PartyCache cache; - size_t calls = 0; - if (use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 0, calls)) != FIELD_MOVE_NO_MEMBER || calls != 0){ - return "a party without the species should fail with no member and not fly."; - } - return check_counts("no member", party, 1, 1, 1, 1); -} - // The users as the settings keep them read back the same, slots from 1. UnitTestResult test_users_text_round_trip(Logger&){ FieldMoveUsers users; @@ -317,19 +422,19 @@ UnitTestResult test_unreadable_users_text_dropped(Logger&){ } // After a restart, the users read from the settings: the first Fly opens -// the party once and reads no summary. +// the party once and only the recorded user's menu. UnitTestResult test_restart_fly_reads_no_summary(Logger& logger){ FieldMoveUsers before; before.record("fly", 2, "pidgey"); PartyCache cache; cache.users() = parse_field_move_users(before.to_text()).users; - FakeParty party({"blastoise", "oddish", "pidgey"}); + FakeParty party = fly_party(); size_t calls = 0; - const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 2, calls)); + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 2, 1, calls)); if (!failure.empty() || calls != 1){ return std::format("the Fly after a restart: failure '{}', {} menu uses.", failure, calls); } - return check_counts("restart", party, 1, 0, 0, 0); + return check_menus("restart", party, 1, 1, 0, 0); } struct AutoStoryPartyRosterInput{ @@ -372,15 +477,19 @@ const AutoStoryPartyRosterCase AUTO_STORY_PARTY_ROSTER_CASES[] = { {.input = {"the first of two of a species wins", test_first_duplicate_wins}, .expectation = {}}, {.input = {"a lookup that doesn't keep the menu closes it", test_closes_when_not_kept}, .expectation = {}}, {.input = {"a cached slot for a TEACH opens nothing", test_cached_slot_opens_nothing}, .expectation = {}}, - {.input = {"a recorded field move user reads no summary", test_recorded_user_reads_no_summary}, .expectation = {}}, + {.input = {"a Fly scan stops at the first menu with FLY", test_scan_stops_at_first_user}, .expectation = {}}, + {.input = {"FLY is picked from its row on the menu", test_fly_row_from_menu}, .expectation = {}}, + {.input = {"a recorded field move user opens only its menu", test_recorded_user_reads_no_summary}, .expectation = {}}, {.input = {"a stale record falls back to the scan and is updated", test_stale_record_scans_and_updates}, .expectation = {}}, - {.input = {"a record of another species is not trusted", test_other_species_record_scans}, .expectation = {}}, + {.input = {"a record of another species is checked by its menu", test_other_species_record_checked_by_menu}, .expectation = {}}, {.input = {"a scan records the user for the next Fly", test_scan_records_for_next_fly}, .expectation = {}}, {.input = {"invalidate() drops the field move users", test_invalidate_drops_records}, .expectation = {}}, - {.input = {"no member of the species fails without flying", test_no_member_failure}, .expectation = {}}, + {.input = {"no menu with FLY fails without flying", test_no_member_failure}, .expectation = {}}, + {.input = {"an unread member menu fails without flying", test_unread_menu_fails}, .expectation = {}}, + {.input = {"an unread field move name fails without flying", test_unread_field_move_fails}, .expectation = {}}, {.input = {"the field move users' text reads back the same", test_users_text_round_trip}, .expectation = {}}, {.input = {"unreadable field move users' text is dropped", test_unreadable_users_text_dropped}, .expectation = {}}, - {.input = {"a Fly after a restart reads no summary", test_restart_fly_reads_no_summary}, .expectation = {}}, + {.input = {"a Fly after a restart opens only the recorded menu", test_restart_fly_reads_no_summary}, .expectation = {}}, }; } // namespace diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp index 4f0bbb79b0..01285bf2a4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp @@ -122,6 +122,9 @@ std::optional read_open_summary(ConsoleHandle& console, ProControll // text are redrawn over a few frames. constexpr Milliseconds MEMBER_SWITCH_SETTLE = 900ms; constexpr size_t SPECIES_READ_TRIES = 3; +// B on a member's menu: it is gone the next frames; checked for 3 s. +constexpr Milliseconds MENU_CLOSE_CHECK = 100ms; +constexpr size_t MENU_CLOSE_CHECKS = 30; class ConsolePartyScreens : public PartyScreens{ public: @@ -142,6 +145,8 @@ class ConsolePartyScreens : public PartyScreens{ tap(m_context, DPAD_LEFT); m_context.wait_for_all_requests(); members = size_t(detect_last_occupied_party_slot(m_console)) + 1; + m_members = members; + m_cursor = 0; return true; } @@ -165,6 +170,10 @@ class ConsolePartyScreens : public PartyScreens{ } virtual bool next_member() override{ + // DOWN on the last member does nothing. + if (m_cursor + 1 < m_members){ + m_cursor++; + } tap(m_context, DPAD_DOWN, 0ms); pbf_wait(m_context, MEMBER_SWITCH_SETTLE); m_context.wait_for_all_requests(); @@ -180,12 +189,45 @@ class ConsolePartyScreens : public PartyScreens{ } virtual bool open_member_menu(size_t slot) override{ - for (size_t c = 0; c < slot; c++){ + // The party menu's UP and DOWN step one member, through CANCEL + // past the ends; the scans never go past them. + for (; m_cursor < slot; m_cursor++){ tap(m_context, DPAD_DOWN); } + for (; m_cursor > slot; m_cursor--){ + tap(m_context, DPAD_UP); + } return open_menu_on_cursor(); } + virtual std::optional read_member_menu() override{ + VideoSnapshot screen = m_console.video().snapshot(); + if (!screen){ + return std::nullopt; + } + std::optional menu = read_party_member_menu(m_console.logger(), m_language, screen); + if (!menu || !menu->all_read()){ + m_console.log(std::format("Party: slot {}'s menu isn't read.", m_cursor + 1), COLOR_RED); + dump_debug_image(m_console, "AutoStory/party", "member_menu", screen); + } + return menu; + } + + virtual bool close_member_menu() override{ + press(m_context, BUTTON_B); + m_context.wait_for_all_requests(); + PartySelectionDetector menu(COLOR_RED); + for (size_t c = 0; c < MENU_CLOSE_CHECKS; c++){ + pbf_wait(m_context, MENU_CLOSE_CHECK); + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_console.video().snapshot(); + if (screen && !menu.detect(screen)){ + return true; + } + } + return false; + } + virtual void close() override{ mash_until_overworld(m_console, m_context, 20000ms); } @@ -201,6 +243,9 @@ class ConsolePartyScreens : public PartyScreens{ ProControllerContext& m_context; StartMenu m_menu; Language m_language; + size_t m_members = 0; + // The member the party menu's cursor is on. + size_t m_cursor = 0; }; } // namespace From c478d807340d798765aa890689fd5ede723fa9be Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 07:14:25 -0800 Subject: [PATCH 09/12] FRLG AutoStory: Fly finds its user by the FLY row in the party menu, not the summary --- .../PokemonFRLG_AutoStoryFieldMoves.h | 8 +- .../PokemonFRLG_AutoStoryPartyRoster.cpp | 94 ++++++++++++------- 2 files changed, 67 insertions(+), 35 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.h index 366b691d83..4037fddbed 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoves.h @@ -34,7 +34,8 @@ namespace PokemonFRLG{ // The GAME step that flies to a town, outdoors: START, POKEMON, the Fly -// user (`slot`, from 1, or the first member read as `species`), FLY on its menu (`menu_row`, from 1: SUMMARY, +// user (`slot`, from 1; or, with `species`, the first member whose menu +// lists FLY, FLY's row read there), FLY on its menu (`menu_row`, from 1: SUMMARY, // then its field moves in move order, so 2 when Fly is its only one; // pokefirered SetPartyMonFieldSelectionActions()), and `town` on the fly // map (kanto_fly_towns()). It ends on the town's landing tile. With @@ -75,8 +76,9 @@ std::vector field_move_specs(); // On the console, a step of this file's; nothing for another step. The // step ends on its pose_after, if it has one. A Fly naming a species opens -// the party once and goes to the Fly user's menu from there; `party` -// keeps the species read, so a later Fly reads no summary. +// the party once and the members' menus down to the first that lists FLY +// (use_field_move()); `party` records that slot, so a later Fly opens +// only its menu. std::optional run_field_move_step( ConsoleHandle& console, ProControllerContext& context, Language language, const Pokemon::StoryStep& step, PartyCache& party diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp index b17eb0cf4d..c5fcdcd83d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp @@ -118,28 +118,40 @@ std::optional open_member_menu_of( namespace{ -// The recorded user's menu from the overworld, and `from_menu` from it: -// the failure, or nothing if the record didn't give the move (the screens -// are closed then). A party that doesn't open is no fault of the record. -std::optional use_recorded_member( - Logger& logger, PartyScreens& screens, const FieldMoveUser& user, std::string_view move, - const FieldMoveFromMenu& from_menu -){ - size_t members = 0; - if (!screens.open_party(members)){ - logger.log("Party: the menu didn't open.", COLOR_RED); - return FIELD_MOVE_NO_MEMBER; +// What a member's menu says about a field move. +struct MemberMenuCheck{ + enum class Result{ + LISTED, // the menu is open and lists the move at `row` + NOT_LISTED, // it doesn't; the menu is closed again + UNREAD, // the menu, or a field move's name on it, wasn't read + }; + Result result = Result::UNREAD; + size_t row = 0; +}; + +// With the party open: slot `slot`'s menu opened and read for `move`. +MemberMenuCheck check_member_menu(Logger& logger, PartyScreens& screens, size_t slot, std::string_view move){ + using Result = MemberMenuCheck::Result; + if (!screens.open_member_menu(slot)){ + logger.log(std::format("Party: slot {}'s menu didn't open.", slot + 1), COLOR_RED); + return {}; } - logger.log(std::format("Party: the {} uses {} from slot {} (recorded).", user.species, move, user.slot + 1)); - if (user.slot < members && screens.open_member_menu(user.slot)){ - std::string failure = from_menu(1); - if (failure.empty()){ - return failure; - } + const std::optional menu = screens.read_member_menu(); + if (!menu){ + return {}; } - logger.log(std::format("Party: slot {} didn't give {}; reading the party.", user.slot + 1, move), COLOR_RED); - screens.close(); - return std::nullopt; + if (const std::optional row = menu->row_of(move)){ + return {.result = Result::LISTED, .row = *row}; + } + // A name not read may be the move. + if (!menu->all_read()){ + return {}; + } + if (!screens.close_member_menu()){ + logger.log(std::format("Party: slot {}'s menu didn't close.", slot + 1), COLOR_RED); + return {}; + } + return {.result = Result::NOT_LISTED}; } } // namespace @@ -148,23 +160,41 @@ std::string use_field_move( Logger& logger, PartyScreens& screens, PartyCache& cache, std::string_view move, std::string_view species, const FieldMoveFromMenu& from_menu ){ - if (const std::optional user = cache.users().find(move); user && user->species == species){ - if (const std::optional done = use_recorded_member(logger, screens, *user, move, from_menu)){ - return *done; + using Result = MemberMenuCheck::Result; + size_t members = 0; + if (!screens.open_party(members)){ + logger.log("Party: the menu didn't open.", COLOR_RED); + return FIELD_MOVE_NO_MEMBER; + } + // The recorded user first, then the others from the lead. + std::vector order; + if (const std::optional user = cache.users().find(move); user && user->slot < members){ + logger.log(std::format("Party: {} recorded for slot {} ({}).", move, user->slot + 1, user->species)); + order.push_back(user->slot); + } + for (size_t slot = 0; slot < members; slot++){ + if (order.empty() || order[0] != slot){ + order.push_back(slot); } - cache.users().forget(move); - cache.invalidate_species(); } - const std::optional slot = open_member_menu_of(logger, screens, cache, species, true); - if (!slot){ - return FIELD_MOVE_NO_MEMBER; + for (const size_t slot : order){ + const MemberMenuCheck check = check_member_menu(logger, screens, slot, move); + if (check.result == Result::UNREAD){ + screens.close(); + return FIELD_MOVE_MENU_UNREAD; + } + if (check.result == Result::LISTED){ + logger.log(std::format("Party: slot {} lists {} on row {}.", slot + 1, move, check.row + 1)); + cache.users().record(std::string(move), slot, std::string(species)); + return from_menu(check.row); + } } - cache.users().record(std::string(move), *slot, std::string(species)); - return from_menu(1); + logger.log(std::format("Party: no member's menu lists {}.", move), COLOR_RED); + cache.users().forget(move); + screens.close(); + return FIELD_MOVE_NO_MEMBER; } - - } // namespace PokemonFRLG } // namespace NintendoSwitch } // namespace PokemonAutomation From 7b072e38b12f175bd67600c40da084f1eeffc035 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 07:14:46 -0800 Subject: [PATCH 10/12] FRLG AutoStory: keep the abilities tests' LF line endings --- .../PokemonFRLG_AutoStoryAbilities_Tests.cpp | 674 +++++++++--------- 1 file changed, 337 insertions(+), 337 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp index 0668f6343c..f188f1e214 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -1,337 +1,337 @@ -/* AutoStory Abilities Tests - * - * From: https://github.com/PokemonAutomation/ - * - * The LEVEL step, and which ends of the MART, TEACH, GRIND and fossil - * steps the story takes as success, failure or a stop. - * - */ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/TestRunners/UnitTest.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "PokemonFRLG_AutoStoryAbilities.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -namespace{ - -class QuietLogger : public Logger{ -public: - using Logger::log; - virtual void log(const std::string&, Color) override{} -}; - -// A game where nothing happens: a lead whose level is set, a patch whose one battle is shiny if set. -class StubMart : public MartActions{ -public: - virtual bool open_buy_list() override{ return true; } - virtual void press_cursor(bool) override{} - virtual std::string read_row(size_t) override{ return ""; } - virtual void dump_screen(std::string_view) override{} - virtual PurchaseEnd buy(const MartBuy&) override{ return PurchaseEnd::FAILED; } - virtual bool leave() override{ return true; } -}; - -class StubTeach : public TeachActions{ -public: - // Its TM Case is empty. - virtual ItemOpen open_item(std::string_view, std::string_view) override{ return ItemOpen::NOT_IN_CASE; } - virtual TeachPrompt choose_member(size_t) override{ return TeachPrompt::FAILED; } - virtual ForgetEnd forget(size_t) override{ return ForgetEnd::FAILED; } - virtual void stop_teaching() override{} - virtual bool leave() override{ return true; } - virtual void dump_screen(std::string_view) override{} -}; - -class StubPatch : public GrindActions{ -public: - bool shiny = false; - - virtual bool find_encounter(Pokemon::Direction) override{ return true; } - virtual EncounterSeen read_encounter() override{ return {.species = "pidgey", .shiny = shiny}; } - virtual GrindFight fight() override{ return GrindFight::FAILED; } - virtual bool needs_heal() override{ return false; } - virtual bool heal_trip() override{ return true; } -}; - -class StubFossils : public ChoiceActions{ -public: - virtual bool talk() override{ return false; } - virtual std::optional read_offer() override{ return std::nullopt; } - virtual void answer(bool) override{} - virtual bool finish() override{ return true; } - virtual std::optional fossil_in_bag() override{ return std::nullopt; } -}; - -struct StubGame{ - std::optional level = 16; - StubMart mart; - StubTeach teach; - StubPatch patch; - StubFossils fossils; -}; - - -struct AutoStoryAbilitiesInput{ - std::string name; - std::function body; -}; - -struct AutoStoryAbilitiesExpectation{ -}; - -struct AutoStoryAbilitiesCase{ - AutoStoryAbilitiesInput input; - AutoStoryAbilitiesExpectation expectation; -}; - -class Test_AutoStoryAbilities : public UnitTest{ -public: - explicit Test_AutoStoryAbilities(AutoStoryAbilitiesCase test_case) - : UnitTest("PokemonFRLG::AutoStoryAbilities - " + 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::string(e.name()) + ": " + e.message(); - } - } - -private: - AutoStoryAbilitiesCase m_case; -}; - - -Pokemon::StoryStep game_step(std::string action, Pokemon::StoryActionArgs args){ - Pokemon::StoryStep step; - step.kind = Pokemon::StoryStepKind::GAME; - step.name = "test"; - step.action = std::move(action); - step.args = std::move(args); - return step; -} - -// The failure name the step ends with ("" for success, "unchanged" for -// one that changed nothing in the game); "none" if it isn't one of these -// steps. -std::string run_step(StubGame& game, const Pokemon::StoryStep& step){ - QuietLogger logger; - const MemberReader members = [&game](size_t slot) -> std::optional{ - if (slot != 0 || !game.level){ - return std::nullopt; - } - return MemberInfo{.species = "squirtle", .level = game.level, .moves = {"water-gun", "surf"}}; - }; - StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils}; - const std::optional outcome = run_ability_game_step(logger, nullptr, step, abilities); - if (!outcome){ - return "none"; - } - return outcome->changed_nothing ? "unchanged" : outcome->failure; -} - -struct StepCase{ - std::string name; - std::function setup; - Pokemon::StoryStep step; - std::string failure; -}; - -std::vector step_cases(){ - const auto none = [](StubGame&){}; - const Pokemon::StoryStep mart = mart_step("mart", "", {.map = "PewterCity_Mart", .lines = {{"potion", 5}}}); - const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); - return { - {"level reached", none, level_step("check", "", {.slot = 0, .level = 16}), "unchanged"}, - {"level below", none, level_step("check", "", {.slot = 0, .level = 17}), "level_below"}, - {"level unread", [](StubGame& game){ game.level.reset(); }, level_step("check", "", {.slot = 0, .level = 16}), "level_unread"}, - {"a Mart purchase that fails", none, mart, "mart_failed"}, - {"a move it knows already succeeds", none, teach_step("teach", "", {.item = "hm03", .move = "surf", .member = 0}), "unchanged"}, - {"a TM not in the TM Case is skipped", none, teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), "unchanged"}, - {"a level that can't be read stops a GRIND", [](StubGame& game){ game.level.reset(); }, grind, "grind_unread"}, - {"a GRIND without a nurse", none, game_step(GRIND_ACTION, {{"slot", int64_t(1)}, {"level", int64_t(20)}}), "bad_args"}, - {"no YES/NO at the fossil", none, fossil_step("fossil", "", Fossil::HELIX), "fossil_failed"}, - {"bad args", none, game_step(MART_ACTION, {{"map", std::string("PewterCity_Mart")}}), "bad_args"}, - {"another game step", none, capture_step("capture", "", {.species = "rattata"}), "none"}, - }; -} - -UnitTestResult test_ability_steps(){ - for (const StepCase& item : step_cases()){ - StubGame game; - item.setup(game); - const std::string failure = run_step(game, item.step); - if (failure != item.failure){ - return std::format("{}: \"{}\", expected \"{}\".", item.name, failure, item.failure); - } - } - return true; -} - - -// TEACH and MART steps are preparation, once per save: a retry from the -// same save skips one that changed nothing. A LEVEL check, which follows -// a GRIND, and the GRIND run every attempt. -UnitTestResult test_once_per_save_steps(){ - const std::vector once{ - teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}), - mart_step("mart", "", {.map = "CeruleanCity_Mart", .lines = {{.item = "potion", .quantity = 3}}}), - }; - for (const Pokemon::StoryStep& step : once){ - if (!step.once_per_save){ - return step.name + ": expected once per save."; - } - } - const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); - if (grind.once_per_save || level_step("level", "", {.slot = 0, .level = 16}).once_per_save){ - return "GRIND and LEVEL: expected every attempt."; - } - return true; -} - - -// A party whose screens count the summaries read. -class CountingScreens : public PartyScreens{ -public: - virtual bool open_party(size_t& members) override{ members = 2; m_opens++; return true; } - virtual bool enter_summary() override{ m_summaries++; return true; } - virtual std::string read_species() override{ m_summaries++; return "squirtle"; } - virtual bool next_member() override{ return true; } - virtual bool leave_summary() override{ return true; } - virtual bool open_member_menu(size_t slot) override{ m_menu = slot; return true; } - virtual std::optional read_member_menu() override{ - return PartyMemberMenu{.field_moves = {"surf"}}; - } - virtual bool close_member_menu() override{ return true; } - virtual void close() override{} - - size_t m_opens = 0; - size_t m_summaries = 0; - size_t m_menu = SIZE_MAX; -}; - -// A TEACH of a field move records its user; the Fly after it opens the -// party once, at that slot, and reads no summary, though the species -// cache was emptied by a reload. A TEACH of a plain TM records nothing. -UnitTestResult test_teach_records_fly_user(){ - StubGame game; - QuietLogger logger; - const MemberReader members = [](size_t slot) -> std::optional{ - if (slot != 0){ - return std::nullopt; - } - return MemberInfo{.species = "squirtle", .level = 16, .moves = {"water-gun", "surf"}}; - }; - PartyCache party; - StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils, {}, &party}; - run_ability_game_step(logger, nullptr, teach_step("teach_surf", "", {.item = "hm03", .move = "surf", .member = 0}), abilities); - run_ability_game_step(logger, nullptr, teach_step("teach_tm", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), abilities); - const std::optional user = party.users().find("surf"); - if (!user || user->slot != 0 || user->species != "squirtle"){ - return "the Surf user isn't recorded as slot 1, squirtle."; - } - if (party.users().find("water-pulse")){ - return "a TM move was recorded as a field move."; - } - party.invalidate_species(); - CountingScreens screens; - size_t flights = 0; - const std::string failure = use_field_move(logger, screens, party, "surf", "squirtle", [&flights](size_t){ - flights++; - return std::string(); - }); - if (!failure.empty() || flights != 1 || screens.m_menu != 0 || screens.m_opens != 1 || screens.m_summaries != 0){ - return std::format( - "Fly after TEACH: failure '{}', {} flights, menu {}, {} party opens, {} summary reads.", - failure, flights, screens.m_menu, screens.m_opens, screens.m_summaries - ); - } - return true; -} - - -// A shiny in a GRIND stops the program, not the checkpoint: a reload -// would lose it. -UnitTestResult test_grind_shiny_stops(){ - StubGame game; - game.patch.shiny = true; - Pokemon::StoryStep step = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); - try{ - run_step(game, step); - }catch (ProgramFinishedException&){ - return true; - } - return "Expected the program to stop on a shiny."; -} - - -UnitTestResult test_level_args(){ - const std::optional back = level_check_of(level_args({.slot = 1, .level = 23})); - if (!back || back->slot != 1 || back->level != 23){ - return "Expected slot 2, level 23 to read back."; - } - const std::vector bad_args{ - {}, - {{"slot", int64_t(1)}}, - {{"min", int64_t(5)}}, - {{"slot", int64_t(0)}, {"min", int64_t(5)}}, - {{"slot", int64_t(1)}, {"min", int64_t(101)}}, - }; - for (const Pokemon::StoryActionArgs& bad : bad_args){ - if (level_check_of(bad)){ - return "Expected args with a missing or out-of-range value refused."; - } - } - return true; -} - -} // namespace - - -const AutoStoryAbilitiesCase AUTO_STORY_ABILITIES_CASES[] = { - { - .input = {"the steps' ends as outcomes", test_ability_steps}, - .expectation = {}, - }, - { - .input = {"a shiny in a GRIND stops the program", test_grind_shiny_stops}, - .expectation = {}, - }, - { - .input = {"a Fly after a TEACH reads no summary", test_teach_records_fly_user}, - .expectation = {}, - }, - { - .input = {"the LEVEL step's args", test_level_args}, - .expectation = {}, - }, - { - .input = {"TEACH and MART run once per save", test_once_per_save_steps}, - .expectation = {}, - }, -}; - -void add_tests_AutoStoryAbilities(UnitTestDatabase& database){ - for (const auto& item : AUTO_STORY_ABILITIES_CASES){ - database.add(item); - } - add_tests_AutoStoryMart(database); - add_tests_AutoStoryTeach(database); - add_tests_AutoStoryGrind(database); - add_tests_AutoStoryChoice(database); -} - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation +/* AutoStory Abilities Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The LEVEL step, and which ends of the MART, TEACH, GRIND and fossil + * steps the story takes as success, failure or a stop. + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "PokemonFRLG_AutoStoryAbilities.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +// A game where nothing happens: a lead whose level is set, a patch whose one battle is shiny if set. +class StubMart : public MartActions{ +public: + virtual bool open_buy_list() override{ return true; } + virtual void press_cursor(bool) override{} + virtual std::string read_row(size_t) override{ return ""; } + virtual void dump_screen(std::string_view) override{} + virtual PurchaseEnd buy(const MartBuy&) override{ return PurchaseEnd::FAILED; } + virtual bool leave() override{ return true; } +}; + +class StubTeach : public TeachActions{ +public: + // Its TM Case is empty. + virtual ItemOpen open_item(std::string_view, std::string_view) override{ return ItemOpen::NOT_IN_CASE; } + virtual TeachPrompt choose_member(size_t) override{ return TeachPrompt::FAILED; } + virtual ForgetEnd forget(size_t) override{ return ForgetEnd::FAILED; } + virtual void stop_teaching() override{} + virtual bool leave() override{ return true; } + virtual void dump_screen(std::string_view) override{} +}; + +class StubPatch : public GrindActions{ +public: + bool shiny = false; + + virtual bool find_encounter(Pokemon::Direction) override{ return true; } + virtual EncounterSeen read_encounter() override{ return {.species = "pidgey", .shiny = shiny}; } + virtual GrindFight fight() override{ return GrindFight::FAILED; } + virtual bool needs_heal() override{ return false; } + virtual bool heal_trip() override{ return true; } +}; + +class StubFossils : public ChoiceActions{ +public: + virtual bool talk() override{ return false; } + virtual std::optional read_offer() override{ return std::nullopt; } + virtual void answer(bool) override{} + virtual bool finish() override{ return true; } + virtual std::optional fossil_in_bag() override{ return std::nullopt; } +}; + +struct StubGame{ + std::optional level = 16; + StubMart mart; + StubTeach teach; + StubPatch patch; + StubFossils fossils; +}; + + +struct AutoStoryAbilitiesInput{ + std::string name; + std::function body; +}; + +struct AutoStoryAbilitiesExpectation{ +}; + +struct AutoStoryAbilitiesCase{ + AutoStoryAbilitiesInput input; + AutoStoryAbilitiesExpectation expectation; +}; + +class Test_AutoStoryAbilities : public UnitTest{ +public: + explicit Test_AutoStoryAbilities(AutoStoryAbilitiesCase test_case) + : UnitTest("PokemonFRLG::AutoStoryAbilities - " + 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::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryAbilitiesCase m_case; +}; + + +Pokemon::StoryStep game_step(std::string action, Pokemon::StoryActionArgs args){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = "test"; + step.action = std::move(action); + step.args = std::move(args); + return step; +} + +// The failure name the step ends with ("" for success, "unchanged" for +// one that changed nothing in the game); "none" if it isn't one of these +// steps. +std::string run_step(StubGame& game, const Pokemon::StoryStep& step){ + QuietLogger logger; + const MemberReader members = [&game](size_t slot) -> std::optional{ + if (slot != 0 || !game.level){ + return std::nullopt; + } + return MemberInfo{.species = "squirtle", .level = game.level, .moves = {"water-gun", "surf"}}; + }; + StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils}; + const std::optional outcome = run_ability_game_step(logger, nullptr, step, abilities); + if (!outcome){ + return "none"; + } + return outcome->changed_nothing ? "unchanged" : outcome->failure; +} + +struct StepCase{ + std::string name; + std::function setup; + Pokemon::StoryStep step; + std::string failure; +}; + +std::vector step_cases(){ + const auto none = [](StubGame&){}; + const Pokemon::StoryStep mart = mart_step("mart", "", {.map = "PewterCity_Mart", .lines = {{"potion", 5}}}); + const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); + return { + {"level reached", none, level_step("check", "", {.slot = 0, .level = 16}), "unchanged"}, + {"level below", none, level_step("check", "", {.slot = 0, .level = 17}), "level_below"}, + {"level unread", [](StubGame& game){ game.level.reset(); }, level_step("check", "", {.slot = 0, .level = 16}), "level_unread"}, + {"a Mart purchase that fails", none, mart, "mart_failed"}, + {"a move it knows already succeeds", none, teach_step("teach", "", {.item = "hm03", .move = "surf", .member = 0}), "unchanged"}, + {"a TM not in the TM Case is skipped", none, teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), "unchanged"}, + {"a level that can't be read stops a GRIND", [](StubGame& game){ game.level.reset(); }, grind, "grind_unread"}, + {"a GRIND without a nurse", none, game_step(GRIND_ACTION, {{"slot", int64_t(1)}, {"level", int64_t(20)}}), "bad_args"}, + {"no YES/NO at the fossil", none, fossil_step("fossil", "", Fossil::HELIX), "fossil_failed"}, + {"bad args", none, game_step(MART_ACTION, {{"map", std::string("PewterCity_Mart")}}), "bad_args"}, + {"another game step", none, capture_step("capture", "", {.species = "rattata"}), "none"}, + }; +} + +UnitTestResult test_ability_steps(){ + for (const StepCase& item : step_cases()){ + StubGame game; + item.setup(game); + const std::string failure = run_step(game, item.step); + if (failure != item.failure){ + return std::format("{}: \"{}\", expected \"{}\".", item.name, failure, item.failure); + } + } + return true; +} + + +// TEACH and MART steps are preparation, once per save: a retry from the +// same save skips one that changed nothing. A LEVEL check, which follows +// a GRIND, and the GRIND run every attempt. +UnitTestResult test_once_per_save_steps(){ + const std::vector once{ + teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}), + mart_step("mart", "", {.map = "CeruleanCity_Mart", .lines = {{.item = "potion", .quantity = 3}}}), + }; + for (const Pokemon::StoryStep& step : once){ + if (!step.once_per_save){ + return step.name + ": expected once per save."; + } + } + const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); + if (grind.once_per_save || level_step("level", "", {.slot = 0, .level = 16}).once_per_save){ + return "GRIND and LEVEL: expected every attempt."; + } + return true; +} + + +// A party whose screens count the summaries read. +class CountingScreens : public PartyScreens{ +public: + virtual bool open_party(size_t& members) override{ members = 2; m_opens++; return true; } + virtual bool enter_summary() override{ m_summaries++; return true; } + virtual std::string read_species() override{ m_summaries++; return "squirtle"; } + virtual bool next_member() override{ return true; } + virtual bool leave_summary() override{ return true; } + virtual bool open_member_menu(size_t slot) override{ m_menu = slot; return true; } + virtual std::optional read_member_menu() override{ + return PartyMemberMenu{.field_moves = {"surf"}}; + } + virtual bool close_member_menu() override{ return true; } + virtual void close() override{} + + size_t m_opens = 0; + size_t m_summaries = 0; + size_t m_menu = SIZE_MAX; +}; + +// A TEACH of a field move records its user; the Fly after it opens the +// party once, at that slot, and reads no summary, though the species +// cache was emptied by a reload. A TEACH of a plain TM records nothing. +UnitTestResult test_teach_records_fly_user(){ + StubGame game; + QuietLogger logger; + const MemberReader members = [](size_t slot) -> std::optional{ + if (slot != 0){ + return std::nullopt; + } + return MemberInfo{.species = "squirtle", .level = 16, .moves = {"water-gun", "surf"}}; + }; + PartyCache party; + StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils, {}, &party}; + run_ability_game_step(logger, nullptr, teach_step("teach_surf", "", {.item = "hm03", .move = "surf", .member = 0}), abilities); + run_ability_game_step(logger, nullptr, teach_step("teach_tm", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), abilities); + const std::optional user = party.users().find("surf"); + if (!user || user->slot != 0 || user->species != "squirtle"){ + return "the Surf user isn't recorded as slot 1, squirtle."; + } + if (party.users().find("water-pulse")){ + return "a TM move was recorded as a field move."; + } + party.invalidate_species(); + CountingScreens screens; + size_t flights = 0; + const std::string failure = use_field_move(logger, screens, party, "surf", "squirtle", [&flights](size_t){ + flights++; + return std::string(); + }); + if (!failure.empty() || flights != 1 || screens.m_menu != 0 || screens.m_opens != 1 || screens.m_summaries != 0){ + return std::format( + "Fly after TEACH: failure '{}', {} flights, menu {}, {} party opens, {} summary reads.", + failure, flights, screens.m_menu, screens.m_opens, screens.m_summaries + ); + } + return true; +} + + +// A shiny in a GRIND stops the program, not the checkpoint: a reload +// would lose it. +UnitTestResult test_grind_shiny_stops(){ + StubGame game; + game.patch.shiny = true; + Pokemon::StoryStep step = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); + try{ + run_step(game, step); + }catch (ProgramFinishedException&){ + return true; + } + return "Expected the program to stop on a shiny."; +} + + +UnitTestResult test_level_args(){ + const std::optional back = level_check_of(level_args({.slot = 1, .level = 23})); + if (!back || back->slot != 1 || back->level != 23){ + return "Expected slot 2, level 23 to read back."; + } + const std::vector bad_args{ + {}, + {{"slot", int64_t(1)}}, + {{"min", int64_t(5)}}, + {{"slot", int64_t(0)}, {"min", int64_t(5)}}, + {{"slot", int64_t(1)}, {"min", int64_t(101)}}, + }; + for (const Pokemon::StoryActionArgs& bad : bad_args){ + if (level_check_of(bad)){ + return "Expected args with a missing or out-of-range value refused."; + } + } + return true; +} + +} // namespace + + +const AutoStoryAbilitiesCase AUTO_STORY_ABILITIES_CASES[] = { + { + .input = {"the steps' ends as outcomes", test_ability_steps}, + .expectation = {}, + }, + { + .input = {"a shiny in a GRIND stops the program", test_grind_shiny_stops}, + .expectation = {}, + }, + { + .input = {"a Fly after a TEACH reads no summary", test_teach_records_fly_user}, + .expectation = {}, + }, + { + .input = {"the LEVEL step's args", test_level_args}, + .expectation = {}, + }, + { + .input = {"TEACH and MART run once per save", test_once_per_save_steps}, + .expectation = {}, + }, +}; + +void add_tests_AutoStoryAbilities(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_ABILITIES_CASES){ + database.add(item); + } + add_tests_AutoStoryMart(database); + add_tests_AutoStoryTeach(database); + add_tests_AutoStoryGrind(database); + add_tests_AutoStoryChoice(database); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation From 98edba06248dfa596921fda939ad544a716fa489 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 08:41:14 -0800 Subject: [PATCH 11/12] FRLG AutoStory: red tests for a member menu with two field moves and a Fly scan past an unread menu The Oddish's menu on console B (12.03, SWEET SCENT and CUT) isn't read, and the Fly scan stops there instead of trying the Pidgey under it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_PartyMemberMenuReader.cpp | 5 +++ ...PokemonFRLG_AutoStoryPartyRoster_Tests.cpp | 45 ++++++++++++++----- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp index 3b0234f7a6..c669f99102 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp @@ -269,6 +269,11 @@ void add_tests_PartyMemberMenuReader(UnitTestDatabase& database){ database.add( "PokemonFRLG/PartyMemberMenuReader/PidgeyFly_eng.png", std::vector{"fly"} ); + // FireRed on console B, 2026-11-13: the Oddish's menu, two field + // moves in blue; SWEET SCENT's row is half name and shadow. + database.add( + "PokemonFRLG/PartyMemberMenuReader/OddishSweetScentCut_eng.png", std::vector{"sweet-scent", "cut"} + ); // The party menu before A: no member's menu. database.add( "PokemonFRLG/PartyMemberMenuReader/PartyList_eng.png", std::nullopt diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp index 7e90706977..2a239e50a5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp @@ -349,26 +349,46 @@ UnitTestResult test_no_member_failure(Logger& logger){ return check_menus("no member", party, 1, 2, 2, 1); } -// A menu not read stops the scan: the party is closed, nothing picked. -UnitTestResult test_unread_menu_fails(Logger& logger){ +// A menu not read is closed with B and the scan goes on: a later member +// that lists FLY flies. +UnitTestResult test_unread_menu_skipped(Logger& logger){ FakeParty party({"blastoise", "pidgey"}, {std::nullopt, menu_with({"fly"})}); PartyCache cache; size_t calls = 0; - if (use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, 1, calls)) != FIELD_MOVE_MENU_UNREAD || calls != 0){ - return "an unread menu should fail as unread and not fly."; + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, 1, calls)); + if (!failure.empty() || calls != 1){ + return std::format("past an unread menu: failure '{}', {} menu uses.", failure, calls); } - return check_menus("unread menu", party, 1, 1, 0, 1); + return check_menus("unread menu", party, 1, 2, 1, 0); } -// A blue row whose name isn't read may be FLY: the scan stops. -UnitTestResult test_unread_field_move_fails(Logger& logger){ +// A blue row whose name isn't read may be FLY, but a later member lists +// it: that one flies (the console's Oddish, 12.03). +UnitTestResult test_unread_field_move_skipped(Logger& logger){ FakeParty party({"oddish", "pidgey"}, {menu_with({"cut", ""}), menu_with({"fly"})}); PartyCache cache; size_t calls = 0; - if (use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, 1, calls)) != FIELD_MOVE_MENU_UNREAD || calls != 0){ - return "an unread field move name should fail as unread and not fly."; + const std::string failure = use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 1, 1, calls)); + if (!failure.empty() || calls != 1){ + return std::format("past an unread field move: failure '{}', {} menu uses.", failure, calls); + } + return check_menus("unread field move", party, 1, 2, 1, 0); +} + +// No menu read lists FLY but one wasn't read: unread, not "no member", +// and the record is kept. +UnitTestResult test_unread_menu_without_fly_fails(Logger& logger){ + FakeParty party({"blastoise", "oddish"}, {std::nullopt, menu_with({"cut"})}); + PartyCache cache; + cache.users().record("fly", 0, "pidgey"); + size_t calls = 0; + if (use_field_move(logger, party, cache, "fly", "pidgey", fly_from(party, 0, 1, calls)) != FIELD_MOVE_MENU_UNREAD || calls != 0){ + return "a party with an unread menu and no FLY should fail as unread and not fly."; + } + if (!cache.users().find("fly")){ + return "an unread menu dropped the Fly record."; } - return check_menus("unread field move", party, 1, 1, 0, 1); + return check_menus("unread menu without fly", party, 1, 2, 2, 1); } // A deposit or withdrawal moves members: nothing is recorded after it. @@ -485,8 +505,9 @@ const AutoStoryPartyRosterCase AUTO_STORY_PARTY_ROSTER_CASES[] = { {.input = {"a scan records the user for the next Fly", test_scan_records_for_next_fly}, .expectation = {}}, {.input = {"invalidate() drops the field move users", test_invalidate_drops_records}, .expectation = {}}, {.input = {"no menu with FLY fails without flying", test_no_member_failure}, .expectation = {}}, - {.input = {"an unread member menu fails without flying", test_unread_menu_fails}, .expectation = {}}, - {.input = {"an unread field move name fails without flying", test_unread_field_move_fails}, .expectation = {}}, + {.input = {"an unread member menu is skipped for a later Fly user", test_unread_menu_skipped}, .expectation = {}}, + {.input = {"an unread field move name is skipped for a later Fly user", test_unread_field_move_skipped}, .expectation = {}}, + {.input = {"an unread menu and no Fly user fails as unread", test_unread_menu_without_fly_fails}, .expectation = {}}, {.input = {"the field move users' text reads back the same", test_users_text_round_trip}, .expectation = {}}, {.input = {"unreadable field move users' text is dropped", test_unreadable_users_text_dropped}, .expectation = {}}, {.input = {"a Fly after a restart opens only the recorded menu", test_restart_fly_reads_no_summary}, .expectation = {}}, From 01e23c29942af1d5a5cb2f152fe8a8b5c9f796ec Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 08:42:21 -0800 Subject: [PATCH 12/12] FRLG AutoStory: read a member menu with long field move names; the Fly scan passes an unread menu SWEET SCENT and its light blue shadow cover half its row, so the row wasn't taken for the menu's window and the Oddish's menu (SWEET SCENT, CUT) wasn't read at 12.03. The shadow now counts as the window's. A member's menu that isn't read is closed with B and the scan goes on; it fails as unread only if no other menu lists the move. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_PartyMemberMenuReader.cpp | 15 ++++++-- .../PokemonFRLG_AutoStoryPartyRoster.cpp | 36 +++++++++++-------- .../PokemonFRLG_AutoStoryPartyRoster.h | 10 +++--- 3 files changed, 41 insertions(+), 20 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp index c669f99102..6081956fc1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp @@ -133,6 +133,13 @@ bool is_blue_text(uint32_t pixel){ const int b = pixel & 0xff; return b > 176 && r < 96 && g < 136; } +// The light blue shadow of a field move's name, (160, 192, 240). +bool is_blue_shadow(uint32_t pixel){ + const int r = (pixel >> 16) & 0xff; + const int g = (pixel >> 8) & 0xff; + const int b = pixel & 0xff; + return r >= 128 && r <= 192 && g >= 160 && g <= 224 && b > 208; +} RowKind classify_row(const ImageViewRGB32& row){ const size_t area = row.width() * row.height(); @@ -142,18 +149,22 @@ RowKind classify_row(const ImageViewRGB32& row){ size_t white = 0; size_t gray = 0; size_t blue = 0; + size_t blue_shadow = 0; for (size_t y = 0; y < row.height(); y++){ for (size_t x = 0; x < row.width(); x++){ const uint32_t pixel = row.pixel(x, y); white += is_white(pixel) ? 1 : 0; gray += is_gray_text(pixel) ? 1 : 0; blue += is_blue_text(pixel) ? 1 : 0; + blue_shadow += is_blue_shadow(pixel) ? 1 : 0; } } // Measured: a name covers 5% to 25% of its row, the window's white // the most of the rest; the party's slots behind the window are teal - // and blue. - if (white * 2 < area){ + // and blue. A long blue name and its shadow cover about half its row + // (SWEET SCENT: 20% blue, 27% shadow, 47% white), so the shadow + // counts as the window's. + if ((white + blue_shadow) * 2 < area){ return RowKind::NONE; } if (blue * 50 >= area && gray * 4 < blue){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp index c5fcdcd83d..81769c4137 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp @@ -123,9 +123,11 @@ struct MemberMenuCheck{ enum class Result{ LISTED, // the menu is open and lists the move at `row` NOT_LISTED, // it doesn't; the menu is closed again - UNREAD, // the menu, or a field move's name on it, wasn't read + UNREAD, // the menu, or a field move's name on it, wasn't read; + // the menu is closed again + STUCK, // the menu didn't open, or didn't close again }; - Result result = Result::UNREAD; + Result result = Result::STUCK; size_t row = 0; }; @@ -137,21 +139,17 @@ MemberMenuCheck check_member_menu(Logger& logger, PartyScreens& screens, size_t return {}; } const std::optional menu = screens.read_member_menu(); - if (!menu){ - return {}; - } - if (const std::optional row = menu->row_of(move)){ - return {.result = Result::LISTED, .row = *row}; - } - // A name not read may be the move. - if (!menu->all_read()){ - return {}; + if (menu){ + if (const std::optional row = menu->row_of(move)){ + return {.result = Result::LISTED, .row = *row}; + } } if (!screens.close_member_menu()){ logger.log(std::format("Party: slot {}'s menu didn't close.", slot + 1), COLOR_RED); return {}; } - return {.result = Result::NOT_LISTED}; + // A name not read may be the move. + return {.result = menu && menu->all_read() ? Result::NOT_LISTED : Result::UNREAD}; } } // namespace @@ -177,21 +175,31 @@ std::string use_field_move( order.push_back(slot); } } + // A menu not read may list the move; the scan goes on to the others. + bool unread = false; for (const size_t slot : order){ const MemberMenuCheck check = check_member_menu(logger, screens, slot, move); - if (check.result == Result::UNREAD){ + if (check.result == Result::STUCK){ screens.close(); return FIELD_MOVE_MENU_UNREAD; } + if (check.result == Result::UNREAD){ + unread = true; + continue; + } if (check.result == Result::LISTED){ logger.log(std::format("Party: slot {} lists {} on row {}.", slot + 1, move, check.row + 1)); cache.users().record(std::string(move), slot, std::string(species)); return from_menu(check.row); } } + screens.close(); + if (unread){ + logger.log(std::format("Party: no menu read lists {}; one wasn't read.", move), COLOR_RED); + return FIELD_MOVE_MENU_UNREAD; + } logger.log(std::format("Party: no member's menu lists {}.", move), COLOR_RED); cache.users().forget(move); - screens.close(); return FIELD_MOVE_NO_MEMBER; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h index 494c37e805..3203990f7c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h @@ -112,16 +112,18 @@ std::optional open_member_menu_of( // What use_field_move() returns when no member's menu lists the move. inline const std::string FIELD_MOVE_NO_MEMBER = "no_member"; -// What it returns when a member's menu isn't read, or lists a field move -// whose name isn't read: the move may be there, so nothing is picked. +// What it returns when no menu read lists the move but a member's menu +// isn't read, or lists a field move whose name isn't read (the move may +// be there), or a menu didn't open or close. inline const std::string FIELD_MOVE_MENU_UNREAD = "menu_unread"; // Runs the move from the member's menu, its row there (SUMMARY is 0) // given; its failure, or empty. using FieldMoveFromMenu = std::function; // The field move `move` (a slug, "fly") used by the first member whose // menu lists it: the party is opened once, the members' menus are opened -// down the party until one lists `move`, and `from_menu` (the console's -// FLY row and map) runs from that menu. No summary is read. Returns its +// down the party until one lists `move` (a menu not read is closed again +// and passed), and `from_menu` (the console's FLY row and map) runs from +// that menu. No summary is read. Returns its // failure, empty on success, FIELD_MOVE_NO_MEMBER if no menu lists the // move, or FIELD_MOVE_MENU_UNREAD. With a record in the cache's users for // `move`, that slot's menu is opened first and the scan runs only if it