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..6081956fc1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMemberMenuReader.cpp @@ -0,0 +1,298 @@ +/* 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; +} +// 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(); + if (area == 0){ + return RowKind::NONE; + } + 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. 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){ + 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"} + ); + // 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 + ); +} + + + +} // 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 21fd494009..507ee6c561 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_BallReader.h" @@ -53,6 +54,7 @@ #include "Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.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" @@ -88,6 +90,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); @@ -111,6 +114,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..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,6 +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_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) @@ -157,6 +164,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 +195,24 @@ 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.party.users() = parsed.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. void throw_if_not_started(ConsoleHandle& console, const Pokemon::Outcome& outcome){ if (outcome.failure == Pokemon::StoryPreflight::FAILURE){ @@ -228,6 +254,9 @@ 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_species(); + 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 @@ -709,6 +738,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_AutoStoryAbilities.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp index 6219a617b1..a8584ae77b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp @@ -25,7 +25,12 @@ 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 || 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 add8e48eff..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{ @@ -36,6 +37,10 @@ struct StoryAbilities{ TeachActions& teach; GrindActions& grind; 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..f188f1e214 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,66 @@ 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 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(){ @@ -246,6 +306,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 0e9dfabf3c..3480d86db7 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), &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); @@ -1003,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.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 d03e617838..9c2b895782 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,16 @@ 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, 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`. 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 new file mode 100644 index 0000000000..27fd346444 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.cpp @@ -0,0 +1,138 @@ +/* AutoStory Field Move Users + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#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(); +} + +std::string FieldMoveUsers::to_text() const{ + 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; +} + +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{ + +// 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; +} + +// 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; +} + + + +} // 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..aa96a97a2e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFieldMoveUsers.h @@ -0,0 +1,89 @@ +/* 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 +#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 = {}; + + friend bool operator==(const FieldMoveUser&, const FieldMoveUser&) = default; +}; + +// 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); + 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(); + + // 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 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. +struct ParsedFieldMoveUsers{ + FieldMoveUsers users = {}; + std::vector rejected = {}; +}; +// `text` read as ParsedFieldMoveUsers says; never throws. +ParsedFieldMoveUsers parse_field_move_users(std::string_view text); + + +} // 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 acd43830b3..1f810c0478 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{ @@ -37,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 @@ -89,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"), }}, @@ -129,6 +133,20 @@ void tap_dpad(ProControllerContext& context, DpadPosition dpad, size_t count, Mi } } +// 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); + 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 +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"; } - 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.menu_row); } // On the fly map: the cursor to the corner, then to the town, and A. @@ -185,7 +195,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 +210,32 @@ 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); + std::string failure; + if (!plan->species.empty()){ + // 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 {}, 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, [&](size_t row){ + return fly_from_member_menu(console, context, row); + }); + if (failure == FIELD_MOVE_NO_MEMBER){ + 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 {}, {}).", + plan->slot + 1, plan->menu_row + 1, town.name, town.cell.x, town.cell.y + )); + failure = open_fly_map(console, context, *plan); } - 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); 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..4037fddbed 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{ @@ -33,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 @@ -73,9 +75,13 @@ 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 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 + 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..81769c4137 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.cpp @@ -0,0 +1,208 @@ +/* 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(); + 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){ + 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{ + +// 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; + // the menu is closed again + STUCK, // the menu didn't open, or didn't close again + }; + Result result = Result::STUCK; + 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 {}; + } + const std::optional menu = screens.read_member_menu(); + 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 {}; + } + // A name not read may be the move. + return {.result = menu && menu->all_read() ? Result::NOT_LISTED : Result::UNREAD}; +} + +} // namespace + +std::string use_field_move( + Logger& logger, PartyScreens& screens, PartyCache& cache, + std::string_view move, std::string_view species, const FieldMoveFromMenu& from_menu +){ + 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); + } + } + // 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::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); + return FIELD_MOVE_NO_MEMBER; +} + +} // 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..3203990f7c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster.h @@ -0,0 +1,145 @@ +/* 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. + * + * 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 +#define PokemonAutomation_PokemonFRLG_AutoStoryPartyRoster_H + +#include +#include +#include +#include +#include +#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{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The species of the first party slots as the last scan read them. +class PartyCache{ +public: + // 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; +}; + + +// 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, 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; +}; + + +// 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 +); + + +// 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 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` (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 +// 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 +); + + +// 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..2a239e50a5 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyRoster_Tests.cpp @@ -0,0 +1,529 @@ +/* AutoStory Party Roster Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Counts the screens a species lookup and a field move's user scan go + * through, on a fake party. + * + */ + +#include +#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)) + , 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{ + 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; + 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{ + 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; + 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 +){ + 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); +} + +// 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 && picked == row ? "" : "fly_no_map"; + }; +} + +// 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 = fly_party(); + PartyCache cache; + 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, 2, 1, calls)); + if (!failure.empty() || calls != 1){ + return std::format("a recorded Fly: failure '{}', {} menu uses.", failure, calls); + } + return check_menus("recorded user", party, 1, 1, 0, 0); +} + +// 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 = 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, 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."; + } + // 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 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", 1, "pidgey"); + size_t calls = 0; + 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_menus("other species", party, 1, 1, 0, 0); +} + +// 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 = fly_party(); + PartyCache cache; + size_t calls = 0; + 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_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 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; + 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, 2, 1, 0); +} + +// 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; + 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 menu without fly", party, 1, 2, 2, 1); +} + +// 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; +} + +// 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 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 = fly_party(); + 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 Fly after a restart: failure '{}', {} menu uses.", failure, calls); + } + return check_menus("restart", party, 1, 1, 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 = {}}, + {.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 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 menu with FLY fails without flying", test_no_member_failure}, .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 = {}}, +}; + +} // 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..01285bf2a4 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,154 @@ 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; +// 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: + 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; + m_members = members; + m_cursor = 0; + 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{ + // 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(); + 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{ + // 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); + } + +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; + size_t m_members = 0; + // The member the party menu's cursor is on. + size_t m_cursor = 0; +}; + } // 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..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, ""); @@ -336,10 +347,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..14ebef4ad6 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 @@ -87,16 +88,30 @@ 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). 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 2de75ee5a7..c5a3c73145 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1956,6 +1956,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 @@ -2181,6 +2183,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 @@ -2259,6 +2262,10 @@ 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 Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.cpp