diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.cpp new file mode 100644 index 0000000000..f25c255d12 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.cpp @@ -0,0 +1,517 @@ +/* Teach Screen Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" +#include "Tests/ImageUnitTest.h" +#include "Tests/TestUtils.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Tests.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_OcrPreprocessing.h" +#include "PokemonFRLG_ItemListReader.h" +#include "PokemonFRLG_SummaryMovesReader.h" +#include "PokemonFRLG_TeachScreenReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// A box in the game's 240x160 pixels. +struct GameBox{ + double x; + double y; + double width; + double height; +}; + +ImageViewRGB32 game_box(const ImageViewRGB32& screen){ + return extract_box_reference(screen, GameSettings::instance().GAME_BOX); +} + +ImageViewRGB32 game_crop(const ImageViewRGB32& screen, const GameBox& box){ + return extract_box_reference( + game_box(screen), + ImageFloatBox(box.x / 240, box.y / 160, box.width / 240, box.height / 160) + ); +} + +// The box is all one color, near `color`. +bool solid(const ImageViewRGB32& screen, const GameBox& box, const FloatPixel& color){ + const ImageStats stats = image_stats(game_crop(screen, box)); + return euclidean_distance(stats.average, color) < 40 && stats.stddev.sum() < 40; +} + +// Measured on the captures (console B, 2026-11-03). Left of the title, the +// frame's color tells the screen: the bag's orange, the TM CASE's mint, +// the party menu's dark teal. +constexpr GameBox CORNER{6, 14, 8, 4}; +const FloatPixel BAG_ORANGE(255, 210, 94); +const FloatPixel TM_CASE_MINT(193, 234, 207); +const FloatPixel PARTY_TEAL(18, 109, 107); +const FloatPixel WHITE(255, 255, 255); + +// The item menu's box, between its rows (OPEN at y 109, REGISTER 125, +// CANCEL 141); blue text box or list below it when it is closed. +constexpr GameBox ITEM_MENU_GAP_1{186, 118, 40, 4}; +constexpr GameBox ITEM_MENU_GAP_2{186, 134, 40, 4}; +// Over the party menu: the YES/NO box above the message box (YES at +// y 77, NO at 93); the message box's right part, past the prompt box's +// end (x 180) and its CANCEL; the prompt box under its text. +constexpr GameBox YES_NO_TOP{180, 72, 30, 4}; +constexpr GameBox MESSAGE_RIGHT{200, 150, 30, 3}; +constexpr GameBox PROMPT_BOTTOM{60, 150, 80, 3}; + +// The cursors' dark arrows, 5 pixels wide and 9 high, rows 16 apart: the +// bag's at x 90, y 12; the TM CASE's at x 81, y 12; the item menu's at +// x 177, y 108; the party YES/NO's at x 169, y 76. +struct ArrowColumn{ + double x; + double top; + size_t rows; +}; +constexpr double ARROW_ROW_STEP = 16; + +std::optional arrow_column(TeachScreen screen){ + switch (screen){ + case TeachScreen::BAG: return ArrowColumn{89, 11, TEACH_LIST_ROWS}; + case TeachScreen::TM_CASE: return ArrowColumn{80, 11, TM_CASE_ROWS}; + case TeachScreen::ITEM_MENU: return ArrowColumn{176, 107, ITEM_MENU_ROWS}; + case TeachScreen::PARTY_YES_NO: return ArrowColumn{168, 75, 2}; + default: return std::nullopt; + } +} + +// The share of the arrow's cell that is dark: about 0.35 with the arrow, +// nothing without (the cell is left of the rows' text). +double dark_share(const ImageViewRGB32& cell){ + size_t dark = 0; + for (size_t y = 0; y < cell.height(); y++){ + for (size_t x = 0; x < cell.width(); x++){ + const Color pixel(cell.pixel(x, y)); + dark += pixel.red() + pixel.green() + pixel.blue() < 330 ? 1 : 0; + } + } + const size_t total = cell.width() * cell.height(); + return total == 0 ? 0 : double(dark) / double(total); +} + + +// Small OCR dictionaries of English names: slug -> how the game writes it. +class NameMatcher : public OCR::SmallDictionaryMatcher{ +public: + NameMatcher(std::initializer_list> names) + : SmallDictionaryMatcher(dictionary(names)) + {} + + // The best match's log10p and slug, if any. + std::optional> match( + Logger& logger, Language language, const ImageViewRGB32& image, + const std::vector& filters + ) const{ + if (!languages()[language]){ + return std::nullopt; + } + const ImageRGB32 ready = preprocess_for_ocr(image); + const OCR::StringMatchResult result = match_substring_from_image_multifiltered( + &logger, language, ready, filters, -1.40, 0.50, 0.01, 0.50 + ); + if (result.results.empty()){ + return std::nullopt; + } + return std::make_pair(result.results.begin()->first, result.results.begin()->second.token); + } + std::string read( + Logger& logger, Language language, const ImageViewRGB32& image, + const std::vector& filters + ) const{ + const std::optional> best = match(logger, language, image, filters); + return best ? best->second : ""; + } + +private: + static JsonObject dictionary(std::initializer_list> names){ + JsonObject english; + for (const auto& [slug, name] : names){ + JsonArray candidates; + candidates.push_back(name); + english[slug] = std::move(candidates); + } + JsonObject json; + json["eng"] = std::move(english); + return json; + } +}; + +const NameMatcher& pocket_matcher(){ + static const NameMatcher matcher{ + {"items", "Items"}, + {"key-items", "Key Items"}, + {"poke-balls", "Poke Balls"}, + }; + return matcher; +} + +// The key items a story meets up to the Rocket Hideout (pokefirered +// src/data/items.h). +const NameMatcher& key_item_matcher(){ + static const NameMatcher matcher{ + {"tm-case", "TM Case"}, + {"teachy-tv", "Teachy TV"}, + {"helix-fossil", "Helix Fossil"}, + {"dome-fossil", "Dome Fossil"}, + {"old-amber", "Old Amber"}, + {"oaks-parcel", "Oak's Parcel"}, + {"town-map", "Town Map"}, + {"bike-voucher", "Bike Voucher"}, + {"bicycle", "Bicycle"}, + {"ss-ticket", "S.S. Ticket"}, + {"old-rod", "Old Rod"}, + {"vs-seeker", "VS Seeker"}, + {"fame-checker", "Fame Checker"}, + {"berry-pouch", "Berry Pouch"}, + {"coin-case", "Coin Case"}, + {"cancel", "Cancel"}, + }; + return matcher; +} + +// A phrase from each message, as the captures show it. +const NameMatcher& text_matcher(){ + static const NameMatcher matcher{ + {"teach-which", "Teach which"}, + {"wants-to-learn", "wants to learn the"}, + {"knows-four", "knows four moves"}, + {"delete-question", "Should a move be deleted"}, + {"which-move", "Which move should be forgotten"}, + {"stop-question", "Stop trying to teach"}, + {"did-not-learn", "did not learn the"}, + {"not-compatible", "are not compatible"}, + }; + return matcher; +} + +TeachText teach_text(const std::string& slug){ + static const std::vector> texts{ + {"teach-which", TeachText::TEACH_WHICH}, + {"wants-to-learn", TeachText::WANTS_TO_LEARN}, + {"knows-four", TeachText::KNOWS_FOUR}, + {"delete-question", TeachText::DELETE_QUESTION}, + {"which-move", TeachText::WHICH_MOVE}, + {"stop-question", TeachText::STOP_QUESTION}, + {"did-not-learn", TeachText::DID_NOT_LEARN}, + {"not-compatible", TeachText::NOT_COMPATIBLE}, + }; + for (const auto& [name, text] : texts){ + if (name == slug){ + return text; + } + } + return TeachText::UNKNOWN; +} + +// The text's lines: the pocket's title from x 16, white on the bag's +// bar; a list row's name; the TM CASE's move after "No03 " (x 88 to 111); +// the message box's two lines, y 124 and 139, from x 8; the prompt's line +// at y 141. +constexpr GameBox POCKET_TITLE{8, 10, 76, 12}; +constexpr double TM_MOVE_LEFT = 110; +constexpr GameBox MESSAGE_LINE_1{6, 121, 226, 13}; +constexpr GameBox MESSAGE_LINE_2{6, 136, 226, 13}; +constexpr GameBox PROMPT_LINE{6, 138, 170, 13}; + +// A list's rows: dark text, and the cursor's row in blue (32, 80, 224). +const std::vector& LIST_TEXT_FILTERS(){ + static const std::vector filters = [](){ + std::vector all = DARK_TEXT_FILTERS(); + all.emplace_back(combine_rgb(0, 0, 128), combine_rgb(128, 144, 255)); + return all; + }(); + return filters; +} + +TeachScreen read_party_screen(const ImageViewRGB32& screen){ + if (solid(screen, YES_NO_TOP, WHITE) && solid(screen, MESSAGE_RIGHT, WHITE)){ + return TeachScreen::PARTY_YES_NO; + } + if (solid(screen, MESSAGE_RIGHT, WHITE)){ + return TeachScreen::PARTY_TEXT; + } + if (solid(screen, PROMPT_BOTTOM, WHITE)){ + return TeachScreen::PARTY_PROMPT; + } + return TeachScreen::OTHER; +} + +} + + +const char* teach_screen_name(TeachScreen screen){ + switch (screen){ + case TeachScreen::OTHER: return "other"; + case TeachScreen::BAG: return "bag"; + case TeachScreen::ITEM_MENU: return "item_menu"; + case TeachScreen::TM_CASE: return "tm_case"; + case TeachScreen::PARTY_PROMPT: return "party_prompt"; + case TeachScreen::PARTY_TEXT: return "party_text"; + case TeachScreen::PARTY_YES_NO: return "party_yes_no"; + case TeachScreen::KNOWN_MOVES: return "known_moves"; + } + return "?"; +} + +const char* teach_text_name(TeachText text){ + switch (text){ + case TeachText::UNKNOWN: return "unknown"; + case TeachText::TEACH_WHICH: return "teach_which"; + case TeachText::WANTS_TO_LEARN: return "wants_to_learn"; + case TeachText::KNOWS_FOUR: return "knows_four"; + case TeachText::DELETE_QUESTION: return "delete_question"; + case TeachText::WHICH_MOVE: return "which_move"; + case TeachText::STOP_QUESTION: return "stop_question"; + case TeachText::DID_NOT_LEARN: return "did_not_learn"; + case TeachText::NOT_COMPATIBLE: return "not_compatible"; + } + return "?"; +} + +TeachScreen read_teach_screen(const ImageViewRGB32& screen){ + const bool menu = solid(screen, ITEM_MENU_GAP_1, WHITE) && solid(screen, ITEM_MENU_GAP_2, WHITE); + if (solid(screen, CORNER, BAG_ORANGE)){ + return menu ? TeachScreen::ITEM_MENU : TeachScreen::BAG; + } + if (solid(screen, CORNER, TM_CASE_MINT)){ + return menu ? TeachScreen::ITEM_MENU : TeachScreen::TM_CASE; + } + if (solid(screen, CORNER, PARTY_TEAL)){ + return read_party_screen(screen); + } + if (read_summary_move_cursor(screen)){ + return TeachScreen::KNOWN_MOVES; + } + return TeachScreen::OTHER; +} + +std::optional read_teach_cursor(TeachScreen screen, const ImageViewRGB32& image){ + if (screen == TeachScreen::KNOWN_MOVES){ + return read_summary_move_cursor(image); + } + const std::optional column = arrow_column(screen); + if (!column){ + return std::nullopt; + } + std::optional cursor; + for (size_t row = 0; row < column->rows; row++){ + const GameBox cell{column->x, column->top + ARROW_ROW_STEP * double(row), 7, 10}; + const double share = dark_share(game_crop(image, cell)); + if (share < 0.15){ + continue; + } + if (cursor){ + return std::nullopt; + } + cursor = row; + } + return cursor; +} + +std::string read_pocket_name(Logger& logger, Language language, const ImageViewRGB32& screen){ + return pocket_matcher().read(logger, language, game_crop(screen, POCKET_TITLE), BRIGHT_TEXT_FILTERS()); +} + +std::string read_key_item(Logger& logger, Language language, const ImageViewRGB32& screen, size_t row){ + const ImageViewRGB32 name = extract_box_reference(game_box(screen), item_list_name_box(int(row))); + return key_item_matcher().read(logger, language, name, LIST_TEXT_FILTERS()); +} + +std::string read_tm_case_move(Logger& logger, Language language, const ImageViewRGB32& screen, size_t row){ + const ImageFloatBox name = item_list_name_box(int(row)); + const GameBox box{TM_MOVE_LEFT, name.y * 160, 200 - TM_MOVE_LEFT, name.height * 160}; + return read_move_name(logger, language, game_crop(screen, box)); +} + +TeachText read_teach_text(Logger& logger, Language language, const ImageViewRGB32& screen){ + const TeachScreen kind = read_teach_screen(screen); + if (kind == TeachScreen::PARTY_PROMPT){ + return teach_text(text_matcher().read(logger, language, game_crop(screen, PROMPT_LINE), DARK_TEXT_FILTERS())); + } + if (kind != TeachScreen::PARTY_TEXT && kind != TeachScreen::PARTY_YES_NO){ + return TeachText::UNKNOWN; + } + // The phrase either line matches best. + std::optional> best; + for (const GameBox& line : {MESSAGE_LINE_1, MESSAGE_LINE_2}){ + const std::optional> match = + text_matcher().match(logger, language, game_crop(screen, line), DARK_TEXT_FILTERS()); + if (match && (!best || match->first < best->first)){ + best = match; + } + } + return best ? teach_text(best->second) : TeachText::UNKNOWN; +} + +std::vector read_teach_rows(Logger& logger, Language language, const ImageViewRGB32& image, TeachScreen screen){ + std::vector rows; + const size_t rows_shown = screen == TeachScreen::BAG ? TEACH_LIST_ROWS : TM_CASE_ROWS; + for (size_t row = 0; row < rows_shown; row++){ + std::string name = screen == TeachScreen::BAG + ? read_key_item(logger, language, image, row) + : read_tm_case_move(logger, language, image, row); + if (name.empty()){ + break; + } + rows.push_back(std::move(name)); + if (rows.back() == "cancel"){ + break; + } + } + return rows; +} + + +namespace{ + +// The language a test image's name ends with: _. +Language language_of_test_image(const std::string& image){ + const std::vector words = parse_words(Filesystem::Path(image).stem().string()); + return words.size() < 2 ? Language::None : language_code_to_enum(words.back()); +} + +std::string cursor_value(const std::optional& cursor){ + return cursor ? std::to_string(*cursor + 1) : "none"; +} + +// What a list or menu shows: its rows from the top to the first not read, +// and its cursor. +void add_list( + std::vector& labels, std::vector& values, + const std::vector& rows, const std::optional& cursor +){ + for (size_t c = 0; c < rows.size(); c++){ + labels.push_back(std::format("row {}", c + 1)); + values.push_back(rows[c]); + } + labels.push_back("cursor"); + values.push_back(cursor_value(cursor)); +} + +// A capture of a screen on the way to a TM taught, named +// _.png. Its golden file holds the screen read, +// then: in the bag, its pocket, the key items from the top (KEY ITEMS +// only) and the cursor's row (from 1, or "none"); in the TM CASE, its +// moves from the top and the cursor's row; in an item menu or YES/NO, the +// cursor's row; over the party menu, the message; on KNOWN MOVES, the five +// rows' moves and the cursor's row. +class Test_TeachScreen : public ImageUnitTest{ +public: + Test_TeachScreen(const std::string& image) + : ImageUnitTest("PokemonFRLG::TeachScreenReader - " + image, {image}) + {} + + virtual UnitTestResult run_on_images( + Logger& logger, CancellableScope& scope, + const std::vector& images + ) const override{ + const Language language = language_of_test_image(image_paths()[0]); + if (language == Language::None || language == Language::EndOfList){ + return "Error: filename must be _."; + } + const ImageViewRGB32& screen = images[0]; + const TeachScreen kind = read_teach_screen(screen); + std::vector labels{"screen"}; + std::vector values{teach_screen_name(kind)}; + add_details(logger, language, screen, kind, labels, values); + return check_against_golden_file(UNIT_TEST_RESOURCE_PATH() + image_paths()[0], labels, values); + } + +private: + static void add_details( + Logger& logger, Language language, const ImageViewRGB32& screen, TeachScreen kind, + std::vector& labels, std::vector& values + ){ + switch (kind){ + case TeachScreen::BAG:{ + const std::string pocket = read_pocket_name(logger, language, screen); + labels.push_back("pocket"); + values.push_back(pocket.empty() ? "none" : pocket); + const std::vector rows = pocket == "key-items" + ? read_teach_rows(logger, language, screen, kind) + : std::vector{}; + add_list(labels, values, rows, read_teach_cursor(kind, screen)); + return; + } + case TeachScreen::TM_CASE: + add_list(labels, values, read_teach_rows(logger, language, screen, kind), read_teach_cursor(kind, screen)); + return; + case TeachScreen::ITEM_MENU: + add_list(labels, values, {}, read_teach_cursor(kind, screen)); + return; + case TeachScreen::PARTY_YES_NO: + labels.push_back("cursor"); + values.push_back(cursor_value(read_teach_cursor(kind, screen))); + [[fallthrough]]; + case TeachScreen::PARTY_PROMPT: + case TeachScreen::PARTY_TEXT: + labels.push_back("text"); + values.push_back(teach_text_name(read_teach_text(logger, language, screen))); + return; + case TeachScreen::KNOWN_MOVES: + for (size_t row = 0; row < SUMMARY_MOVE_ROWS; row++){ + const std::string move = read_summary_move_name(logger, language, screen, row); + labels.push_back(std::format("move {}", row + 1)); + values.push_back(move.empty() ? "none" : move); + } + labels.push_back("cursor"); + values.push_back(cursor_value(read_teach_cursor(kind, screen))); + return; + case TeachScreen::OTHER: + return; + } + } +}; + +} + +void add_tests_TeachScreenReader(UnitTestDatabase& database){ + // FireRed on console B, 2026-11-03: TM03 taught to the lead from the + // bag, B on the move to forget, and YES to stop. + for (const char* image : { + "01_BagItems_eng.png", + "02_BagKeyItems_eng.png", + "03_KeyItemsTmCase_eng.png", + "04_TmCaseMenu_eng.png", + "05_TmCaseList_eng.png", + "06_Tm03Menu_eng.png", + "07_TeachWhich_eng.png", + "08_WantsToLearn_eng.png", + "09_KnowsFour_eng.png", + "10_DeleteQuestion_eng.png", + "11_WhichMove_eng.png", + "12_KnownMoves_eng.png", + "13_StopQuestion_eng.png", + "14_DidNotLearn_eng.png", + }){ + database.add(std::string("PokemonFRLG/TeachScreenReader/") + image); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.h new file mode 100644 index 0000000000..2e1dc393f5 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.h @@ -0,0 +1,112 @@ +/* Teach Screen Reader + * + * From: https://github.com/PokemonAutomation/ + * + * Reads the screens a TM is taught through, from the bag to the move it + * replaces, as the game shows them (console B, 2026-11-03): the bag's + * pockets, TM CASE in KEY ITEMS and its OPEN/REGISTER/CANCEL menu, the TM + * CASE's list and a TM's USE/GIVE/EXIT menu, the party menu's "Teach which + * POKEMON?", its messages and YES/NO, and the KNOWN MOVES page picking the + * move to forget (read with PokemonFRLG_SummaryMovesReader.h). + * + * Which screen shows is told from the colors of its background, its boxes + * and the dark arrow of its cursor, measured on those captures in the + * game's 240x160 pixels: the bag's frame is orange, the TM CASE's mint, + * the party menu's dark teal. Names and messages are read by OCR, in + * English only so far: in another language nothing is read. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_TeachScreenReader_H +#define PokemonAutomation_PokemonFRLG_TeachScreenReader_H + +#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{ + + +enum class TeachScreen{ + OTHER, + // A pocket's list, its cursor live. + BAG, + // OPEN/REGISTER/CANCEL over the bag, or USE/GIVE/EXIT over the TM CASE. + ITEM_MENU, + // The TM CASE's list, its cursor live. + TM_CASE, + // "Teach which POKEMON?" + PARTY_PROMPT, + // A message over the party menu. + PARTY_TEXT, + // A message over the party menu with YES/NO. + PARTY_YES_NO, + // The KNOWN MOVES page with its red cursor: the move to forget. + KNOWN_MOVES, +}; +const char* teach_screen_name(TeachScreen screen); + +TeachScreen read_teach_screen(const ImageViewRGB32& screen); + + +// Rows a list or menu shows at once: the bag's, the TM CASE's (its info +// box is below), the item menu's. +constexpr size_t TEACH_LIST_ROWS = 6; +constexpr size_t TM_CASE_ROWS = 5; +constexpr size_t ITEM_MENU_ROWS = 3; + +// The row the cursor is on: the dark arrow in the bag's list, the TM +// CASE's list, the item menu (0: OPEN or USE) or the party menu's YES/NO +// (0: YES); the red box on KNOWN MOVES. Nothing if no row or more than one +// has it. +std::optional read_teach_cursor(TeachScreen screen, const ImageViewRGB32& image); + +// The open pocket's name: "items", "key-items" or "poke-balls"; empty if +// not read. +std::string read_pocket_name(Logger& logger, Language language, const ImageViewRGB32& screen); + +// The key item in the bag's row `row`: "tm-case", "teachy-tv", ... or +// "cancel"; empty if not read. +std::string read_key_item(Logger& logger, Language language, const ImageViewRGB32& screen, size_t row); + +// The move of the TM or HM in the TM CASE's row `row`, as a slug such as +// "water-pulse"; empty for CLOSE or a move not read. +std::string read_tm_case_move(Logger& logger, Language language, const ImageViewRGB32& screen, size_t row); + +// The rows of KEY ITEMS (`screen` BAG) or the TM CASE from the top, up to +// the first not read; KEY ITEMS' end with its "cancel". +std::vector read_teach_rows(Logger& logger, Language language, const ImageViewRGB32& image, TeachScreen screen); + +// The messages of the party menu while a TM is taught. +enum class TeachText{ + UNKNOWN, + TEACH_WHICH, // "Teach which POKEMON?" + WANTS_TO_LEARN, // " wants to learn the move ." + KNOWS_FOUR, // "However, already knows four moves." + DELETE_QUESTION, // "Should a move be deleted and replaced with ?" + WHICH_MOVE, // "Which move should be forgotten?" + STOP_QUESTION, // "Stop trying to teach ?" + DID_NOT_LEARN, // " did not learn the move ." + NOT_COMPATIBLE, // " and are not compatible." +}; +const char* teach_text_name(TeachText text); + +// The message over the party menu, from the prompt's or the message box's +// first two lines. +TeachText read_teach_text(Logger& logger, Language language, const ImageViewRGB32& screen); + + +void add_tests_TeachScreenReader(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 8ab074b5ee..d142a9a2ef 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_PartyMenuDetector.h" #include "Inference/Menus/PokemonFRLG_SaveCardReader.h" #include "Inference/Menus/PokemonFRLG_SummaryMovesReader.h" +#include "Inference/Menus/PokemonFRLG_TeachScreenReader.h" #include "Inference/PokemonFRLG_BattleLevelUpReader.h" #include "Inference/PokemonFRLG_BattleSelectionArrowDetector.h" #include "Inference/PokemonFRLG_PartyLevelUpReader.h" @@ -41,6 +42,7 @@ #include "Overworld/PokemonFRLG_PlayerFacingReader.h" #include "Programs/PokemonFRLG_NamingScreenKeyboard.h" #include "PokemonFRLG_Navigation.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h" @@ -696,6 +698,7 @@ static void add_tests_AutoStoryReaders(UnitTestDatabase& database){ add_tests_OptionMenuReader(database); add_tests_SaveCardReader(database); add_tests_SummaryMovesReader(database); + add_tests_TeachScreenReader(database); } void add_tests(UnitTestDatabase& database){ @@ -737,6 +740,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStoryRngLoop(database); add_tests_AutoStoryCapture(database); add_tests_AutoStoryPcStorage(database); + add_tests_AutoStoryAbilities(database); add_tests_NamingCursor(database); add_tests_NamingPlan(database); add_tests_NamingKeys(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp new file mode 100644 index 0000000000..d02816e771 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp @@ -0,0 +1,111 @@ +/* AutoStory Abilities + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "PokemonFRLG_AutoStoryAbilities.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::Outcome; + + +namespace{ + +Outcome mart(Logger& logger, const MartPlan& plan, StoryAbilities& abilities){ + const MartResult result = run_mart(logger, abilities.mart, plan); + const std::string message = mart_message(plan, result); + const bool ok = result.end == MartEnd::DONE || result.end == MartEnd::NOTHING_TO_BUY; + logger.log(message, result.end == MartEnd::DONE ? COLOR_BLACK : COLOR_RED); + return ok ? Pokemon::outcome_ok() : Pokemon::outcome_failed(std::string("mart_") + mart_end_name(result.end), message); +} + +Outcome teach(Logger& logger, const TeachPlan& plan, StoryAbilities& abilities){ + const TeachResult result = run_teach(logger, abilities.teach, abilities.members, plan); + // NO_ITEM: skipped, with run_teach()'s log line. + if (result.end == TeachEnd::LEARNED || result.end == TeachEnd::ALREADY_KNOWN || result.end == TeachEnd::NO_ITEM){ + return Pokemon::outcome_ok(); + } + return Pokemon::outcome_failed(std::string("teach_") + teach_end_name(result.end), teach_message(plan, result)); +} + +Outcome level(Logger& logger, const LevelCheck& check, StoryAbilities& abilities){ + const LevelResult result = run_level_check(logger, abilities.members, check); + switch (result.end){ + case LevelEnd::REACHED: + return Pokemon::outcome_ok(); + case LevelEnd::BELOW: + return Pokemon::outcome_failed("level_below", std::to_string(*result.level) + " < " + std::to_string(check.level)); + case LevelEnd::UNREAD: + break; + } + return Pokemon::outcome_failed("level_unread"); +} + +Outcome grind(Logger& logger, VideoStream* stream, const GrindPlan& plan, StoryAbilities& abilities){ + const GrindResult result = run_grind(logger, abilities.grind, abilities.members, plan); + const std::string message = grind_message(plan, result); + if (result.end == GrindEnd::SHINY){ + // Not a failed Outcome, which would reload the save. + if (stream != nullptr){ + throw ProgramFinishedException(message, *stream); + } + throw ProgramFinishedException(message); + } + if (result.end == GrindEnd::REACHED){ + return Pokemon::outcome_ok(); + } + return Pokemon::outcome_failed(std::string("grind_") + grind_end_name(result.end), message); +} + +Outcome fossil(Logger& logger, Fossil fossil, StoryAbilities& abilities){ + const ChoiceResult result = run_fossil_choice(logger, abilities.choice, fossil); + if (result.end == ChoiceEnd::TAKEN){ + return Pokemon::outcome_ok(); + } + logger.log("Choice: " + result.detail, COLOR_RED); + return Pokemon::outcome_failed(std::string("fossil_") + choice_end_name(result.end), result.detail); +} + +} + + +std::optional run_ability_game_step( + Logger& logger, VideoStream* stream, const Pokemon::StoryStep& step, StoryAbilities& abilities +){ + const std::string_view variant = step.variant; + if (variant.starts_with(MART_VARIANT_PREFIX)){ + const std::optional plan = parse_mart_variant(variant); + return plan ? mart(logger, *plan, abilities) : Pokemon::outcome_failed("bad_variant", step.variant); + } + if (variant.starts_with(TEACH_VARIANT_PREFIX)){ + const std::optional plan = parse_teach_variant(variant); + return plan ? teach(logger, *plan, abilities) : Pokemon::outcome_failed("bad_variant", step.variant); + } + if (variant.starts_with(LEVEL_VARIANT_PREFIX)){ + const std::optional check = parse_level_variant(variant); + return check ? level(logger, *check, abilities) : Pokemon::outcome_failed("bad_variant", step.variant); + } + if (variant.starts_with(GRIND_VARIANT_PREFIX)){ + const std::optional plan = parse_grind_variant(variant); + if (!plan || !step.target){ + return Pokemon::outcome_failed("bad_variant", step.variant + (step.target ? "" : " (no nurse)")); + } + return grind(logger, stream, *plan, abilities); + } + if (variant.starts_with(FOSSIL_VARIANT_PREFIX)){ + const std::optional choice = parse_fossil_variant(variant); + return choice ? fossil(logger, *choice, abilities) : Pokemon::outcome_failed("bad_variant", step.variant); + } + return std::nullopt; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h new file mode 100644 index 0000000000..2a61bfb467 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h @@ -0,0 +1,61 @@ +/* AutoStory Abilities + * + * From: https://github.com/PokemonAutomation/ + * + * The GAME steps beyond walking and talking that later checkpoints name + * in the table: MART (a budgeted buy list), TEACH (a TM or HM), LEVEL (a + * member's level checked), GRIND (wild battles to a level) and + * CHOICE(fossil). Each is a variant of a GAME step; this runs the one a + * step names with the game steps it is given. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryAbilities_H +#define PokemonAutomation_PokemonFRLG_AutoStoryAbilities_H + +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "PokemonFRLG_AutoStoryChoice.h" +#include "PokemonFRLG_AutoStoryGrind.h" +#include "PokemonFRLG_AutoStoryMart.h" +#include "PokemonFRLG_AutoStoryMember.h" +#include "PokemonFRLG_AutoStoryTeach.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The game steps the abilities take. +struct StoryAbilities{ + MemberReader members; + MartActions& mart; + TeachActions& teach; + GrindActions& grind; + ChoiceActions& choice; +}; + +// A MART, TEACH, LEVEL, GRIND or fossil step with `abilities`: nothing for +// another variant. A GRIND that meets a shiny throws +// ProgramFinishedException, with a screenshot from `stream` if given, so +// the segment stops without reloading. Any other end but success is a +// failed Outcome; a MART that buys nothing because the money doesn't +// cover it, and a TEACH whose TM isn't in the TM CASE, succeed, with the +// reason logged. +std::optional run_ability_game_step( + Logger& logger, VideoStream* stream, const Pokemon::StoryStep& step, StoryAbilities& abilities +); + + +// These steps' tests, with the Mart's, TEACH's, GRIND's and the fossil's. +void add_tests_AutoStoryAbilities(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp new file mode 100644 index 0000000000..a0f06a450f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -0,0 +1,216 @@ +/* AutoStory Abilities Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The LEVEL step, and which ends of the MART, TEACH, GRIND and fossil + * steps the story takes as success, failure or a stop. + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "PokemonFRLG_AutoStoryAbilities.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +// A game where nothing happens: a lead whose level is set, a Mart whose +// money is set, a patch whose one battle is shiny if set. +class StubMart : public MartActions{ +public: + size_t money = 3000; + + virtual bool open_buy_list() override{ return true; } + virtual std::optional read_money() override{ return money; } + virtual void move_cursor(size_t, size_t) override{} + virtual std::string read_row(size_t) override{ return ""; } + virtual PurchaseEnd buy(const MartBuy&) override{ return PurchaseEnd::FAILED; } + virtual bool leave() override{ return true; } +}; + +class StubTeach : public TeachActions{ +public: + // Its TM Case is empty. + virtual ItemOpen open_item(std::string_view, std::string_view) override{ return ItemOpen::NOT_IN_CASE; } + virtual TeachPrompt choose_member(size_t) override{ return TeachPrompt::FAILED; } + virtual ForgetEnd forget(size_t) override{ return ForgetEnd::FAILED; } + virtual void stop_teaching() override{} + virtual bool leave() override{ return true; } + virtual void dump_screen(std::string_view) override{} +}; + +class StubPatch : public GrindActions{ +public: + bool shiny = false; + + virtual bool find_encounter(Pokemon::Direction) override{ return true; } + virtual EncounterSeen read_encounter() override{ return {.species = "pidgey", .shiny = shiny}; } + virtual GrindFight fight() override{ return GrindFight::FAILED; } + virtual bool needs_heal() override{ return false; } + virtual bool heal_trip() override{ return true; } + virtual std::optional win_chance(const MemberInfo&, std::string_view) override{ return std::nullopt; } +}; + +class StubFossils : public ChoiceActions{ +public: + virtual bool talk() override{ return false; } + virtual std::optional read_offer() override{ return std::nullopt; } + virtual void answer(bool) override{} + virtual bool finish() override{ return true; } + virtual std::optional fossil_in_bag() override{ return std::nullopt; } +}; + +struct StubGame{ + std::optional level = 16; + StubMart mart; + StubTeach teach; + StubPatch patch; + StubFossils fossils; +}; + + +class Test_AutoStoryAbilities : public UnitTest{ +public: + Test_AutoStoryAbilities(std::string name, std::function body) + : UnitTest("PokemonFRLG::AutoStoryAbilities - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +Pokemon::StoryStep game_step(std::string variant){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = "test"; + step.variant = std::move(variant); + return step; +} + +// The failure name the step ends with ("" for success); "none" if it +// isn't one of these steps. +std::string run_step(StubGame& game, const Pokemon::StoryStep& step){ + QuietLogger logger; + const MemberReader members = [&game](size_t slot) -> std::optional{ + if (slot != 0 || !game.level){ + return std::nullopt; + } + return MemberInfo{.species = "squirtle", .level = game.level, .moves = {"water-gun", "surf"}}; + }; + StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils}; + const std::optional outcome = run_ability_game_step(logger, nullptr, step, abilities); + return outcome ? outcome->failure : "none"; +} + +struct StepCase{ + std::string name; + std::function setup; + Pokemon::StoryStep step; + std::string failure; +}; + +std::vector step_cases(){ + const auto none = [](StubGame&){}; + const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); + return { + {"level reached", none, level_step("check", "", {.slot = 0, .level = 16}), ""}, + {"level below", none, level_step("check", "", {.slot = 0, .level = 17}), "level_below"}, + {"level unread", [](StubGame& game){ game.level.reset(); }, level_step("check", "", {.slot = 0, .level = 16}), "level_unread"}, + {"a Mart with too little money succeeds", [](StubGame& game){ game.mart.money = 100; }, game_step("mart PewterCity_Mart budget=2000 potion=5"), ""}, + {"a Mart purchase that fails", none, game_step("mart PewterCity_Mart budget=2000 potion=5"), "mart_failed"}, + {"a move it knows already succeeds", none, game_step("teach hm03 surf slot=1"), ""}, + {"a TM not in the TM Case is skipped", none, game_step("teach tm03 water-pulse slot=1 forget=water-gun"), ""}, + {"a level that can't be read stops a GRIND", [](StubGame& game){ game.level.reset(); }, grind, "grind_unread"}, + {"a GRIND without a nurse", none, game_step("grind slot=1 level=20"), "bad_variant"}, + {"no YES/NO at the fossil", none, fossil_step("fossil", "", Fossil::HELIX), "fossil_failed"}, + {"a bad variant", none, game_step("mart PewterCity_Mart"), "bad_variant"}, + {"another game step", none, game_step("capture rattata"), "none"}, + }; +} + +UnitTestResult test_ability_steps(){ + for (const StepCase& item : step_cases()){ + StubGame game; + item.setup(game); + const std::string failure = run_step(game, item.step); + if (failure != item.failure){ + return std::format("{}: \"{}\", expected \"{}\".", item.name, failure, item.failure); + } + } + return true; +} + + +// A shiny in a GRIND stops the program, not the checkpoint: a reload +// would lose it. +UnitTestResult test_grind_shiny_stops(){ + StubGame game; + game.patch.shiny = true; + Pokemon::StoryStep step = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); + try{ + run_step(game, step); + }catch (ProgramFinishedException&){ + return true; + } + return "Expected the program to stop on a shiny."; +} + + +UnitTestResult test_level_variant(){ + const std::string variant = level_variant({.slot = 1, .level = 23}); + const std::optional back = parse_level_variant(variant); + if (variant != "level slot=2 min=23" || !back || back->slot != 1 || back->level != 23){ + return "Unexpected level variant \"" + variant + "\"."; + } + for (std::string_view bad : {"level", "level slot=1", "level min=5", "level slot=0 min=5", "level slot=1 min=101"}){ + if (parse_level_variant(bad)){ + return "Expected \"" + std::string(bad) + "\" refused."; + } + } + return true; +} + +} + + +void add_tests_AutoStoryAbilities(UnitTestDatabase& database){ + const auto add = [&](std::string name, UnitTestResult (*body)()){ + database.add(std::move(name), body); + }; + add("the steps' ends as outcomes", test_ability_steps); + add("a shiny in a GRIND stops the program", test_grind_shiny_stops); + add("the LEVEL step's variant", test_level_variant); + add_tests_AutoStoryMart(database); + add_tests_AutoStoryTeach(database); + add_tests_AutoStoryGrind(database); + add_tests_AutoStoryChoice(database); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp index 7bb032b45a..d4ca584649 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp @@ -7,6 +7,7 @@ #include #include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Tools/DebugDumper.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonTools/Async/InferenceRoutines.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" @@ -14,6 +15,7 @@ #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_BagDetector.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleFlashWatcher.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_WildEncounterReader.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.h" @@ -433,6 +435,70 @@ std::optional run_storage_game_step( } +bool pace_until_battle(Logger& logger, PatchSteps& steps, size_t max_steps){ + for (size_t c = 0; c < max_steps; c++){ + if (steps.step()){ + return true; + } + // The flash can be missed (console B, 2026-11-03): the battle's + // first text then waits for A, and the D-pad does nothing. Found a + // step late, the player stays where the battle started, but the + // step after it still counts as taken. + if (steps.battle_shows()){ + logger.log(std::format("Pacing: a battle shows after step {}; its flash was missed.", c + 1), COLOR_ORANGE); + return true; + } + } + if (steps.overworld_shows()){ + return false; + } + if (steps.battle_shows()){ + logger.log(std::format("Pacing: a battle shows after the last of {} steps; its flash was missed.", max_steps), COLOR_ORANGE); + return true; + } + logger.log(std::format("Pacing: no battle in {} steps, and the overworld doesn't show.", max_steps), COLOR_RED); + steps.dump_screen("no-battle-not-overworld"); + return false; +} + + +ConsolePatchSteps::ConsolePatchSteps(ConsoleHandle& console, ProControllerContext& context, Direction pace, PaceSpot& spot) + : m_console(console) + , m_context(context) + , m_pace(pace) + , m_spot(spot) +{} + +bool ConsolePatchSteps::step(){ + const Direction way = m_spot.displaced ? opposite(m_pace) : m_pace; + BattleFlashWatcher battle(COLOR_RED); + const int ret = run_until( + m_console, m_context, + [&](ProControllerContext& context){ + step_once(context, way, m_spot.facing); + }, + {battle} + ); + m_spot = {.displaced = !m_spot.displaced, .facing = way}; + return ret == 0; +} + +bool ConsolePatchSteps::battle_shows(){ + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_console.video().snapshot(); + return screen && BattleScreenDetector(COLOR_RED).detect(screen); +} + +bool ConsolePatchSteps::overworld_shows(){ + return PokemonFRLG::overworld_shows(m_console, m_context); +} + +void ConsolePatchSteps::dump_screen(std::string_view label){ + m_context.wait_for_all_requests(); + dump_debug_image(m_console, "AutoStory/pace", std::string(label), m_console.video().snapshot()); +} + + ConsoleCaptureActions::ConsoleCaptureActions(ConsoleHandle& console, ProControllerContext& context, Language language) : m_console(console) , m_context(context) @@ -440,27 +506,9 @@ ConsoleCaptureActions::ConsoleCaptureActions(ConsoleHandle& console, ProControll {} bool ConsoleCaptureActions::find_encounter(Direction pace){ - // Steps in the patch before giving up: about 10 % of steps in grass - // start a battle at Route 4's rates. - constexpr size_t MAX_STEPS = 200; - std::optional facing; - Direction way = pace; - for (size_t c = 0; c < MAX_STEPS; c++){ - BattleFlashWatcher battle(COLOR_RED); - const int ret = run_until( - m_console, m_context, - [&](ProControllerContext& context){ - step_once(context, way, facing); - }, - {battle} - ); - if (ret == 0){ - return true; - } - facing = way; - way = opposite(way); - } - return false; + PaceSpot spot; + ConsolePatchSteps steps(m_console, m_context, pace, spot); + return pace_until_battle(m_console.logger(), steps, PACE_MAX_STEPS); } EncounterSeen ConsoleCaptureActions::read_encounter(){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h index 21d145aeab..17a8017b84 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h @@ -194,6 +194,58 @@ std::optional run_storage_game_step( ); +// Where pacing has left the player: on the patch's tile, or one tile +// `pace` from it, as the last step taken left it. +struct PaceSpot{ + bool displaced = false; + // The way the player faces after its last step; nothing before one. + std::optional facing = std::nullopt; +}; + +// The game steps of pacing in a patch for a wild battle, injected so the +// search runs in tests. +class PatchSteps{ +public: + virtual ~PatchSteps() = default; + + // One step, `pace` or back as the last left the player: whether a + // battle's flash showed. + virtual bool step() = 0; + // Whether a battle shows: its text box, with an HP box or the menu. + virtual bool battle_shows() = 0; + // Whether the overworld is up, with no text or menu open. + virtual bool overworld_shows() = 0; + // Saves the screen as a debug image, named `label`. + virtual void dump_screen(std::string_view label) = 0; +}; + +// From the overworld, in the patch: steps until a wild battle starts, +// `max_steps` at most. True once one has. +bool pace_until_battle(Logger& logger, PatchSteps& steps, size_t max_steps); + +// Steps in a patch before pacing gives up: about 10 % of steps in grass +// start a battle at Route 4's rates. +constexpr size_t PACE_MAX_STEPS = 200; + +// The console's PatchSteps: `pace` and back from `spot`, which each step +// updates. +class ConsolePatchSteps : public PatchSteps{ +public: + ConsolePatchSteps(ConsoleHandle& console, ProControllerContext& context, Pokemon::Direction pace, PaceSpot& spot); + + virtual bool step() override; + virtual bool battle_shows() override; + virtual bool overworld_shows() override; + virtual void dump_screen(std::string_view label) override; + +private: + ConsoleHandle& m_console; + ProControllerContext& m_context; + Pokemon::Direction m_pace; + PaceSpot& m_spot; +}; + + // The console's capture steps. Encounters are found as the overworld // shiny hunt finds them, a shiny heard as the shiny hunts hear it // (handle_encounter()), and runs as they run (flee_battle()). The wild diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp index e021d50c17..f052619db5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include "Common/Cpp/Exceptions.h" @@ -511,6 +512,88 @@ UnitTestResult test_capture_in_segment(){ return true; } + + +// A patch where the battle starts on step `battle_step` (from 1): the +// flash shows unless missed; its screen shows from `screen_after` steps +// later on (0: right after the step), or never. +struct FakePatch : public PatchSteps{ + size_t battle_step = 0; + bool flash_missed = false; + std::optional screen_after = 0; + // Whether the overworld shows when no battle does. + bool overworld = true; + + size_t steps = 0; + size_t moved = 0; + std::vector dumps = {}; + + bool battle_started() const{ + return battle_step != 0 && steps >= battle_step; + } + virtual bool step() override{ + if (battle_started()){ + // The D-pad does nothing in a battle. + steps++; + return false; + } + steps++; + moved++; + return steps == battle_step && !flash_missed; + } + virtual bool battle_shows() override{ + return battle_started() && screen_after && steps >= battle_step + *screen_after; + } + virtual bool overworld_shows() override{ + return !battle_started() && overworld; + } + virtual void dump_screen(std::string_view label) override{ + dumps.emplace_back(label); + } +}; + +struct PaceCase{ + std::string name; + FakePatch patch; + bool found; + // Steps the player took on the overworld: none in a battle. + size_t moved; + size_t dumps = 0; +}; + +UnitTestResult test_pace_until_battle(){ + const auto patch = [](size_t battle_step, bool flash_missed, std::optional screen_after, bool overworld){ + FakePatch fake; + fake.battle_step = battle_step; + fake.flash_missed = flash_missed; + fake.screen_after = screen_after; + fake.overworld = overworld; + return fake; + }; + std::vector cases{ + {"the flash on step 5", patch(5, false, 0, true), true, 5}, + // Console B, 2026-11-03: "Wild RATTATA appeared!" waited for A + // while 193 more steps paced in vain. + {"the flash missed, the text box right after", patch(5, true, 0, true), true, 5}, + {"the flash missed, the text box a step later", patch(5, true, 1, true), true, 5}, + {"the flash missed, the text box only after the last step", patch(PACE_MAX_STEPS, true, 0, true), true, PACE_MAX_STEPS}, + {"no battle: the overworld, no image", patch(0, false, 0, true), false, PACE_MAX_STEPS}, + {"no battle, not the overworld: an image", patch(0, false, 0, false), false, PACE_MAX_STEPS, 1}, + }; + for (PaceCase& item : cases){ + LineLogger logger; + const bool found = pace_until_battle(logger, item.patch, PACE_MAX_STEPS); + if (found != item.found || item.patch.moved != item.moved || item.patch.dumps.size() != item.dumps){ + return std::format( + "{}: expected found {}, {} steps moved, {} images; got {}, {}, {} ({}).", + item.name, item.found, item.moved, item.dumps, + found, item.patch.moved, item.patch.dumps.size(), joined(logger.lines) + ); + } + } + return true; +} + } @@ -522,6 +605,7 @@ void add_tests_AutoStoryCapture(UnitTestDatabase& database){ add("the table's variant", test_capture_variant); add("messages", test_capture_messages); add("capture and PC steps in a segment: reloads and stops", test_capture_in_segment); + add("pacing finds a battle whose flash was missed", test_pace_until_battle); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp new file mode 100644 index 0000000000..c6e7603425 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp @@ -0,0 +1,165 @@ +/* AutoStory Choice + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryChoice.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; + + +const char* fossil_name(Fossil fossil){ + switch (fossil){ + case Fossil::DOME: return "dome"; + case Fossil::HELIX: return "helix"; + } + return "?"; +} + +std::optional fossil_from_name(std::string_view name){ + for (Fossil fossil : {Fossil::DOME, Fossil::HELIX}){ + if (name == fossil_name(fossil)){ + return fossil; + } + } + return std::nullopt; +} + +Pokemon::TilePos fossil_tile(Fossil fossil){ + return fossil == Fossil::DOME ? Pokemon::TilePos{13, 7} : Pokemon::TilePos{14, 7}; +} + +const char* choice_end_name(ChoiceEnd end){ + switch (end){ + case ChoiceEnd::TAKEN: return "taken"; + case ChoiceEnd::WRONG_ONE: return "wrong_one"; + case ChoiceEnd::FAILED: return "failed"; + } + return "?"; +} + + +std::string fossil_variant(Fossil fossil){ + return std::string(FOSSIL_VARIANT_PREFIX) + fossil_name(fossil); +} + +std::optional parse_fossil_variant(std::string_view variant){ + if (!variant.starts_with(FOSSIL_VARIANT_PREFIX)){ + return std::nullopt; + } + return fossil_from_name(variant.substr(FOSSIL_VARIANT_PREFIX.size())); +} + +Pokemon::StoryStep fossil_step(std::string name, std::string why, Fossil fossil){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = std::move(name); + step.why = std::move(why); + step.variant = fossil_variant(fossil); + return step; +} + + +namespace{ + +ChoiceResult choice_end(ChoiceEnd end, std::string detail){ + return {.end = end, .confirmed = false, .detail = std::move(detail)}; +} + +// NO on the prompt, then the overworld; ends as `end`. +ChoiceResult decline(ChoiceActions& actions, ChoiceEnd end, std::string detail){ + actions.answer(false); + if (!actions.finish()){ + return choice_end(ChoiceEnd::FAILED, "the overworld didn't come back after NO"); + } + return choice_end(end, std::move(detail)); +} + +} + +ChoiceResult run_fossil_choice(Logger& logger, ChoiceActions& actions, Fossil fossil){ + if (!actions.talk()){ + return choice_end(ChoiceEnd::FAILED, "no YES/NO after talking to the fossil"); + } + // Unread, the offer is taken to be the fossil the table faced the + // player to. + const std::optional offer = actions.read_offer(); + if (offer && *offer != fossil){ + return decline(actions, ChoiceEnd::WRONG_ONE, std::format("facing the {} fossil, not the {}", fossil_name(*offer), fossil_name(fossil))); + } + actions.answer(true); + if (!actions.finish()){ + return choice_end(ChoiceEnd::FAILED, "the overworld didn't come back after the fossil"); + } + const std::optional held = actions.fossil_in_bag(); + if (held && *held != fossil){ + return choice_end(ChoiceEnd::FAILED, std::format("the bag holds the {} fossil", fossil_name(*held))); + } + logger.log(std::format( + "Choice: took the {} fossil{}{}.", fossil_name(fossil), offer ? "" : ", by where the player faces (the prompt isn't read)", + held ? ", seen in the bag" : " (the bag isn't read)" + )); + return {.end = ChoiceEnd::TAKEN, .confirmed = held.has_value(), .detail = ""}; +} + + +ConsoleChoiceActions::ConsoleChoiceActions(ConsoleHandle& console, ProControllerContext& context) + : m_console(console) + , m_context(context) +{} + +bool ConsoleChoiceActions::talk(){ + pbf_press_button(m_context, BUTTON_A, 160ms, 500ms); + const WallClock deadline = current_time() + 5000ms; + while (current_time() < deadline){ + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_console.video().snapshot(); + if (screen && yes_no_cursor(screen)){ + return true; + } + pbf_wait(m_context, 250ms); + } + return false; +} + +std::optional ConsoleChoiceActions::read_offer(){ + m_console.log("Choice: no reader for the fossil prompt's text yet.", COLOR_RED); + return std::nullopt; +} + +void ConsoleChoiceActions::answer(bool yes){ + // Reads the cursor (it opens on YES) and answers; B answers NO. + answer_yes_no(m_console, m_context, yes, BUTTON_B, 5000ms); +} + +bool ConsoleChoiceActions::finish(){ + try{ + mash_until_overworld(m_console, m_context, 30000ms); + return true; + }catch (OperationFailedException& e){ + m_console.log("Choice: " + e.message(), COLOR_RED); + return false; + } +} + +std::optional ConsoleChoiceActions::fossil_in_bag(){ + // The item list reader has no names for the fossils yet. + return std::nullopt; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h new file mode 100644 index 0000000000..831ceaec6e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h @@ -0,0 +1,130 @@ +/* AutoStory Choice + * + * From: https://github.com/PokemonAutomation/ + * + * CHOICE steps: a story pick between two things the player takes one of. + * The first is Mt. Moon's fossil (pokefirered data/maps/MtMoon_B2F): after + * Super Nerd Miguel is beaten (the battle step's job), the DOME FOSSIL + * lies at (13, 7) and the HELIX FOSSIL at (14, 7). A on one: "You want + * the DOME/HELIX FOSSIL?" YES/NO. YES: " obtained the ... FOSSIL!", + * then Miguel walks to the other and takes it; NO: nothing happens and + * both stay. + * + * The table walks the player to face the chosen fossil; the step reads + * which fossil the prompt offers before it answers YES, and answers NO + * (B) and stops if it offers the other. A prompt it can't read is taken + * to offer the fossil the player faces, and answered YES. After the + * scene the bag is read for the fossil, where a reader can. + * + * The decisions take their game steps from a ChoiceActions, so they run + * in tests against a fake Mt. Moon. On the console the prompt's text has + * no reader yet: the step waits for the YES/NO box, answers YES by the + * player's place, and clears the scene to the overworld. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryChoice_H +#define PokemonAutomation_PokemonFRLG_AutoStoryChoice_H + +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The `fossil` option: HELIX by default (the world record's). +enum class Fossil{ + DOME, + HELIX, +}; +const char* fossil_name(Fossil fossil); +std::optional fossil_from_name(std::string_view name); + +// Where `fossil` lies on MtMoon_B2F (map.json object_events). +Pokemon::TilePos fossil_tile(Fossil fossil); + +// The prefix of a GAME step's variant that names the fossil CHOICE. +inline constexpr std::string_view FOSSIL_VARIANT_PREFIX = "fossil "; + +// "fossil helix" or "fossil dome". +std::string fossil_variant(Fossil fossil); +std::optional parse_fossil_variant(std::string_view variant); + +// The table's CHOICE(fossil) step, the player facing the fossil. +Pokemon::StoryStep fossil_step(std::string name, std::string why, Fossil fossil); + + +// The game steps the fossil CHOICE takes, injected so its decisions run +// in tests. +class ChoiceActions{ +public: + virtual ~ChoiceActions() = default; + + // Facing the fossil: A, until its YES/NO shows. False if none did. + virtual bool talk() = 0; + // On the YES/NO: the fossil the prompt offers; nothing if unread. + virtual std::optional read_offer() = 0; + // YES (A) or NO (B) on the YES/NO. + virtual void answer(bool yes) = 0; + // The scene's text to the overworld. False if it didn't come back. + virtual bool finish() = 0; + // From the overworld: the fossil in the bag's Key Items; nothing if + // it can't be read. + virtual std::optional fossil_in_bag() = 0; +}; + +enum class ChoiceEnd{ + TAKEN, + // The prompt offered the other fossil: NO answered. + WRONG_ONE, + FAILED, +}; +const char* choice_end_name(ChoiceEnd end); + +struct ChoiceResult{ + ChoiceEnd end = ChoiceEnd::FAILED; + // TAKEN: whether the bag confirmed it. + bool confirmed = false; + std::string detail = {}; +}; + +// Facing the fossil: takes `fossil`. +ChoiceResult run_fossil_choice(Logger& logger, ChoiceActions& actions, Fossil fossil); + + +// The console's fossil CHOICE: talks until the YES/NO box shows, has no +// reader for the prompt's text yet, answers by the box's cursor, and +// clears the scene to the overworld. +class ConsoleChoiceActions : public ChoiceActions{ +public: + ConsoleChoiceActions(ConsoleHandle& console, ProControllerContext& context); + + virtual bool talk() override; + virtual std::optional read_offer() override; + virtual void answer(bool yes) override; + virtual bool finish() override; + virtual std::optional fossil_in_bag() override; + +private: + ConsoleHandle& m_console; + ProControllerContext& m_context; +}; + + +void add_tests_AutoStoryChoice(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp new file mode 100644 index 0000000000..d9fe28b9e6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp @@ -0,0 +1,199 @@ +/* AutoStory Choice Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The fossil CHOICE against a fake MtMoon_B2F that runs its scripts.inc: + * YES on a fossil takes it and Miguel the other; NO leaves both. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryChoice.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +class FakeFossilRoom : public ChoiceActions{ +public: + explicit FakeFossilRoom(Fossil facing) + : facing(facing) + {} + + Fossil facing; + bool offer_readable = true; + bool bag_readable = true; + std::optional taken = std::nullopt; + size_t fossils_left = 2; + std::string error = {}; + + virtual bool talk() override{ + if (fossils_left < 2){ + return false; + } + m_prompt = true; + return true; + } + virtual std::optional read_offer() override{ + if (!m_prompt){ + error = "read the offer with no prompt"; + } + return offer_readable ? std::optional(facing) : std::nullopt; + } + virtual void answer(bool yes) override{ + if (!m_prompt){ + error = "answered with no prompt"; + } + m_prompt = false; + if (yes){ + // The player takes this one, Miguel the other. + taken = facing; + fossils_left = 0; + } + } + virtual bool finish() override{ + if (m_prompt){ + error = "left the prompt unanswered"; + } + return true; + } + virtual std::optional fossil_in_bag() override{ + return bag_readable ? taken : std::nullopt; + } + +private: + bool m_prompt = false; +}; + + +class Test_AutoStoryChoice : public UnitTest{ +public: + Test_AutoStoryChoice(std::string name, std::function body) + : UnitTest("PokemonFRLG::AutoStoryChoice - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +struct ChoiceCase{ + std::string name = {}; + Fossil wanted = Fossil::HELIX; + Fossil facing = Fossil::HELIX; + std::function setup = {}; + ChoiceEnd end = ChoiceEnd::TAKEN; + std::optional taken = std::nullopt; + bool confirmed = false; +}; + +std::vector choice_cases(){ + return { + {.name = "HELIX, the default", .taken = Fossil::HELIX, .confirmed = true}, + {.name = "DOME", .wanted = Fossil::DOME, .facing = Fossil::DOME, .taken = Fossil::DOME, .confirmed = true}, + { + .name = "facing the other fossil: NO, both left", + .facing = Fossil::DOME, + .end = ChoiceEnd::WRONG_ONE, + }, + // The console has no reader for the prompt's text: the table has + // walked the player to face the wanted fossil, so YES takes it + // (console B: answering NO and stopping left 00.13 stuck there). + { + .name = "an unread prompt: YES, facing the wanted fossil", + .setup = [](FakeFossilRoom& room){ room.offer_readable = false; }, + .taken = Fossil::HELIX, + .confirmed = true, + }, + { + .name = "an unread prompt and an unread bag: YES", + .setup = [](FakeFossilRoom& room){ room.offer_readable = false; room.bag_readable = false; }, + .taken = Fossil::HELIX, + }, + { + .name = "taken, the bag unread", + .setup = [](FakeFossilRoom& room){ room.bag_readable = false; }, + .taken = Fossil::HELIX, + }, + { + .name = "both already gone", + .setup = [](FakeFossilRoom& room){ room.fossils_left = 0; }, + .end = ChoiceEnd::FAILED, + }, + }; +} + +UnitTestResult test_fossil_choice(){ + for (const ChoiceCase& item : choice_cases()){ + QuietLogger logger; + FakeFossilRoom room(item.facing); + if (item.setup){ + item.setup(room); + } + const ChoiceResult result = run_fossil_choice(logger, room, item.wanted); + if (!room.error.empty()){ + return item.name + ": " + room.error; + } + if (result.end != item.end || room.taken != item.taken || result.confirmed != item.confirmed){ + return std::format("{}: ended {} ({}), expected {}.", item.name, + choice_end_name(result.end), result.detail, choice_end_name(item.end)); + } + } + return true; +} + + +UnitTestResult test_fossil_variant(){ + if (fossil_variant(Fossil::HELIX) != "fossil helix" || parse_fossil_variant("fossil dome") != Fossil::DOME){ + return "Expected \"fossil helix\" and \"fossil dome\"."; + } + for (std::string_view bad : {"fossil", "fossil old_amber", "fossil helix dome", "grind level=18"}){ + if (parse_fossil_variant(bad)){ + return "Expected \"" + std::string(bad) + "\" refused."; + } + } + // MtMoon_B2F map.json: DOME at (13, 7), HELIX at (14, 7). + if (!(fossil_tile(Fossil::DOME) == Pokemon::TilePos{13, 7}) || !(fossil_tile(Fossil::HELIX) == Pokemon::TilePos{14, 7})){ + return "The fossils' tiles aren't MtMoon_B2F's."; + } + return true; +} + +} + + +void add_tests_AutoStoryChoice(UnitTestDatabase& database){ + const auto add = [&](std::string name, UnitTestResult (*body)()){ + database.add(std::move(name), body); + }; + add("the fossil on a fake Mt. Moon", test_fossil_choice); + add("the table's variant", test_fossil_variant); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 3142ce314b..a25dcbe4e2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -15,10 +15,12 @@ #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryAbilities.h" #include "PokemonFRLG_AutoStoryBattleData.h" #include "PokemonFRLG_AutoStoryCapture.h" #include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStorySummary.h" +#include "PokemonFRLG_AutoStoryTeachScreens.h" #include "PokemonFRLG_AutoStoryWinChance.h" namespace PokemonAutomation{ @@ -448,7 +450,66 @@ Outcome StoryExecutor::ready(RunState& state, const StoryStep& step){ return get_ready(m_env, state, step); } -Outcome StoryExecutor::game(RunState&, const StoryStep& step){ +namespace{ + +bool walked(StoryEnv& env, RunState& state, const StoryStep& step){ + const Outcome outcome = walk_route(env, state, step); + if (outcome.succeeded() && outcome.pose){ + state.pose = *outcome.pose; + } + return outcome.succeeded(); +} + +// A GRIND's trip from the patch to the nurse (`step`'s target) and back +// to `patch`, starting where pacing left the player (`spot`). +bool grind_heal_trip(StoryEnv& env, RunState& state, const StoryStep& step, const Pokemon::Pose& patch, const GrindSpot& spot){ + std::optional here = story_pose(patch); + if (!here){ + return false; + } + if (spot.displaced && spot.facing){ + here->tile = here->tile.next(*spot.facing); + } + if (spot.facing){ + here->facing = spot.facing; + } + state.pose = to_pose(*here); + StoryStep walk; + walk.kind = StoryStepKind::ROUTE; + walk.name = step.name + "_to_nurse"; + walk.target = step.target; + if (!walked(env, state, walk)){ + return false; + } + heal_at_center(env.console, env.context); + // PP too: a grind's battles spend more than its attacks have. + healed_by_nurse(env.supplies); + walk.name = step.name + "_back_to_patch"; + walk.target = patch; + return walked(env, state, walk); +} + +// A MART, TEACH, LEVEL, GRIND or fossil step on the console; nothing for +// another variant. +std::optional run_abilities(StoryEnv& env, RunState& state, const StoryStep& step){ + const Pokemon::Pose patch = state.pose; + ConsoleMartActions mart(env.console, env.context, env.language, env.supplies); + ConsoleTeachScreens teach_screens(env.console, env.context, env.language); + ScreenTeachActions teach(env.console.logger(), teach_screens); + ConsoleGrindActions grind( + env.console, env.context, env.language, env.supplies, env.checks, + [&](const GrindSpot& spot){ + return grind_heal_trip(env, state, step, patch, spot); + } + ); + ConsoleChoiceActions choice(env.console, env.context); + StoryAbilities abilities{console_member_reader(env.console, env.context, env.language), mart, teach, grind, choice}; + return run_ability_game_step(env.console.logger(), &env.console, step, abilities); +} + +} + +Outcome StoryExecutor::game(RunState& state, const StoryStep& step){ if (step.variant == CLOSE_TRAINER_CARD){ close_trainer_card(m_env.console, m_env.context); return Pokemon::outcome_ok(); @@ -463,6 +524,10 @@ Outcome StoryExecutor::game(RunState&, const StoryStep& step){ if (stored){ return *stored; } + const std::optional ability = run_abilities(m_env, state, step); + if (ability){ + return *ability; + } return Pokemon::unsupported_step(step); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index 3981c37b97..a0000f2d66 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -239,7 +239,9 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ // LEAVE_GIFT_SUMMARY: back from Gift RNG (leave_gift_summary()). // A capture or a PC deposit or withdrawal (capture_step(), pc_step() // in PokemonFRLG_AutoStoryCapture.h); a shiny met in a capture stops - // the program without reloading. + // the program without reloading. A MART, TEACH, LEVEL, GRIND or + // fossil CHOICE (PokemonFRLG_AutoStoryAbilities.h); a GRIND heals by + // routing to its target, the nurse, and back. virtual Pokemon::Outcome game(Pokemon::RunState& state, const StoryStep& step) override; private: diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp new file mode 100644 index 0000000000..6393acf42b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp @@ -0,0 +1,373 @@ +/* AutoStory Grind + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryGrind.h" +#include "PokemonFRLG_AutoStoryVariantWords.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::Direction; + + +const char* grind_end_name(GrindEnd end){ + switch (end){ + case GrindEnd::REACHED: return "reached"; + case GrindEnd::LEVEL_CAP: return "level_cap"; + case GrindEnd::NO_ESTIMATE: return "no_estimate"; + case GrindEnd::OUT_OF_ENCOUNTERS: return "out_of_encounters"; + case GrindEnd::NO_ENCOUNTER: return "no_encounter"; + case GrindEnd::SHINY: return "shiny"; + case GrindEnd::PLAYER_FAINTED: return "player_fainted"; + case GrindEnd::UNREAD: return "unread"; + case GrindEnd::REFUSED: return "refused"; + case GrindEnd::FAILED: return "failed"; + } + return "?"; +} + + +std::string grind_variant(const GrindPlan& plan){ + std::string variant = std::format( + "{}slot={} level={} encounters={} pace={} heal_every={}", + GRIND_VARIANT_PREFIX, plan.member + 1, plan.level, plan.max_encounters, + direction_name(plan.pace), plan.heal_every + ); + if (!plan.trainer.empty()){ + variant += std::format(" beat={} chance={:.0f}", plan.trainer, 100 * plan.min_chance); + } + return variant; +} + +namespace{ + +bool set_grind_word(GrindPlan& plan, std::string_view word){ + const std::optional pair = variant_pair(word); + if (!pair){ + return false; + } + if (pair->key == "beat"){ + plan.trainer = std::string(pair->value); + return !plan.trainer.empty(); + } + if (pair->key == "pace"){ + for (Direction direction : Pokemon::ALL_DIRECTIONS){ + if (pair->value == direction_name(direction)){ + plan.pace = direction; + return true; + } + } + return false; + } + const std::optional number = variant_number(pair->value, 4); + if (!number){ + return false; + } + if (pair->key == "slot" && *number >= 1 && *number <= PARTY_SLOTS){ + plan.member = *number - 1; + }else if (pair->key == "level" && *number >= 2 && *number <= 100){ + plan.level = (unsigned)*number; + }else if (pair->key == "encounters" && *number >= 1){ + plan.max_encounters = *number; + }else if (pair->key == "heal_every"){ + plan.heal_every = *number; + }else if (pair->key == "chance" && *number >= 1 && *number <= 100){ + plan.min_chance = static_cast(*number) / 100; + }else{ + return false; + } + return true; +} + +} + +std::optional parse_grind_variant(std::string_view variant){ + if (!variant.starts_with(GRIND_VARIANT_PREFIX)){ + return std::nullopt; + } + GrindPlan plan; + bool level_seen = false; + bool chance_seen = false; + for (std::string_view word : variant_words(variant.substr(GRIND_VARIANT_PREFIX.size()))){ + if (!set_grind_word(plan, word)){ + return std::nullopt; + } + level_seen |= word.starts_with("level="); + chance_seen |= word.starts_with("chance="); + } + // A chance needs a trainer to be against. + if (!level_seen || (chance_seen && plan.trainer.empty())){ + return std::nullopt; + } + return plan; +} + +Pokemon::StoryStep grind_step(std::string name, std::string why, const GrindPlan& plan, Pokemon::Pose nurse){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = std::move(name); + step.why = std::move(why); + step.variant = grind_variant(plan); + step.target = std::move(nurse); + return step; +} + + +namespace{ + +// One GRIND step under way. +class GrindRun{ +public: + GrindRun(Logger& logger, GrindActions& actions, const MemberReader& reader, const GrindPlan& plan) + : m_logger(logger) + , m_actions(actions) + , m_reader(reader) + , m_plan(plan) + {} + + GrindResult run(){ + if (m_plan.member != 0){ + return end(GrindEnd::REFUSED, "only the lead grinds: the battle handler fights with it alone"); + } + if (!read_level()){ + return end(GrindEnd::UNREAD, "couldn't read the member's level"); + } + if (over()){ + return m_result; + } + while (true){ + if (m_result.encounters >= m_plan.max_encounters){ + return end(GrindEnd::OUT_OF_ENCOUNTERS, ""); + } + if (heal_due() && !heal()){ + return end(GrindEnd::FAILED, "the trip to the nurse and back failed"); + } + if (!battle()){ + return m_result; + } + if (over()){ + if (m_result.end != GrindEnd::REACHED || heal()){ + return m_result; + } + return end(GrindEnd::FAILED, "the last trip to the nurse failed"); + } + } + } + +private: + GrindResult end(GrindEnd end, std::string detail){ + m_result.end = end; + m_result.detail = std::move(detail); + return m_result; + } + bool read_level(){ + std::optional member = m_reader(m_plan.member); + if (!member || !member->level){ + return false; + } + m_result.level = member->level; + m_member = std::move(*member); + return true; + } + bool reached() const{ + return m_result.level && *m_result.level >= m_plan.level; + } + // Whether the step ends at the member just read, its end set if so: + // the level reached; or with a trainer, the win chance reached, else + // the level cap. + bool over(){ + if (!m_plan.trainer.empty()){ + return chance_over(); + } + if (!reached()){ + return false; + } + end(GrindEnd::REACHED, ""); + return true; + } + bool chance_over(){ + const std::optional estimate = m_actions.win_chance(m_member, m_plan.trainer); + if (!estimate){ + end(GrindEnd::NO_ESTIMATE, std::format("the sim has no win chance against {}", m_plan.trainer)); + return true; + } + m_result.chance = estimate->chance; + m_logger.log(std::format( + "Grind: level {} against {}: the sim wins {:.0f}% with {}.", + *m_result.level, m_plan.trainer, 100 * estimate->chance, estimate->inputs + )); + if (estimate->chance >= m_plan.min_chance){ + end(GrindEnd::REACHED, ""); + return true; + } + if (reached()){ + end(GrindEnd::LEVEL_CAP, std::format("Lv{} is the cap, short of the win chance", m_plan.level)); + return true; + } + return false; + } + bool heal_due(){ + return m_actions.needs_heal() || (m_plan.heal_every > 0 && m_since_heal >= m_plan.heal_every); + } + bool heal(){ + m_logger.log(std::format("Grind: to the nurse after {} battles.", m_since_heal)); + m_since_heal = 0; + m_result.heals++; + return m_actions.heal_trip(); + } + + // One wild battle, from the patch back to it. False if the step ends + // (the result is set). + bool battle(){ + if (!m_actions.find_encounter(m_plan.pace)){ + end(GrindEnd::NO_ENCOUNTER, ""); + return false; + } + m_result.encounters++; + const EncounterSeen seen = m_actions.read_encounter(); + if (seen.shiny){ + m_logger.log("Grind: a shiny! Stopping in its battle.", COLOR_BLUE); + end(GrindEnd::SHINY, seen.species); + return false; + } + switch (m_actions.fight()){ + case GrindFight::OVER: + break; + case GrindFight::LOST: + end(GrindEnd::PLAYER_FAINTED, ""); + return false; + case GrindFight::FAILED: + end(GrindEnd::FAILED, "the battle didn't end on the overworld"); + return false; + } + m_since_heal++; + if (!read_level()){ + end(GrindEnd::FAILED, "couldn't read the level after a battle"); + return false; + } + m_logger.log(std::format("Grind: battle {} ({}), level {}.", m_result.encounters, seen.species, *m_result.level)); + return true; + } + + Logger& m_logger; + GrindActions& m_actions; + const MemberReader& m_reader; + const GrindPlan& m_plan; + size_t m_since_heal = 0; + MemberInfo m_member; + GrindResult m_result; +}; + +} + +GrindResult run_grind(Logger& logger, GrindActions& actions, const MemberReader& reader, const GrindPlan& plan){ + GrindResult result = GrindRun(logger, actions, reader, plan).run(); + logger.log(grind_message(plan, result), result.end == GrindEnd::REACHED ? COLOR_BLACK : COLOR_RED); + return result; +} + +std::string grind_message(const GrindPlan& plan, const GrindResult& result){ + const std::string level = result.level ? std::to_string(*result.level) : "?"; + const std::string chance = plan.trainer.empty() ? "" : std::format( + ", win chance {} of {:.0f}% against {}", + result.chance ? std::format("{:.0f}%", 100 * *result.chance) : "?", 100 * plan.min_chance, plan.trainer + ); + const std::string tally = std::format( + "level {} of {}{}, {} encounters, {} trips to the nurse", level, plan.level, chance, result.encounters, result.heals + ); + if (result.end == GrindEnd::SHINY){ + return std::format( + "Grind: a shiny {} in encounter {}. Stopped in its battle without running, for you to decide.", + result.detail.empty() ? "Pokemon" : result.detail, result.encounters + ); + } + if (result.detail.empty()){ + return std::format("Grind slot {}: {}: {}.", plan.member + 1, grind_end_name(result.end), tally); + } + return std::format("Grind slot {}: {}: {}: {}.", plan.member + 1, grind_end_name(result.end), result.detail, tally); +} + +PartyMember lead_as_read(const MemberInfo& read, const PartyMember& tracked){ + std::vector moves; + for (const std::string& move : read.moves){ + const auto known = std::find_if(tracked.moves.begin(), tracked.moves.end(), [&](const KnownMove& item){ + return item.move == move; + }); + const int full = max_pp(move); + moves.emplace_back(SummaryMove{.move = move, .pp = known == tracked.moves.end() ? full : known->pp, .max_pp = full}); + } + const uint8_t level = read.level ? static_cast(std::min(*read.level, 100u)) : battle_level(tracked); + return member_from_summary(read.species.empty() ? tracked.species : read.species, level, moves, read.stats); +} + +std::optional healed_win_chance(PartyMember lead, int potions, std::string_view trainer){ + restore_pp(lead); + return story_win_chance(lead, potions, 1.0, trainer); +} + + +ConsoleGrindActions::ConsoleGrindActions( + ConsoleHandle& console, ProControllerContext& context, Language language, + Supplies& supplies, StoryChecks checks, HealTrip heal_trip +) + : m_console(console) + , m_context(context) + , m_language(language) + , m_supplies(supplies) + , m_checks(checks) + , m_encounters(console, context, language) + , m_heal_trip(std::move(heal_trip)) +{} + +bool ConsoleGrindActions::find_encounter(Direction pace){ + // As ConsoleCaptureActions::find_encounter(), keeping track of the + // tile: a battle starts on the tile just stepped onto. + ConsolePatchSteps steps(m_console, m_context, pace, m_spot); + return pace_until_battle(m_console.logger(), steps, PACE_MAX_STEPS); +} + +EncounterSeen ConsoleGrindActions::read_encounter(){ + return m_encounters.read_encounter(); +} + +GrindFight ConsoleGrindActions::fight(){ + try{ + const BattleEnd end = fight_battle(m_console, m_context, m_supplies, BattleKind::WILD_FIGHT, m_checks, m_language); + return end == BattleEnd::WON ? GrindFight::OVER : GrindFight::LOST; + }catch (OperationFailedException& e){ + m_console.log("Grind: " + e.message(), COLOR_RED); + return GrindFight::FAILED; + } +} + +bool ConsoleGrindActions::needs_heal(){ + return m_supplies.hurt || m_supplies.status != StatusCondition::NONE || attacks_low_on_pp(m_supplies); +} + +std::optional ConsoleGrindActions::win_chance(const MemberInfo& member, std::string_view trainer){ + m_supplies.lead = lead_as_read(member, m_supplies.lead); + return healed_win_chance(m_supplies.lead, m_supplies.potions, trainer); +} + +bool ConsoleGrindActions::heal_trip(){ + if (!m_heal_trip || !m_heal_trip(m_spot)){ + return false; + } + // Back on the patch's tile, facing as the route left it. + m_spot = {}; + return true; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h new file mode 100644 index 0000000000..408278cfae --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h @@ -0,0 +1,209 @@ +/* AutoStory Grind + * + * From: https://github.com/PokemonAutomation/ + * + * GRIND(who, where, level): fight wild battles in a patch until a party + * member reaches a level, then heal. Or GRIND(who, where, trainer): until + * the battle sim (PokemonFRLG_AutoStoryWinChance.h) says the member beats + * the next boss often enough, the level then a cap: between battles, with + * the level, moves and stats just read, healed, and the bag's Potions. The table stands the player in the + * patch (as for a capture) and names the Pokemon Center's nurse as the + * step's target: between rounds, and at the end, the step walks there, + * heals and walks back to where it started. + * + * Each battle is the story's battle handler as it is (fight_battle(), + * WILD_FIGHT: it fights while the lead is healthy and runs otherwise); + * move-learn prompts, evolutions and switching are its business. So the + * member that grinds must lead the party: the step refuses another slot. + * It heals when the battle handler says the lead is hurt or has a status, + * when its attacks are low on PP, or after `heal_every` battles; the + * nurse restores PP as well. It is bounded by encounters, and a + * shiny stops it as it stops a capture: nothing pressed. + * + * The member is read with a MemberReader before the first battle and + * after each win. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryGrind_H +#define PokemonAutomation_PokemonFRLG_AutoStoryGrind_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/Language.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryBattleData.h" +#include "PokemonFRLG_AutoStoryCapture.h" +#include "PokemonFRLG_AutoStoryMember.h" +#include "PokemonFRLG_AutoStoryParty.h" +#include "PokemonFRLG_AutoStoryWinChance.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +struct GrindPlan{ + // The party slot that grinds: the lead (0) only. + size_t member = 0; + // Without a trainer, the level to reach; with one, the cap: the step + // stops there if the chance is still short. + unsigned level = 2; + // Wild battles, of any species, before the step gives up. + size_t max_encounters = 60; + // The way the player steps to look for a battle, then back. + Pokemon::Direction pace = Pokemon::Direction::EAST; + // Battles between visits to the nurse; 0: only when hurt. + size_t heal_every = 0; + // The next boss step's trainer, e.g. "TRAINER_RIVAL_CERULEAN_BULBASAUR": + // grind until the sim's win chance against it is `min_chance` or + // more. Empty: grind to `level`. + std::string trainer = {}; + double min_chance = MIN_WIN_CHANCE; +}; + +// The prefix of a GAME step's variant that names a GRIND step. +inline constexpr std::string_view GRIND_VARIANT_PREFIX = "grind "; + +// `plan` as a variant: "grind slot=1 level=18 encounters=60 pace=east +// heal_every=8", the slot counted from 1, and with a trainer +// " beat=TRAINER_RIVAL_CERULEAN_BULBASAUR chance=70", the chance in +// percent. The step's target is the nurse. +std::string grind_variant(const GrindPlan& plan); +std::optional parse_grind_variant(std::string_view variant); + +// The table's GRIND step: `nurse` is where the player faces the nurse. +Pokemon::StoryStep grind_step(std::string name, std::string why, const GrindPlan& plan, Pokemon::Pose nurse); + + +enum class GrindFight{ + // The battle ended with the overworld back and the lead standing, + // won or run from. + OVER, + // The lead fainted: a blackout. + LOST, + FAILED, +}; + +// The game steps a GRIND step takes, injected so its decisions run in +// tests. +class GrindActions{ +public: + virtual ~GrindActions() = default; + + // From the overworld, in the patch: steps `pace` and back until a wild + // battle starts. False if none did. + virtual bool find_encounter(Pokemon::Direction pace) = 0; + // From a wild battle's start: whether it is shiny, and its species. + virtual EncounterSeen read_encounter() = 0; + // From the battle menu: the battle handler, to the overworld. + virtual GrindFight fight() = 0; + // Whether the lead is hurt, has a status or is low on PP in its + // attacks, as the battles left it. + virtual bool needs_heal() = 0; + // From the patch: to the nurse, heal, back to the patch. False if it + // didn't get there and back. + virtual bool heal_trip() = 0; + // The sim's chance for `member`, as just read, healed, against + // `trainer`; none if the sim lacks the species or the trainer. + virtual std::optional win_chance(const MemberInfo& member, std::string_view trainer) = 0; +}; + +enum class GrindEnd{ + // The level, or the win chance, reached. + REACHED, + // The level cap reached with the win chance still short. + LEVEL_CAP, + // The sim has no chance for the member against the trainer. + NO_ESTIMATE, + OUT_OF_ENCOUNTERS, + NO_ENCOUNTER, + // A shiny showed: stopped in its battle, nothing pressed. + SHINY, + PLAYER_FAINTED, + // The member's level couldn't be read: no battle fought. + UNREAD, + REFUSED, + FAILED, +}; +const char* grind_end_name(GrindEnd end); + +struct GrindResult{ + GrindEnd end = GrindEnd::FAILED; + size_t encounters = 0; + size_t heals = 0; + std::optional level = std::nullopt; + // The last win chance against the plan's trainer. + std::optional chance = std::nullopt; + std::string detail = {}; +}; + +// From the overworld in the patch: grinds as `plan` says. +GrindResult run_grind(Logger& logger, GrindActions& actions, const MemberReader& reader, const GrindPlan& plan); + +std::string grind_message(const GrindPlan& plan, const GrindResult& result); + +// The story's lead as `read` shows it (species, level, moves, stats), +// each move's PP as `tracked` counts it for a move of that name, else +// full. +PartyMember lead_as_read(const MemberInfo& read, const PartyMember& tracked); + +// The sim's chance for `lead` with `potions` against `trainer`, once the +// nurse has healed it (full HP and PP). +std::optional healed_win_chance(PartyMember lead, int potions, std::string_view trainer); + + +// Where pacing left the player, for the trip to the nurse. +using GrindSpot = PaceSpot; + +// The console's GRIND steps: encounters found by pacing as a capture +// does, the shiny heard as a capture hears it, battles by fight_battle(), +// the trip to the nurse and back by the caller (the story's routes and +// nurse), told where pacing left the player. +class ConsoleGrindActions : public GrindActions{ +public: + using HealTrip = std::function; + + ConsoleGrindActions( + ConsoleHandle& console, ProControllerContext& context, Language language, + Supplies& supplies, StoryChecks checks, HealTrip heal_trip + ); + + virtual bool find_encounter(Pokemon::Direction pace) override; + virtual EncounterSeen read_encounter() override; + virtual GrindFight fight() override; + virtual bool needs_heal() override; + virtual bool heal_trip() override; + // With the bag's Potions. The member read becomes the story's lead, + // so the boss's own check before its battle plays the same one. + virtual std::optional win_chance(const MemberInfo& member, std::string_view trainer) override; + +private: + ConsoleHandle& m_console; + ProControllerContext& m_context; + Language m_language; + Supplies& m_supplies; + StoryChecks m_checks; + ConsoleCaptureActions m_encounters; + HealTrip m_heal_trip; + GrindSpot m_spot; +}; + + +void add_tests_AutoStoryGrind(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp new file mode 100644 index 0000000000..16e871eb9f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp @@ -0,0 +1,475 @@ +/* AutoStory Grind Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The GRIND step against a fake patch: wild battles that each give EXP, + * a lead that gets hurt after a few, a nurse to walk to, and the bounds + * and stops (a shiny, a blackout, a level that can't be read); and + * grinding until the sim's win chance against the next boss is enough, + * with a level cap. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryBattleSim.h" +#include "PokemonFRLG_AutoStoryGrind.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +constexpr std::string_view RIVAL = "TRAINER_RIVAL_CERULEAN_BULBASAUR"; + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +class FakePatch : public GrindActions{ +public: + unsigned level = 16; + bool level_readable = true; + // Wins for each level gained. + size_t wins_per_level = 2; + size_t wins = 0; + // The lead is hurt after this many battles since the nurse. + size_t hurt_after = 3; + // Encounters the patch has; then none start. + size_t encounters_available = 100; + // The encounter (from 1) that is shiny, or that is lost; 0: none. + size_t shiny_at = 0; + size_t lost_at = 0; + bool heal_fails = false; + // The sim's chance at each level; none: no estimate. + std::function(unsigned level)> chance_at = {}; + + size_t encounters = 0; + size_t fights = 0; + size_t heals = 0; + size_t chances = 0; + std::string error = {}; + + std::optional read_member(size_t slot){ + if (m_in_battle){ + error = "read the level in a battle"; + } + if (!level_readable || slot != 0){ + return std::nullopt; + } + return MemberInfo{.species = "squirtle", .level = level, .moves = {}}; + } + virtual bool find_encounter(Pokemon::Direction) override{ + if (m_in_battle){ + error = "looked for a battle in a battle"; + } + if (encounters >= encounters_available){ + return false; + } + encounters++; + m_in_battle = true; + return true; + } + virtual EncounterSeen read_encounter() override{ + return {.species = "pidgey", .shiny = encounters == shiny_at}; + } + virtual GrindFight fight() override{ + if (!m_in_battle){ + error = "fought off a battle"; + } + m_in_battle = false; + fights++; + m_since_heal++; + if (encounters == lost_at){ + return GrindFight::LOST; + } + wins++; + if (wins % wins_per_level == 0){ + level++; + } + return GrindFight::OVER; + } + virtual bool needs_heal() override{ + return m_since_heal >= hurt_after; + } + virtual bool heal_trip() override{ + if (m_in_battle){ + error = "walked to the nurse in a battle"; + } + heals++; + m_since_heal = 0; + return !heal_fails; + } + virtual std::optional win_chance(const MemberInfo& member, std::string_view trainer) override{ + if (m_in_battle){ + error = "asked the sim in a battle"; + } + if (trainer != RIVAL){ + error = "asked the sim about " + std::string(trainer); + } + chances++; + const std::optional chance = chance_at && member.level ? chance_at(*member.level) : std::nullopt; + if (!chance){ + return std::nullopt; + } + return WinEstimate{.battles = 100, .wins = size_t(*chance * 100), .chance = *chance, .inputs = "a fake lead"}; + } + +private: + bool m_in_battle = false; + size_t m_since_heal = 0; +}; + + +class Test_AutoStoryGrind : public UnitTest{ +public: + Test_AutoStoryGrind(std::string name, std::function body) + : UnitTest("PokemonFRLG::AutoStoryGrind - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +struct GrindCase{ + std::string name = {}; + GrindPlan plan = {}; + std::function setup = {}; + GrindEnd end = GrindEnd::REACHED; + size_t encounters = 0; + size_t fights = 0; + size_t heals = 0; + // The level it ended at, if it matters. + std::optional level = std::nullopt; +}; + +GrindPlan squirtle_to(unsigned level){ + return {.member = 0, .level = level, .max_encounters = 20, .pace = Pokemon::Direction::EAST, .heal_every = 0}; +} + +// Until the rival is 70%, Lv`cap` at most. +GrindPlan beat_rival(unsigned cap){ + GrindPlan plan = squirtle_to(cap); + plan.trainer = std::string(RIVAL); + return plan; +} + +// 40% at Lv16, 5% more a level, 72% from Lv19. +void winnable_from_19(FakePatch& patch){ + patch.chance_at = [](unsigned level) -> std::optional{ + return level >= 19 ? 0.72 : 0.40 + 0.05 * (level - 16); + }; +} +void never_winnable(FakePatch& patch){ + patch.chance_at = [](unsigned) -> std::optional{ return 0.50; }; +} + +std::vector grind_cases_1(){ + return { + { + .name = "16 to 18: a heal when hurt, and one at the end", + .plan = squirtle_to(18), + .encounters = 4, .fights = 4, .heals = 2, + }, + { + .name = "already there: nothing fought", + .plan = squirtle_to(16), + }, + { + .name = "a heal every two battles", + .plan = [](){ GrindPlan plan = squirtle_to(18); plan.heal_every = 2; return plan; }(), + .encounters = 4, .fights = 4, .heals = 2, + }, + { + .name = "not the lead", + .plan = [](){ GrindPlan plan = squirtle_to(18); plan.member = 1; return plan; }(), + .end = GrindEnd::REFUSED, + }, + { + .name = "a level that can't be read: nothing fought", + .plan = squirtle_to(18), + .setup = [](FakePatch& patch){ patch.level_readable = false; }, + .end = GrindEnd::UNREAD, + }, + }; +} + +std::vector grind_cases_2(){ + return { + { + .name = "out of encounters", + .plan = [](){ GrindPlan plan = squirtle_to(30); plan.max_encounters = 3; return plan; }(), + .end = GrindEnd::OUT_OF_ENCOUNTERS, + .encounters = 3, .fights = 3, .heals = 0, + }, + { + .name = "a shiny stops it before its battle", + .plan = squirtle_to(18), + .setup = [](FakePatch& patch){ patch.shiny_at = 2; }, + .end = GrindEnd::SHINY, + .encounters = 2, .fights = 1, .heals = 0, + }, + { + .name = "a blackout", + .plan = squirtle_to(18), + .setup = [](FakePatch& patch){ patch.lost_at = 2; }, + .end = GrindEnd::PLAYER_FAINTED, + .encounters = 2, .fights = 2, .heals = 0, + }, + { + .name = "the trip to the nurse fails", + .plan = squirtle_to(18), + .setup = [](FakePatch& patch){ patch.heal_fails = true; }, + .end = GrindEnd::FAILED, + .encounters = 3, .fights = 3, .heals = 1, + }, + { + .name = "no battle starts", + .plan = squirtle_to(18), + .setup = [](FakePatch& patch){ patch.encounters_available = 1; }, + .end = GrindEnd::NO_ENCOUNTER, + .encounters = 1, .fights = 1, .heals = 0, + }, + }; +} + +// Grinding until the rival is winnable: the chance is asked before the +// first battle and after each. +std::vector grind_cases_3(){ + return { + { + .name = "until 70% against the rival: the first level that is", + .plan = beat_rival(30), + .setup = winnable_from_19, + .encounters = 6, .fights = 6, .heals = 2, + .level = 19, + }, + { + .name = "winnable already: nothing fought", + .plan = beat_rival(30), + .setup = [](FakePatch& patch){ patch.chance_at = [](unsigned){ return std::optional(0.80); }; }, + .level = 16, + }, + { + .name = "winnable past the level cap: the chance decides", + .plan = beat_rival(16), + .setup = [](FakePatch& patch){ patch.chance_at = [](unsigned){ return std::optional(0.80); }; }, + .level = 16, + }, + { + .name = "the level cap before the chance: stopped, no last heal", + .plan = beat_rival(18), + .setup = never_winnable, + .end = GrindEnd::LEVEL_CAP, + .encounters = 4, .fights = 4, .heals = 1, + .level = 18, + }, + { + .name = "out of encounters before the chance", + .plan = [](){ GrindPlan plan = beat_rival(30); plan.max_encounters = 3; return plan; }(), + .setup = never_winnable, + .end = GrindEnd::OUT_OF_ENCOUNTERS, + .encounters = 3, .fights = 3, .heals = 0, + }, + { + .name = "no chance from the sim: nothing fought", + .plan = beat_rival(30), + .end = GrindEnd::NO_ESTIMATE, + }, + }; +} + +std::vector grind_cases(){ + std::vector cases; + for (std::vector part : {grind_cases_1(), grind_cases_2(), grind_cases_3()}){ + cases.insert(cases.end(), part.begin(), part.end()); + } + return cases; +} + +UnitTestResult check_grind_case(const GrindCase& item){ + QuietLogger logger; + FakePatch patch; + if (item.setup){ + item.setup(patch); + } + const GrindResult result = run_grind(logger, patch, [&patch](size_t slot){ + return patch.read_member(slot); + }, item.plan); + if (!patch.error.empty()){ + return item.name + ": " + patch.error; + } + if (result.end != item.end){ + return std::format("{}: ended {}, expected {} ({}).", item.name, + grind_end_name(result.end), grind_end_name(item.end), result.detail); + } + if (patch.encounters != item.encounters || patch.fights != item.fights || patch.heals != item.heals){ + return std::format("{}: {} encounters, {} fights, {} heals; expected {}, {}, {}.", item.name, + patch.encounters, patch.fights, patch.heals, item.encounters, item.fights, item.heals); + } + if (item.level && result.level != item.level){ + return std::format("{}: ended at level {}, expected {}.", item.name, result.level.value_or(0), *item.level); + } + const size_t chances = item.plan.trainer.empty() ? 0 : patch.fights + 1; + if (patch.chances != chances){ + return std::format("{}: the sim asked {} times, expected {}.", item.name, patch.chances, chances); + } + return true; +} + +UnitTestResult test_grind(){ + for (const GrindCase& item : grind_cases()){ + const UnitTestResult result = check_grind_case(item); + if (result.result != UnitTestResult::PASSED){ + return result; + } + } + return true; +} + + +// The cap's stop says what was short: the level, the chance and the +// trainer. +UnitTestResult test_grind_cap_message(){ + QuietLogger logger; + FakePatch patch; + never_winnable(patch); + const GrindPlan plan = beat_rival(18); + const GrindResult result = run_grind(logger, patch, [&patch](size_t slot){ + return patch.read_member(slot); + }, plan); + const std::string message = grind_message(plan, result); + const std::string expected = + "Grind slot 1: level_cap: Lv18 is the cap, short of the win chance: level 18 of 18, win chance 50% of 70%" + " against TRAINER_RIVAL_CERULEAN_BULBASAUR, 4 encounters, 1 trips to the nurse."; + if (message != expected){ + return "Expected \"" + expected + "\", got \"" + message + "\"."; + } + return true; +} + + +// The lead the sim plays is the one read: its species, level, moves and +// stats; the PP the battles left in a move it still knows, and a new +// one's full. +UnitTestResult test_lead_as_read(){ + PartyMember tracked = new_member("wartortle", 22); + tracked.moves = {{.move = "bite", .pp = 10}, {.move = "tail-whip", .pp = 30}, {.move = "bubble", .pp = 5}, {.move = "withdraw", .pp = 40}}; + const Stats stats{.hp = 68, .attack = 40, .defense = 50, .sp_attack = 41, .sp_defense = 49, .speed = 38}; + const MemberInfo read{.species = "wartortle", .level = 23, .moves = {"bite", "water-pulse", "bubble", "withdraw"}, .stats = stats}; + const PartyMember lead = lead_as_read(read, tracked); + std::string moves; + for (const KnownMove& move : lead.moves){ + moves += std::format("{} {}, ", move.move, move.pp); + } + if (moves != "bite 10, water-pulse 20, bubble 5, withdraw 40, "){ + return "Unexpected moves: " + moves; + } + if (lead.species != "wartortle" || lead.level != 23 || battle_level(lead) != 23 || !lead.moves_read + || !lead.stats || lead.stats->hp != 68 || lead.stats->speed != 38 + ){ + return "Expected the species, level and stats read."; + } + return true; +} + + +// Console B at the end of 00.15 (2026-11-03): Wartortle Lv22, 65 HP, +// with Water Pulse taught over Tail Whip, and 10 Potions. The sim, the +// levels since the summary added to its stats, wins against the +// Cerulean rival about 42% at Lv22, 62% at Lv23, 66% at Lv24 and 76% at +// Lv25: a GRIND to 70% stops at Lv25. +UnitTestResult test_console_party(){ + Stats stats = combatant("wartortle", 22, OWN_GENES)->stats; + stats.hp = 65; + const MemberInfo read{.species = "wartortle", .level = 22, .moves = {"bite", "water-pulse", "bubble", "withdraw"}, .stats = stats}; + const PartyMember at22 = lead_as_read(read, PartyMember{}); + for (uint8_t level = 22; level <= 25; level++){ + PartyMember lead = at22; + lead.moves_through_level = level; + const std::optional estimate = healed_win_chance(lead, 10, RIVAL); + if (!estimate || (estimate->chance >= MIN_WIN_CHANCE) != (level == 25)){ + return std::format( + "Lv{}: {:.1f}%; expected the first at {:.0f}% or more at Lv25.", + level, estimate ? 100 * estimate->chance : 0.0, 100 * MIN_WIN_CHANCE + ); + } + } + return true; +} + + +UnitTestResult test_grind_variant(){ + GrindPlan plan = squirtle_to(18); + plan.max_encounters = 60; + plan.pace = Pokemon::Direction::NORTH; + plan.heal_every = 8; + const std::string variant = grind_variant(plan); + if (variant != "grind slot=1 level=18 encounters=60 pace=north heal_every=8"){ + return "Unexpected variant \"" + variant + "\"."; + } + const std::optional back = parse_grind_variant(variant); + if (!back || back->level != 18 || back->max_encounters != 60 || back->pace != Pokemon::Direction::NORTH + || back->heal_every != 8 || back->member != 0 + ){ + return "\"" + variant + "\" didn't read back as its plan."; + } + GrindPlan rival = beat_rival(30); + rival.max_encounters = 100; + rival.pace = Pokemon::Direction::WEST; + const std::string rival_variant = grind_variant(rival); + if (rival_variant != "grind slot=1 level=30 encounters=100 pace=west heal_every=0 beat=TRAINER_RIVAL_CERULEAN_BULBASAUR chance=70"){ + return "Unexpected variant \"" + rival_variant + "\"."; + } + const std::optional rival_back = parse_grind_variant(rival_variant + " chance=75"); + if (!rival_back || rival_back->trainer != RIVAL || rival_back->level != 30 || rival_back->min_chance != 0.75){ + return "\"" + rival_variant + " chance=75\" didn't read back as its plan."; + } + for (std::string_view bad : { + "grind", "grind slot=1", "grind slot=1 level=101", "grind slot=7 level=18", "grind level=18 pace=up", + "grind level=18 encounters=0", "capture rattata", "grind level=30 beat=", "grind level=30 chance=70", + "grind level=30 beat=TRAINER_X chance=0", "grind level=30 beat=TRAINER_X chance=101", + }){ + if (parse_grind_variant(bad)){ + return "Expected \"" + std::string(bad) + "\" refused."; + } + } + return true; +} + +} + + +void add_tests_AutoStoryGrind(UnitTestDatabase& database){ + const auto add = [&](std::string name, UnitTestResult (*body)()){ + database.add(std::move(name), body); + }; + add("grinding on a fake patch", test_grind); + add("the table's variant", test_grind_variant); + add("the level cap's message", test_grind_cap_message); + add("the lead the sim plays is the one read", test_lead_as_read); + add("console B's party stops at Lv25 against the Cerulean rival", test_console_party); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp new file mode 100644 index 0000000000..39cab8c78f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp @@ -0,0 +1,432 @@ +/* AutoStory Mart + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryMart.h" +#include "PokemonFRLG_AutoStoryVariantWords.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; + + +namespace{ + +// The quantity box's most (shop.c Task_BuyHowManyDialogueInit). +constexpr size_t MAX_QUANTITY = 99; + +// Prices from pokefirered src/data/items.json. +constexpr MartStockItem POKE_BALL{"poke-ball", 200}; +constexpr MartStockItem GREAT_BALL{"great-ball", 600}; +constexpr MartStockItem ULTRA_BALL{"ultra-ball", 1200}; +constexpr MartStockItem POTION{"potion", 300}; +constexpr MartStockItem SUPER_POTION{"super-potion", 700}; +constexpr MartStockItem HYPER_POTION{"hyper-potion", 1200}; +constexpr MartStockItem MAX_POTION{"max-potion", 2500}; +constexpr MartStockItem FULL_RESTORE{"full-restore", 3000}; +constexpr MartStockItem REVIVE{"revive", 1500}; +constexpr MartStockItem ANTIDOTE{"antidote", 100}; +constexpr MartStockItem PARLYZ_HEAL{"parlyz-heal", 200}; +constexpr MartStockItem AWAKENING{"awakening", 250}; +constexpr MartStockItem BURN_HEAL{"burn-heal", 250}; +constexpr MartStockItem ICE_HEAL{"ice-heal", 250}; +constexpr MartStockItem FULL_HEAL{"full-heal", 600}; +constexpr MartStockItem ESCAPE_ROPE{"escape-rope", 550}; +constexpr MartStockItem REPEL{"repel", 350}; +constexpr MartStockItem SUPER_REPEL{"super-repel", 500}; +constexpr MartStockItem MAX_REPEL{"max-repel", 700}; + +// Each Mart's `_Items` list in pokefirered data/maps//scripts.inc. +const std::map, std::less<>>& mart_stocks(){ + static const std::map, std::less<>> stocks = { + {"ViridianCity_Mart", {POKE_BALL, POTION, ANTIDOTE, PARLYZ_HEAL}}, + {"PewterCity_Mart", {POKE_BALL, POTION, ANTIDOTE, PARLYZ_HEAL, AWAKENING, BURN_HEAL, ESCAPE_ROPE, REPEL}}, + {"CeruleanCity_Mart", { + POKE_BALL, SUPER_POTION, POTION, ANTIDOTE, PARLYZ_HEAL, AWAKENING, BURN_HEAL, ESCAPE_ROPE, REPEL, + }}, + {"VermilionCity_Mart", {POKE_BALL, SUPER_POTION, ANTIDOTE, PARLYZ_HEAL, AWAKENING, ICE_HEAL, REPEL}}, + {"LavenderTown_Mart", { + GREAT_BALL, SUPER_POTION, REVIVE, ANTIDOTE, PARLYZ_HEAL, BURN_HEAL, ICE_HEAL, ESCAPE_ROPE, SUPER_REPEL, + }}, + {"FuchsiaCity_Mart", {ULTRA_BALL, GREAT_BALL, SUPER_POTION, REVIVE, FULL_HEAL, MAX_REPEL}}, + {"SaffronCity_Mart", {GREAT_BALL, HYPER_POTION, REVIVE, FULL_HEAL, ESCAPE_ROPE, MAX_REPEL}}, + {"CinnabarIsland_Mart", {ULTRA_BALL, GREAT_BALL, HYPER_POTION, REVIVE, FULL_HEAL, ESCAPE_ROPE, MAX_REPEL}}, + {"IndigoPlateau_PokemonCenter_1F", { + ULTRA_BALL, GREAT_BALL, FULL_RESTORE, MAX_POTION, REVIVE, FULL_HEAL, MAX_REPEL, + }}, + }; + return stocks; +} + +std::optional stock_row(const std::vector& stock, std::string_view item){ + for (size_t row = 0; row < stock.size(); row++){ + if (stock[row].item == item){ + return row; + } + } + return std::nullopt; +} + +// Sets one "key=value" of a Mart variant into `plan`. False if it can't. +bool set_mart_word(MartPlan& plan, std::string_view word){ + const std::optional pair = variant_pair(word); + const std::optional number = pair ? variant_number(pair->value) : std::nullopt; + if (!number){ + return false; + } + if (pair->key == "budget"){ + plan.budget = *number; + }else if (pair->key == "floor"){ + plan.money_floor = *number; + }else if (*number >= 1 && *number <= MAX_QUANTITY && stock_row(mart_stock(plan.map), pair->key)){ + plan.lines.push_back({std::string(pair->key), *number}); + }else{ + return false; + } + return true; +} + +} + + +const std::vector& mart_stock(std::string_view map){ + static const std::vector NONE; + const auto found = mart_stocks().find(map); + return found == mart_stocks().end() ? NONE : found->second; +} + +const char* mart_end_name(MartEnd end){ + switch (end){ + case MartEnd::DONE: return "done"; + case MartEnd::NOTHING_TO_BUY: return "nothing_to_buy"; + case MartEnd::NO_MONEY_READ: return "no_money_read"; + case MartEnd::FAILED: return "failed"; + } + return "?"; +} + + +std::string mart_variant(const MartPlan& plan){ + std::string variant = std::format("{}{} budget={}", MART_VARIANT_PREFIX, plan.map, plan.budget); + if (plan.money_floor){ + variant += std::format(" floor={}", *plan.money_floor); + } + for (const MartLine& line : plan.lines){ + variant += std::format(" {}={}", line.item, line.quantity); + } + return variant; +} + +std::optional parse_mart_variant(std::string_view variant){ + if (!variant.starts_with(MART_VARIANT_PREFIX)){ + return std::nullopt; + } + const std::vector words = variant_words(variant.substr(MART_VARIANT_PREFIX.size())); + if (words.empty() || mart_stock(words[0]).empty()){ + return std::nullopt; + } + MartPlan plan; + plan.map = std::string(words[0]); + for (size_t c = 1; c < words.size(); c++){ + if (!set_mart_word(plan, words[c])){ + return std::nullopt; + } + } + if (plan.lines.empty()){ + return std::nullopt; + } + return plan; +} + +Pokemon::StoryStep mart_step(std::string name, std::string why, const MartPlan& plan){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = std::move(name); + step.why = std::move(why); + step.variant = mart_variant(plan); + return step; +} + + +std::optional> plan_mart_buys( + const std::vector& stock, const MartPlan& plan, size_t money +){ + std::vector buys; + size_t left = std::min(plan.budget, money); + for (const MartLine& line : plan.lines){ + const std::optional row = stock_row(stock, line.item); + if (!row){ + return std::nullopt; + } + const size_t price = stock[*row].price; + const size_t quantity = std::min({line.quantity, left / price, MAX_QUANTITY}); + if (quantity == 0){ + continue; + } + buys.push_back({.row = *row, .item = line.item, .quantity = quantity, .cost = quantity * price}); + left -= quantity * price; + } + return buys; +} + +QuantityPresses quantity_presses(size_t quantity){ + if (quantity <= 1){ + return {}; + } + // RIGHT from 1 reaches 11, 21, ...: never past `quantity`, so never + // stopped at the most. + const size_t right = (quantity - 1) / 10; + return {.right = right, .up = quantity - 1 - right * 10}; +} + + +namespace{ + +// One Mart step under way. +class MartRun{ +public: + MartRun(Logger& logger, MartActions& actions, const MartPlan& plan) + : m_logger(logger) + , m_actions(actions) + , m_plan(plan) + {} + + MartResult run(){ + if (!m_actions.open_buy_list()){ + return end(MartEnd::FAILED, "the BUY list didn't show"); + } + const std::optional read = m_actions.read_money(); + const std::optional money = read ? read : m_plan.money_floor; + if (!money){ + return leave(MartEnd::NO_MONEY_READ, ""); + } + m_logger.log(std::format("Mart: ${} ({}), budget ${}.", *money, read ? "read" : "the table's floor", m_plan.budget)); + const std::optional> buys = plan_mart_buys(mart_stock(m_plan.map), m_plan, *money); + if (!buys){ + return leave(MartEnd::FAILED, "an item the Mart doesn't sell"); + } + if (buys->empty()){ + return leave(MartEnd::NOTHING_TO_BUY, ""); + } + for (const MartBuy& buy : *buys){ + if (!buy_one(buy)){ + return leave(MartEnd::FAILED, m_result.detail); + } + } + if (!money_checks(read)){ + return leave(MartEnd::FAILED, m_result.detail); + } + return leave(MartEnd::DONE, ""); + } + +private: + MartResult end(MartEnd end, std::string detail){ + m_result.end = end; + m_result.detail = std::move(detail); + return m_result; + } + // Out to the overworld, then ends as `end`, unless that fails. + MartResult leave(MartEnd end, std::string detail){ + if (!m_actions.leave()){ + return this->end(MartEnd::FAILED, "the overworld didn't come back after the Mart"); + } + return this->end(end, std::move(detail)); + } + + bool buy_one(const MartBuy& buy){ + m_actions.move_cursor(m_cursor, buy.row); + m_cursor = buy.row; + const std::string item = m_actions.read_row(buy.row); + if (!item.empty() && item != buy.item){ + m_result.detail = std::format("row {} is {}, not {}", buy.row + 1, item, buy.item); + return false; + } + if (item.empty()){ + m_logger.log(std::format("Mart: couldn't read row {}; buying it by position.", buy.row + 1), COLOR_ORANGE); + } + switch (m_actions.buy(buy)){ + case PurchaseEnd::BOUGHT: + m_logger.log(std::format("Mart: bought {} {} for ${}.", buy.quantity, buy.item, buy.cost)); + m_result.bought.push_back(buy); + m_result.spent += buy.cost; + return true; + case PurchaseEnd::NOT_ENOUGH_MONEY: + m_result.detail = std::format("not enough money for {} {}", buy.quantity, buy.item); + return false; + case PurchaseEnd::WRONG_QUANTITY: + m_result.detail = std::format("the quantity box didn't show {} for {}", buy.quantity, buy.item); + return false; + case PurchaseEnd::FAILED: + break; + } + m_result.detail = std::format("buying {} {} didn't come back to the list", buy.quantity, buy.item); + return false; + } + + // With the money read before, it is read again: the difference must + // be what was spent. + bool money_checks(const std::optional& before){ + if (!before){ + return true; + } + const std::optional after = m_actions.read_money(); + if (!after || *before - *after == m_result.spent){ + return true; + } + m_result.detail = std::format("${} before and ${} after, but ${} bought", *before, *after, m_result.spent); + return false; + } + + Logger& m_logger; + MartActions& m_actions; + const MartPlan& m_plan; + size_t m_cursor = 0; + MartResult m_result; +}; + +} + +MartResult run_mart(Logger& logger, MartActions& actions, const MartPlan& plan){ + return MartRun(logger, actions, plan).run(); +} + +std::string mart_message(const MartPlan& plan, const MartResult& result){ + std::string bought; + for (const MartBuy& buy : result.bought){ + bought += std::format("{}{} {}", bought.empty() ? "" : ", ", buy.quantity, buy.item); + } + if (bought.empty()){ + bought = "nothing"; + } + switch (result.end){ + case MartEnd::DONE: + return std::format("Mart ({}): bought {} for ${}.", plan.map, bought, result.spent); + case MartEnd::NOTHING_TO_BUY: + return std::format("Mart ({}): the money or budget covers none of the list; bought nothing.", plan.map); + case MartEnd::NO_MONEY_READ: + return std::format( + "Mart ({}): the money box can't be read and the table gives no floor; bought nothing.", plan.map + ); + case MartEnd::FAILED: + return std::format("Mart ({}): {}; bought {} for ${}.", plan.map, result.detail, bought, result.spent); + } + return "Mart: ?"; +} + + +ConsoleMartActions::ConsoleMartActions( + ConsoleHandle& console, ProControllerContext& context, Language language, Supplies& supplies +) + : m_console(console) + , m_context(context) + , m_language(language) + , m_supplies(supplies) +{} + +bool ConsoleMartActions::open_buy_list(){ + // "May I help you?" with BUY on top, then the list with the cursor on + // its top row, as buy_items() found them. + pbf_press_button(m_context, BUTTON_A, 160ms, 2000ms); + pbf_press_button(m_context, BUTTON_A, 160ms, 2000ms); + m_context.wait_for_all_requests(); + m_row = 0; + m_lowest_row = 0; + return true; +} + +std::optional ConsoleMartActions::read_money(){ + // No reader for the money box yet. + return std::nullopt; +} + +void ConsoleMartActions::move_cursor(size_t from, size_t to){ + for (size_t c = from; c < to; c++){ + pbf_press_dpad(m_context, DPAD_DOWN, 160ms, 300ms); + } + for (size_t c = to; c < from; c++){ + pbf_press_dpad(m_context, DPAD_UP, 160ms, 300ms); + } + m_context.wait_for_all_requests(); + m_row = to; + m_lowest_row = std::max(m_lowest_row, to); +} + +std::string ConsoleMartActions::read_row(size_t row){ + // Rows past the window's last but one may have scrolled the list. + if (m_lowest_row + 1 >= (size_t)ITEM_LIST_ROWS){ + return ""; + } + VideoSnapshot screen = m_console.video().snapshot(); + if (!screen){ + return ""; + } + return read_item_list_name(m_console.logger(), m_language, screen, (int)row); +} + +PurchaseEnd ConsoleMartActions::buy(const MartBuy& buy){ + // "How many?" drops presses while its text prints. + pbf_press_button(m_context, BUTTON_A, 160ms, 2500ms); + const QuantityPresses presses = quantity_presses(buy.quantity); + for (size_t c = 0; c < presses.right; c++){ + pbf_press_dpad(m_context, DPAD_RIGHT, 160ms, 340ms); + } + for (size_t c = 0; c < presses.up; c++){ + pbf_press_dpad(m_context, DPAD_UP, 160ms, 340ms); + } + // "That will be..." YES/NO, YES, "Here you are!"; back to the list. + pbf_press_button(m_context, BUTTON_A, 160ms, 3500ms); + pbf_press_button(m_context, BUTTON_A, 160ms, 2000ms); + pbf_press_button(m_context, BUTTON_A, 160ms, 1500ms); + m_context.wait_for_all_requests(); + count_supplies(m_supplies, buy.item, buy.quantity); + return PurchaseEnd::BOUGHT; +} + +bool ConsoleMartActions::leave(){ + pbf_press_button(m_context, BUTTON_B, 160ms, 1500ms); + pbf_press_button(m_context, BUTTON_B, 160ms, 1500ms); + try{ + mash_until_overworld(m_console, m_context, 20000ms); + return true; + }catch (OperationFailedException& e){ + m_console.log("Mart: " + e.message(), COLOR_RED); + return false; + } +} + + +void count_supplies(Supplies& supplies, std::string_view item, size_t quantity){ + int Supplies::* count = nullptr; + if (item == "potion"){ + count = &Supplies::potions; + }else if (item == "antidote"){ + count = &Supplies::antidotes; + }else if (item == "parlyz-heal"){ + count = &Supplies::parlyz_heals; + } + if (count == nullptr){ + return; + } + if (std::find(supplies.pocket.begin(), supplies.pocket.end(), item) == supplies.pocket.end()){ + supplies.pocket.emplace_back(item); + } + supplies.*count += (int)quantity; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h new file mode 100644 index 0000000000..28de24cd5b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h @@ -0,0 +1,225 @@ +/* AutoStory Mart + * + * From: https://github.com/PokemonAutomation/ + * + * A story step at any Poke Mart: a buy list in priority order, within a + * budget, as pokefirered's shop.c runs the BUY menu: + * + * - Talking to the clerk: BUY, SELL, SEE YA!, on BUY. A on BUY opens the + * Mart's list (its stock in the map's scripts.inc order, then CANCEL), + * the cursor on the top row, and the money box. + * - A on an item the player can't pay one of: "You don't have enough + * money." and back to the list. Otherwise "How many?" with the + * quantity box on 1. Its most is the money over the price, at most 99. + * UP adds one and wraps from the most to 1; DOWN takes one and wraps + * from 1 to the most; RIGHT adds ten and LEFT takes ten, both stopping + * at the ends (menu_helpers.c AdjustQuantityAccordingToDPadInput). + * - A on the quantity: "... And you wanted N? That will be $X." YES/NO on + * YES; YES: "Here you are! Thank you!", the money taken, back to the + * list with the cursor on the row bought. + * + * The step never opens SELL. Each line buys as many as its quantity, + * the budget left and the money left allow, in the order listed; a line + * that can't buy one is skipped. The money is read from the money box + * when a reader exists; without one the step counts on the table's + * floor (the least the ledger says the player has) and, with neither, + * buys nothing: a quantity typed past the most wraps, and buys the wrong + * number. + * + * The decisions take their game steps from a MartActions, so they run in + * tests against a fake Mart; ConsoleMartActions does them on the console + * with the item list reader, whose names cover the items a new game meets + * before the Boulder Badge (a row it can't read is bought by position). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryMart_H +#define PokemonAutomation_PokemonFRLG_AutoStoryMart_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/Language.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "PokemonFRLG_AutoStoryBattle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// One item a Mart sells: its slug (as read_item_list_name() names it, +// e.g. "parlyz-heal") and its price (pokefirered items.json). +struct MartStockItem{ + std::string_view item; + size_t price; +}; + +// The BUY list of the Mart on map `map` (e.g. "PewterCity_Mart"), in row +// order, CANCEL not included; empty for a map whose stock isn't known. +const std::vector& mart_stock(std::string_view map); + +// One line of a buy list: an item and how many. +struct MartLine{ + std::string item = {}; + size_t quantity = 1; +}; + +// What a Mart step buys. +struct MartPlan{ + // The Mart's map, for its stock. + std::string map = {}; + // In priority order. + std::vector lines = {}; + // The most the step spends. + size_t budget = 0; + // The least money the player has here, from the money plan: used + // when the money box can't be read. + std::optional money_floor = std::nullopt; +}; + +// The prefix of a GAME step's variant that names a Mart step. +inline constexpr std::string_view MART_VARIANT_PREFIX = "mart "; + +// `plan` as a variant: "mart PewterCity_Mart budget=2000 floor=2400 +// potion=5 repel=3", the lines in order. +std::string mart_variant(const MartPlan& plan); +// A variant from mart_variant(); nothing if it isn't one, has no line, or +// names an item its Mart doesn't sell. +std::optional parse_mart_variant(std::string_view variant); + +// The table's Mart step. +Pokemon::StoryStep mart_step(std::string name, std::string why, const MartPlan& plan); + + +// One purchase the step makes. +struct MartBuy{ + // The list's row, from 0. + size_t row = 0; + std::string item = {}; + size_t quantity = 0; + size_t cost = 0; +}; + +// What `plan` buys at a Mart with `stock` and `money`: each line as many +// as fit in the budget and the money left, in order, at most 99; lines +// that buy none are left out. Nothing if a line's item isn't stocked. +std::optional> plan_mart_buys( + const std::vector& stock, const MartPlan& plan, size_t money +); + +// The presses that turn the quantity box from 1 into `quantity` without +// passing its most: RIGHT adds ten, then UP one at a time. +struct QuantityPresses{ + size_t right = 0; + size_t up = 0; +}; +QuantityPresses quantity_presses(size_t quantity); + + +enum class PurchaseEnd{ + // "Here you are!": bought, back at the list. + BOUGHT, + // "You don't have enough money.": back at the list. + NOT_ENOUGH_MONEY, + // The quantity box showed another number: backed out with B. + WRONG_QUANTITY, + FAILED, +}; + +// The game steps a Mart step takes, injected so its decisions run in +// tests. +class MartActions{ +public: + virtual ~MartActions() = default; + + // Facing the clerk: talk, BUY, to the list with the cursor on its top + // row. False if the list didn't show. + virtual bool open_buy_list() = 0; + // On the list: the money box; nothing if it can't be read. + virtual std::optional read_money() = 0; + // On the list: the cursor from row `from` to row `to`. + virtual void move_cursor(size_t from, size_t to) = 0; + // On the list: row `row`'s item slug; empty if it can't be read. + virtual std::string read_row(size_t row) = 0; + // On the list, the cursor on `buy`'s row: A, its quantity typed as + // quantity_presses() says, A, YES. The quantity box is read before + // the A, if it can be: another number backs out. + virtual PurchaseEnd buy(const MartBuy& buy) = 0; + // From the list: CANCEL, SEE YA!, to the overworld. False if it didn't + // come back. + virtual bool leave() = 0; +}; + +enum class MartEnd{ + DONE, + // The plan bought nothing: the money (or its floor) doesn't cover one + // of anything. The Mart isn't touched. + NOTHING_TO_BUY, + // Neither the money box nor the table's floor gave the money. + NO_MONEY_READ, + FAILED, +}; +const char* mart_end_name(MartEnd end); + +struct MartResult{ + MartEnd end = MartEnd::FAILED; + std::vector bought = {}; + size_t spent = 0; + // FAILED: what failed. + std::string detail = {}; +}; + +// Facing the clerk: buys as `plan` says, then back to the overworld. +MartResult run_mart(Logger& logger, MartActions& actions, const MartPlan& plan); + +std::string mart_message(const MartPlan& plan, const MartResult& result); + + +// Counts `quantity` of `item` into `supplies`, if it is one the battles +// use (Potions, Antidotes, Parlyz Heals); a new one goes to the end of the +// pocket, where the bag adds it. +void count_supplies(Supplies& supplies, std::string_view item, size_t quantity); + + +// The console's Mart. The money box and the quantity box have no reader +// yet, so the money is the table's floor and the quantity is typed by +// presses. Potions, Antidotes and Parlyz Heals bought are counted into +// `supplies`. +class ConsoleMartActions : public MartActions{ +public: + ConsoleMartActions(ConsoleHandle& console, ProControllerContext& context, Language language, Supplies& supplies); + + virtual bool open_buy_list() override; + virtual std::optional read_money() override; + virtual void move_cursor(size_t from, size_t to) override; + virtual std::string read_row(size_t row) override; + virtual PurchaseEnd buy(const MartBuy& buy) override; + virtual bool leave() override; + +private: + ConsoleHandle& m_console; + ProControllerContext& m_context; + Language m_language; + Supplies& m_supplies; + size_t m_row = 0; + // The lowest row the cursor has reached: past the window's rows the + // list scrolls, and a screen row is no longer the list's. + size_t m_lowest_row = 0; +}; + + +void add_tests_AutoStoryMart(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp new file mode 100644 index 0000000000..78bcf52cb5 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp @@ -0,0 +1,401 @@ +/* AutoStory Mart Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The Mart step against a fake Mart that runs the BUY menu as + * pokefirered's shop.c does (see PokemonFRLG_AutoStoryMart.h): the list + * keeps its cursor on the row bought, the quantity box's most is the + * money over the price and UP wraps from it to 1, and an item the player + * can't pay one of is refused. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryMart.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +class FakeMart : public MartActions{ +public: + FakeMart(std::string_view map, size_t money) + : stock(mart_stock(map)) + , money(money) + {} + + std::vector stock; + size_t money; + bool money_readable = true; + bool rows_readable = true; + bool quantity_readable = true; + // Rows that read as another item. + std::map misread = {}; + // Each purchase takes this much more than its price: a bug to catch. + size_t overcharge = 0; + std::map bag = {}; + size_t list_opened = 0; + bool in_list = false; + std::string error = {}; + + virtual bool open_buy_list() override{ + in_list = true; + m_cursor = 0; + list_opened++; + return true; + } + virtual std::optional read_money() override{ + if (!in_list){ + error = "read the money off the list"; + } + return money_readable ? std::optional(money) : std::nullopt; + } + virtual void move_cursor(size_t from, size_t to) override{ + if (from != m_cursor){ + error = std::format("moved from row {}, but the cursor was on row {}", from, m_cursor); + } + // The list is the stock, then CANCEL. + m_cursor = std::min(to, stock.size()); + } + virtual std::string read_row(size_t row) override{ + if (row != m_cursor){ + error = std::format("read row {}, the cursor on row {}", row, m_cursor); + } + const auto found = misread.find(row); + if (found != misread.end()){ + return found->second; + } + return rows_readable && row < stock.size() ? std::string(stock[row].item) : ""; + } + virtual PurchaseEnd buy(const MartBuy& buy) override{ + if (m_cursor >= stock.size()){ + error = "A on CANCEL"; + in_list = false; + return PurchaseEnd::FAILED; + } + const size_t price = stock[m_cursor].price; + if (price > money){ + return PurchaseEnd::NOT_ENOUGH_MONEY; + } + const size_t quantity = typed_quantity(buy.quantity, std::min(99, money / price)); + if (quantity_readable && quantity != buy.quantity){ + return PurchaseEnd::WRONG_QUANTITY; + } + money -= quantity * price + overcharge; + bag[std::string(stock[m_cursor].item)] += quantity; + return PurchaseEnd::BOUGHT; + } + virtual bool leave() override{ + in_list = false; + return true; + } + +private: + // The box after quantity_presses(wanted), from 1, with this most. + static size_t typed_quantity(size_t wanted, size_t most){ + const QuantityPresses presses = quantity_presses(wanted); + size_t quantity = 1; + for (size_t c = 0; c < presses.right; c++){ + quantity = std::min(quantity + 10, most); + } + for (size_t c = 0; c < presses.up; c++){ + quantity = quantity + 1 > most ? 1 : quantity + 1; + } + return quantity; + } + + size_t m_cursor = 0; +}; + + +class Test_AutoStoryMart : public UnitTest{ +public: + Test_AutoStoryMart(std::string name, std::function body) + : UnitTest("PokemonFRLG::AutoStoryMart - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +MartPlan pewter_plan(size_t budget, std::vector lines, std::optional floor = std::nullopt){ + return {.map = "PewterCity_Mart", .lines = std::move(lines), .budget = budget, .money_floor = floor}; +} + +std::string bag_string(const std::map& bag){ + std::string text; + for (const auto& item : bag){ + text += std::format("{}{} {}", text.empty() ? "" : ", ", item.second, item.first); + } + return text.empty() ? "nothing" : text; +} + +struct MartCase{ + std::string name = {}; + MartPlan plan = {}; + size_t money = 0; + std::function setup = {}; + MartEnd end = MartEnd::DONE; + std::map bag = {}; + size_t money_after = 0; +}; + +std::vector mart_cases_1(){ + return { + { + .name = "priority order within the budget, a line cut to what fits", + .plan = pewter_plan(2000, {{"potion", 5}, {"repel", 3}, {"antidote", 3}}), + .money = 3000, + .bag = {{"potion", 5}, {"repel", 1}, {"antidote", 1}}, + .money_after = 1050, + }, + { + .name = "the money, below the budget, limits it", + .plan = pewter_plan(2000, {{"potion", 5}}), + .money = 700, + .bag = {{"potion", 2}}, + .money_after = 100, + }, + { + .name = "a line that can't buy one is skipped", + .plan = pewter_plan(400, {{"escape-rope", 1}, {"antidote", 2}}), + .money = 3000, + .bag = {{"antidote", 2}}, + .money_after = 2800, + }, + { + .name = "twenty-five by RIGHT and UP", + .plan = pewter_plan(10000, {{"poke-ball", 25}}), + .money = 6000, + .bag = {{"poke-ball", 25}}, + .money_after = 1000, + }, + }; +} + +std::vector mart_cases_2(){ + return { + { + .name = "unread money: the table's floor", + .plan = pewter_plan(2000, {{"potion", 5}}, 1000), + .money = 1200, + .setup = [](FakeMart& mart){ mart.money_readable = false; }, + .bag = {{"potion", 3}}, + .money_after = 300, + }, + { + .name = "unread money and no floor: nothing bought", + .plan = pewter_plan(2000, {{"potion", 5}}), + .money = 3000, + .setup = [](FakeMart& mart){ mart.money_readable = false; }, + .end = MartEnd::NO_MONEY_READ, + .money_after = 3000, + }, + { + .name = "a floor above the money: the quantity box wraps, and its read catches it", + .plan = pewter_plan(2000, {{"potion", 3}}, 1000), + .money = 500, + .setup = [](FakeMart& mart){ mart.money_readable = false; }, + .end = MartEnd::FAILED, + .money_after = 500, + }, + { + .name = "too poor for any of it", + .plan = pewter_plan(2000, {{"potion", 5}}), + .money = 250, + .end = MartEnd::NOTHING_TO_BUY, + .money_after = 250, + }, + }; +} + +std::vector mart_cases_3(){ + return { + { + .name = "a row that reads as another item stops it", + .plan = pewter_plan(2000, {{"potion", 1}, {"antidote", 1}}), + .money = 3000, + .setup = [](FakeMart& mart){ mart.misread[2] = "parlyz-heal"; }, + .end = MartEnd::FAILED, + .bag = {{"potion", 1}}, + .money_after = 2700, + }, + { + .name = "rows that can't be read are bought by position", + .plan = pewter_plan(2000, {{"repel", 2}, {"potion", 1}}), + .money = 3000, + .setup = [](FakeMart& mart){ mart.rows_readable = false; }, + .bag = {{"repel", 2}, {"potion", 1}}, + .money_after = 2000, + }, + { + .name = "more money gone than bought fails", + .plan = pewter_plan(2000, {{"potion", 1}}), + .money = 3000, + .setup = [](FakeMart& mart){ mart.overcharge = 10; }, + .end = MartEnd::FAILED, + .bag = {{"potion", 1}}, + .money_after = 2690, + }, + }; +} + +std::vector mart_cases(){ + std::vector cases; + for (std::vector part : {mart_cases_1(), mart_cases_2(), mart_cases_3()}){ + cases.insert(cases.end(), part.begin(), part.end()); + } + return cases; +} + +UnitTestResult check_mart_case(const MartCase& item){ + QuietLogger logger; + FakeMart mart(item.plan.map, item.money); + if (item.setup){ + item.setup(mart); + } + const MartResult result = run_mart(logger, mart, item.plan); + if (!mart.error.empty()){ + return item.name + ": " + mart.error; + } + if (result.end != item.end){ + return std::format("{}: ended {}, expected {} ({}).", item.name, + mart_end_name(result.end), mart_end_name(item.end), result.detail); + } + if (mart.bag != item.bag || mart.money != item.money_after){ + return std::format("{}: bag {}, ${}; expected {}, ${}.", item.name, + bag_string(mart.bag), mart.money, bag_string(item.bag), item.money_after); + } + if (mart.in_list){ + return item.name + ": left in the Mart's list."; + } + return true; +} + +UnitTestResult test_mart_buys(){ + for (const MartCase& item : mart_cases()){ + const UnitTestResult result = check_mart_case(item); + if (result.result != UnitTestResult::PASSED){ + return result; + } + } + return true; +} + + +// The presses for each quantity reach it from 1 in a box whose most is +// just that quantity, so RIGHT never stops at the most early. +UnitTestResult test_quantity_presses(){ + for (size_t quantity = 1; quantity <= 99; quantity++){ + const QuantityPresses presses = quantity_presses(quantity); + const size_t reached = 1 + presses.right * 10 + presses.up; + if (reached != quantity || presses.up > 9){ + return std::format("{}: {} RIGHT and {} UP reach {}.", quantity, presses.right, presses.up, reached); + } + } + return true; +} + + +UnitTestResult test_mart_variant(){ + const MartPlan plan = pewter_plan(2000, {{"potion", 5}, {"repel", 3}}, 2400); + const std::string variant = mart_variant(plan); + if (variant != "mart PewterCity_Mart budget=2000 floor=2400 potion=5 repel=3"){ + return "Unexpected variant \"" + variant + "\"."; + } + const std::optional back = parse_mart_variant(variant); + if (!back || back->map != plan.map || back->budget != 2000 || back->money_floor != plan.money_floor + || back->lines.size() != 2 || back->lines[1].item != "repel" || back->lines[1].quantity != 3 + ){ + return "\"" + variant + "\" didn't read back as its plan."; + } + for (std::string_view bad : { + "mart", "mart PewterCity_Mart budget=2000", "mart Nowhere_Mart potion=1", + "mart ViridianCity_Mart repel=1", "mart PewterCity_Mart potion=0", "mart PewterCity_Mart potion=100", + "mart PewterCity_Mart potion", "teach hm03 surf slot=1", + }){ + if (parse_mart_variant(bad)){ + return "Expected \"" + std::string(bad) + "\" refused."; + } + } + return true; +} + + +// Each Mart's stock is its scripts.inc list, with known prices. +UnitTestResult test_mart_stock(){ + const std::vector& viridian = mart_stock("ViridianCity_Mart"); + if (viridian.size() != 4 || viridian[3].item != "parlyz-heal" || viridian[1].price != 300){ + return "Viridian's stock isn't POKE BALL, POTION (300), ANTIDOTE, PARLYZ HEAL."; + } + const std::vector& cerulean = mart_stock("CeruleanCity_Mart"); + if (cerulean.size() != 9 || cerulean[1].item != "super-potion" || cerulean[2].item != "potion"){ + return "Cerulean sells SUPER POTION above POTION."; + } + if (!mart_stock("Route4_PokemonCenter_1F").empty()){ + return "Expected no stock for a map without a Mart."; + } + return true; +} + + +// Potions, Antidotes and Parlyz Heals bought go into the battles' supplies. +UnitTestResult test_count_supplies(){ + Supplies supplies; + supplies.pocket = {"potion"}; + supplies.potions = 1; + count_supplies(supplies, "antidote", 3); + count_supplies(supplies, "potion", 2); + count_supplies(supplies, "repel", 4); + count_supplies(supplies, "poke-ball", 5); + if (supplies.potions != 3 || supplies.antidotes != 3 || supplies.pocket != std::vector{"potion", "antidote"}){ + return std::format("Supplies {} potions, {} antidotes, {} pocket rows.", + supplies.potions, supplies.antidotes, supplies.pocket.size()); + } + return true; +} + +} + + +void add_tests_AutoStoryMart(UnitTestDatabase& database){ + const auto add = [&](std::string name, UnitTestResult (*body)()){ + database.add(std::move(name), body); + }; + add("buy lists on a fake Mart", test_mart_buys); + add("quantity presses", test_quantity_presses); + add("the table's variant", test_mart_variant); + add("Mart stocks", test_mart_stock); + add("bought supplies counted", test_count_supplies); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp new file mode 100644 index 0000000000..5500e5e21f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp @@ -0,0 +1,94 @@ +/* AutoStory Member + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonFRLG_AutoStoryMember.h" +#include "PokemonFRLG_AutoStorySummary.h" +#include "PokemonFRLG_AutoStoryVariantWords.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +MemberReader console_member_reader(ConsoleHandle& console, ProControllerContext& context, Language language){ + return [&console, &context, language](size_t slot) -> std::optional{ + const std::optional read = read_party_summary(console, context, StartMenu::FULL, language, slot); + if (!read || read->species.empty() || !read->level || read->moves.empty()){ + console.log(std::format("Party: couldn't read the member in slot {}.", slot + 1), COLOR_RED); + return std::nullopt; + } + MemberInfo info{.species = read->species, .level = read->level, .moves = {}, .stats = read->stats}; + for (const SummaryMove& move : read->moves){ + info.moves.push_back(move.move); + } + return info; + }; +} + + +std::string level_variant(const LevelCheck& check){ + return std::format("{}slot={} min={}", LEVEL_VARIANT_PREFIX, check.slot + 1, check.level); +} + +std::optional parse_level_variant(std::string_view variant){ + if (!variant.starts_with(LEVEL_VARIANT_PREFIX)){ + return std::nullopt; + } + LevelCheck check; + bool slot_seen = false; + bool level_seen = false; + for (std::string_view word : variant_words(variant.substr(LEVEL_VARIANT_PREFIX.size()))){ + const std::optional pair = variant_pair(word); + const std::optional number = pair ? variant_number(pair->value, 3) : std::nullopt; + if (!number){ + return std::nullopt; + } + if (pair->key == "slot" && *number >= 1 && *number <= PARTY_SLOTS){ + check.slot = *number - 1; + slot_seen = true; + }else if (pair->key == "min" && *number >= 1 && *number <= 100){ + check.level = (unsigned)*number; + level_seen = true; + }else{ + return std::nullopt; + } + } + if (!slot_seen || !level_seen){ + return std::nullopt; + } + return check; +} + +Pokemon::StoryStep level_step(std::string name, std::string why, const LevelCheck& check){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = std::move(name); + step.why = std::move(why); + step.variant = level_variant(check); + return step; +} + +LevelResult run_level_check(Logger& logger, const MemberReader& reader, const LevelCheck& check){ + const std::optional member = reader(check.slot); + if (!member || !member->level){ + logger.log(std::format("Level: couldn't read slot {}'s level.", check.slot + 1), COLOR_RED); + return {}; + } + const bool reached = *member->level >= check.level; + logger.log(std::format( + "Level: slot {} ({}) is level {}, {} {}.", + check.slot + 1, member->species.empty() ? "?" : member->species, + *member->level, reached ? "at least" : "below", check.level + )); + return {.end = reached ? LevelEnd::REACHED : LevelEnd::BELOW, .level = member->level}; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h new file mode 100644 index 0000000000..e2795c6c53 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h @@ -0,0 +1,103 @@ +/* AutoStory Member + * + * From: https://github.com/PokemonAutomation/ + * + * What the story reads about one party member: its species, level, stats + * and moves, as the summary screen shows them (page 1: level; page 2: + * stats; page 3: the four moves). The story's steps take them from a MemberReader, so their + * decisions run in tests against a fake party; on the console they read + * the member's summary (read_party_summary(), PokemonFRLG_AutoStorySummary.h). + * A member that can't be read stops every step that needs its level or + * moves instead of guessing. + * + * Also the LEVEL step: a check, for the table, that a member has reached + * a level, before a fight that needs it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryMember_H +#define PokemonAutomation_PokemonFRLG_AutoStoryMember_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "CommonFramework/Language.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "PokemonFRLG_AutoStoryDamage.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +constexpr size_t PARTY_SLOTS = 6; +constexpr size_t MOVE_SLOTS = 4; + +// A party member as its summary shows it. +struct MemberInfo{ + // The species' slug, e.g. "squirtle"; empty if not read. + std::string species = {}; + // 1-100; nothing if not read. + std::optional level = std::nullopt; + // Its moves' slugs in the summary's order (e.g. "water-gun"), one to + // four; empty if not read. + std::vector moves = {}; + // POKEMON SKILLS (HP as its maximum); none if not read. + std::optional stats = std::nullopt; +}; + +// Reads party slot `slot` (0-5), from the overworld back to the +// overworld: its summary, read; nothing if the slot is empty or the +// summary couldn't be read. +using MemberReader = std::function(size_t slot)>; + +// The console's reader: the member's summary, opened from the START +// menu's POKEMON, in a game in `language`. The steps that read members +// come after the Pokedex, so the START menu is the full one. A member +// whose species, level or moves aren't all read is nothing. +MemberReader console_member_reader(ConsoleHandle& console, ProControllerContext& context, Language language); + + +// What a LEVEL step checks: party slot `slot` (0-5) is at least `level`. +struct LevelCheck{ + size_t slot = 0; + unsigned level = 1; +}; + +// The prefix of a GAME step's variant that names a LEVEL step. +inline constexpr std::string_view LEVEL_VARIANT_PREFIX = "level "; + +// `check` as a variant: "level slot=1 min=16", the slot counted from 1. +std::string level_variant(const LevelCheck& check); +// A variant from level_variant(); nothing if it isn't one. +std::optional parse_level_variant(std::string_view variant); + +// The table's LEVEL step. +Pokemon::StoryStep level_step(std::string name, std::string why, const LevelCheck& check); + +enum class LevelEnd{ + REACHED, + BELOW, + // The member couldn't be read: nothing is known. + UNREAD, +}; +struct LevelResult{ + LevelEnd end = LevelEnd::UNREAD; + std::optional level = std::nullopt; +}; + +// Reads the member and compares. +LevelResult run_level_check(Logger& logger, const MemberReader& reader, const LevelCheck& check); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp new file mode 100644 index 0000000000..8e1e45b00a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp @@ -0,0 +1,292 @@ +/* AutoStory Teach + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonFRLG_AutoStoryTeach.h" +#include "PokemonFRLG_AutoStoryVariantWords.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +bool is_hm_move(std::string_view move){ + // HM01-HM07, FRLG's HMs. + for (std::string_view hm : {"cut", "fly", "surf", "strength", "flash", "rock-smash", "waterfall"}){ + if (move == hm){ + return true; + } + } + return false; +} + +const char* teach_end_name(TeachEnd end){ + switch (end){ + case TeachEnd::LEARNED: return "learned"; + case TeachEnd::ALREADY_KNOWN: return "already_known"; + case TeachEnd::REFUSED: return "refused"; + case TeachEnd::UNREAD: return "unread"; + case TeachEnd::NO_ITEM: return "no_item"; + case TeachEnd::FAILED: return "failed"; + } + return "?"; +} + + +std::string teach_variant(const TeachPlan& plan){ + std::string variant = std::format("{}{} {} slot={}", TEACH_VARIANT_PREFIX, plan.item, plan.move, plan.member + 1); + if (!plan.forget_move.empty()){ + variant += " forget=" + plan.forget_move; + }else if (plan.forget_slot){ + variant += std::format(" forget_slot={}", *plan.forget_slot + 1); + } + return variant; +} + +namespace{ + +bool is_tm_or_hm(std::string_view item){ + return item.size() == 4 && (item.starts_with("tm") || item.starts_with("hm")) + && variant_number(item.substr(2), 2).has_value(); +} + +bool set_teach_word(TeachPlan& plan, std::string_view word){ + const std::optional pair = variant_pair(word); + if (!pair){ + return false; + } + if (pair->key == "forget" && !pair->value.empty()){ + plan.forget_move = std::string(pair->value); + return true; + } + const std::optional number = variant_number(pair->value, 1); + if (pair->key == "slot" && number && *number >= 1 && *number <= PARTY_SLOTS){ + plan.member = *number - 1; + return true; + } + if (pair->key == "forget_slot" && number && *number >= 1 && *number <= MOVE_SLOTS){ + plan.forget_slot = *number - 1; + return true; + } + return false; +} + +} + +std::optional parse_teach_variant(std::string_view variant){ + if (!variant.starts_with(TEACH_VARIANT_PREFIX)){ + return std::nullopt; + } + const std::vector words = variant_words(variant.substr(TEACH_VARIANT_PREFIX.size())); + if (words.size() < 3 || !is_tm_or_hm(words[0]) || variant_pair(words[1])){ + return std::nullopt; + } + TeachPlan plan{.item = std::string(words[0]), .move = std::string(words[1])}; + bool slot_seen = false; + for (size_t c = 2; c < words.size(); c++){ + if (!set_teach_word(plan, words[c])){ + return std::nullopt; + } + slot_seen |= words[c].starts_with("slot="); + } + if (!slot_seen){ + return std::nullopt; + } + return plan; +} + +Pokemon::StoryStep teach_step(std::string name, std::string why, const TeachPlan& plan){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = std::move(name); + step.why = std::move(why); + step.variant = teach_variant(plan); + return step; +} + + +TeachDecision decide_teach(const TeachPlan& plan, const std::vector& moves){ + if (std::find(moves.begin(), moves.end(), plan.move) != moves.end()){ + return {.already_known = true}; + } + if (moves.size() < MOVE_SLOTS){ + return {}; + } + std::optional slot = plan.forget_slot; + if (!plan.forget_move.empty()){ + const auto found = std::find(moves.begin(), moves.end(), plan.forget_move); + if (found == moves.end()){ + return {.error = std::format("it doesn't know {}, the move to forget", plan.forget_move)}; + } + slot = size_t(found - moves.begin()); + } + if (!slot){ + return {.error = "it knows four moves and the table names none to forget"}; + } + if (is_hm_move(moves[*slot])){ + return {.error = std::format("{} is an HM move, which can't be forgotten", moves[*slot])}; + } + return {.forget = slot}; +} + + +namespace{ + +// One TEACH step under way. +class TeachRun{ +public: + TeachRun(TeachActions& actions, const MemberReader& reader, const TeachPlan& plan) + : m_actions(actions) + , m_reader(reader) + , m_plan(plan) + {} + + TeachResult run(){ + const std::optional member = m_reader(m_plan.member); + if (!member || member->moves.empty()){ + return end(TeachEnd::UNREAD, "couldn't read the member's moves"); + } + const TeachDecision decision = decide_teach(m_plan, member->moves); + if (decision.already_known){ + return end(TeachEnd::ALREADY_KNOWN, ""); + } + if (!decision.error.empty()){ + return end(TeachEnd::REFUSED, decision.error); + } + if (decision.forget){ + m_result.forgot = member->moves[*decision.forget]; + } + switch (m_actions.open_item(m_plan.item, m_plan.move)){ + case ItemOpen::OPENED: + break; + case ItemOpen::NOT_IN_CASE: + return leave(TeachEnd::NO_ITEM, std::format("no {} in the TM Case", m_plan.item)); + case ItemOpen::FAILED: + m_actions.dump_screen("open-failed"); + return leave(TeachEnd::FAILED, std::format("couldn't open {} from the TM Case", m_plan.item)); + } + if (!teach(decision.forget)){ + return leave(m_result.end, m_result.detail); + } + if (!m_actions.leave()){ + return failed("leave-failed", "the overworld didn't come back"); + } + return confirm(decision.forget); + } + +private: + TeachResult end(TeachEnd end, std::string detail){ + m_result.end = end; + m_result.detail = std::move(detail); + return m_result; + } + // FAILED, with the screen saved as `label`. + TeachResult failed(std::string_view label, std::string detail){ + m_actions.dump_screen(label); + return end(TeachEnd::FAILED, std::move(detail)); + } + TeachResult leave(TeachEnd end, std::string detail){ + if (!m_actions.leave()){ + return failed("leave-failed", "the overworld didn't come back"); + } + return this->end(end, std::move(detail)); + } + // Sets the result, saves the screen and gives up teaching. False. + bool give_up(TeachEnd end, std::string detail){ + m_actions.dump_screen(std::string("gave-up-") + teach_end_name(end)); + m_actions.stop_teaching(); + m_result.end = end; + m_result.detail = std::move(detail); + return false; + } + + // On "Teach which POKEMON?": the member and its prompts. False if + // it wasn't learned (the result is set). + bool teach(std::optional forget){ + switch (m_actions.choose_member(m_plan.member)){ + case TeachPrompt::LEARNED: + if (forget){ + return give_up(TeachEnd::FAILED, "it learned without forgetting: the moves read were wrong"); + } + return true; + case TeachPrompt::DELETE_PROMPT: + if (!forget){ + return give_up(TeachEnd::FAILED, "it asked to forget a move, but the moves read had room"); + } + return forget_move(*forget); + case TeachPrompt::NOT_COMPATIBLE: + return give_up(TeachEnd::REFUSED, std::format("it can't learn {}", m_plan.move)); + case TeachPrompt::ALREADY_KNOWS: + return give_up(TeachEnd::FAILED, std::format("the game says it knows {} already", m_plan.move)); + case TeachPrompt::FAILED: + break; + } + return give_up(TeachEnd::FAILED, "the party menu's answer wasn't read"); + } + + bool forget_move(size_t slot){ + switch (m_actions.forget(slot)){ + case ForgetEnd::LEARNED: + return true; + case ForgetEnd::HM_REFUSED: + return give_up(TeachEnd::REFUSED, "the game won't forget an HM move"); + case ForgetEnd::FAILED: + break; + } + return give_up(TeachEnd::FAILED, "the moves page didn't answer"); + } + + TeachResult confirm(std::optional forget){ + const std::optional after = m_reader(m_plan.member); + if (!after || after->moves.empty()){ + return failed("moves-unread", "couldn't read the moves after teaching"); + } + const std::vector& moves = after->moves; + const bool landed = forget + ? *forget < moves.size() && moves[*forget] == m_plan.move + : std::find(moves.begin(), moves.end(), m_plan.move) != moves.end(); + if (!landed){ + return failed("not-learned", std::format("{} isn't among its moves after teaching", m_plan.move)); + } + return end(TeachEnd::LEARNED, ""); + } + + TeachActions& m_actions; + const MemberReader& m_reader; + const TeachPlan& m_plan; + TeachResult m_result; +}; + +} + +TeachResult run_teach(Logger& logger, TeachActions& actions, const MemberReader& reader, const TeachPlan& plan){ + TeachResult result = TeachRun(actions, reader, plan).run(); + const Color color = result.end == TeachEnd::LEARNED ? COLOR_BLACK : result.end == TeachEnd::NO_ITEM ? COLOR_ORANGE : COLOR_RED; + logger.log(teach_message(plan, result), color); + return result; +} + +std::string teach_message(const TeachPlan& plan, const TeachResult& result){ + const std::string what = std::format("Teach {} ({}) to slot {}", plan.move, plan.item, plan.member + 1); + switch (result.end){ + case TeachEnd::LEARNED: + return result.forgot.empty() + ? std::format("{}: learned.", what) + : std::format("{}: learned, forgot {}.", what, result.forgot); + case TeachEnd::ALREADY_KNOWN: + return std::format("{}: it knows it already; nothing done.", what); + case TeachEnd::NO_ITEM: + return std::format("{}: {}; skipped.", what, result.detail); + default: + return std::format("{}: {}: {}.", what, teach_end_name(result.end), result.detail); + } +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h new file mode 100644 index 0000000000..3756cc3fc0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h @@ -0,0 +1,177 @@ +/* AutoStory Teach + * + * From: https://github.com/PokemonAutomation/ + * + * A story step that teaches a TM or HM from the bag to a party member, + * forgetting a move the table names, as the game runs it (console B, + * 2026-11-03; the screens are in PokemonFRLG_AutoStoryTeachScreens.h): + * + * - BAG, KEY ITEMS, TM CASE, OPEN, the TM or HM, USE: the party menu, + * "Teach which POKEMON?", each member ABLE or NOT ABLE. A on a member + * that knows the move says so; one NOT ABLE: " and are not + * compatible.". + * - " wants to learn the move ."; with fewer than four moves + * it learns. + * - With four: "However, already knows four moves.", "Should a + * move be deleted and replaced with ?" YES/NO. YES opens the + * moves page; A on a move forgets it and it learns. An HM move can't be + * forgotten (pokefirered: "HM moves can't be forgotten now.") and the + * moves page shows again. B there, then "Stop trying to teach ?" + * YES, leaves it unlearned. + * - A TM is used up; an HM is not. + * + * A TM or HM the TM CASE hasn't got skips the step, with a log line: the + * table can teach a TM a run may not have won yet. + * + * The step reads the member's moves first (MemberReader) and decides + * everything before it opens the bag: the move to forget, by name or + * slot; a refusal if the member already knows the move, has four moves + * and no move to forget is named, or the move named is an HM move. After + * it, the moves are read again: the step succeeds only if the new move + * shows in the forgotten move's place. + * + * The decisions take their game steps from a TeachActions, so they run in + * tests against a fake party and TM Case; on the console they are + * ScreenTeachActions (PokemonFRLG_AutoStoryTeachScreens.h). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryTeach_H +#define PokemonAutomation_PokemonFRLG_AutoStoryTeach_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "PokemonFRLG_AutoStoryMember.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What a TEACH step teaches. +struct TeachPlan{ + // The TM or HM's slug, e.g. "hm03", "tm28". + std::string item = {}; + // The move it holds, e.g. "surf". + std::string move = {}; + // The party slot (0-5). + size_t member = 0; + // The move to forget when it knows four: by name, or else by its + // slot (0-3). Neither: it must have a free slot. + std::string forget_move = {}; + std::optional forget_slot = std::nullopt; +}; + +// Whether `move` is an HM's, which the game won't let a Pokemon forget. +bool is_hm_move(std::string_view move); + +// The prefix of a GAME step's variant that names a TEACH step. +inline constexpr std::string_view TEACH_VARIANT_PREFIX = "teach "; + +// `plan` as a variant: "teach hm03 surf slot=1 forget=tail-whip" or +// "... forget_slot=2", slots counted from 1, no forget when it has room. +std::string teach_variant(const TeachPlan& plan); +std::optional parse_teach_variant(std::string_view variant); + +Pokemon::StoryStep teach_step(std::string name, std::string why, const TeachPlan& plan); + + +// The move slot `plan` forgets for a member that knows `moves`: nothing +// when it has room. Empty `error` if it can be taught, else why not. +struct TeachDecision{ + std::optional forget = std::nullopt; + std::string error = {}; + // It knows the move already: nothing to do. + bool already_known = false; +}; +TeachDecision decide_teach(const TeachPlan& plan, const std::vector& moves); + + +// What A on the member showed. +enum class TeachPrompt{ + LEARNED, + // "Delete an older move to make room?" + DELETE_PROMPT, + NOT_COMPATIBLE, + ALREADY_KNOWS, + FAILED, +}; + +enum class ForgetEnd{ + LEARNED, + // "HM moves can't be forgotten now.": back on the moves page. + HM_REFUSED, + FAILED, +}; + +// What opening the TM or HM from the bag came to. +enum class ItemOpen{ + // On "Teach which POKEMON?". + OPENED, + // The TM CASE's list was read and hasn't got it. + NOT_IN_CASE, + FAILED, +}; + +// The game steps a TEACH step takes, injected so its decisions run in +// tests. +class TeachActions{ +public: + virtual ~TeachActions() = default; + + // From the overworld: the bag, the TM Case, `item` (which holds + // `move`), USE, to the party menu. + virtual ItemOpen open_item(std::string_view item, std::string_view move) = 0; + // On "Teach which POKEMON?": A on `slot`. + virtual TeachPrompt choose_member(size_t slot) = 0; + // On "Delete an older move?": YES, then A on move `slot` (0-3). + virtual ForgetEnd forget(size_t slot) = 0; + // From any of its prompts: give up teaching (NO, "Stop trying?" YES). + virtual void stop_teaching() = 0; + // Back to the overworld. False if it didn't come back. + virtual bool leave() = 0; + // Saves the screen as a debug image, named `label`: the step failed. + virtual void dump_screen(std::string_view label) = 0; +}; + +enum class TeachEnd{ + LEARNED, + ALREADY_KNOWN, + // decide_teach() or the game refused it. + REFUSED, + // The member's moves couldn't be read: nothing was pressed. + UNREAD, + // The TM or HM isn't in the TM CASE: skipped, nothing taught. + NO_ITEM, + FAILED, +}; +const char* teach_end_name(TeachEnd end); + +struct TeachResult{ + TeachEnd end = TeachEnd::FAILED; + // The move forgotten, if any. + std::string forgot = {}; + std::string detail = {}; +}; + +// 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); + +std::string teach_message(const TeachPlan& plan, const TeachResult& result); + + +void add_tests_AutoStoryTeach(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp new file mode 100644 index 0000000000..fdaa5b8d21 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp @@ -0,0 +1,416 @@ +/* AutoStory Teach Screens + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryTeachScreens.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; + + +const char* teach_press_name(TeachPress press){ + switch (press){ + case TeachPress::A: return "A"; + case TeachPress::B: return "B"; + case TeachPress::UP: return "UP"; + case TeachPress::DOWN: return "DOWN"; + case TeachPress::LEFT: return "LEFT"; + case TeachPress::RIGHT: return "RIGHT"; + } + return "?"; +} + + +namespace{ + +// Looks a step makes before it gives up on a screen that doesn't change. +constexpr size_t MAX_LOOKS = 40; +// Looks at the same moves page after A on a move: the game refused it. +constexpr size_t MOVES_PAGE_STILL = 8; + +std::string rows_text(const std::vector& rows){ + std::string text; + for (const std::string& row : rows){ + text += (text.empty() ? "" : ", ") + row; + } + return text.empty() ? "none read" : text; +} + +} + + +ScreenTeachActions::ScreenTeachActions(Logger& logger, TeachScreens& screens) + : m_logger(logger) + , m_screens(screens) +{} + +void ScreenTeachActions::press(TeachPress press){ + m_screens.press(press); +} + +std::optional ScreenTeachActions::wait_for(TeachScreen screen, size_t looks){ + for (size_t c = 0; c < looks; c++){ + TeachView view = m_screens.look(); + if (view.screen == screen){ + return view; + } + } + m_logger.log(std::format("Teach: {} didn't show.", teach_screen_name(screen)), COLOR_RED); + return std::nullopt; +} + +bool ScreenTeachActions::move_cursor_to(TeachScreen screen, size_t row){ + for (size_t c = 0; c < TEACH_LIST_ROWS * 2; c++){ + const TeachView view = m_screens.look(); + if (view.screen != screen || !view.cursor){ + m_logger.log(std::format("Teach: lost the cursor on {}.", teach_screen_name(screen)), COLOR_RED); + return false; + } + if (*view.cursor == row){ + return true; + } + press(*view.cursor < row ? TeachPress::DOWN : TeachPress::UP); + } + return false; +} + +bool ScreenTeachActions::to_key_items(){ + for (size_t c = 0; c < 4; c++){ + const std::optional view = wait_for(TeachScreen::BAG); + if (!view){ + return false; + } + if (view->pocket == "key-items"){ + return true; + } + if (view->pocket == "items"){ + press(TeachPress::RIGHT); + }else if (view->pocket == "poke-balls"){ + press(TeachPress::LEFT); + }else{ + m_logger.log("Teach: the bag's pocket wasn't read.", COLOR_RED); + return false; + } + } + return false; +} + +ItemOpen ScreenTeachActions::open_row(TeachScreen screen, std::string_view name){ + const std::optional view = wait_for(screen); + if (!view){ + return ItemOpen::FAILED; + } + const auto found = std::find(view->rows.begin(), view->rows.end(), name); + if (found == view->rows.end()){ + m_logger.log(std::format("Teach: no {} in {} ({}).", name, teach_screen_name(screen), rows_text(view->rows)), COLOR_RED); + // No rows: nothing was read. + return view->rows.empty() ? ItemOpen::FAILED : ItemOpen::NOT_IN_CASE; + } + if (!move_cursor_to(screen, size_t(found - view->rows.begin()))){ + return ItemOpen::FAILED; + } + press(TeachPress::A); + if (!wait_for(TeachScreen::ITEM_MENU) || !move_cursor_to(TeachScreen::ITEM_MENU, 0)){ + return ItemOpen::FAILED; + } + press(TeachPress::A); + return ItemOpen::OPENED; +} + +ItemOpen ScreenTeachActions::open_item(std::string_view item, std::string_view move){ + if (!m_screens.open_bag()){ + m_logger.log("Teach: the bag didn't open.", COLOR_RED); + return ItemOpen::FAILED; + } + if (!to_key_items() || open_row(TeachScreen::BAG, "tm-case") != ItemOpen::OPENED){ + return ItemOpen::FAILED; + } + const ItemOpen opened = open_row(TeachScreen::TM_CASE, move); + if (opened != ItemOpen::OPENED){ + m_logger.log(std::format("Teach: couldn't use {} ({}) from the TM CASE.", item, move), COLOR_RED); + return opened; + } + return wait_for(TeachScreen::PARTY_PROMPT).has_value() ? ItemOpen::OPENED : ItemOpen::FAILED; +} + +TeachPrompt ScreenTeachActions::choose_member(size_t slot){ + if (!wait_for(TeachScreen::PARTY_PROMPT)){ + return TeachPrompt::FAILED; + } + // The menu opens on the lead; DOWN steps through the slots. + for (size_t c = 0; c < slot; c++){ + press(TeachPress::DOWN); + } + press(TeachPress::A); + return member_answer(); +} + +TeachPrompt ScreenTeachActions::member_answer(){ + bool incompatible = false; + size_t prompts = 0; + for (size_t c = 0; c < MAX_LOOKS; c++){ + const TeachView view = m_screens.look(); + switch (view.screen){ + case TeachScreen::PARTY_TEXT: + if (view.text == TeachText::WHICH_MOVE){ + return TeachPrompt::DELETE_PROMPT; + } + incompatible |= view.text == TeachText::NOT_COMPATIBLE; + press(TeachPress::A); + break; + case TeachScreen::PARTY_YES_NO: + return view.text == TeachText::STOP_QUESTION ? TeachPrompt::FAILED : TeachPrompt::DELETE_PROMPT; + case TeachScreen::KNOWN_MOVES: + return TeachPrompt::DELETE_PROMPT; + case TeachScreen::TM_CASE: + return TeachPrompt::LEARNED; + case TeachScreen::PARTY_PROMPT: + // Back on the prompt after a message, or not left yet. + if (incompatible){ + return TeachPrompt::NOT_COMPATIBLE; + } + if (++prompts > MOVES_PAGE_STILL){ + return TeachPrompt::FAILED; + } + break; + default: + break; + } + } + return TeachPrompt::FAILED; +} + +void ScreenTeachActions::answer_to_forget(const TeachView& view){ + // YES to delete a move; NO to stop trying, back to the moves. + if (view.text == TeachText::STOP_QUESTION){ + press(TeachPress::B); + }else{ + press(view.cursor == 1u ? TeachPress::UP : TeachPress::A); + } +} + +ForgetEnd ScreenTeachActions::forget(size_t slot){ + bool picked = false; + size_t still = 0; + // Looks at a screen not placed since the move was picked. + size_t unplaced = 0; + for (size_t c = 0; c < MAX_LOOKS; c++){ + const TeachView view = m_screens.look(); + switch (view.screen){ + case TeachScreen::PARTY_YES_NO: + answer_to_forget(view); + break; + case TeachScreen::PARTY_TEXT: + press(TeachPress::A); + break; + case TeachScreen::KNOWN_MOVES: + if (picked){ + if (++still > MOVES_PAGE_STILL){ + return ForgetEnd::HM_REFUSED; + } + }else if (view.cursor && *view.cursor != slot){ + press(*view.cursor < slot ? TeachPress::DOWN : TeachPress::UP); + }else if (view.cursor){ + press(TeachPress::A); + picked = true; + } + break; + case TeachScreen::TM_CASE: + case TeachScreen::BAG: + case TeachScreen::ITEM_MENU: + return picked ? ForgetEnd::LEARNED : ForgetEnd::FAILED; + default: + // After the pick, its messages: B pages through them, once the + // moves page has closed (the first look). + if (picked && ++unplaced > 1){ + press(TeachPress::B); + } + break; + } + } + if (picked && unplaced > 0){ + // The moves page closed on the pick: the moves read after decide. + m_logger.log("Teach: the TM CASE didn't show after the forget; reading the moves will tell.", COLOR_ORANGE); + return ForgetEnd::LEARNED; + } + return ForgetEnd::FAILED; +} + +void ScreenTeachActions::stop_teaching(){ + for (size_t c = 0; c < MAX_LOOKS; c++){ + const TeachView view = m_screens.look(); + switch (view.screen){ + case TeachScreen::KNOWN_MOVES: + case TeachScreen::PARTY_PROMPT: + press(TeachPress::B); + break; + case TeachScreen::PARTY_YES_NO: + // NO to deleting a move, then YES to stop trying. + if (view.text == TeachText::DELETE_QUESTION){ + press(TeachPress::B); + }else{ + press(view.cursor == 1u ? TeachPress::UP : TeachPress::A); + } + break; + case TeachScreen::PARTY_TEXT: + press(TeachPress::A); + break; + default: + return; + } + } +} + +void ScreenTeachActions::dump_screen(std::string_view label){ + m_screens.dump_screen(label); +} + +bool ScreenTeachActions::leave(){ + for (size_t c = 0; c < MAX_LOOKS; c++){ + const TeachView view = m_screens.look(); + switch (view.screen){ + case TeachScreen::BAG: + case TeachScreen::ITEM_MENU: + case TeachScreen::TM_CASE: + case TeachScreen::PARTY_PROMPT: + press(TeachPress::B); + break; + case TeachScreen::PARTY_TEXT: + case TeachScreen::PARTY_YES_NO: + case TeachScreen::KNOWN_MOVES: + stop_teaching(); + break; + case TeachScreen::OTHER: + return m_screens.to_overworld(); + } + } + return false; +} + + +ConsoleTeachScreens::ConsoleTeachScreens(ConsoleHandle& console, ProControllerContext& context, Language language) + : m_console(console) + , m_context(context) + , m_language(language) +{} + +bool ConsoleTeachScreens::open_bag(){ + try{ + open_bag_from_overworld(m_console, m_context); + m_context.wait_for_all_requests(); + return true; + }catch (OperationFailedException& e){ + m_console.log("Teach: " + e.message(), COLOR_RED); + return false; + } +} + +TeachView ConsoleTeachScreens::look(){ + // Two looks 150 ms apart that agree: the screen has stopped changing. + std::optional>> last; + for (size_t c = 0; c < 10; c++){ + m_context.wait_for_all_requests(); + VideoSnapshot snapshot = m_console.video().snapshot(); + if (snapshot){ + const TeachScreen screen = read_teach_screen(snapshot); + const std::optional cursor = read_teach_cursor(screen, snapshot); + if (last && last->first == screen && last->second == cursor){ + TeachView view = read_view(snapshot, screen, cursor); + log_view(view); + return view; + } + last.emplace(screen, cursor); + } + pbf_wait(m_context, 150ms); + } + return {}; +} + +TeachView ConsoleTeachScreens::read_view(const ImageViewRGB32& image, TeachScreen screen, std::optional cursor){ + Logger& logger = m_console.logger(); + TeachView view{.screen = screen, .cursor = cursor}; + switch (screen){ + case TeachScreen::BAG: + view.pocket = read_pocket_name(logger, m_language, image); + if (view.pocket == "key-items"){ + view.rows = read_teach_rows(logger, m_language, image, screen); + } + break; + case TeachScreen::TM_CASE: + view.rows = read_teach_rows(logger, m_language, image, screen); + break; + case TeachScreen::PARTY_PROMPT: + case TeachScreen::PARTY_TEXT: + case TeachScreen::PARTY_YES_NO: + view.text = read_teach_text(logger, m_language, image); + break; + default: + break; + } + return view; +} + +void ConsoleTeachScreens::log_view(const TeachView& view){ + std::string line = std::format( + "Teach: {}, cursor {}", teach_screen_name(view.screen), view.cursor ? std::to_string(*view.cursor + 1) : "none" + ); + if (!view.pocket.empty()){ + line += ", " + view.pocket; + } + if (!view.rows.empty()){ + line += " (" + rows_text(view.rows) + ")"; + } + if (view.text != TeachText::UNKNOWN){ + line += std::string(", \"") + teach_text_name(view.text) + "\""; + } + if (line != m_logged){ + m_console.log(line + "."); + m_logged = line; + } +} + +void ConsoleTeachScreens::press(TeachPress press){ + switch (press){ + case TeachPress::A: pbf_press_button(m_context, BUTTON_A, 160ms, 240ms); break; + case TeachPress::B: pbf_press_button(m_context, BUTTON_B, 160ms, 240ms); break; + case TeachPress::UP: pbf_press_dpad(m_context, DPAD_UP, 160ms, 240ms); break; + case TeachPress::DOWN: pbf_press_dpad(m_context, DPAD_DOWN, 160ms, 240ms); break; + case TeachPress::LEFT: pbf_press_dpad(m_context, DPAD_LEFT, 160ms, 240ms); break; + case TeachPress::RIGHT: pbf_press_dpad(m_context, DPAD_RIGHT, 160ms, 240ms); break; + } + m_context.wait_for_all_requests(); +} + +void ConsoleTeachScreens::dump_screen(std::string_view label){ + m_context.wait_for_all_requests(); + dump_debug_image(m_console, "AutoStory/teach", std::string(label), m_console.video().snapshot()); +} + +bool ConsoleTeachScreens::to_overworld(){ + try{ + mash_until_overworld(m_console, m_context, 20000ms); + return true; + }catch (OperationFailedException& e){ + m_console.log("Teach: " + e.message(), COLOR_RED); + return false; + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h new file mode 100644 index 0000000000..8fbb380d00 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h @@ -0,0 +1,161 @@ +/* AutoStory Teach Screens + * + * From: https://github.com/PokemonAutomation/ + * + * The TEACH step's game steps on the console, screen by screen as console + * B showed them (2026-11-03, FireRed, TM03 to a Wartortle with four + * moves): + * + * - START, BAG: the bag opens on the pocket it was left on (ITEMS); + * RIGHT goes to KEY ITEMS, LEFT back (POKE BALLS is right of KEY ITEMS). + * - KEY ITEMS: TEACHY TV, TM CASE, HELIX FOSSIL, CANCEL. A on TM CASE: + * OPEN/REGISTER/CANCEL, OPEN on top; A: the TM CASE's list ("No03 + * WATER PULSE x1", "No39 ROCK TOMB x1", CLOSE). + * - A on a TM: USE/GIVE/EXIT, USE on top; A: the party menu, "Teach which + * POKEMON?", each member ABLE or NOT ABLE, the cursor on the lead. + * - A on a member: " wants to learn the move ."; with room it + * learns. With four: "However, already knows four moves.", + * "Should a move be deleted and replaced with ?" YES/NO (YES on + * top), YES: "Which move should be forgotten?", then KNOWN MOVES with + * the four moves and the new one fifth, the red cursor on the first. A + * on a move forgets it: "1, 2 and... ... Poof!", " forgot .", + * "And... learned !", which the reader doesn't place (read + * "other"; B pages through them), then the TM CASE's list. B instead: "Stop trying to teach ?" + * YES/NO, YES: " did not learn the move ." and the TM CASE's + * list again, the TM kept. + * - From the TM CASE's list, B closes it to the bag, and B the bag. + * + * Each step looks at the screen before it presses, and stops at a screen + * it doesn't expect instead of pressing on. The screens come from a + * TeachScreens, so the steps run in tests against a fake bag, TM CASE and + * party menu that answer as the console did. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryTeachScreens_H +#define PokemonAutomation_PokemonFRLG_AutoStoryTeachScreens_H + +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/Language.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.h" +#include "PokemonFRLG_AutoStoryTeach.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// A screen on the way, read. +struct TeachView{ + TeachScreen screen = TeachScreen::OTHER; + // The cursor's row, from the top. + std::optional cursor = std::nullopt; + // In the bag: the pocket's name ("items", "key-items", "poke-balls"). + std::string pocket = {}; + // In KEY ITEMS, its items ("tm-case", ...); in the TM CASE, its TMs' + // moves ("water-pulse", ...): from the top to the first not read. + std::vector rows = {}; + // Over the party menu: its message. + TeachText text = TeachText::UNKNOWN; +}; + +enum class TeachPress{ + A, + B, + UP, + DOWN, + LEFT, + RIGHT, +}; +const char* teach_press_name(TeachPress press); + +// The console's screens and buttons, as the TEACH step uses them. +class TeachScreens{ +public: + virtual ~TeachScreens() = default; + + // From the overworld: START, BAG. False if the bag didn't open. + virtual bool open_bag() = 0; + // The screen, once it has stopped changing. + virtual TeachView look() = 0; + virtual void press(TeachPress press) = 0; + // B until the overworld is back. False if it didn't come back. + virtual bool to_overworld() = 0; + // Saves the screen as a debug image, named `label`. + virtual void dump_screen(std::string_view label) = 0; +}; + + +// The TEACH step's game steps through `screens`. +class ScreenTeachActions : public TeachActions{ +public: + ScreenTeachActions(Logger& logger, TeachScreens& screens); + + virtual ItemOpen open_item(std::string_view item, std::string_view move) override; + virtual TeachPrompt choose_member(size_t slot) override; + virtual ForgetEnd forget(size_t slot) override; + virtual void stop_teaching() override; + virtual bool leave() override; + virtual void dump_screen(std::string_view label) override; + +private: + // Looks until `screen` shows, `looks` times at most. + std::optional wait_for(TeachScreen screen, size_t looks = 12); + // On `screen`: the cursor to `row`. False if it didn't get there. + bool move_cursor_to(TeachScreen screen, size_t row); + // In the bag: to KEY ITEMS. + bool to_key_items(); + // On the list `screen`: A on the row `name`, then A on the item menu's + // top row (OPEN or USE). NOT_IN_CASE: the rows read haven't got it. + ItemOpen open_row(TeachScreen screen, std::string_view name); + // After A on a member: what it showed. + TeachPrompt member_answer(); + // On a YES/NO while forgetting: the answer that goes on to the moves. + void answer_to_forget(const TeachView& view); + void press(TeachPress press); + + Logger& m_logger; + TeachScreens& m_screens; +}; + + +// The console's screens: read with PokemonFRLG_TeachScreenReader.h in a +// game in `language`. +class ConsoleTeachScreens : public TeachScreens{ +public: + ConsoleTeachScreens(ConsoleHandle& console, ProControllerContext& context, Language language); + + virtual bool open_bag() override; + virtual TeachView look() override; + virtual void press(TeachPress press) override; + virtual bool to_overworld() override; + virtual void dump_screen(std::string_view label) override; + +private: + // The screen in `image`, read. + TeachView read_view(const ImageViewRGB32& image, TeachScreen screen, std::optional cursor); + void log_view(const TeachView& view); + + ConsoleHandle& m_console; + ProControllerContext& m_context; + Language m_language; + // The last view logged. + std::string m_logged; +}; + + +void add_tests_AutoStoryTeachScreens(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp new file mode 100644 index 0000000000..d46eef5517 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp @@ -0,0 +1,485 @@ +/* AutoStory Teach Screens Tests + * + * The console's TEACH steps against a fake bag, TM CASE and party menu + * that answer as console B did on 2026-11-03 (FireRed): the bag left on + * ITEMS; KEY ITEMS with TEACHY TV, TM CASE, HELIX FOSSIL; TM03 WATER + * PULSE and TM39 ROCK TOMB in the TM CASE; a Wartortle Lv22 with BITE, + * TAIL WHIP, BUBBLE, WITHDRAW. That run's step failed with "couldn't open + * tm03 from the TM Case": the console's steps had no readers and stopped + * before the bag. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryTeachScreens.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +struct FakeTm{ + std::string move; + size_t count = 1; +}; + +// The game's state behind the screens. +enum class FakeScreen{ + OVERWORLD, + START_MENU, + BAG, + BAG_MENU, + TM_CASE, + TM_MENU, + PROMPT, + TEXT, + // Messages the reader doesn't place: "other". + UNREAD_TEXT, + DELETE_YES_NO, + STOP_YES_NO, + KNOWN_MOVES, +}; + +// The bag, TM CASE and party menu as console B showed them. +struct FakeTeachGame{ + std::vector pockets{"items", "key-items", "poke-balls"}; + size_t pocket = 0; + std::vector key_items{"teachy-tv", "tm-case", "helix-fossil", "cancel"}; + size_t bag_cursor = 0; + std::vector tms{{"water-pulse", 1}, {"rock-tomb", 1}}; + std::vector moves{"bite", "tail-whip", "bubble", "withdraw"}; + std::set compatible{"water-pulse", "rock-tomb"}; + + FakeScreen screen = FakeScreen::OVERWORLD; + size_t cursor = 0; + // The messages left to page through, and the screen after them. + std::deque texts = {}; + FakeScreen after_texts = FakeScreen::OVERWORLD; + // The messages after a move is forgotten ("1, 2 and... Poof!", "... + // forgot TAIL WHIP.", "And... learned WATER PULSE!") read as "other", + // as on console B (2026-11-03). + bool forget_texts_unread = false; + // The TM in use, by row. + size_t tm = 0; + std::vector presses = {}; + std::vector dumps = {}; + std::string error = {}; +}; + +std::vector tm_rows(const FakeTeachGame& game){ + std::vector rows; + for (const FakeTm& tm : game.tms){ + if (tm.count > 0){ + rows.push_back(tm.move); + } + } + return rows; +} + +void show_texts(FakeTeachGame& game, std::deque texts, FakeScreen after){ + game.texts = std::move(texts); + game.after_texts = after; + game.screen = FakeScreen::TEXT; +} + +void move_cursor(FakeTeachGame& game, TeachPress press, size_t rows){ + if (press == TeachPress::UP && game.cursor > 0){ + game.cursor--; + }else if (press == TeachPress::DOWN && game.cursor + 1 < rows){ + game.cursor++; + } +} + +std::string tm_move(const FakeTeachGame& game){ + const std::vector rows = tm_rows(game); + return game.tm < rows.size() ? rows[game.tm] : ""; +} + +void use_up(FakeTeachGame& game){ + const std::string move = tm_move(game); + for (FakeTm& tm : game.tms){ + if (tm.move == move && tm.count > 0){ + tm.count--; + return; + } + } +} + +void choose_member(FakeTeachGame& game){ + const std::string move = tm_move(game); + if (!game.compatible.contains(move)){ + show_texts(game, {TeachText::NOT_COMPATIBLE}, FakeScreen::PROMPT); + return; + } + if (game.moves.size() < MOVE_SLOTS){ + game.moves.push_back(move); + use_up(game); + game.cursor = 0; + show_texts(game, {TeachText::WANTS_TO_LEARN, TeachText::UNKNOWN}, FakeScreen::TM_CASE); + return; + } + show_texts(game, {TeachText::WANTS_TO_LEARN, TeachText::KNOWS_FOUR}, FakeScreen::DELETE_YES_NO); + game.cursor = 0; +} + +void press_bag(FakeTeachGame& game, TeachPress press){ + const bool key_items = game.pockets[game.pocket] == "key-items"; + switch (press){ + case TeachPress::LEFT: + case TeachPress::RIGHT: + if (press == TeachPress::LEFT && game.pocket > 0){ + game.pocket--; + game.cursor = 0; + }else if (press == TeachPress::RIGHT && game.pocket + 1 < game.pockets.size()){ + game.pocket++; + game.cursor = 0; + } + return; + case TeachPress::A: + if (key_items && game.key_items[game.cursor] == "tm-case"){ + game.screen = FakeScreen::BAG_MENU; + game.bag_cursor = game.cursor; + game.cursor = 0; + } + return; + case TeachPress::B: + game.screen = FakeScreen::START_MENU; + return; + default: + move_cursor(game, press, key_items ? game.key_items.size() : 4); + } +} + +void press_bag_menu(FakeTeachGame& game, TeachPress press){ + if (press == TeachPress::A && game.cursor == 0){ + game.screen = FakeScreen::TM_CASE; + game.cursor = 0; + }else if (press == TeachPress::A || press == TeachPress::B){ + game.screen = FakeScreen::BAG; + game.cursor = game.bag_cursor; + }else{ + move_cursor(game, press, 3); + } +} + +void press_tm_case(FakeTeachGame& game, TeachPress press){ + const size_t rows = tm_rows(game).size(); + if (press == TeachPress::B || (press == TeachPress::A && game.cursor == rows)){ + game.screen = FakeScreen::BAG; + game.cursor = game.bag_cursor; + }else if (press == TeachPress::A){ + game.tm = game.cursor; + game.screen = FakeScreen::TM_MENU; + game.cursor = 0; + }else{ + move_cursor(game, press, rows + 1); + } +} + +void press_tm_menu(FakeTeachGame& game, TeachPress press){ + if (press == TeachPress::A && game.cursor == 0){ + game.screen = FakeScreen::PROMPT; + }else if (press == TeachPress::A || press == TeachPress::B){ + game.screen = FakeScreen::TM_CASE; + game.cursor = game.tm; + }else{ + move_cursor(game, press, 3); + } +} + +void press_yes_no(FakeTeachGame& game, TeachPress press){ + const bool yes = press == TeachPress::A && game.cursor == 0; + const bool no = press == TeachPress::B || (press == TeachPress::A && game.cursor == 1); + if (game.screen == FakeScreen::DELETE_YES_NO && yes){ + show_texts(game, {TeachText::WHICH_MOVE}, FakeScreen::KNOWN_MOVES); + game.cursor = 0; + }else if (game.screen == FakeScreen::STOP_YES_NO && yes){ + show_texts(game, {TeachText::DID_NOT_LEARN}, FakeScreen::TM_CASE); + game.cursor = game.tm; + }else if (no){ + game.screen = game.screen == FakeScreen::DELETE_YES_NO ? FakeScreen::STOP_YES_NO : FakeScreen::DELETE_YES_NO; + game.cursor = 0; + }else{ + move_cursor(game, press, 2); + } +} + +void press_known_moves(FakeTeachGame& game, TeachPress press){ + if (press == TeachPress::B || (press == TeachPress::A && game.cursor == MOVE_SLOTS)){ + game.screen = FakeScreen::STOP_YES_NO; + game.cursor = 0; + }else if (press == TeachPress::A){ + if (is_hm_move(game.moves[game.cursor])){ + return; + } + game.moves[game.cursor] = tm_move(game); + use_up(game); + show_texts(game, {TeachText::UNKNOWN, TeachText::UNKNOWN, TeachText::UNKNOWN}, FakeScreen::TM_CASE); + if (game.forget_texts_unread){ + game.screen = FakeScreen::UNREAD_TEXT; + } + game.cursor = 0; + }else{ + move_cursor(game, press, MOVE_SLOTS + 1); + } +} + +void press_game(FakeTeachGame& game, TeachPress press){ + switch (game.screen){ + case FakeScreen::OVERWORLD: + case FakeScreen::START_MENU: + game.error = std::format("pressed {} off the menus", teach_press_name(press)); + return; + case FakeScreen::BAG: press_bag(game, press); return; + case FakeScreen::BAG_MENU: press_bag_menu(game, press); return; + case FakeScreen::TM_CASE: press_tm_case(game, press); return; + case FakeScreen::TM_MENU: press_tm_menu(game, press); return; + case FakeScreen::DELETE_YES_NO: + case FakeScreen::STOP_YES_NO: press_yes_no(game, press); return; + case FakeScreen::KNOWN_MOVES: press_known_moves(game, press); return; + case FakeScreen::PROMPT: + if (press == TeachPress::A){ + choose_member(game); + }else if (press == TeachPress::B){ + game.screen = FakeScreen::TM_CASE; + game.cursor = game.tm; + } + return; + case FakeScreen::TEXT: + case FakeScreen::UNREAD_TEXT: + game.texts.pop_front(); + if (game.texts.empty()){ + game.screen = game.after_texts; + } + return; + } +} + +TeachView view_of(const FakeTeachGame& game){ + switch (game.screen){ + case FakeScreen::OVERWORLD: + case FakeScreen::START_MENU: + case FakeScreen::UNREAD_TEXT: + return {}; + case FakeScreen::BAG:{ + const bool key_items = game.pockets[game.pocket] == "key-items"; + return {.screen = TeachScreen::BAG, .cursor = game.cursor, .pocket = game.pockets[game.pocket], + .rows = key_items ? game.key_items : std::vector{}}; + } + case FakeScreen::BAG_MENU: + case FakeScreen::TM_MENU: + return {.screen = TeachScreen::ITEM_MENU, .cursor = game.cursor}; + case FakeScreen::TM_CASE: + return {.screen = TeachScreen::TM_CASE, .cursor = game.cursor, .rows = tm_rows(game)}; + case FakeScreen::PROMPT: + return {.screen = TeachScreen::PARTY_PROMPT, .text = TeachText::TEACH_WHICH}; + case FakeScreen::TEXT: + return {.screen = TeachScreen::PARTY_TEXT, .text = game.texts.front()}; + case FakeScreen::DELETE_YES_NO: + return {.screen = TeachScreen::PARTY_YES_NO, .cursor = game.cursor, .text = TeachText::DELETE_QUESTION}; + case FakeScreen::STOP_YES_NO: + return {.screen = TeachScreen::PARTY_YES_NO, .cursor = game.cursor, .text = TeachText::STOP_QUESTION}; + case FakeScreen::KNOWN_MOVES: + return {.screen = TeachScreen::KNOWN_MOVES, .cursor = game.cursor}; + } + return {}; +} + +class FakeTeachScreens : public TeachScreens{ +public: + explicit FakeTeachScreens(FakeTeachGame& game) + : m_game(game) + {} + + virtual bool open_bag() override{ + if (m_game.screen != FakeScreen::OVERWORLD){ + m_game.error = "opened the bag off the overworld"; + return false; + } + m_game.screen = FakeScreen::BAG; + m_game.cursor = 0; + return true; + } + virtual TeachView look() override{ + return view_of(m_game); + } + virtual void press(TeachPress press) override{ + m_game.presses.emplace_back(teach_press_name(press)); + if (m_game.presses.size() > 200){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "more than 200 presses"); + } + press_game(m_game, press); + } + virtual bool to_overworld() override{ + if (m_game.screen == FakeScreen::START_MENU || m_game.screen == FakeScreen::OVERWORLD){ + m_game.screen = FakeScreen::OVERWORLD; + return true; + } + return false; + } + virtual void dump_screen(std::string_view label) override{ + m_game.dumps.emplace_back(label); + } + +private: + FakeTeachGame& m_game; +}; + + +struct ScreensCase{ + std::string name = {}; + std::function setup = {}; + TeachPlan plan = {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}; + TeachEnd end = TeachEnd::LEARNED; + std::vector moves = {"bite", "water-pulse", "bubble", "withdraw"}; + // TM03's count after. + size_t tm03 = 0; +}; + +void left_on_poke_balls(FakeTeachGame& game){ + game.pocket = 2; +} +void three_moves(FakeTeachGame& game){ + game.moves = {"bite", "bubble", "withdraw"}; +} +void no_tm03(FakeTeachGame& game){ + game.tms = {{"rock-tomb", 1}}; +} +void forget_texts_unread(FakeTeachGame& game){ + game.forget_texts_unread = true; +} +void nothing_compatible(FakeTeachGame& game){ + game.compatible.clear(); +} + +std::vector screens_cases(){ + return { + {.name = "console B: TM03 over TAIL WHIP"}, + { + // Console B, 2026-11-03: known_moves, then "other" until the + // step gave up; the move was learned. + .name = "the texts after the forget read as other", + .setup = forget_texts_unread, + }, + { + .name = "the bag left on POKE BALLS", + .setup = left_on_poke_balls, + }, + { + .name = "a free slot: no move forgotten", + .setup = three_moves, + .plan = {.item = "tm03", .move = "water-pulse", .member = 0}, + .moves = {"bite", "bubble", "withdraw", "water-pulse"}, + }, + { + .name = "no TM03 in the TM CASE: skipped, back to the overworld", + .setup = no_tm03, + .end = TeachEnd::NO_ITEM, + .moves = {"bite", "tail-whip", "bubble", "withdraw"}, + }, + { + .name = "not compatible: given up, back to the overworld", + .setup = nothing_compatible, + .end = TeachEnd::REFUSED, + .moves = {"bite", "tail-whip", "bubble", "withdraw"}, + .tm03 = 1, + }, + }; +} + +UnitTestResult check_screens_case(const ScreensCase& item){ + QuietLogger logger; + FakeTeachGame game; + if (item.setup){ + item.setup(game); + } + FakeTeachScreens screens(game); + ScreenTeachActions actions(logger, screens); + const MemberReader reader = [&game](size_t) -> std::optional{ + if (game.screen != FakeScreen::OVERWORLD){ + game.error = "read the summary off the overworld"; + } + return MemberInfo{.species = "wartortle", .level = 22, .moves = game.moves}; + }; + const TeachResult result = run_teach(logger, actions, reader, item.plan); + const size_t tm03 = game.tms.empty() || game.tms[0].move != "water-pulse" ? 0 : game.tms[0].count; + std::string presses; + for (const std::string& press : game.presses){ + presses += press + " "; + } + if (!game.error.empty()){ + return std::format("{}: {} (presses: {}).", item.name, game.error, presses); + } + if (result.end != item.end || game.moves != item.moves || tm03 != item.tm03){ + return std::format("{}: ended {} ({}), TM03 x{}; presses: {}.", + item.name, teach_end_name(result.end), result.detail, tm03, presses); + } + if (game.screen != FakeScreen::OVERWORLD){ + return std::format("{}: didn't end on the overworld; presses: {}.", item.name, presses); + } + // A debug image for each failure, none otherwise. + const bool failed = item.end == TeachEnd::FAILED || item.end == TeachEnd::REFUSED; + if (failed == game.dumps.empty()){ + return std::format("{}: {} debug images.", item.name, game.dumps.size()); + } + return true; +} + +UnitTestResult test_screens(){ + for (const ScreensCase& item : screens_cases()){ + const UnitTestResult result = check_screens_case(item); + if (result.result != UnitTestResult::PASSED){ + return result; + } + } + return true; +} + + +class Test_AutoStoryTeachScreens : public UnitTest{ +public: + Test_AutoStoryTeachScreens(std::string name, std::function body) + : UnitTest("PokemonFRLG::AutoStoryTeachScreens - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + +} + + +void add_tests_AutoStoryTeachScreens(UnitTestDatabase& database){ + database.add("TM03 through the console's screens", test_screens); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp new file mode 100644 index 0000000000..514c3c5540 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp @@ -0,0 +1,407 @@ +/* AutoStory Teach Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The TEACH step against a fake party and TM Case that answer as + * pokefirered's tm_case.c and party_menu.c do (see + * PokemonFRLG_AutoStoryTeach.h): a member with room learns, one with four + * moves asks to forget one, an HM move can't be forgotten, a TM is used up + * and an HM is not. The party is console B's (2026-11-02): Squirtle Lv16 + * with WATER GUN, TAIL WHIP, BUBBLE, WITHDRAW. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryTeach.h" +#include "PokemonFRLG_AutoStoryTeachScreens.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +struct FakeMon{ + std::string species; + std::vector moves; + std::set compatible; +}; + +struct FakeDisc{ + std::string move; + size_t count = 1; +}; + +class FakeTeachGame : public TeachActions{ +public: + std::vector party; + std::map tm_case = {}; + bool moves_readable = true; + // What the reader says before teaching, if not the party's moves. + std::optional> stale_moves = std::nullopt; + // The moves page forgets nothing: a bug the confirmation must catch. + bool forget_ignored = false; + // The bag or the TM Case didn't open. + bool open_fails = false; + size_t items_opened = 0; + size_t stopped = 0; + std::string error = {}; + + std::optional read_member(size_t slot){ + if (m_screen != Screen::OVERWORLD){ + error = "read the summary off the overworld"; + } + if (slot >= party.size() || !moves_readable){ + return std::nullopt; + } + MemberInfo info{.species = party[slot].species, .level = 16, .moves = party[slot].moves}; + if (stale_moves && items_opened == 0){ + info.moves = *stale_moves; + } + return info; + } + virtual ItemOpen open_item(std::string_view item, std::string_view) override{ + items_opened++; + if (open_fails){ + m_screen = Screen::BAG; + return ItemOpen::FAILED; + } + const auto found = tm_case.find(std::string(item)); + if (found == tm_case.end() || found->second.count == 0){ + m_screen = Screen::BAG; + return ItemOpen::NOT_IN_CASE; + } + m_item = found->first; + m_screen = Screen::CHOOSE_MEMBER; + return ItemOpen::OPENED; + } + virtual TeachPrompt choose_member(size_t slot) override{ + if (m_screen != Screen::CHOOSE_MEMBER || slot >= party.size()){ + error = "chose a member off the party menu"; + return TeachPrompt::FAILED; + } + m_slot = slot; + FakeMon& mon = party[slot]; + const std::string& move = tm_case[m_item].move; + if (std::find(mon.moves.begin(), mon.moves.end(), move) != mon.moves.end()){ + return TeachPrompt::ALREADY_KNOWS; + } + if (!mon.compatible.contains(move)){ + return TeachPrompt::NOT_COMPATIBLE; + } + if (mon.moves.size() < MOVE_SLOTS){ + mon.moves.push_back(move); + used_up(); + return TeachPrompt::LEARNED; + } + m_screen = Screen::DELETE_PROMPT; + return TeachPrompt::DELETE_PROMPT; + } + virtual ForgetEnd forget(size_t slot) override{ + if (m_screen != Screen::DELETE_PROMPT){ + error = "forgot a move off the prompt"; + return ForgetEnd::FAILED; + } + std::vector& moves = party[m_slot].moves; + if (is_hm_move(moves[slot])){ + return ForgetEnd::HM_REFUSED; + } + if (!forget_ignored){ + moves[slot] = tm_case[m_item].move; + } + used_up(); + m_screen = Screen::CHOOSE_MEMBER; + return ForgetEnd::LEARNED; + } + virtual void stop_teaching() override{ + stopped++; + m_screen = Screen::BAG; + } + virtual bool leave() override{ + m_screen = Screen::OVERWORLD; + return true; + } + virtual void dump_screen(std::string_view) override{} + +private: + enum class Screen{ + OVERWORLD, + BAG, + CHOOSE_MEMBER, + DELETE_PROMPT, + }; + + // A TM is used up; an HM is not. + void used_up(){ + if (m_item.starts_with("tm")){ + tm_case[m_item].count--; + } + } + + Screen m_screen = Screen::OVERWORLD; + std::string m_item; + size_t m_slot = 0; +}; + + +MemberReader reader_of(FakeTeachGame& game){ + return [&game](size_t slot){ + return game.read_member(slot); + }; +} + + +class Test_AutoStoryTeach : public UnitTest{ +public: + Test_AutoStoryTeach(std::string name, std::function body) + : UnitTest("PokemonFRLG::AutoStoryTeach - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +FakeTeachGame console_b_party(){ + FakeTeachGame game; + game.party = { + {"squirtle", {"water-gun", "tail-whip", "bubble", "withdraw"}, {"surf", "strength", "dig", "rock-smash"}}, + {"rattata", {"tackle", "tail-whip", "quick-attack"}, {"dig", "cut"}}, + {"oddish", {"absorb", "cut", "poison-powder", "acid"}, {"cut", "flash"}}, + }; + game.tm_case = {{"hm03", {"surf", 1}}, {"tm28", {"dig", 1}}, {"hm01", {"cut", 1}}}; + return game; +} + +struct TeachCase{ + std::string name = {}; + TeachPlan plan = {}; + std::function setup = {}; + TeachEnd end = TeachEnd::LEARNED; + // The member's moves after the step. + std::vector moves = {}; + // Whether the bag was opened at all. + bool opened = true; +}; + +std::vector teach_cases_1(){ + return { + { + .name = "Surf over TAIL WHIP by name", + .plan = {.item = "hm03", .move = "surf", .member = 0, .forget_move = "tail-whip"}, + .moves = {"water-gun", "surf", "bubble", "withdraw"}, + }, + { + .name = "Strength over the fourth slot by number", + .plan = {.item = "hm04", .move = "strength", .member = 0, .forget_slot = 3}, + .setup = [](FakeTeachGame& game){ game.tm_case["hm04"] = {"strength", 1}; }, + .moves = {"water-gun", "tail-whip", "bubble", "strength"}, + }, + { + .name = "a TM into a free slot", + .plan = {.item = "tm28", .move = "dig", .member = 1}, + .moves = {"tackle", "tail-whip", "quick-attack", "dig"}, + }, + { + .name = "a move it knows already: nothing pressed", + .plan = {.item = "hm01", .move = "cut", .member = 2}, + .end = TeachEnd::ALREADY_KNOWN, + .moves = {"absorb", "cut", "poison-powder", "acid"}, + .opened = false, + }, + }; +} + +std::vector teach_cases_2(){ + return { + { + .name = "four moves and none named to forget", + .plan = {.item = "hm03", .move = "surf", .member = 0}, + .end = TeachEnd::REFUSED, + .moves = {"water-gun", "tail-whip", "bubble", "withdraw"}, + .opened = false, + }, + { + .name = "a move to forget it doesn't know (the console Squirtle has no Tackle)", + .plan = {.item = "hm03", .move = "surf", .member = 0, .forget_move = "tackle"}, + .end = TeachEnd::REFUSED, + .moves = {"water-gun", "tail-whip", "bubble", "withdraw"}, + .opened = false, + }, + { + .name = "an HM move named to forget", + .plan = {.item = "tm28", .move = "dig", .member = 2, .forget_move = "cut"}, + .end = TeachEnd::REFUSED, + .moves = {"absorb", "cut", "poison-powder", "acid"}, + .opened = false, + }, + { + .name = "not compatible: given up, back on the overworld", + .plan = {.item = "hm01", .move = "cut", .member = 0, .forget_move = "withdraw"}, + .end = TeachEnd::REFUSED, + .moves = {"water-gun", "tail-whip", "bubble", "withdraw"}, + }, + }; +} + +std::vector teach_cases_3(){ + return { + { + .name = "moves read with room, but the game asks to forget one", + .plan = {.item = "hm03", .move = "surf", .member = 0}, + .setup = [](FakeTeachGame& game){ game.stale_moves = std::vector{"water-gun", "bubble"}; }, + .end = TeachEnd::FAILED, + .moves = {"water-gun", "tail-whip", "bubble", "withdraw"}, + }, + { + .name = "moves that can't be read: nothing pressed", + .plan = {.item = "hm03", .move = "surf", .member = 0, .forget_move = "tail-whip"}, + .setup = [](FakeTeachGame& game){ game.moves_readable = false; }, + .end = TeachEnd::UNREAD, + .moves = {"water-gun", "tail-whip", "bubble", "withdraw"}, + .opened = false, + }, + { + .name = "an item the TM Case hasn't got: skipped", + .plan = {.item = "hm05", .move = "flash", .member = 2, .forget_move = "acid"}, + .end = TeachEnd::NO_ITEM, + .moves = {"absorb", "cut", "poison-powder", "acid"}, + }, + { + .name = "the TM Case didn't open", + .plan = {.item = "hm03", .move = "surf", .member = 0, .forget_move = "tail-whip"}, + .setup = [](FakeTeachGame& game){ game.open_fails = true; }, + .end = TeachEnd::FAILED, + .moves = {"water-gun", "tail-whip", "bubble", "withdraw"}, + }, + { + .name = "the move didn't land: the read after catches it", + .plan = {.item = "hm03", .move = "surf", .member = 0, .forget_move = "tail-whip"}, + .setup = [](FakeTeachGame& game){ game.forget_ignored = true; }, + .end = TeachEnd::FAILED, + .moves = {"water-gun", "tail-whip", "bubble", "withdraw"}, + }, + }; +} + +std::vector teach_cases(){ + std::vector cases; + for (std::vector part : {teach_cases_1(), teach_cases_2(), teach_cases_3()}){ + cases.insert(cases.end(), part.begin(), part.end()); + } + return cases; +} + +UnitTestResult check_teach_case(const TeachCase& item){ + QuietLogger logger; + FakeTeachGame game = console_b_party(); + if (item.setup){ + item.setup(game); + } + const TeachResult result = run_teach(logger, game, reader_of(game), item.plan); + if (!game.error.empty()){ + return item.name + ": " + game.error; + } + if (result.end != item.end){ + return std::format("{}: ended {}, expected {} ({}).", item.name, + teach_end_name(result.end), teach_end_name(item.end), result.detail); + } + if (game.party[item.plan.member].moves != item.moves){ + return item.name + ": the moves after aren't the ones expected."; + } + if ((game.items_opened > 0) != item.opened){ + return item.name + (item.opened ? ": the bag wasn't opened." : ": the bag was opened."); + } + return true; +} + +UnitTestResult test_teach(){ + for (const TeachCase& item : teach_cases()){ + const UnitTestResult result = check_teach_case(item); + if (result.result != UnitTestResult::PASSED){ + return result; + } + } + return true; +} + + +// A TM is used up, an HM is not. +UnitTestResult test_tm_used_up(){ + QuietLogger logger; + FakeTeachGame game = console_b_party(); + run_teach(logger, game, reader_of(game), {.item = "tm28", .move = "dig", .member = 1}); + run_teach(logger, game, reader_of(game), {.item = "hm03", .move = "surf", .member = 0, .forget_move = "withdraw"}); + if (game.tm_case["tm28"].count != 0 || game.tm_case["hm03"].count != 1){ + return "Expected TM28 used up and HM03 kept."; + } + return true; +} + + +UnitTestResult test_teach_variant(){ + const TeachPlan plan{.item = "hm03", .move = "surf", .member = 0, .forget_move = "tail-whip"}; + const std::string variant = teach_variant(plan); + if (variant != "teach hm03 surf slot=1 forget=tail-whip"){ + return "Unexpected variant \"" + variant + "\"."; + } + const std::optional back = parse_teach_variant(variant); + if (!back || back->item != "hm03" || back->move != "surf" || back->member != 0 || back->forget_move != "tail-whip"){ + return "\"" + variant + "\" didn't read back as its plan."; + } + const std::optional by_slot = parse_teach_variant("teach tm28 dig slot=2 forget_slot=4"); + if (!by_slot || by_slot->member != 1 || by_slot->forget_slot != 3u){ + return "\"teach tm28 dig slot=2 forget_slot=4\" didn't read back."; + } + for (std::string_view bad : { + "teach", "teach hm03 surf", "teach potion surf slot=1", "teach hm03 surf slot=7", + "teach hm03 surf slot=1 forget_slot=5", "teach hm03 slot=1", "mart PewterCity_Mart potion=1", + }){ + if (parse_teach_variant(bad)){ + return "Expected \"" + std::string(bad) + "\" refused."; + } + } + return true; +} + +} + + +void add_tests_AutoStoryTeach(UnitTestDatabase& database){ + const auto add = [&](std::string name, UnitTestResult (*body)()){ + database.add(std::move(name), body); + }; + add("TMs and HMs on a fake party", test_teach); + add("a TM is used up, an HM kept", test_tm_used_up); + add("the table's variant", test_teach_variant); + add_tests_AutoStoryTeachScreens(database); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.cpp new file mode 100644 index 0000000000..c3e6bcedb1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.cpp @@ -0,0 +1,56 @@ +/* AutoStory Variant Words + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonFRLG_AutoStoryVariantWords.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +std::vector variant_words(std::string_view text){ + std::vector words; + while (!text.empty()){ + const size_t space = text.find(' '); + const std::string_view word = text.substr(0, space); + if (!word.empty()){ + words.push_back(word); + } + if (space == std::string_view::npos){ + break; + } + text.remove_prefix(space + 1); + } + return words; +} + +std::optional variant_pair(std::string_view word){ + const size_t equals = word.find('='); + if (equals == std::string_view::npos || equals == 0){ + return std::nullopt; + } + return VariantPair{word.substr(0, equals), word.substr(equals + 1)}; +} + +std::optional variant_number(std::string_view text, size_t max_digits){ + if (text.empty() || text.size() > max_digits){ + return std::nullopt; + } + size_t value = 0; + for (char c : text){ + if (c < '0' || c > '9'){ + return std::nullopt; + } + value = value * 10 + size_t(c - '0'); + } + return value; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.h new file mode 100644 index 0000000000..eaa22836fd --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.h @@ -0,0 +1,43 @@ +/* AutoStory Variant Words + * + * From: https://github.com/PokemonAutomation/ + * + * Reading a GAME step's variant: words split on spaces, "key=value" + * pairs, and small numbers. The table writes variants such as + * "mart PewterCity_Mart budget=2000 potion=5"; the steps read them back. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryVariantWords_H +#define PokemonAutomation_PokemonFRLG_AutoStoryVariantWords_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// `text`'s words, split on spaces, empty words dropped. +std::vector variant_words(std::string_view text); + +// A word "key=value" as its two halves; nothing without an '='. +struct VariantPair{ + std::string_view key; + std::string_view value; +}; +std::optional variant_pair(std::string_view word); + +// `text` as a number of up to `max_digits` decimal digits; nothing if it +// isn't one. +std::optional variant_number(std::string_view text, size_t max_digits = 6); + + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 09845c48e3..c0c52598bf 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1769,6 +1769,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryDetector.h Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.cpp Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.h + Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.cpp + Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.h Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TrainerCardDetector.cpp Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TrainerCardDetector.h Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleLevelUpReader.cpp @@ -1839,6 +1841,9 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -1854,13 +1859,24 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryDamage.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryDamage.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFoeTracker.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFoeTracker.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp @@ -1877,6 +1893,14 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp