diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.cpp index 431763d87c..2658d8da07 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.cpp @@ -185,6 +185,11 @@ BBQOption::BBQOption(OCR::LanguageOCROption* language_option) "Hatch Quest - Fix time for eggs:
Fix the time before doing a hatch egg quest.", LockMode::UNLOCK_WHILE_RUNNING, false ) + , AUTO_BATTLE_HEAL_PERCENT( + "Auto Battle Quest - Heal Below HP %:
Between passes, heal at the Pokemon Center only if your lead's HP is below this percentage. " + "If its HP could not be read, heal anyway.", + LockMode::UNLOCK_WHILE_RUNNING, 50, 0, 100 + ) , CATCH_ON_WIN(true) , NUM_RETRIES( "Number of Retries:
Reattempt a quest this many times if it fails.", @@ -207,6 +212,7 @@ BBQOption::BBQOption(OCR::LanguageOCROption* language_option) PA_ADD_OPTION(NUM_EGGS); PA_ADD_OPTION(OUT_OF_EGGS); PA_ADD_OPTION(FIX_TIME_FOR_HATCH); + PA_ADD_OPTION(AUTO_BATTLE_HEAL_PERCENT); PA_ADD_OPTION(BATTLE_AI); PA_ADD_OPTION(CATCH_ON_WIN); PA_ADD_OPTION(NUM_RETRIES); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h index f5715a10c7..ab37cc67c1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h @@ -93,6 +93,9 @@ class BBQOption : public GroupOption{ EnumDropdownOption OUT_OF_EGGS; BooleanCheckBoxOption FIX_TIME_FOR_HATCH; + //Auto battle quest + SimpleIntegerOption AUTO_BATTLE_HEAL_PERCENT; + //Tera raid TeraAIOption BATTLE_AI; TeraFarmerCatchOnWin CATCH_ON_WIN; diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp index aa8ef76ecb..c66c6adbfe 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,456 @@ 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). + static constexpr int BOARD_SECONDS = 5; // Open the quest panel, read it, close it. + + // 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; + // The lead's HP read in each clear, in turn. Past the end, it is unknown. + std::vector> hp_per_clear; + // Kills heard on each flight back, in turn: the lead finishing a kill + // after the clear ends. Past the end, none. + std::vector kills_per_return; + // Whether each board read finds the quest, in turn. Past the end, it does. + std::vector quest_on_board_per_read; + + 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; + const std::optional hp = m_clears < hp_per_clear.size() ? hp_per_clear[m_clears] : std::nullopt; + m_kills += kills_per_clear[m_clears++]; + if (m_kills >= stop_at_kills){ + seconds -= CLEAR_TAIL_SECONDS; + } + return hp; + } + virtual void return_to_plaza() override{ + steps.push_back("return"); + seconds += RETURN_SECONDS; + if (m_returns < kills_per_return.size()){ + m_kills += kills_per_return[m_returns]; + } + m_returns++; + } + virtual bool quest_on_board() override{ + steps.push_back("board"); + seconds += BOARD_SECONDS; + const bool on_board = m_reads >= quest_on_board_per_read.size() || quest_on_board_per_read[m_reads]; + m_reads++; + return on_board; + } + virtual void heal() override{ + steps.push_back("heal"); + seconds += HEAL_SECONDS; + } + +private: + uint64_t m_kills = 0; + size_t m_clears = 0; + size_t m_returns = 0; + size_t m_reads = 0; +}; + +// One pass as it shows in the expected steps. +const std::string PASS = "fly clear return heal"; +// A pass that returns without healing. +const std::string LAST_PASS = "fly clear return"; + +std::string passes(int count, const std::string& pass = PASS){ + std::vector ret(count, pass); + return join(ret, " "); +} + +std::string auto_battle_result_to_string(BBQAutoBattleResult result){ + switch (result){ + case BBQAutoBattleResult::TargetReached: return "TargetReached"; + case BBQAutoBattleResult::NoKills: return "NoKills"; + case BBQAutoBattleResult::TimeLimit: return "TimeLimit"; + case BBQAutoBattleResult::QuestDone: return "QuestDone"; + } + return "?"; +} + +struct BBQAutoBattleScenario{ + std::string name; + uint64_t kill_target = 10; + int time_limit_minutes = 35; + std::vector kills_per_clear; + std::vector> hp_per_clear = {}; // Unknown when not given. + std::vector kills_per_return = {}; // None when not given. + uint64_t check_board_within_kills = 0; // Off unless a scenario tests it. + std::vector quest_on_board_per_read = {}; // On the board when not given. + int heal_below_hp_percent = 50; + BBQAutoBattleResult expected_result = BBQAutoBattleResult::TargetReached; + 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; + actions.hp_per_clear = m_scenario.hp_per_clear; + actions.kills_per_return = m_scenario.kills_per_return; + actions.quest_on_board_per_read = m_scenario.quest_on_board_per_read; + + RecordingLogger logger; + BBQAutoBattlePolicy policy; + policy.kill_target = m_scenario.kill_target; + policy.time_limit = std::chrono::minutes(m_scenario.time_limit_minutes); + policy.heal_below_hp_percent = (uint8_t)m_scenario.heal_below_hp_percent; + policy.check_board_within_kills = m_scenario.check_board_within_kills; + BBQAutoBattleResult result; + try{ + result = run_auto_battle(logger, actions, policy); + }catch (const std::runtime_error&){ + return "Expected the loop to stop, but it cleared more often than scripted."; + } + if (result != m_scenario.expected_result){ + return "Expected " + auto_battle_result_to_string(m_scenario.expected_result) + + ", got " + auto_battle_result_to_string(result); + } + 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; + constexpr int LAST_PASS_SAVED_SECONDS = ScriptedAutoBattle::CLEAR_TAIL_SECONDS + ScriptedAutoBattle::HEAL_SECONDS; + const BBQAutoBattleScenario scenarios[] = { + { + // The final pass stops clearing at the target, and skips the heal and re-fly. + .name = "auto battle 10 at 2 kills per pass", + .kills_per_clear = {2, 2, 2, 2, 2}, + .expected_steps = passes(4) + " " + LAST_PASS, + .expected_seconds = 5 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS, + .expected_log = { + "Auto Battle pass 1: 2 kills, 2/10 in total, HP ?, 46 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 2: 2 kills, 4/10 in total, HP ?, 148 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 3: 2 kills, 6/10 in total, HP ?, 250 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 4: 2 kills, 8/10 in total, HP ?, 352 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 5: 2 kills, 10/10 in total, HP ?, 448 s elapsed. Target reached: return without healing.", + }, + }, + { + .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(9) + " " + LAST_PASS, + .expected_seconds = 10 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS, + }, + { + // Kills heard before the clear can stop still count. + .name = "kills past the target", + .kills_per_clear = {4, 4, 4}, + .expected_steps = passes(2) + " " + LAST_PASS, + .expected_seconds = 3 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS, + }, + { + .name = "passes with no kill go again", + .kills_per_clear = {0, 0, 5, 0, 5}, + .expected_steps = passes(4) + " " + LAST_PASS, + .expected_seconds = 5 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS, + }, + { + .name = "gives up after 3 passes with no kill", + .kills_per_clear = {0, 0, 0}, + .expected_result = BBQAutoBattleResult::NoKills, + .expected_steps = passes(2) + " " + LAST_PASS, + .expected_seconds = 3 * PASS_SECONDS - ScriptedAutoBattle::HEAL_SECONDS, + .expected_log = { + "Auto Battle pass 1: 0 kills, 0/10 in total, HP ?, 46 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 2: 0 kills, 0/10 in total, HP ?, 148 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 3: 0 kills, 0/10 in total, HP ?, 250 s elapsed. No kill in 3 passes in a row: return and give up.", + }, + }, + { + // Only passes in a row count. + .name = "a kill resets the empty passes", + .kills_per_clear = {0, 0, 1, 0, 0, 0}, + .expected_result = BBQAutoBattleResult::NoKills, + .expected_steps = passes(5) + " " + LAST_PASS, + .expected_seconds = 6 * PASS_SECONDS - ScriptedAutoBattle::HEAL_SECONDS, + }, + { + // The pass that ends past the limit is the last. + .name = "gives up at the time limit", + .time_limit_minutes = 5, + .kills_per_clear = {1, 1, 1, 1}, + .expected_result = BBQAutoBattleResult::TimeLimit, + .expected_steps = passes(3) + " " + LAST_PASS, + .expected_seconds = 4 * PASS_SECONDS - ScriptedAutoBattle::HEAL_SECONDS, + .expected_log = { + "Auto Battle pass 1: 1 kills, 1/10 in total, HP ?, 46 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 2: 1 kills, 2/10 in total, HP ?, 148 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 3: 1 kills, 3/10 in total, HP ?, 250 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 4: 1 kills, 4/10 in total, HP ?, 352 s elapsed. Time limit of 5 min reached: return and give up.", + }, + }, + { + // Reaching the target counts as reached, even past the time limit. + .name = "target reached past the time limit", + .time_limit_minutes = 5, + .kills_per_clear = {3, 3, 3, 3}, + .expected_steps = passes(3) + " " + LAST_PASS, + .expected_seconds = 4 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS, + }, + { + // Same kills as "auto battle 10 at 2 kills per pass", 4 heals (112 s) faster. + .name = "high HP skips the heal", + .kills_per_clear = {2, 2, 2, 2, 2}, + .hp_per_clear = {0.8, 0.8, 0.8, 0.8, 0.8}, + .expected_steps = passes(5, LAST_PASS), + .expected_seconds = 5 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS - 4 * ScriptedAutoBattle::HEAL_SECONDS, + .expected_log = { + "Auto Battle pass 1: 2 kills, 2/10 in total, HP 80%, 46 s elapsed. Below the target and HP at or above 50%: return and go again without healing.", + "Auto Battle pass 2: 2 kills, 4/10 in total, HP 80%, 120 s elapsed. Below the target and HP at or above 50%: return and go again without healing.", + "Auto Battle pass 3: 2 kills, 6/10 in total, HP 80%, 194 s elapsed. Below the target and HP at or above 50%: return and go again without healing.", + "Auto Battle pass 4: 2 kills, 8/10 in total, HP 80%, 268 s elapsed. Below the target and HP at or above 50%: return and go again without healing.", + "Auto Battle pass 5: 2 kills, 10/10 in total, HP 80%, 336 s elapsed. Target reached: return without healing.", + }, + }, + { + // Same kills as "auto battle 30 at 3 kills per pass", 9 heals (252 s) faster. + .name = "high HP skips the heal in auto battle 30", + .kill_target = 30, + .kills_per_clear = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, + .hp_per_clear = {0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9}, + .expected_steps = passes(10, LAST_PASS), + .expected_seconds = 10 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS - 9 * ScriptedAutoBattle::HEAL_SECONDS, + }, + { + .name = "low HP heals", + .kills_per_clear = {2, 2, 2, 2, 2}, + .hp_per_clear = {0.3, 0.3, 0.3, 0.3, 0.3}, + .expected_steps = passes(4) + " " + LAST_PASS, + .expected_seconds = 5 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS, + .expected_log = { + "Auto Battle pass 1: 2 kills, 2/10 in total, HP 30%, 46 s elapsed. Below the target and HP below 50%: return, heal and go again.", + "Auto Battle pass 2: 2 kills, 4/10 in total, HP 30%, 148 s elapsed. Below the target and HP below 50%: return, heal and go again.", + "Auto Battle pass 3: 2 kills, 6/10 in total, HP 30%, 250 s elapsed. Below the target and HP below 50%: return, heal and go again.", + "Auto Battle pass 4: 2 kills, 8/10 in total, HP 30%, 352 s elapsed. Below the target and HP below 50%: return, heal and go again.", + "Auto Battle pass 5: 2 kills, 10/10 in total, HP 30%, 448 s elapsed. Target reached: return without healing.", + }, + }, + { + // Unknown HP heals, as every pass did before the threshold. + .name = "unknown HP heals", + .kills_per_clear = {2, 2, 2, 2, 2}, + .hp_per_clear = {0.8, std::nullopt, 0.8, std::nullopt, 0.8}, + .expected_steps = LAST_PASS + " " + PASS + " " + LAST_PASS + " " + PASS + " " + LAST_PASS, + .expected_seconds = 5 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS - 2 * ScriptedAutoBattle::HEAL_SECONDS, + }, + { + // HP at the threshold skips the heal; just below heals. + .name = "heal threshold boundary", + .kills_per_clear = {3, 3, 3, 3}, + .hp_per_clear = {0.5, 0.49, 0.5, 0.5}, + .expected_steps = LAST_PASS + " " + PASS + " " + LAST_PASS + " " + LAST_PASS, + .expected_seconds = 4 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS - 2 * ScriptedAutoBattle::HEAL_SECONDS, + .expected_log = { + "Auto Battle pass 1: 3 kills, 3/10 in total, HP 50%, 46 s elapsed. Below the target and HP at or above 50%: return and go again without healing.", + "Auto Battle pass 2: 3 kills, 6/10 in total, HP 49%, 120 s elapsed. Below the target and HP below 50%: return, heal and go again.", + "Auto Battle pass 3: 3 kills, 9/10 in total, HP 50%, 222 s elapsed. Below the target and HP at or above 50%: return and go again without healing.", + "Auto Battle pass 4: 3 kills, 12/10 in total, HP 50%, 290 s elapsed. Target reached: return without healing.", + }, + }, + { + .name = "a threshold of 100% heals unless HP is full", + .kills_per_clear = {4, 4, 4}, + .hp_per_clear = {1.0, 0.99, 1.0}, + .heal_below_hp_percent = 100, + .expected_steps = LAST_PASS + " " + PASS + " " + LAST_PASS, + .expected_seconds = 3 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS - ScriptedAutoBattle::HEAL_SECONDS, + }, + { + .name = "a threshold of 0% heals only when HP is unknown", + .kills_per_clear = {4, 4, 4}, + .hp_per_clear = {0.01, std::nullopt, 0.01}, + .heal_below_hp_percent = 0, + .expected_steps = LAST_PASS + " " + PASS + " " + LAST_PASS, + .expected_seconds = 3 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS - ScriptedAutoBattle::HEAL_SECONDS, + }, + { + // The limits still end the attempt when no pass heals. + .name = "gives up after 3 passes with no kill and high HP", + .kills_per_clear = {0, 0, 0}, + .hp_per_clear = {1.0, 1.0, 1.0}, + .expected_result = BBQAutoBattleResult::NoKills, + .expected_steps = passes(3, LAST_PASS), + .expected_seconds = 3 * (PASS_SECONDS - ScriptedAutoBattle::HEAL_SECONDS), + }, + { + // R3b: "pass 2: 1 kills, 4/10 in total" after "2/10". A kill heard after a pass's + // line counts in the next one, so the passes add up to the total. + .name = "a kill heard on the way back counts in the next pass", + .kills_per_clear = {2, 1, 3, 4}, + .kills_per_return = {1}, + .expected_steps = passes(3) + " " + LAST_PASS, + .expected_seconds = 4 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS, + .expected_log = { + "Auto Battle pass 1: 2 kills, 2/10 in total, HP ?, 46 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 2: 2 kills, 4/10 in total, HP ?, 148 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 3: 3 kills, 7/10 in total, HP ?, 250 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 4: 4 kills, 11/10 in total, HP ?, 346 s elapsed. Target reached: return without healing.", + }, + }, + { + // A pass whose only kill was heard on the previous flight back is not empty. + .name = "a kill heard on the way back resets the empty passes", + .kills_per_clear = {0, 0, 0, 0, 0, 0}, + .kills_per_return = {0, 1}, + .expected_result = BBQAutoBattleResult::NoKills, + .expected_steps = passes(5) + " " + LAST_PASS, + .expected_seconds = 6 * PASS_SECONDS - ScriptedAutoBattle::HEAL_SECONDS, + }, + { + .name = "a kill heard on the way back that reaches the target skips the heal", + .kills_per_clear = {3, 3, 3}, + .kills_per_return = {0, 0, 1}, + .expected_steps = passes(2) + " " + LAST_PASS, + .expected_seconds = 3 * PASS_SECONDS - ScriptedAutoBattle::HEAL_SECONDS, + .expected_log = { + "Auto Battle pass 1: 3 kills, 3/10 in total, HP ?, 46 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 2: 3 kills, 6/10 in total, HP ?, 148 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 3: 3 kills, 9/10 in total, HP ?, 250 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle: kills heard on the way back reached the target, 10/10. Stop without healing.", + }, + }, + { + // R3b: 9 kills heard, but the game had completed the quest. The board read + // replaces the 5th pass and its heal. + .name = "near the target, a board without the quest ends it", + .kills_per_clear = {3, 3, 3}, + .check_board_within_kills = 2, + .quest_on_board_per_read = {false}, + .expected_result = BBQAutoBattleResult::QuestDone, + .expected_steps = passes(2) + " " + LAST_PASS + " board", + .expected_seconds = 3 * PASS_SECONDS - ScriptedAutoBattle::HEAL_SECONDS + ScriptedAutoBattle::BOARD_SECONDS, + .expected_log = { + "Auto Battle pass 1: 3 kills, 3/10 in total, HP ?, 46 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 2: 3 kills, 6/10 in total, HP ?, 148 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 3: 3 kills, 9/10 in total, HP ?, 250 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle: the quest is no longer on the board at 9/10 kills heard. Stop: the game completed it.", + }, + }, + { + // Each pass near the target reads the board until the quest is gone. + .name = "near the target, a board with the quest goes again", + .kills_per_clear = {4, 4, 1, 1}, + .check_board_within_kills = 2, + .quest_on_board_per_read = {true, false}, + .expected_result = BBQAutoBattleResult::QuestDone, + .expected_steps = PASS + " " + LAST_PASS + " board heal " + LAST_PASS + " board", + .expected_seconds = 3 * PASS_SECONDS - ScriptedAutoBattle::HEAL_SECONDS + 2 * ScriptedAutoBattle::BOARD_SECONDS, + .expected_log = { + "Auto Battle pass 1: 4 kills, 4/10 in total, HP ?, 46 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle pass 2: 4 kills, 8/10 in total, HP ?, 148 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle: the quest is still on the board at 8/10 kills heard. Go again.", + "Auto Battle pass 3: 1 kills, 9/10 in total, HP ?, 255 s elapsed. Below the target and HP unknown: return, heal and go again.", + "Auto Battle: the quest is no longer on the board at 9/10 kills heard. Stop: the game completed it.", + }, + }, + { + // Far from the target the board is never read, and reaching the target + // needs no read. + .name = "far from the target, no board read", + .kills_per_clear = {5, 5}, + .check_board_within_kills = 2, + .quest_on_board_per_read = {false}, + .expected_steps = PASS + " " + LAST_PASS, + .expected_seconds = 2 * PASS_SECONDS - LAST_PASS_SAVED_SECONDS, + }, + { + // High HP skips the heal but not the read. + .name = "near the target with high HP, read the board without healing", + .kill_target = 30, + .kills_per_clear = {10, 10, 9, 1}, + .hp_per_clear = {0.9, 0.9, 0.9, 0.9}, + .check_board_within_kills = 2, + .expected_steps = passes(2, LAST_PASS) + " " + LAST_PASS + " board " + LAST_PASS, + .expected_seconds = 4 * (PASS_SECONDS - ScriptedAutoBattle::HEAL_SECONDS) - ScriptedAutoBattle::CLEAR_TAIL_SECONDS + ScriptedAutoBattle::BOARD_SECONDS, + }, + }; + for (const BBQAutoBattleScenario& scenario : scenarios){ + database.add(scenario); + } +} + + void add_tests_BBQ(UnitTestDatabase& database){ database.add(); @@ -134,6 +586,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..95627ca4c3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp @@ -4,6 +4,8 @@ * */ +#include +#include #include #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/Tools/ErrorDumper.h" @@ -27,6 +29,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 +1247,230 @@ 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; + uint64_t empty_passes = 0; + //The kill sound is heard in every step, not only while clearing: the lead can finish a kill + //after the clear ends, as the flight back starts. Each pass counts the kills since the last + //pass log, so a kill heard after it goes to the next pass and the passes add up to the total. + uint64_t kills_before = actions.kills(); + while (actions.kills() < policy.kill_target){ + pass++; + + actions.fly_to_battle_area(); + const std::optional hp = actions.clear(policy.kill_target); + + const uint64_t kills = actions.kills(); + empty_passes = kills == kills_before ? empty_passes + 1 : 0; + const auto elapsed = std::chrono::duration_cast(actions.now() - start); + + //Unknown HP heals, as every pass did before the threshold existed. The log rounds HP + //down, so it shows below the threshold exactly when it is. + const bool heal = !hp || *hp * 100 < policy.heal_below_hp_percent; + const std::string hp_text = hp ? std::to_string((int)std::floor(*hp * 100)) + "%" : "?"; + const std::string threshold_text = std::to_string(policy.heal_below_hp_percent) + "%"; + + std::optional end; + std::string next; + if (!hp){ + next = "Below the target and HP unknown: return, heal and go again."; + }else if (heal){ + next = "Below the target and HP below " + threshold_text + ": return, heal and go again."; + }else{ + next = "Below the target and HP at or above " + threshold_text + ": return and go again without healing."; + } + if (kills >= policy.kill_target){ + end = BBQAutoBattleResult::TargetReached; + next = "Target reached: return without healing."; + }else if (empty_passes >= policy.max_empty_passes){ + end = BBQAutoBattleResult::NoKills; + next = "No kill in " + std::to_string(empty_passes) + " passes in a row: return and give up."; + }else if (elapsed >= policy.time_limit){ + end = BBQAutoBattleResult::TimeLimit; + next = "Time limit of " + std::to_string(policy.time_limit.count()) + " min reached: return and give up."; + } + 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 + ); + kills_before = kills; - if (current_quest == BBQuests::auto_30){ - target_number = 30; + //The next quest starts from Central Plaza, so return even when done. + actions.return_to_plaza(); + if (end){ + return *end; + } + if (actions.kills() >= policy.kill_target){ + logger.log( + "Auto Battle: kills heard on the way back reached the target, " + + std::to_string(actions.kills()) + "/" + std::to_string(policy.kill_target) + + ". Stop without healing." + ); + return BBQAutoBattleResult::TargetReached; + } + //The heard count can fall short of the game's: a kill whose sound was missed still counts + //in game. Near the target, read the board before going again. The read (~5 s) costs much + //less than a pass and its heal. + if (actions.kills() + policy.check_board_within_kills >= policy.kill_target){ + const std::string count_text = std::to_string(actions.kills()) + "/" + std::to_string(policy.kill_target); + if (!actions.quest_on_board()){ + logger.log("Auto Battle: the quest is no longer on the board at " + count_text + " kills heard. Stop: the game completed it."); + return BBQAutoBattleResult::QuestDone; + } + logger.log("Auto Battle: the quest is still on the board at " + count_text + " kills heard. Go again."); + } + //Skipping the heal also skips its re-fly: return_to_plaza() already lands on the Central + //Plaza fly point, which is where the flight to Chargestone starts from. + if (heal){ + actions.heal(); + } } + 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, + const BBQOption& options, + BBQuests quest + ) + : m_env(env), m_stream(stream), m_context(context) + , m_stats(stats), m_tracker(tracker), m_hp_watcher(hp_watcher) + , m_options(options), m_quest(quest) + {} + + 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 bool quest_on_board() override{ + const std::vector quests = read_quests(m_env.program_info(), m_stream, m_context, m_options); + return std::find(quests.begin(), quests.end(), m_quest) != quests.end(); + } + 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; + const BBQOption& m_options; + BBQuests m_quest; +}; + +} + +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 + ); + + //The time limits are about 3x the slowest attempts seen with a correct lead. + BBQAutoBattlePolicy policy; + policy.kill_target = 10; + policy.time_limit = std::chrono::minutes(35); + + if (current_quest == BBQuests::auto_30){ + policy.kill_target = 30; + policy.time_limit = std::chrono::minutes(60); } + policy.heal_below_hp_percent = BBQ_OPTIONS.AUTO_BATTLE_HEAL_PERCENT; + + ConsoleBBQAutoBattleActions actions(env, stream, context, stats, tracker, sensors.lets_go_hp, BBQ_OPTIONS, current_quest); + 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..daca511d04 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,70 @@ 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; + + //At Central Plaza, read the quest panel. Returns whether this quest is still on it: the game + //removes a quest once it is completed. + virtual bool quest_on_board() = 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; + //Give up after this many passes in a row with no kill. + uint64_t max_empty_passes = 3; + //Give up after the pass that ends past this time. + std::chrono::minutes time_limit = std::chrono::minutes(35); + //Between passes, heal only if the lead's HP is below this percentage or unknown. + uint8_t heal_below_hp_percent = 50; + //After a pass that ends this close to the target, read the board before going again, and + //stop if the quest is gone. 0 never reads it. + uint64_t check_board_within_kills = 2; +}; + +//Why run_auto_battle() returned. +enum class BBQAutoBattleResult{ + TargetReached, + NoKills, //max_empty_passes passes in a row had no kill. + TimeLimit, + QuestDone, //The quest left the board before the heard kills reached the target. +}; + +//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. +//It gives up early when a limit in `policy` is reached; the board check then decides the quest +//failed. +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 );