diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp index aa8ef76ecb..034a90c164 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp @@ -4,6 +4,8 @@ * */ +#include +#include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "Tests/ImageUnitTest.h" @@ -122,6 +124,199 @@ static void add_tests_TeraEncounterAction(UnitTestDatabase& database){ } +namespace{ + +// Keeps every line logged, so a test can check the pass log. +class RecordingLogger : public Logger{ +public: + std::vector lines; + + virtual void log(const std::string& msg, Color) override{ + lines.push_back(msg); + } +}; + +std::string join(const std::vector& items, const std::string& separator){ + std::string ret; + for (const std::string& item : items){ + if (!ret.empty()){ + ret += separator; + } + ret += item; + } + return ret; +} + +// Auto Battle steps that report scripted kills, and charge each step the +// seconds measured on one live pass (bbq-m5 log, 2026-10-21). +class ScriptedAutoBattle : public BBQAutoBattleActions{ +public: + static constexpr int FLY_SECONDS = 20; // Fly to Chargestone, wait 3 s, walk in (~19.5 s). + static constexpr int CLEAR_SECONDS = 26; // Battling, then 6 s with no kill. + static constexpr int CLEAR_TAIL_SECONDS = 6; // Skipped when the clear stops at `stop_at_kills`. + static constexpr int RETURN_SECONDS = 28; // Fly back to Central Plaza. + static constexpr int HEAL_SECONDS = 28; // Walk to the nurse and heal (14 s), then re-fly (14 s). + + // Kills heard in each clear, in turn. Running past the end throws, which + // also stops a loop that would never end. + std::vector kills_per_clear; + + std::vector steps; + int seconds = 0; + + virtual uint64_t kills() const override{ + return m_kills; + } + virtual WallClock now() const override{ + return WallClock{} + std::chrono::seconds(seconds); + } + virtual void fly_to_battle_area() override{ + steps.push_back("fly"); + seconds += FLY_SECONDS; + } + virtual std::optional clear(uint64_t stop_at_kills) override{ + if (m_clears >= kills_per_clear.size()){ + throw std::runtime_error("Cleared more often than scripted."); + } + steps.push_back("clear"); + seconds += CLEAR_SECONDS; + m_kills += kills_per_clear[m_clears++]; + if (m_kills >= stop_at_kills){ + seconds -= CLEAR_TAIL_SECONDS; + } + return std::nullopt; + } + virtual void return_to_plaza() override{ + steps.push_back("return"); + seconds += RETURN_SECONDS; + } + virtual void heal() override{ + steps.push_back("heal"); + seconds += HEAL_SECONDS; + } + +private: + uint64_t m_kills = 0; + size_t m_clears = 0; +}; + +// One pass as it shows in the expected steps. +const std::string PASS = "fly clear return heal"; + +std::string passes(int count){ + std::vector ret(count, PASS); + return join(ret, " "); +} + +struct BBQAutoBattleScenario{ + std::string name; + uint64_t kill_target = 10; + std::vector kills_per_clear; + bool expected_endless = false; // Runs past the script without stopping. + std::string expected_steps; + int expected_seconds = 0; + std::vector expected_log = {}; // Checked when not empty. +}; + +class Test_BBQAutoBattle : public UnitTest{ +public: + Test_BBQAutoBattle(BBQAutoBattleScenario scenario) + : UnitTest("PokemonSV::BBQAutoBattle - " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + ScriptedAutoBattle actions; + actions.kills_per_clear = m_scenario.kills_per_clear; + + RecordingLogger logger; + BBQAutoBattlePolicy policy; + policy.kill_target = m_scenario.kill_target; + bool endless = false; + try{ + run_auto_battle(logger, actions, policy); + }catch (const std::runtime_error&){ + endless = true; + } + if (endless != m_scenario.expected_endless){ + return endless + ? "Expected the loop to stop, but it cleared more often than scripted." + : "Expected the loop to run past the script, but it stopped."; + } + const std::string steps = join(actions.steps, " "); + if (steps != m_scenario.expected_steps){ + return "Expected steps: " + m_scenario.expected_steps + "\nActual steps: " + steps; + } + if (actions.seconds != m_scenario.expected_seconds){ + return "Expected " + std::to_string(m_scenario.expected_seconds) + " seconds, got " + + std::to_string(actions.seconds); + } + if (!m_scenario.expected_log.empty() && logger.lines != m_scenario.expected_log){ + return "Expected log:\n" + join(m_scenario.expected_log, "\n") + + "\nActual log:\n" + join(logger.lines, "\n"); + } + return true; + } + +private: + const BBQAutoBattleScenario m_scenario; +}; + +} + +static void add_tests_BBQAutoBattle(UnitTestDatabase& database){ + constexpr int PASS_SECONDS = ScriptedAutoBattle::FLY_SECONDS + ScriptedAutoBattle::CLEAR_SECONDS + + ScriptedAutoBattle::RETURN_SECONDS + ScriptedAutoBattle::HEAL_SECONDS; + const BBQAutoBattleScenario scenarios[] = { + { + // The final pass still heals and re-flies, though the quest is done. + .name = "auto battle 10 at 2 kills per pass", + .kills_per_clear = {2, 2, 2, 2, 2}, + .expected_steps = passes(5), + .expected_seconds = 5 * PASS_SECONDS, + .expected_log = { + "Auto Battle pass 1: 2 kills, 2/10 in total, HP ?, 46 s elapsed. Below the target: return, heal and go again.", + "Auto Battle pass 2: 2 kills, 4/10 in total, HP ?, 148 s elapsed. Below the target: return, heal and go again.", + "Auto Battle pass 3: 2 kills, 6/10 in total, HP ?, 250 s elapsed. Below the target: return, heal and go again.", + "Auto Battle pass 4: 2 kills, 8/10 in total, HP ?, 352 s elapsed. Below the target: return, heal and go again.", + "Auto Battle pass 5: 2 kills, 10/10 in total, HP ?, 454 s elapsed. Target reached: return and heal.", + }, + }, + { + .name = "auto battle 30 at 3 kills per pass", + .kill_target = 30, + .kills_per_clear = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, + .expected_steps = passes(10), + .expected_seconds = 10 * PASS_SECONDS, + }, + { + // A clear keeps going while kills are heard, past the target. + .name = "kills past the target", + .kills_per_clear = {4, 4, 4}, + .expected_steps = passes(3), + .expected_seconds = 3 * PASS_SECONDS, + }, + { + .name = "passes with no kill go again", + .kills_per_clear = {0, 0, 5, 0, 5}, + .expected_steps = passes(5), + .expected_seconds = 5 * PASS_SECONDS, + }, + { + // Nothing bounds the loop: with no kills it never ends. + .name = "no kills never stops", + .kills_per_clear = {0, 0, 0, 0, 0, 0}, + .expected_endless = true, + .expected_steps = passes(6) + " fly", + .expected_seconds = 6 * PASS_SECONDS + ScriptedAutoBattle::FLY_SECONDS, + }, + }; + for (const BBQAutoBattleScenario& scenario : scenarios){ + database.add(scenario); + } +} + + void add_tests_BBQ(UnitTestDatabase& database){ database.add(); @@ -134,6 +329,7 @@ void add_tests_BBQ(UnitTestDatabase& database){ database.add("PokemonSV/BlueberryPoints/6740.png", 6740, 1280, 720); add_tests_TeraEncounterAction(database); + add_tests_BBQAutoBattle(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp index c90bae7a04..75e9c06f72 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp @@ -4,6 +4,9 @@ * */ +#include +#include +#include #include #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/Tools/ErrorDumper.h" @@ -27,6 +30,7 @@ #include "VideoGames/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" #include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" #include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" +#include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" #include "VideoGames/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" #include "VideoGames/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" #include "VideoGames/PokemonSV/Programs/PokemonSV_MenuNavigation.h" @@ -1244,75 +1248,170 @@ void quest_tera_raid( day_skip_from_overworld(console, context); } -void quest_auto_battle( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest +BBQAutoBattleResult run_auto_battle( + Logger& logger, + BBQAutoBattleActions& actions, + const BBQAutoBattlePolicy& policy ){ - stream.log("Quest: Auto Battle 10/30"); - - - OverworldSensors sensors( - env.logger(), stream, context - ); - - LetsGoEncounterBotStats stats; - LetsGoEncounterBotTracker tracker( - env, stream, - stats, - sensors.lets_go_kill - ); - - uint64_t target_number = 10; + const WallClock start = actions.now(); + uint64_t pass = 0; + while (actions.kills() < policy.kill_target){ + pass++; + const uint64_t kills_before = actions.kills(); + + actions.fly_to_battle_area(); + //Clear until no kill has been heard for 6 seconds, even past the target. + const std::optional hp = actions.clear(std::numeric_limits::max()); + + const uint64_t kills = actions.kills(); + const auto elapsed = std::chrono::duration_cast(actions.now() - start); + const std::string hp_text = hp ? std::to_string((int)std::floor(*hp * 100)) + "%" : "?"; + + std::optional end; + std::string next = "Below the target: return, heal and go again."; + if (kills >= policy.kill_target){ + end = BBQAutoBattleResult::TargetReached; + next = "Target reached: return and heal."; + } + logger.log( + "Auto Battle pass " + std::to_string(pass) + ": " + + std::to_string(kills - kills_before) + " kills, " + + std::to_string(kills) + "/" + std::to_string(policy.kill_target) + " in total, " + + "HP " + hp_text + ", " + + std::to_string(elapsed.count()) + " s elapsed. " + + next + ); - if (current_quest == BBQuests::auto_30){ - target_number = 30; + actions.return_to_plaza(); + actions.heal(); + if (end){ + return *end; + } } + return BBQAutoBattleResult::TargetReached; +} - while (stats.m_kills < target_number){ - - central_to_chargestone(env.program_info(), stream, context); +namespace{ + +class ConsoleBBQAutoBattleActions : public BBQAutoBattleActions{ +public: + ConsoleBBQAutoBattleActions( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotStats& stats, + LetsGoEncounterBotTracker& tracker, + LetsGoHpWatcher& hp_watcher + ) + : m_env(env), m_stream(stream), m_context(context) + , m_stats(stats), m_tracker(tracker), m_hp_watcher(hp_watcher) + {} + + virtual uint64_t kills() const override{ + return m_stats.m_kills; + } + virtual WallClock now() const override{ + return current_time(); + } + virtual void fly_to_battle_area() override{ + central_to_chargestone(m_env.program_info(), m_stream, m_context); //Wait for spawns - pbf_wait(context, 3000ms); - context.wait_for_all_requests(); + pbf_wait(m_context, 3000ms); + m_context.wait_for_all_requests(); //Forward and right, stay in the battle court - safe zone - pbf_press_button(context, BUTTON_L, 160ms, 400ms); - pbf_move_left_joystick(context, {0, +1}, 2000ms, 400ms); - pbf_move_left_joystick(context, {+1, 0}, 1440ms, 400ms); - pbf_press_button(context, BUTTON_L, 160ms, 400ms); + pbf_press_button(m_context, BUTTON_L, 160ms, 400ms); + pbf_move_left_joystick(m_context, {0, +1}, 2000ms, 400ms); + pbf_move_left_joystick(m_context, {+1, 0}, 1440ms, 400ms); + pbf_press_button(m_context, BUTTON_L, 160ms, 400ms); + } + virtual std::optional clear(uint64_t stop_at_kills) override{ + //The watcher runs for the whole quest. Forget what it read before this clear, so a reading + //from an earlier pass is never reported as this one's. + m_hp_watcher.clear(); - use_lets_go_to_clear_in_front(stream, context, tracker, false, [&](ProControllerContext& context){ + use_lets_go_to_clear_in_front(m_stream, m_context, m_tracker, false, [&](ProControllerContext& context){ pbf_move_left_joystick(context, {0, -1}, 1440ms, 400ms); pbf_wait(context, 12000ms); context.wait_for_all_requests(); - }); + }, + [&]{ return m_stats.m_kills >= stop_at_kills; } + ); - context.wait_for_all_requests(); - return_to_plaza(env.program_info(), stream, context); + m_context.wait_for_all_requests(); - OverworldWatcher done_healing(stream.logger(), COLOR_BLUE); - pbf_move_left_joystick(context, {0, +1}, 800ms, 160ms); + //Read before leaving: the HP bar is only on screen in the overworld with the lead out. + const double hp = m_hp_watcher.last_known_value(); + if (hp <= 0){ + return std::nullopt; + } + return hp; + } + virtual void return_to_plaza() override{ + PokemonSV::return_to_plaza(m_env.program_info(), m_stream, m_context); + } + virtual void heal() override{ + OverworldWatcher done_healing(m_stream.logger(), COLOR_BLUE); + pbf_move_left_joystick(m_context, {0, +1}, 800ms, 160ms); - pbf_mash_button(context, BUTTON_A, 2400ms); - context.wait_for_all_requests(); + pbf_mash_button(m_context, BUTTON_A, 2400ms); + m_context.wait_for_all_requests(); int exit = run_until( - stream, context, + m_stream, m_context, [&](ProControllerContext& context){ pbf_mash_button(context, BUTTON_B, 16000ms); }, { { done_healing } } ); if (exit == 0){ - stream.log("Overworld detected."); + m_stream.log("Overworld detected."); } - open_map_from_overworld(env.program_info(), stream, context); - pbf_press_button(context, BUTTON_ZL, 320ms, 800ms); - fly_to_overworld_from_map(env.program_info(), stream, context); + open_map_from_overworld(m_env.program_info(), m_stream, m_context); + pbf_press_button(m_context, BUTTON_ZL, 320ms, 800ms); + fly_to_overworld_from_map(m_env.program_info(), m_stream, m_context); + } + +private: + ProgramEnvironment& m_env; + VideoStream& m_stream; + ProControllerContext& m_context; + LetsGoEncounterBotStats& m_stats; + LetsGoEncounterBotTracker& m_tracker; + LetsGoHpWatcher& m_hp_watcher; +}; + +} + +void quest_auto_battle( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +){ + stream.log("Quest: Auto Battle 10/30"); + + + OverworldSensors sensors( + env.logger(), stream, context + ); + + LetsGoEncounterBotStats stats; + LetsGoEncounterBotTracker tracker( + env, stream, + stats, + sensors.lets_go_kill + ); + + BBQAutoBattlePolicy policy; + policy.kill_target = 10; + + if (current_quest == BBQuests::auto_30){ + policy.kill_target = 30; } + + ConsoleBBQAutoBattleActions actions(env, stream, context, stats, tracker, sensors.lets_go_hp); + run_auto_battle(stream.logger(), actions, policy); } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h index 21ad16aa71..d643fa3ce3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h @@ -7,7 +7,10 @@ #ifndef PokemonAutomation_PokemonSV_BlueberryQuests_H #define PokemonAutomation_PokemonSV_BlueberryQuests_H +#include #include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Logging/AbstractLogger.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" @@ -159,6 +162,52 @@ void quest_auto_battle( BBQuests current_quest ); +//The game steps of one Auto Battle pass. They are injected so that the loop's decisions (when +//to go again, when to stop) run in tests without a Switch. +class BBQAutoBattleActions{ +public: + virtual ~BBQAutoBattleActions() = default; + + //Kills heard since the quest started. Kills are counted as they are heard, in any step. + virtual uint64_t kills() const = 0; + + //The current time, to time the passes. + virtual WallClock now() const = 0; + + //Fly from Central Plaza to Chargestone Cavern, wait for spawns, and walk into the battle court. + virtual void fly_to_battle_area() = 0; + + //Send the lead out with Let's Go until no kill has been heard for 6 seconds, or until + //kills() reaches `stop_at_kills`, whichever comes first. Returns the lead's last known HP, + //from 0 to 1, or nothing if it could not be read. + virtual std::optional clear(uint64_t stop_at_kills) = 0; + + //Fly back to Central Plaza. Leaving the cave respawns its Pokemon. + virtual void return_to_plaza() = 0; + + //Walk to the nurse and heal, then fly to the Central Plaza fly point again: the flight to + //Chargestone moves the map cursor from there. + virtual void heal() = 0; +}; + +struct BBQAutoBattlePolicy{ + uint64_t kill_target = 10; +}; + +//Why run_auto_battle() returned. +enum class BBQAutoBattleResult{ + TargetReached, +}; + +//Clear Chargestone Cavern, one pass at a time, until the kills reach the target, and return why +//it stopped. It ends at Central Plaza, where the next quest starts. Logs one line per pass: its +//kills, the total, the lead's HP, the time spent, and what happens next. +BBQAutoBattleResult run_auto_battle( + Logger& logger, + BBQAutoBattleActions& actions, + const BBQAutoBattlePolicy& policy +); + } } } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp index d21bb3b405..e3c7070f7c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp @@ -176,7 +176,8 @@ bool use_lets_go_to_clear_in_front( VideoStream& stream, ProControllerContext& context, LetsGoEncounterBotTracker& tracker, bool throw_ball_if_bubble, - std::function&& command + std::function&& command, + std::function stop_early ){ // ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = env.current_stats(); @@ -213,12 +214,22 @@ bool use_lets_go_to_clear_in_front( command(context); context.wait_for_all_requests(); command = nullptr; + }else if (stop_early){ + // Wait in short steps, so the clear ends soon after `stop_early` is met. + while (current_time() < tracker.last_kill() + timeout && !stop_early()){ + context.wait_until(std::min(tracker.last_kill() + timeout, current_time() + Milliseconds(200))); + } }else{ // cout << "Waiting out... " << timeout.count() << " seconds" << endl; context.wait_until(tracker.last_kill() + timeout); } // timeout = std::chrono::seconds(3); + if (stop_early && stop_early()){ + stream.log("Stopping the clear early."); + break; + } + WallClock now = current_time(); WallClock last_kill_time = tracker.last_kill(); WallDuration last_kill; diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h index 3e06d2019a..bb2c73ec98 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h @@ -165,11 +165,14 @@ class LetsGoEncounterBotTracker{ // chain has ended. // The function tracks kill chain by sound detection from `tracker`. The function // does not handle any pokemon battle encounters (turn-based battles). +// If `stop_early` is set, it is checked after the command and while waiting +// for the kill chain to end, and the function returns once it is true. bool use_lets_go_to_clear_in_front( VideoStream& stream, ProControllerContext& context, LetsGoEncounterBotTracker& tracker, bool throw_ball_if_bubble, - std::function&& command + std::function&& command, + std::function stop_early = nullptr );