From d37290cbe1b737c578fe65efa672026a3a833c0e Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 21:56:11 -0800 Subject: [PATCH 01/10] FRLG AutoStory: MART, TEACH, LEVEL, GRIND and fossil CHOICE steps New GAME step variants for later checkpoints, each with its decisions behind an actions interface and tested against a fake that follows pokefirered: - MART: a buy list in priority order within a budget at any Mart whose stock is known (scripts.inc lists, items.json prices); money from the money box or the table's floor, never past the quantity box's most. - TEACH: a TM or HM to a party member, the move to forget named by name or slot; refused for HM moves and missing names; confirmed by reading the moves again. - LEVEL: a member's level checked against a minimum. - GRIND: wild battles with the existing battle handler until the lead reaches a level, bounded, healing at the step's nurse between rounds. - CHOICE(fossil): DOME or HELIX at Mt. Moon B2F; NO unless the prompt reads as the wanted fossil. Members are read through a MemberReader callable for the summary-screen reader being built separately; until then the console steps that need it, and the TM Case, money box and fossil prompt, stop instead of pressing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../PokemonFRLG_AutoStoryAbilities.cpp | 110 +++++ .../PokemonFRLG_AutoStoryAbilities.h | 60 +++ .../PokemonFRLG_AutoStoryAbilities_Tests.cpp | 212 +++++++++ .../AutoStory/PokemonFRLG_AutoStoryChoice.cpp | 167 +++++++ .../AutoStory/PokemonFRLG_AutoStoryChoice.h | 129 ++++++ .../PokemonFRLG_AutoStoryChoice_Tests.cpp | 190 ++++++++ .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 66 ++- .../AutoStory/PokemonFRLG_AutoStoryEvents.h | 4 +- .../AutoStory/PokemonFRLG_AutoStoryGrind.cpp | 323 +++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryGrind.h | 176 +++++++ .../PokemonFRLG_AutoStoryGrind_Tests.cpp | 295 ++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryMart.cpp | 432 ++++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryMart.h | 225 +++++++++ .../PokemonFRLG_AutoStoryMart_Tests.cpp | 401 ++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryMember.cpp | 87 ++++ .../AutoStory/PokemonFRLG_AutoStoryMember.h | 97 ++++ .../AutoStory/PokemonFRLG_AutoStoryTeach.cpp | 302 ++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryTeach.h | 182 ++++++++ .../PokemonFRLG_AutoStoryTeach_Tests.cpp | 391 ++++++++++++++++ .../PokemonFRLG_AutoStoryVariantWords.cpp | 56 +++ .../PokemonFRLG_AutoStoryVariantWords.h | 43 ++ SerialPrograms/cmake/SourceFiles.cmake | 19 + 23 files changed, 3967 insertions(+), 2 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 785a4e91f1..3a0e8d94a3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -39,6 +39,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" @@ -727,6 +728,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..fe2c3e7559 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp @@ -0,0 +1,110 @@ +/* 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); + if (result.end == TeachEnd::LEARNED || result.end == TeachEnd::ALREADY_KNOWN){ + 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..03e7df25e0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h @@ -0,0 +1,60 @@ +/* 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 succeeds, 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..8fe964678b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -0,0 +1,212 @@ +/* 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: + virtual bool open_item(std::string_view) override{ return false; } + 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; } +}; + +class StubPatch : public GrindActions{ +public: + bool shiny = false; + + virtual bool find_encounter(Pokemon::Direction) override{ return true; } + virtual EncounterSeen read_encounter() override{ return {.species = "pidgey", .shiny = shiny}; } + virtual GrindFight fight() override{ return GrindFight::FAILED; } + virtual bool needs_heal() override{ return false; } + virtual bool heal_trip() override{ return true; } +}; + +class StubFossils : public ChoiceActions{ +public: + virtual bool talk() override{ return false; } + virtual std::optional read_offer() override{ return std::nullopt; } + virtual void answer(bool) override{} + virtual bool finish() override{ return true; } + virtual std::optional fossil_in_bag() override{ return std::nullopt; } +}; + +struct StubGame{ + std::optional level = 16; + StubMart mart; + StubTeach teach; + StubPatch patch; + StubFossils fossils; +}; + + +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 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_AutoStoryChoice.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp new file mode 100644 index 0000000000..a0b3a92406 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp @@ -0,0 +1,167 @@ +/* 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::UNREAD: return "unread"; + 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"); + } + const std::optional offer = actions.read_offer(); + if (!offer){ + return decline(actions, ChoiceEnd::UNREAD, "couldn't read which fossil the prompt offers"); + } + if (*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), 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){ + // The cursor opens on YES; B answers NO. + pbf_press_button(m_context, yes ? BUTTON_A : BUTTON_B, 160ms, 800ms); + m_context.wait_for_all_requests(); +} + +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..aa91b7a239 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h @@ -0,0 +1,129 @@ +/* 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, or can't be read. 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, so the console step stops with NO answered. + * + */ + +#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, + // The prompt couldn't be read: NO answered. + UNREAD, + 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, then, with no reader for the +// prompt's text yet, answers NO and stops. +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..96cd3d8adf --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp @@ -0,0 +1,190 @@ +/* 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, + }, + { + .name = "an unread prompt: NO, both left", + .setup = [](FakeFossilRoom& room){ room.offer_readable = false; }, + .end = ChoiceEnd::UNREAD, + }, + { + .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 b168e39156..ff8737157d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -15,6 +15,7 @@ #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_AutoStoryCapture.h" #include "PokemonFRLG_AutoStoryEvents.h" @@ -413,7 +414,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); + env.supplies.hurt = false; + env.supplies.hp_red = false; + env.supplies.status = StatusCondition::NONE; + 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); + ConsoleTeachActions teach(env.console); + 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), 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(); @@ -428,6 +488,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 8589288101..2cff032f3c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -225,7 +225,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..74b1128ecf --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp @@ -0,0 +1,323 @@ +/* AutoStory Grind + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleFlashWatcher.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryGrind.h" +#include "PokemonFRLG_AutoStoryVariantWords.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::Direction; + + +namespace{ + +Direction opposite_direction(Direction direction){ + switch (direction){ + case Direction::NORTH: return Direction::SOUTH; + case Direction::EAST: return Direction::WEST; + case Direction::SOUTH: return Direction::NORTH; + case Direction::WEST: return Direction::EAST; + } + return direction; +} + +} + + +const char* grind_end_name(GrindEnd end){ + switch (end){ + case GrindEnd::REACHED: return "reached"; + 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){ + return 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 + ); +} + +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 == "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{ + 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; + 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="); + } + if (!level_seen){ + 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 (reached()){ + return end(GrindEnd::REACHED, ""); + } + 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 (reached()){ + return heal() ? end(GrindEnd::REACHED, "") : 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(){ + const std::optional member = m_reader(m_plan.member); + if (!member || !member->level){ + return false; + } + m_result.level = member->level; + return true; + } + bool reached() const{ + return m_result.level && *m_result.level >= m_plan.level; + } + 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; + 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 tally = std::format( + "level {} of {}, {} encounters, {} trips to the nurse", level, plan.level, 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); +} + + +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. + constexpr size_t MAX_STEPS = 200; + for (size_t c = 0; c < MAX_STEPS; c++){ + const Direction way = m_spot.displaced ? opposite_direction(pace) : 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}; + if (ret == 0){ + return true; + } + } + return false; +} + +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; +} + +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..cbf28231be --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h @@ -0,0 +1,176 @@ +/* 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. 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, + * or after `heal_every` battles. It is bounded by encounters, and a + * shiny stops it as it stops a capture: nothing pressed. + * + * The level is read with a MemberReader before the first battle and after + * each win; the console has no summary reader yet, so there the step + * stops before its first battle. + * + */ + +#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_AutoStoryCapture.h" +#include "PokemonFRLG_AutoStoryMember.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +struct GrindPlan{ + // The party slot that grinds: the lead (0) only. + size_t member = 0; + 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 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. 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 or has a status, 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; +}; + +enum class GrindEnd{ + REACHED, + 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; + 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); + + +// Where pacing left the player, for the trip to the nurse: on the patch's +// tile, or one tile `pace` from it, as the last step taken left it. +struct GrindSpot{ + bool displaced = false; + // The way the player faces after its last step; nothing before one. + std::optional facing = std::nullopt; +}; + +// 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; + +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..8fd6424a19 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp @@ -0,0 +1,295 @@ +/* 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). + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryGrind.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 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; + + size_t encounters = 0; + size_t fights = 0; + size_t heals = 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; + } + +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; +}; + +GrindPlan squirtle_to(unsigned level){ + return {.member = 0, .level = level, .max_encounters = 20, .pace = Pokemon::Direction::EAST, .heal_every = 0}; +} + +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, + }, + }; +} + +std::vector grind_cases(){ + std::vector cases; + for (std::vector part : {grind_cases_1(), grind_cases_2()}){ + 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); + } + 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; +} + + +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."; + } + 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", + }){ + 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); +} + + + +} +} +} 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..f576db16c8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp @@ -0,0 +1,87 @@ +/* AutoStory Member + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonFRLG_AutoStoryMember.h" +#include "PokemonFRLG_AutoStoryVariantWords.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +MemberReader console_member_reader(ConsoleHandle& console){ + return [&console](size_t slot) -> std::optional{ + console.log(std::format( + "Party: no summary-screen reader yet; can't read the member in slot {}.", slot + 1 + ), COLOR_RED); + return std::nullopt; + }; +} + + +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..728710819e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h @@ -0,0 +1,97 @@ +/* AutoStory Member + * + * From: https://github.com/PokemonAutomation/ + * + * What the story reads about one party member: its species, level and + * moves, as the summary screen shows them (page 1: level; page 3: the + * four moves). The story's steps take them from a MemberReader, so their + * decisions run in tests against a fake party; the summary-screen reader + * is being built separately and plugs in as a MemberReader. Until it + * does, console_member_reader() reads nothing, and every step that needs a + * member's level or moves stops 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 "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StorySteps.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 = {}; +}; + +// 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, until the summary-screen reader lands: reads +// nothing and logs why, so the steps that need it stop. +MemberReader console_member_reader(ConsoleHandle& console); + + +// 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..47ee0ac743 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp @@ -0,0 +1,302 @@ +/* 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::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]; + } + if (!m_actions.open_item(m_plan.item)){ + 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 end(TeachEnd::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; + } + TeachResult leave(TeachEnd end, std::string detail){ + if (!m_actions.leave()){ + return this->end(TeachEnd::FAILED, "the overworld didn't come back"); + } + return this->end(end, std::move(detail)); + } + // Sets the result and gives up teaching. False. + bool give_up(TeachEnd end, std::string detail){ + 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 end(TeachEnd::FAILED, "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 end(TeachEnd::FAILED, 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(); + logger.log(teach_message(plan, result), result.end == TeachEnd::LEARNED ? COLOR_BLACK : COLOR_RED); + 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); + default: + return std::format("{}: {}: {}.", what, teach_end_name(result.end), result.detail); + } +} + + +ConsoleTeachActions::ConsoleTeachActions(ConsoleHandle& console) + : m_console(console) +{} + +bool ConsoleTeachActions::open_item(std::string_view item){ + m_console.log(std::format("Teach: no reader for the TM Case yet; not opening {}.", item), COLOR_RED); + return false; +} + +TeachPrompt ConsoleTeachActions::choose_member(size_t){ + return TeachPrompt::FAILED; +} + +ForgetEnd ConsoleTeachActions::forget(size_t){ + return ForgetEnd::FAILED; +} + +void ConsoleTeachActions::stop_teaching(){} + +bool ConsoleTeachActions::leave(){ + // Nothing was opened. + return true; +} + + + +} +} +} 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..97d568b18d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h @@ -0,0 +1,182 @@ +/* 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 pokefirered runs it (tm_case.c, + * party_menu.c): + * + * - BAG, KEY ITEMS, TM CASE, the TM or HM, USE: "Booted up a TM/HM. It + * contained . Teach to a POKEMON?" YES/NO. + * - YES: the party menu, "Teach which POKEMON?", each member ABLE or NOT + * ABLE. A on a member that knows the move: " knows + * already."; one NOT ABLE: " and are not compatible.". + * - With fewer than four moves it learns: " learned !". + * - With four: " is trying to learn . But can't learn + * more than four moves. Delete an older move to make room for ?" + * YES opens the moves page; A on a move forgets it ("1, 2, and... + * Poof!") and it learns. An HM move can't be forgotten: "HM moves + * can't be forgotten now." and the moves page again. NO, then "Stop + * trying to teach ?" YES, leaves it unlearned. + * - A TM is used up; an HM is not. + * + * 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 the TM Case, + * the party menu's prompts and the moves page have no readers yet, and + * the summary reader is pending (MemberReader): the console step stops at + * its first read. + * + */ + +#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 "NintendoSwitch/NintendoSwitch_ConsoleHandle.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, +}; + +// 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`, USE, YES, to the + // party menu. False if the item isn't there or the party didn't show. + virtual bool open_item(std::string_view item) = 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; +}; + +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, + 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); + + +// The console's TEACH steps: the TM Case and the prompts have no readers +// yet, so each step fails instead of pressing blind. The step reaches them +// only once a MemberReader reads moves. +class ConsoleTeachActions : public TeachActions{ +public: + explicit ConsoleTeachActions(ConsoleHandle& console); + + virtual bool open_item(std::string_view item) 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; + +private: + ConsoleHandle& m_console; +}; + + +void add_tests_AutoStoryTeach(UnitTestDatabase& database); + + + +} +} +} +#endif 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..272d9b909b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp @@ -0,0 +1,391 @@ +/* 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" + +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; + 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 bool open_item(std::string_view item) override{ + items_opened++; + const auto found = tm_case.find(std::string(item)); + if (found == tm_case.end() || found->second.count == 0){ + m_screen = Screen::BAG; + return false; + } + m_item = found->first; + m_screen = Screen::CHOOSE_MEMBER; + return true; + } + 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; + } + +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", + .plan = {.item = "hm05", .move = "flash", .member = 2, .forget_move = "acid"}, + .end = TeachEnd::FAILED, + .moves = {"absorb", "cut", "poison-powder", "acid"}, + }, + { + .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); +} + + + +} +} +} 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 f741a595d2..fd06c1671b 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1833,6 +1833,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 @@ -1840,9 +1843,20 @@ 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_AutoStoryEvents.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.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_AutoStoryPcStorage.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage_Tests.cpp @@ -1854,6 +1868,11 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp 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_AutoStoryVariantWords.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVariantWords.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_EliteFourFarmer.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_EliteFourFarmer.h From feea08186da99a5082129af2a6de6261559386e5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 22:12:37 -0800 Subject: [PATCH 02/10] FRLG AutoStory: console_member_reader reads the member's summary TEACH, LEVEL and GRIND stopped at every member read: the console reader was a stub until the summary reader landed (#120's read_party_summary()). It now opens the member's summary and gives its species, level and moves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 2 +- .../AutoStory/PokemonFRLG_AutoStoryMember.cpp | 19 +++++++++++++------ .../AutoStory/PokemonFRLG_AutoStoryMember.h | 17 ++++++++++------- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 9ab29e157c..180216b90e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -464,7 +464,7 @@ std::optional run_abilities(StoryEnv& env, RunState& state, const Story } ); ConsoleChoiceActions choice(env.console, env.context); - StoryAbilities abilities{console_member_reader(env.console), mart, teach, grind, choice}; + 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); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp index f576db16c8..a88c6d9d32 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp @@ -6,6 +6,7 @@ #include #include "PokemonFRLG_AutoStoryMember.h" +#include "PokemonFRLG_AutoStorySummary.h" #include "PokemonFRLG_AutoStoryVariantWords.h" namespace PokemonAutomation{ @@ -13,12 +14,18 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -MemberReader console_member_reader(ConsoleHandle& console){ - return [&console](size_t slot) -> std::optional{ - console.log(std::format( - "Party: no summary-screen reader yet; can't read the member in slot {}.", slot + 1 - ), COLOR_RED); - return std::nullopt; +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 = {}}; + for (const SummaryMove& move : read->moves){ + info.moves.push_back(move.move); + } + return info; }; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h index 728710819e..2d437c640d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h @@ -5,10 +5,10 @@ * What the story reads about one party member: its species, level and * moves, as the summary screen shows them (page 1: level; page 3: the * four moves). The story's steps take them from a MemberReader, so their - * decisions run in tests against a fake party; the summary-screen reader - * is being built separately and plugs in as a MemberReader. Until it - * does, console_member_reader() reads nothing, and every step that needs a - * member's level or moves stops instead of guessing. + * 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. @@ -25,6 +25,7 @@ #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" @@ -53,9 +54,11 @@ struct MemberInfo{ // summary couldn't be read. using MemberReader = std::function(size_t slot)>; -// The console's reader, until the summary-screen reader lands: reads -// nothing and logs why, so the steps that need it stop. -MemberReader console_member_reader(ConsoleHandle& console); +// 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`. From a50f17071482a81a7764590e040ccb964e5fe772 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 00:25:36 -0800 Subject: [PATCH 03/10] FRLG fossil CHOICE: answer YES when the prompt can't be read The console has no reader for "You want the HELIX FOSSIL?", so the step answered NO and stopped, and 00.13 could never take a fossil. The table walks the player to face the wanted fossil, so an unread prompt is now taken to offer that one and answered YES; the console answers through answer_yes_no(), which reads the box's cursor, and the scene is cleared to the overworld as before. A prompt read as the other fossil still gets NO. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/PokemonFRLG_AutoStoryChoice.cpp | 16 +++++++--------- .../AutoStory/PokemonFRLG_AutoStoryChoice.h | 13 +++++++------ .../PokemonFRLG_AutoStoryChoice_Tests.cpp | 13 +++++++++++-- 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp index a0b3a92406..c6e7603425 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp @@ -44,7 +44,6 @@ const char* choice_end_name(ChoiceEnd end){ switch (end){ case ChoiceEnd::TAKEN: return "taken"; case ChoiceEnd::WRONG_ONE: return "wrong_one"; - case ChoiceEnd::UNREAD: return "unread"; case ChoiceEnd::FAILED: return "failed"; } return "?"; @@ -93,11 +92,10 @@ ChoiceResult run_fossil_choice(Logger& logger, ChoiceActions& actions, Fossil fo 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){ - return decline(actions, ChoiceEnd::UNREAD, "couldn't read which fossil the prompt offers"); - } - if (*offer != fossil){ + 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); @@ -109,7 +107,8 @@ ChoiceResult run_fossil_choice(Logger& logger, ChoiceActions& actions, Fossil fo 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), held ? ", seen in the bag" : " (the bag isn't read)" + "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 = ""}; } @@ -140,9 +139,8 @@ std::optional ConsoleChoiceActions::read_offer(){ } void ConsoleChoiceActions::answer(bool yes){ - // The cursor opens on YES; B answers NO. - pbf_press_button(m_context, yes ? BUTTON_A : BUTTON_B, 160ms, 800ms); - m_context.wait_for_all_requests(); + // 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(){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h index aa91b7a239..831ceaec6e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.h @@ -12,12 +12,14 @@ * * 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, or can't be read. After the + * (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, so the console step stops with NO answered. + * 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. * */ @@ -84,8 +86,6 @@ enum class ChoiceEnd{ TAKEN, // The prompt offered the other fossil: NO answered. WRONG_ONE, - // The prompt couldn't be read: NO answered. - UNREAD, FAILED, }; const char* choice_end_name(ChoiceEnd end); @@ -101,8 +101,9 @@ struct ChoiceResult{ ChoiceResult run_fossil_choice(Logger& logger, ChoiceActions& actions, Fossil fossil); -// The console's fossil CHOICE: talks, then, with no reader for the -// prompt's text yet, answers NO and stops. +// 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); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp index 96cd3d8adf..d9fe28b9e6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice_Tests.cpp @@ -118,10 +118,19 @@ std::vector choice_cases(){ .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: NO, both left", + .name = "an unread prompt: YES, facing the wanted fossil", .setup = [](FakeFossilRoom& room){ room.offer_readable = false; }, - .end = ChoiceEnd::UNREAD, + .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", From 4636c38ec165d9a737e51a775ff96822966d5030 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 01:41:31 -0800 Subject: [PATCH 04/10] FRLG AutoStory GRIND: heal when low on PP; the nurse restores PP A grind's battles spend more PP than the lead's attacks have: it now goes to the nurse when they run low, and the trip back counts the PP restored, so the battle loop doesn't fall back to Tackle after the nurse. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 5 ++--- .../Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp | 2 +- .../Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h | 6 ++++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index bebddb9cef..1c92b1f46f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -448,9 +448,8 @@ bool grind_heal_trip(StoryEnv& env, RunState& state, const StoryStep& step, cons return false; } heal_at_center(env.console, env.context); - env.supplies.hurt = false; - env.supplies.hp_red = false; - env.supplies.status = StatusCondition::NONE; + // 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); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp index 74b1128ecf..5819c1792f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp @@ -304,7 +304,7 @@ GrindFight ConsoleGrindActions::fight(){ } bool ConsoleGrindActions::needs_heal(){ - return m_supplies.hurt || m_supplies.status != StatusCondition::NONE; + return m_supplies.hurt || m_supplies.status != StatusCondition::NONE || attacks_low_on_pp(m_supplies); } bool ConsoleGrindActions::heal_trip(){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h index cbf28231be..9921c2443c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h @@ -13,7 +13,8 @@ * 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, - * or after `heal_every` battles. It is bounded by encounters, and a + * 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 level is read with a MemberReader before the first battle and after @@ -92,7 +93,8 @@ class GrindActions{ virtual EncounterSeen read_encounter() = 0; // From the battle menu: the battle handler, to the overworld. virtual GrindFight fight() = 0; - // Whether the lead is hurt or has a status, as the battles left it. + // 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. From 57736556537e93aacc2d481b4e51ca56cafcefe4 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 07:26:54 -0800 Subject: [PATCH 05/10] FRLG AutoStory TEACH: test the console's steps through the TM CASE's screens (red) Console B, 2026-11-03: the TEACH step failed with "couldn't open tm03 from the TM Case". ConsoleTeachActions had no readers and returned before the bag. The TEACH step's console side becomes ScreenTeachActions over a TeachScreens (the screen read, a press), and a fake bag, TM CASE and party menu answer as the console's captures did: TM03 over TAIL WHIP, the bag left on POKE BALLS, a free slot, no TM03, not compatible. The actions are still the old stub, so the test fails with the console's message. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Menus/PokemonFRLG_TeachScreenReader.h | 105 +++++ .../PokemonFRLG_AutoStoryAbilities_Tests.cpp | 2 +- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 4 +- .../AutoStory/PokemonFRLG_AutoStoryTeach.cpp | 28 +- .../AutoStory/PokemonFRLG_AutoStoryTeach.h | 60 +-- .../PokemonFRLG_AutoStoryTeachScreens.cpp | 75 +++ .../PokemonFRLG_AutoStoryTeachScreens.h | 134 ++++++ ...okemonFRLG_AutoStoryTeachScreens_Tests.cpp | 443 ++++++++++++++++++ .../PokemonFRLG_AutoStoryTeach_Tests.cpp | 4 +- SerialPrograms/cmake/SourceFiles.cmake | 4 + 10 files changed, 789 insertions(+), 70 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp 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..86c7617d7f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.h @@ -0,0 +1,105 @@ +/* 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. +constexpr size_t TEACH_LIST_ROWS = 6; +constexpr size_t ITEM_MENU_ROWS = 3; + +// The row the dark arrow is on: 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). +// 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 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/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp index 8fe964678b..30dd927749 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -44,7 +44,7 @@ class StubMart : public MartActions{ class StubTeach : public TeachActions{ public: - virtual bool open_item(std::string_view) override{ return false; } + virtual bool open_item(std::string_view, std::string_view) override{ return false; } virtual TeachPrompt choose_member(size_t) override{ return TeachPrompt::FAILED; } virtual ForgetEnd forget(size_t) override{ return ForgetEnd::FAILED; } virtual void stop_teaching() override{} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index b85003cc17..64e4624e93 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -20,6 +20,7 @@ #include "PokemonFRLG_AutoStoryCapture.h" #include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStorySummary.h" +#include "PokemonFRLG_AutoStoryTeachScreens.h" #include "PokemonFRLG_AutoStoryWinChance.h" namespace PokemonAutomation{ @@ -493,7 +494,8 @@ bool grind_heal_trip(StoryEnv& env, RunState& state, const StoryStep& step, cons 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); - ConsoleTeachActions teach(env.console); + 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){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp index 47ee0ac743..d2c904826b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp @@ -159,7 +159,7 @@ class TeachRun{ if (decision.forget){ m_result.forgot = member->moves[*decision.forget]; } - if (!m_actions.open_item(m_plan.item)){ + if (!m_actions.open_item(m_plan.item, m_plan.move)){ return leave(TeachEnd::FAILED, std::format("couldn't open {} from the TM Case", m_plan.item)); } if (!teach(decision.forget)){ @@ -271,32 +271,6 @@ std::string teach_message(const TeachPlan& plan, const TeachResult& result){ } -ConsoleTeachActions::ConsoleTeachActions(ConsoleHandle& console) - : m_console(console) -{} - -bool ConsoleTeachActions::open_item(std::string_view item){ - m_console.log(std::format("Teach: no reader for the TM Case yet; not opening {}.", item), COLOR_RED); - return false; -} - -TeachPrompt ConsoleTeachActions::choose_member(size_t){ - return TeachPrompt::FAILED; -} - -ForgetEnd ConsoleTeachActions::forget(size_t){ - return ForgetEnd::FAILED; -} - -void ConsoleTeachActions::stop_teaching(){} - -bool ConsoleTeachActions::leave(){ - // Nothing was opened. - return true; -} - - - } } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h index 97d568b18d..ff8156aa9d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h @@ -3,21 +3,21 @@ * 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 pokefirered runs it (tm_case.c, - * party_menu.c): + * 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, the TM or HM, USE: "Booted up a TM/HM. It - * contained . Teach to a POKEMON?" YES/NO. - * - YES: the party menu, "Teach which POKEMON?", each member ABLE or NOT - * ABLE. A on a member that knows the move: " knows - * already."; one NOT ABLE: " and are not compatible.". - * - With fewer than four moves it learns: " learned !". - * - With four: " is trying to learn . But can't learn - * more than four moves. Delete an older move to make room for ?" - * YES opens the moves page; A on a move forgets it ("1, 2, and... - * Poof!") and it learns. An HM move can't be forgotten: "HM moves - * can't be forgotten now." and the moves page again. NO, then "Stop - * trying to teach ?" YES, leaves it unlearned. + * - 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. * * The step reads the member's moves first (MemberReader) and decides @@ -28,10 +28,8 @@ * 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 the TM Case, - * the party menu's prompts and the moves page have no readers yet, and - * the summary reader is pending (MemberReader): the console step stops at - * its first read. + * tests against a fake party and TM Case; on the console they are + * ScreenTeachActions (PokemonFRLG_AutoStoryTeachScreens.h). * */ @@ -45,7 +43,6 @@ #include #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "PokemonFRLG_AutoStoryMember.h" @@ -116,9 +113,10 @@ class TeachActions{ public: virtual ~TeachActions() = default; - // From the overworld: the bag, the TM Case, `item`, USE, YES, to the - // party menu. False if the item isn't there or the party didn't show. - virtual bool open_item(std::string_view item) = 0; + // From the overworld: the bag, the TM Case, `item` (which holds + // `move`), USE, to the party menu. False if the item isn't there or the + // party didn't show. + virtual bool 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). @@ -154,24 +152,6 @@ TeachResult run_teach(Logger& logger, TeachActions& actions, const MemberReader& std::string teach_message(const TeachPlan& plan, const TeachResult& result); -// The console's TEACH steps: the TM Case and the prompts have no readers -// yet, so each step fails instead of pressing blind. The step reaches them -// only once a MemberReader reads moves. -class ConsoleTeachActions : public TeachActions{ -public: - explicit ConsoleTeachActions(ConsoleHandle& console); - - virtual bool open_item(std::string_view item) 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; - -private: - ConsoleHandle& m_console; -}; - - void add_tests_AutoStoryTeach(UnitTestDatabase& database); 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..dcfce42149 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp @@ -0,0 +1,75 @@ +/* AutoStory Teach Screens + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonFRLG_AutoStoryTeachScreens.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +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 "?"; +} + + +ScreenTeachActions::ScreenTeachActions(Logger& logger, TeachScreens& screens) + : m_logger(logger) + , m_screens(screens) +{} + +bool ScreenTeachActions::open_item(std::string_view item, std::string_view){ + m_logger.log(std::string("Teach: no reader for the TM Case yet; not opening ") + std::string(item) + ".", COLOR_RED); + return false; +} +TeachPrompt ScreenTeachActions::choose_member(size_t){ + return TeachPrompt::FAILED; +} +ForgetEnd ScreenTeachActions::forget(size_t){ + return ForgetEnd::FAILED; +} +void ScreenTeachActions::stop_teaching(){ + (void)m_screens; +} +bool ScreenTeachActions::leave(){ + // Nothing was opened. + return true; +} + + +ConsoleTeachScreens::ConsoleTeachScreens(ConsoleHandle& console, ProControllerContext& context, Language language) + : m_console(console) + , m_context(context) + , m_language(language) +{} + +bool ConsoleTeachScreens::open_bag(){ + (void)m_console; + (void)m_context; + (void)m_language; + return false; +} +TeachView ConsoleTeachScreens::look(){ + return {}; +} +void ConsoleTeachScreens::press(TeachPress){} +bool ConsoleTeachScreens::to_overworld(){ + return true; +} + + + +} +} +} 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..6b5475304a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h @@ -0,0 +1,134 @@ +/* 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; 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; +}; + + +// The TEACH step's game steps through `screens`. +class ScreenTeachActions : public TeachActions{ +public: + ScreenTeachActions(Logger& logger, TeachScreens& screens); + + virtual bool 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; + +private: + 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; + +private: + ConsoleHandle& m_console; + ProControllerContext& m_context; + Language m_language; +}; + + +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..ecc243afc7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp @@ -0,0 +1,443 @@ +/* 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, + 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 TM in use, by row. + size_t tm = 0; + std::vector presses = {}; + 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}, FakeScreen::TM_CASE); + 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: + 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: + 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; + } + +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; +}; + +std::vector screens_cases(){ + return { + {.name = "console B: TM03 over TAIL WHIP"}, + { + .name = "the bag left on POKE BALLS", + .setup = [](FakeTeachGame& game){ game.pocket = 2; }, + }, + { + .name = "a free slot: no move forgotten", + .setup = [](FakeTeachGame& game){ game.moves = {"bite", "bubble", "withdraw"}; }, + .plan = {.item = "tm03", .move = "water-pulse", .member = 0}, + .moves = {"bite", "bubble", "withdraw", "water-pulse"}, + }, + { + .name = "no TM03 in the TM CASE: back to the overworld", + .setup = [](FakeTeachGame& game){ game.tms = {{"rock-tomb", 1}}; }, + .end = TeachEnd::FAILED, + .moves = {"bite", "tail-whip", "bubble", "withdraw"}, + }, + { + .name = "not compatible: given up, back to the overworld", + .setup = [](FakeTeachGame& game){ game.compatible.clear(); }, + .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); + } + 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 index 272d9b909b..72f44f0d41 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp @@ -21,6 +21,7 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "PokemonFRLG_AutoStoryTeach.h" +#include "PokemonFRLG_AutoStoryTeachScreens.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -72,7 +73,7 @@ class FakeTeachGame : public TeachActions{ } return info; } - virtual bool open_item(std::string_view item) override{ + virtual bool open_item(std::string_view item, std::string_view) override{ items_opened++; const auto found = tm_case.find(std::string(item)); if (found == tm_case.end() || found->second.count == 0){ @@ -382,6 +383,7 @@ void add_tests_AutoStoryTeach(UnitTestDatabase& database){ 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/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 7e9b553784..ced23b7490 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1769,6 +1769,7 @@ 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.h Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TrainerCardDetector.cpp Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TrainerCardDetector.h Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleLevelUpReader.cpp @@ -1894,6 +1895,9 @@ file(GLOB LIBRARY_SOURCES 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 From 7a3192d196d631146f87861388c37eb17d2eefe6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 07:32:41 -0800 Subject: [PATCH 06/10] FRLG AutoStory TEACH: read the bag, the TM CASE and the party menu's prompts The console's TEACH step opened nothing (console B, 2026-11-03: "couldn't open tm03 from the TM Case"). TeachScreenReader reads each screen of the way from captures of that run: the bag's pocket and KEY ITEMS' rows, the OPEN and USE menus, the TM CASE's moves, the party menu's messages and YES/NO, and the KNOWN MOVES page's cursor. ScreenTeachActions looks before every press: KEY ITEMS, TM CASE, OPEN, the TM, USE, the member, YES, the move to forget, then B out of the TM CASE and the bag to the overworld. The fake screens' test passes, and the 14 frames are image tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Menus/PokemonFRLG_TeachScreenReader.cpp | 517 ++++++++++++++++++ .../Menus/PokemonFRLG_TeachScreenReader.h | 15 +- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../PokemonFRLG_AutoStoryTeachScreens.cpp | 337 +++++++++++- .../PokemonFRLG_AutoStoryTeachScreens.h | 19 + ...okemonFRLG_AutoStoryTeachScreens_Tests.cpp | 21 +- SerialPrograms/cmake/SourceFiles.cmake | 1 + 7 files changed, 891 insertions(+), 21 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.cpp 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 index 86c7617d7f..2e1dc393f5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TeachScreenReader.h @@ -55,13 +55,16 @@ const char* teach_screen_name(TeachScreen screen); TeachScreen read_teach_screen(const ImageViewRGB32& screen); -// Rows a list or menu shows at once. +// 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 dark arrow is on: 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). -// Nothing if no row or more than one has it. +// 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 @@ -76,6 +79,10 @@ std::string read_key_item(Logger& logger, Language language, const ImageViewRGB3 // "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, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index ce5f8865ac..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" @@ -697,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){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp index dcfce42149..65ca21fab1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp @@ -4,12 +4,21 @@ * */ +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.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){ @@ -24,27 +33,246 @@ const char* teach_press_name(TeachPress press){ } +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) {} -bool ScreenTeachActions::open_item(std::string_view item, std::string_view){ - m_logger.log(std::string("Teach: no reader for the TM Case yet; not opening ") + std::string(item) + ".", COLOR_RED); +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; } -TeachPrompt ScreenTeachActions::choose_member(size_t){ + +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; +} + +bool ScreenTeachActions::open_row(TeachScreen screen, std::string_view name){ + const std::optional view = wait_for(screen); + if (!view){ + return false; + } + 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); + return false; + } + if (!move_cursor_to(screen, size_t(found - view->rows.begin()))){ + return false; + } + press(TeachPress::A); + if (!wait_for(TeachScreen::ITEM_MENU) || !move_cursor_to(TeachScreen::ITEM_MENU, 0)){ + return false; + } + press(TeachPress::A); + return true; +} + +bool 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 false; + } + if (!to_key_items() || !open_row(TeachScreen::BAG, "tm-case")){ + return false; + } + if (!open_row(TeachScreen::TM_CASE, move)){ + m_logger.log(std::format("Teach: couldn't use {} ({}) from the TM CASE.", item, move), COLOR_RED); + return false; + } + return wait_for(TeachScreen::PARTY_PROMPT).has_value(); +} + +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; } -ForgetEnd ScreenTeachActions::forget(size_t){ + +ForgetEnd ScreenTeachActions::forget(size_t slot){ + bool picked = false; + size_t still = 0; + for (size_t c = 0; c < MAX_LOOKS; c++){ + const TeachView view = m_screens.look(); + switch (view.screen){ + case TeachScreen::PARTY_YES_NO: + // 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); + } + 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: + return picked ? ForgetEnd::LEARNED : ForgetEnd::FAILED; + default: + break; + } + } return ForgetEnd::FAILED; } + void ScreenTeachActions::stop_teaching(){ - (void)m_screens; + 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; + } + } } + bool ScreenTeachActions::leave(){ - // Nothing was opened. - return true; + 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; } @@ -55,17 +283,100 @@ ConsoleTeachScreens::ConsoleTeachScreens(ConsoleHandle& console, ProControllerCo {} bool ConsoleTeachScreens::open_bag(){ - (void)m_console; - (void)m_context; - (void)m_language; - return false; + 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 {}; } -void ConsoleTeachScreens::press(TeachPress){} + +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(); +} + bool ConsoleTeachScreens::to_overworld(){ - return true; + 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 index 6b5475304a..237600cf5c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h @@ -101,6 +101,19 @@ class ScreenTeachActions : public TeachActions{ virtual bool leave() 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). + bool open_row(TeachScreen screen, std::string_view name); + // After A on a member: what it showed. + TeachPrompt member_answer(); + void press(TeachPress press); + Logger& m_logger; TeachScreens& m_screens; }; @@ -118,9 +131,15 @@ class ConsoleTeachScreens : public TeachScreens{ virtual bool to_overworld() 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; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp index ecc243afc7..5d1883820e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp @@ -338,28 +338,41 @@ struct ScreensCase{ 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 nothing_compatible(FakeTeachGame& game){ + game.compatible.clear(); +} + std::vector screens_cases(){ return { {.name = "console B: TM03 over TAIL WHIP"}, { .name = "the bag left on POKE BALLS", - .setup = [](FakeTeachGame& game){ game.pocket = 2; }, + .setup = left_on_poke_balls, }, { .name = "a free slot: no move forgotten", - .setup = [](FakeTeachGame& game){ game.moves = {"bite", "bubble", "withdraw"}; }, + .setup = three_moves, .plan = {.item = "tm03", .move = "water-pulse", .member = 0}, .moves = {"bite", "bubble", "withdraw", "water-pulse"}, }, { .name = "no TM03 in the TM CASE: back to the overworld", - .setup = [](FakeTeachGame& game){ game.tms = {{"rock-tomb", 1}}; }, + .setup = no_tm03, .end = TeachEnd::FAILED, .moves = {"bite", "tail-whip", "bubble", "withdraw"}, }, { .name = "not compatible: given up, back to the overworld", - .setup = [](FakeTeachGame& game){ game.compatible.clear(); }, + .setup = nothing_compatible, .end = TeachEnd::REFUSED, .moves = {"bite", "tail-whip", "bubble", "withdraw"}, .tm03 = 1, diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index ced23b7490..c0c52598bf 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1769,6 +1769,7 @@ 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 From eac06708148f4393eecb965b96e79d7292db8af5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 07:51:34 -0800 Subject: [PATCH 07/10] FRLG AutoStory TEACH: skip, with a log line, when the TM isn't in the TM CASE A row can teach a TM the run may not have won yet: 00.15 teaches TM03 Water Pulse, which only Misty gives. open_item() now tells a TM CASE whose list was read without the TM (NOT_IN_CASE) from a bag or case that didn't open (FAILED); NOT_IN_CASE ends the step NO_ITEM, logged in orange and a success. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG_AutoStoryAbilities.cpp | 3 +- .../PokemonFRLG_AutoStoryAbilities.h | 3 +- .../PokemonFRLG_AutoStoryAbilities_Tests.cpp | 4 ++- .../AutoStory/PokemonFRLG_AutoStoryTeach.cpp | 13 +++++++-- .../AutoStory/PokemonFRLG_AutoStoryTeach.h | 19 +++++++++++-- .../PokemonFRLG_AutoStoryTeachScreens.cpp | 28 ++++++++++--------- .../PokemonFRLG_AutoStoryTeachScreens.h | 6 ++-- ...okemonFRLG_AutoStoryTeachScreens_Tests.cpp | 4 +-- .../PokemonFRLG_AutoStoryTeach_Tests.cpp | 23 +++++++++++---- 9 files changed, 72 insertions(+), 31 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp index fe2c3e7559..d02816e771 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp @@ -26,7 +26,8 @@ Outcome mart(Logger& logger, const MartPlan& plan, StoryAbilities& abilities){ Outcome teach(Logger& logger, const TeachPlan& plan, StoryAbilities& abilities){ const TeachResult result = run_teach(logger, abilities.teach, abilities.members, plan); - if (result.end == TeachEnd::LEARNED || result.end == TeachEnd::ALREADY_KNOWN){ + // 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)); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h index 03e7df25e0..2a61bfb467 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h @@ -43,7 +43,8 @@ struct StoryAbilities{ // 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 succeeds, with the reason logged. +// 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 ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp index 30dd927749..4830597a18 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -44,7 +44,8 @@ class StubMart : public MartActions{ class StubTeach : public TeachActions{ public: - virtual bool open_item(std::string_view, std::string_view) override{ return false; } + // 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{} @@ -139,6 +140,7 @@ std::vector step_cases(){ {"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"}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp index d2c904826b..2805fdf7df 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp @@ -30,6 +30,7 @@ const char* teach_end_name(TeachEnd end){ 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 "?"; @@ -159,7 +160,12 @@ class TeachRun{ if (decision.forget){ m_result.forgot = member->moves[*decision.forget]; } - if (!m_actions.open_item(m_plan.item, m_plan.move)){ + 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: return leave(TeachEnd::FAILED, std::format("couldn't open {} from the TM Case", m_plan.item)); } if (!teach(decision.forget)){ @@ -252,7 +258,8 @@ class TeachRun{ TeachResult run_teach(Logger& logger, TeachActions& actions, const MemberReader& reader, const TeachPlan& plan){ TeachResult result = TeachRun(actions, reader, plan).run(); - logger.log(teach_message(plan, result), result.end == TeachEnd::LEARNED ? COLOR_BLACK : COLOR_RED); + 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; } @@ -265,6 +272,8 @@ std::string teach_message(const TeachPlan& plan, const TeachResult& result){ : 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 index ff8156aa9d..7914d115f3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h @@ -20,6 +20,9 @@ * 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 @@ -107,6 +110,15 @@ enum class ForgetEnd{ 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{ @@ -114,9 +126,8 @@ class TeachActions{ virtual ~TeachActions() = default; // From the overworld: the bag, the TM Case, `item` (which holds - // `move`), USE, to the party menu. False if the item isn't there or the - // party didn't show. - virtual bool open_item(std::string_view item, std::string_view move) = 0; + // `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). @@ -134,6 +145,8 @@ enum class TeachEnd{ 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); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp index 65ca21fab1..0aa892e240 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp @@ -107,40 +107,42 @@ bool ScreenTeachActions::to_key_items(){ return false; } -bool ScreenTeachActions::open_row(TeachScreen screen, std::string_view name){ +ItemOpen ScreenTeachActions::open_row(TeachScreen screen, std::string_view name){ const std::optional view = wait_for(screen); if (!view){ - return false; + 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); - return false; + // 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 false; + return ItemOpen::FAILED; } press(TeachPress::A); if (!wait_for(TeachScreen::ITEM_MENU) || !move_cursor_to(TeachScreen::ITEM_MENU, 0)){ - return false; + return ItemOpen::FAILED; } press(TeachPress::A); - return true; + return ItemOpen::OPENED; } -bool ScreenTeachActions::open_item(std::string_view item, std::string_view move){ +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 false; + return ItemOpen::FAILED; } - if (!to_key_items() || !open_row(TeachScreen::BAG, "tm-case")){ - return false; + if (!to_key_items() || open_row(TeachScreen::BAG, "tm-case") != ItemOpen::OPENED){ + return ItemOpen::FAILED; } - if (!open_row(TeachScreen::TM_CASE, move)){ + 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 false; + return opened; } - return wait_for(TeachScreen::PARTY_PROMPT).has_value(); + return wait_for(TeachScreen::PARTY_PROMPT).has_value() ? ItemOpen::OPENED : ItemOpen::FAILED; } TeachPrompt ScreenTeachActions::choose_member(size_t slot){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h index 237600cf5c..6cf4ad4488 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h @@ -94,7 +94,7 @@ class ScreenTeachActions : public TeachActions{ public: ScreenTeachActions(Logger& logger, TeachScreens& screens); - virtual bool open_item(std::string_view item, std::string_view move) override; + 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; @@ -108,8 +108,8 @@ class ScreenTeachActions : public TeachActions{ // 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). - bool open_row(TeachScreen screen, std::string_view name); + // 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(); void press(TeachPress press); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp index 5d1883820e..7d28ffbb2e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp @@ -365,9 +365,9 @@ std::vector screens_cases(){ .moves = {"bite", "bubble", "withdraw", "water-pulse"}, }, { - .name = "no TM03 in the TM CASE: back to the overworld", + .name = "no TM03 in the TM CASE: skipped, back to the overworld", .setup = no_tm03, - .end = TeachEnd::FAILED, + .end = TeachEnd::NO_ITEM, .moves = {"bite", "tail-whip", "bubble", "withdraw"}, }, { diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp index 72f44f0d41..ba53f44543 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp @@ -56,6 +56,8 @@ class FakeTeachGame : public TeachActions{ 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 = {}; @@ -73,16 +75,20 @@ class FakeTeachGame : public TeachActions{ } return info; } - virtual bool open_item(std::string_view item, std::string_view) override{ + 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 false; + return ItemOpen::NOT_IN_CASE; } m_item = found->first; m_screen = Screen::CHOOSE_MEMBER; - return true; + return ItemOpen::OPENED; } virtual TeachPrompt choose_member(size_t slot) override{ if (m_screen != Screen::CHOOSE_MEMBER || slot >= party.size()){ @@ -278,11 +284,18 @@ std::vector teach_cases_3(){ .opened = false, }, { - .name = "an item the TM Case hasn't got", + .name = "an item the TM Case hasn't got: skipped", .plan = {.item = "hm05", .move = "flash", .member = 2, .forget_move = "acid"}, - .end = TeachEnd::FAILED, + .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"}, From b88e7cd602f1cb65b6212fe0d9c4f2620291928a Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 07:51:34 -0800 Subject: [PATCH 08/10] FRLG AutoStory GRIND: grind until the sim beats the next boss often enough GrindPlan takes a trainer (variant "beat=TRAINER_... chance=70"): the step then grinds until the battle sim's win chance against that trainer reaches min_chance (MIN_WIN_CHANCE, 70%), checked before the first battle and after each, with the member just read, healed, and the bag's Potions. Its level is then a cap: reached short of the chance, the step stops LEVEL_CAP with the level, the chance and the trainer in its message; the encounter cap still holds. The summary's stats now come with MemberInfo, and on the console the member read becomes the story's lead (lead_as_read()), so the boss's own check plays the same one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG_AutoStoryAbilities_Tests.cpp | 1 + .../AutoStory/PokemonFRLG_AutoStoryGrind.cpp | 98 ++++++++- .../AutoStory/PokemonFRLG_AutoStoryGrind.h | 46 ++++- .../PokemonFRLG_AutoStoryGrind_Tests.cpp | 186 +++++++++++++++++- .../AutoStory/PokemonFRLG_AutoStoryMember.cpp | 2 +- .../AutoStory/PokemonFRLG_AutoStoryMember.h | 9 +- 6 files changed, 322 insertions(+), 20 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp index 4830597a18..7fdb9cb13b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -61,6 +61,7 @@ class StubPatch : public GrindActions{ 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{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp index 5819c1792f..c29671588d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonTools/Async/InferenceRoutines.h" @@ -37,6 +38,8 @@ Direction opposite_direction(Direction 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"; @@ -50,11 +53,15 @@ const char* grind_end_name(GrindEnd end){ std::string grind_variant(const GrindPlan& plan){ - return std::format( + 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{ @@ -64,6 +71,10 @@ bool set_grind_word(GrindPlan& plan, std::string_view 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)){ @@ -85,6 +96,8 @@ bool set_grind_word(GrindPlan& plan, std::string_view word){ 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; } @@ -99,13 +112,16 @@ std::optional parse_grind_variant(std::string_view variant){ } 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="); } - if (!level_seen){ + // A chance needs a trainer to be against. + if (!level_seen || (chance_seen && plan.trainer.empty())){ return std::nullopt; } return plan; @@ -141,8 +157,8 @@ class GrindRun{ if (!read_level()){ return end(GrindEnd::UNREAD, "couldn't read the member's level"); } - if (reached()){ - return end(GrindEnd::REACHED, ""); + if (over()){ + return m_result; } while (true){ if (m_result.encounters >= m_plan.max_encounters){ @@ -154,8 +170,11 @@ class GrindRun{ if (!battle()){ return m_result; } - if (reached()){ - return heal() ? end(GrindEnd::REACHED, "") : end(GrindEnd::FAILED, "the last trip to the nurse failed"); + if (over()){ + if (m_result.end != GrindEnd::REACHED || heal()){ + return m_result; + } + return end(GrindEnd::FAILED, "the last trip to the nurse failed"); } } } @@ -167,16 +186,51 @@ class GrindRun{ return m_result; } bool read_level(){ - const std::optional member = m_reader(m_plan.member); + 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); } @@ -225,6 +279,7 @@ class GrindRun{ const MemberReader& m_reader; const GrindPlan& m_plan; size_t m_since_heal = 0; + MemberInfo m_member; GrindResult m_result; }; @@ -238,8 +293,12 @@ GrindResult run_grind(Logger& logger, GrindActions& actions, const MemberReader& 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, result.encounters, result.heals + "level {} of {}{}, {} encounters, {} trips to the nurse", level, plan.level, chance, result.encounters, result.heals ); if (result.end == GrindEnd::SHINY){ return std::format( @@ -253,6 +312,24 @@ std::string grind_message(const GrindPlan& plan, const GrindResult& result){ 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, @@ -307,6 +384,11 @@ 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; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h index 9921c2443c..a6b51cb8ec 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h @@ -3,7 +3,10 @@ * From: https://github.com/PokemonAutomation/ * * GRIND(who, where, level): fight wild battles in a patch until a party - * member reaches a level, then heal. The table stands the player in the + * 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. @@ -17,9 +20,8 @@ * nurse restores PP as well. It is bounded by encounters, and a * shiny stops it as it stops a capture: nothing pressed. * - * The level is read with a MemberReader before the first battle and after - * each win; the console has no summary reader yet, so there the step - * stops before its first battle. + * The member is read with a MemberReader before the first battle and + * after each win. * */ @@ -39,8 +41,11 @@ #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{ @@ -50,6 +55,8 @@ 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; @@ -57,13 +64,20 @@ struct GrindPlan{ 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. The step's target is the nurse. +// 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); @@ -99,10 +113,18 @@ class GrindActions{ // 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. @@ -120,6 +142,8 @@ struct GrindResult{ 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 = {}; }; @@ -128,6 +152,15 @@ GrindResult run_grind(Logger& logger, GrindActions& actions, const MemberReader& 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: on the patch's // tile, or one tile `pace` from it, as the last step taken left it. @@ -155,6 +188,9 @@ class ConsoleGrindActions : public GrindActions{ 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; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp index 8fd6424a19..16e871eb9f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp @@ -4,7 +4,9 @@ * * 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 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. * */ @@ -14,6 +16,7 @@ #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryBattleSim.h" #include "PokemonFRLG_AutoStoryGrind.h" namespace PokemonAutomation{ @@ -23,6 +26,8 @@ namespace PokemonFRLG{ namespace{ +constexpr std::string_view RIVAL = "TRAINER_RIVAL_CERULEAN_BULBASAUR"; + class QuietLogger : public Logger{ public: using Logger::log; @@ -44,10 +49,13 @@ class FakePatch : public GrindActions{ 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){ @@ -100,6 +108,20 @@ class FakePatch : public GrindActions{ 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; @@ -134,12 +156,31 @@ struct GrindCase{ 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 { { @@ -209,9 +250,55 @@ std::vector grind_cases_2(){ }; } +// 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()}){ + for (std::vector part : {grind_cases_1(), grind_cases_2(), grind_cases_3()}){ cases.insert(cases.end(), part.begin(), part.end()); } return cases; @@ -237,6 +324,13 @@ UnitTestResult check_grind_case(const GrindCase& item){ 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; } @@ -251,6 +345,77 @@ UnitTestResult test_grind(){ } +// 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; @@ -266,9 +431,21 @@ UnitTestResult test_grind_variant(){ ){ 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=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."; @@ -286,6 +463,9 @@ void add_tests_AutoStoryGrind(UnitTestDatabase& database){ }; 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_AutoStoryMember.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp index a88c6d9d32..5500e5e21f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.cpp @@ -21,7 +21,7 @@ MemberReader console_member_reader(ConsoleHandle& console, ProControllerContext& 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 = {}}; + MemberInfo info{.species = read->species, .level = read->level, .moves = {}, .stats = read->stats}; for (const SummaryMove& move : read->moves){ info.moves.push_back(move.move); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h index 2d437c640d..e2795c6c53 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMember.h @@ -2,9 +2,9 @@ * * From: https://github.com/PokemonAutomation/ * - * What the story reads about one party member: its species, level and - * moves, as the summary screen shows them (page 1: level; page 3: the - * four moves). The story's steps take them from a MemberReader, so their + * 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 @@ -29,6 +29,7 @@ #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{ @@ -47,6 +48,8 @@ struct MemberInfo{ // 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 From 574483de13b6db0ee767e1670919ebfcda252539 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 08:23:26 -0800 Subject: [PATCH 09/10] FRLG AutoStory GRIND/CAPTURE: find a battle whose flash was missed On console B (run m53) GRIND paced all 200 steps while "Wild RATTATA appeared!" waited for A: the battle's flash was missed and the D-pad does nothing in a battle. Pacing now also checks for the battle screen after each step, and before giving up checks the overworld once more, logging and saving a debug image if it doesn't show. GRIND and CAPTURE share the pacing loop through a PatchSteps seam, tested with a fake patch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG_AutoStoryCapture.cpp | 90 ++++++++++++++----- .../AutoStory/PokemonFRLG_AutoStoryCapture.h | 52 +++++++++++ .../PokemonFRLG_AutoStoryCapture_Tests.cpp | 84 +++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryGrind.cpp | 36 +------- .../AutoStory/PokemonFRLG_AutoStoryGrind.h | 9 +- 5 files changed, 209 insertions(+), 62 deletions(-) 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_AutoStoryGrind.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp index c29671588d..6393acf42b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp @@ -7,8 +7,6 @@ #include #include #include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleFlashWatcher.h" #include "PokemonFRLG_AutoStoryActions.h" #include "PokemonFRLG_AutoStoryGrind.h" #include "PokemonFRLG_AutoStoryVariantWords.h" @@ -20,21 +18,6 @@ namespace PokemonFRLG{ using Pokemon::Direction; -namespace{ - -Direction opposite_direction(Direction direction){ - switch (direction){ - case Direction::NORTH: return Direction::SOUTH; - case Direction::EAST: return Direction::WEST; - case Direction::SOUTH: return Direction::NORTH; - case Direction::WEST: return Direction::EAST; - } - return direction; -} - -} - - const char* grind_end_name(GrindEnd end){ switch (end){ case GrindEnd::REACHED: return "reached"; @@ -347,23 +330,8 @@ ConsoleGrindActions::ConsoleGrindActions( bool ConsoleGrindActions::find_encounter(Direction pace){ // As ConsoleCaptureActions::find_encounter(), keeping track of the // tile: a battle starts on the tile just stepped onto. - constexpr size_t MAX_STEPS = 200; - for (size_t c = 0; c < MAX_STEPS; c++){ - const Direction way = m_spot.displaced ? opposite_direction(pace) : 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}; - if (ret == 0){ - return true; - } - } - return false; + ConsolePatchSteps steps(m_console, m_context, pace, m_spot); + return pace_until_battle(m_console.logger(), steps, PACE_MAX_STEPS); } EncounterSeen ConsoleGrindActions::read_encounter(){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h index a6b51cb8ec..408278cfae 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h @@ -162,13 +162,8 @@ PartyMember lead_as_read(const MemberInfo& read, const PartyMember& tracked); std::optional healed_win_chance(PartyMember lead, int potions, std::string_view trainer); -// Where pacing left the player, for the trip to the nurse: on the patch's -// tile, or one tile `pace` from it, as the last step taken left it. -struct GrindSpot{ - bool displaced = false; - // The way the player faces after its last step; nothing before one. - std::optional facing = std::nullopt; -}; +// 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(), From 0b79952ace3b309c7a88605380f04b97e6bc5c13 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 08:23:26 -0800 Subject: [PATCH 10/10] FRLG AutoStory TEACH: page through the texts after a forget On console B (run m53) the teach worked but the step failed with "the moves page didn't answer": after A on the move to forget, the "Poof!", "forgot" and "learned" texts read as "other" and nothing was pressed. After the pick, B now pages through unplaced screens until the TM CASE (or the bag) shows; if neither does, the moves read afterwards decide. Every TEACH failure saves a debug image. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG_AutoStoryAbilities_Tests.cpp | 1 + .../AutoStory/PokemonFRLG_AutoStoryTeach.cpp | 17 +++++--- .../AutoStory/PokemonFRLG_AutoStoryTeach.h | 2 + .../PokemonFRLG_AutoStoryTeachScreens.cpp | 40 ++++++++++++++++--- .../PokemonFRLG_AutoStoryTeachScreens.h | 10 ++++- ...okemonFRLG_AutoStoryTeachScreens_Tests.cpp | 31 +++++++++++++- .../PokemonFRLG_AutoStoryTeach_Tests.cpp | 1 + 7 files changed, 89 insertions(+), 13 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp index 7fdb9cb13b..a0f06a450f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -50,6 +50,7 @@ class StubTeach : public TeachActions{ 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{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp index 2805fdf7df..8e1e45b00a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp @@ -166,13 +166,14 @@ class TeachRun{ 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 end(TeachEnd::FAILED, "the overworld didn't come back"); + return failed("leave-failed", "the overworld didn't come back"); } return confirm(decision.forget); } @@ -183,14 +184,20 @@ class TeachRun{ 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 this->end(TeachEnd::FAILED, "the overworld didn't come back"); + return failed("leave-failed", "the overworld didn't come back"); } return this->end(end, std::move(detail)); } - // Sets the result and gives up teaching. False. + // 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); @@ -236,14 +243,14 @@ class TeachRun{ TeachResult confirm(std::optional forget){ const std::optional after = m_reader(m_plan.member); if (!after || after->moves.empty()){ - return end(TeachEnd::FAILED, "couldn't read the moves after teaching"); + 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 end(TeachEnd::FAILED, std::format("{} isn't among its moves after teaching", m_plan.move)); + return failed("not-learned", std::format("{} isn't among its moves after teaching", m_plan.move)); } return end(TeachEnd::LEARNED, ""); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h index 7914d115f3..3756cc3fc0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h @@ -136,6 +136,8 @@ class TeachActions{ 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{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp index 0aa892e240..fdaa5b8d21 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp @@ -7,6 +7,7 @@ #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" @@ -192,19 +193,25 @@ TeachPrompt ScreenTeachActions::member_answer(){ 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: - // 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); - } + answer_to_forget(view); break; case TeachScreen::PARTY_TEXT: press(TeachPress::A); @@ -222,11 +229,23 @@ ForgetEnd ScreenTeachActions::forget(size_t slot){ } 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; } @@ -255,6 +274,10 @@ void ScreenTeachActions::stop_teaching(){ } } +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(); @@ -371,6 +394,11 @@ void ConsoleTeachScreens::press(TeachPress press){ 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); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h index 6cf4ad4488..8fbb380d00 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h @@ -18,7 +18,9 @@ * "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; B instead: "Stop trying to teach ?" + * 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. @@ -86,6 +88,8 @@ class TeachScreens{ 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; }; @@ -99,6 +103,7 @@ class ScreenTeachActions : public TeachActions{ 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. @@ -112,6 +117,8 @@ class ScreenTeachActions : public TeachActions{ 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; @@ -129,6 +136,7 @@ class ConsoleTeachScreens : public TeachScreens{ 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. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp index 7d28ffbb2e..d46eef5517 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp @@ -50,6 +50,8 @@ enum class FakeScreen{ TM_MENU, PROMPT, TEXT, + // Messages the reader doesn't place: "other". + UNREAD_TEXT, DELETE_YES_NO, STOP_YES_NO, KNOWN_MOVES, @@ -70,9 +72,14 @@ struct FakeTeachGame{ // 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 = {}; }; @@ -224,7 +231,10 @@ void press_known_moves(FakeTeachGame& game, TeachPress press){ } game.moves[game.cursor] = tm_move(game); use_up(game); - show_texts(game, {TeachText::UNKNOWN, TeachText::UNKNOWN}, FakeScreen::TM_CASE); + 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); @@ -253,6 +263,7 @@ void press_game(FakeTeachGame& game, TeachPress press){ } return; case FakeScreen::TEXT: + case FakeScreen::UNREAD_TEXT: game.texts.pop_front(); if (game.texts.empty()){ game.screen = game.after_texts; @@ -265,6 +276,7 @@ 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"; @@ -322,6 +334,9 @@ class FakeTeachScreens : public TeachScreens{ } return false; } + virtual void dump_screen(std::string_view label) override{ + m_game.dumps.emplace_back(label); + } private: FakeTeachGame& m_game; @@ -347,6 +362,9 @@ void three_moves(FakeTeachGame& game){ 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(); } @@ -354,6 +372,12 @@ void nothing_compatible(FakeTeachGame& game){ 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, @@ -410,6 +434,11 @@ UnitTestResult check_screens_case(const ScreensCase& item){ 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; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp index ba53f44543..514c3c5540 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp @@ -136,6 +136,7 @@ class FakeTeachGame : public TeachActions{ m_screen = Screen::OVERWORLD; return true; } + virtual void dump_screen(std::string_view) override{} private: enum class Screen{