diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp index e09313cee1..a3b3b05999 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp @@ -70,6 +70,20 @@ constexpr std::pair ENGLISH_ITEM_NAMES[] = { // Mt. Moon's, which top the pocket above the story's items. {"moon-stone", "Moon Stone"}, {"nugget", "Nugget"}, + // The rest of the Marts' stock. The Fuchsia Mart's ULTRA BALL row read + // as PARLYZ HEAL, the nearest name there was, and 12.01 bought + // nothing (console B, 2026-11-12). + {"great-ball", "Great Ball"}, + {"ultra-ball", "Ultra Ball"}, + {"hyper-potion", "Hyper Potion"}, + {"max-potion", "Max Potion"}, + {"revive", "Revive"}, + {"burn-heal", "Burn Heal"}, + {"ice-heal", "Ice Heal"}, + {"full-heal", "Full Heal"}, + {"x-attack", "X Attack"}, + {"x-defend", "X Defend"}, + {"dire-hit", "Dire Hit"}, {"cancel", "Cancel"}, }; @@ -241,7 +255,7 @@ class Test_Route17ItemNames : public UnitTest{ virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const ItemNameMatcher& matcher = ItemNameMatcher::instance(); - for (const std::string& text : {"FARE CANCY", "RARE CANOY", "RARE CANDY"}){ + for (const char* text : {"FARE CANCY", "RARE CANOY", "RARE CANDY"}){ const std::string item = matcher.match(Language::English, text); if (item != "rare-candy"){ return std::format("Expected \"{}\" read as rare-candy, got \"{}\".", text, item); @@ -337,6 +351,9 @@ void add_tests_ItemListReader(UnitTestDatabase& database){ database.add("PokemonFRLG/ItemListReader/ItemsPocketMoonStone_eng.png"); // The Viridian Mart's BUY list, the same day, the cursor on POTION. database.add("PokemonFRLG/ItemListReader/MartBuyList_eng.png"); + // The Fuchsia Mart's, the cursor on ULTRA BALL (console B, 2026-11-12): six + // rows, none of them in the reader's dictionary yet. + database.add("PokemonFRLG/ItemListReader/FuchsiaMartBuyList_eng.png"); database.add(); database.add(); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp index 1f2bc021b7..b7839f7106 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp @@ -128,6 +128,8 @@ constexpr std::string_view MAP_NAMES[] = { "Route18", "Route18_EastEntrance_1F", "FuchsiaCity", + // Fuchsia's Mart: Super Potions before Koga's gym (12.01). + "FuchsiaCity_Mart", // The Safari Zone, pokeguy's way through it: its entrance, the // center, east, north and west areas, and the Secret House (HM03). "FuchsiaCity_SafariZone_Entrance", @@ -136,6 +138,9 @@ constexpr std::string_view MAP_NAMES[] = { "SafariZone_North", "SafariZone_West", "SafariZone_SecretHouse", + // Koga's gym, and the Warden's house (GOLD TEETH for HM04). + "FuchsiaCity_Gym", + "FuchsiaCity_WardensHouse", "CeruleanCave_1F", "CeruleanCave_2F", "CeruleanCave_B1F", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 0acc5a3140..159281afb2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -54,6 +54,8 @@ #include "Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows_Tests.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryHealing.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.h" #include "Programs/AutoStory/Data/Json_Tests.h" @@ -105,6 +107,8 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& database){ add_tests_AutoStorySnorlax(database); add_tests_AutoStorySlope(database); add_tests_AutoStorySafari(database); + add_tests_AutoStoryFuchsiaGym(database); + add_tests_AutoStoryHealing(database); } void add_tests(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp index 3a4d114578..6219a617b1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp @@ -21,9 +21,6 @@ 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); logger.log(message, result.end == MartEnd::DONE ? COLOR_BLACK : COLOR_RED); - if (result.end == MartEnd::NOTHING_TO_BUY){ - return Pokemon::outcome_unchanged(); - } return result.end == MartEnd::DONE ? Pokemon::outcome_ok() : Pokemon::outcome_failed(std::format("mart_{}", mart_end_name(result.end)), message); } 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 c8c61be7bb..5763b66376 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -28,14 +28,10 @@ class QuietLogger : public Logger{ 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. +// A game where nothing happens: a lead whose level 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 press_cursor(bool) override{} virtual std::string read_row(size_t) override{ return ""; } virtual void dump_screen(std::string_view) override{} @@ -152,13 +148,12 @@ struct StepCase{ std::vector step_cases(){ const auto none = [](StubGame&){}; - const Pokemon::StoryStep mart = mart_step("mart", "", {.map = "PewterCity_Mart", .lines = {{"potion", 5}}, .budget = 2000}); + const Pokemon::StoryStep mart = mart_step("mart", "", {.map = "PewterCity_Mart", .lines = {{"potion", 5}}}); 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}), "unchanged"}, {"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; }, mart, "unchanged"}, {"a Mart purchase that fails", none, mart, "mart_failed"}, {"a move it knows already succeeds", none, teach_step("teach", "", {.item = "hm03", .move = "surf", .member = 0}), "unchanged"}, {"a TM not in the TM Case is skipped", none, teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "water-gun"}), "unchanged"}, @@ -189,7 +184,7 @@ UnitTestResult test_ability_steps(){ UnitTestResult test_once_per_save_steps(){ const std::vector once{ teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}), - mart_step("mart", "", {.map = "CeruleanCity_Mart", .lines = {{.item = "potion", .quantity = 3}}, .budget = 1500, .money_floor = 1500}), + mart_step("mart", "", {.map = "CeruleanCity_Mart", .lines = {{.item = "potion", .quantity = 3}}}), }; for (const Pokemon::StoryStep& step : once){ if (!step.once_per_save){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 0ae29df980..8787da3930 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -58,9 +58,6 @@ constexpr Milliseconds INTRO_A_EVERY = 1500ms; constexpr Milliseconds INTRO_QUIET = 3000ms; constexpr Milliseconds INTRO_STUCK = 15000ms; constexpr Milliseconds INTRO_TIMEOUT = 600000ms; -// "Wait about 8 s" after YES at the nurse (console B, 2026-11-01): 1.5 s -// between presses did not heal. -constexpr Milliseconds HEAL_TIME = 8000ms; DpadPosition dpad(Direction direction){ switch (direction){ @@ -116,6 +113,10 @@ std::optional start_cursor_row(ConsoleHandle& console, ProControllerContext // The START menu's cursor onto `row`, read from the arrow. As // move_cursor_to_position(), for a menu of any length. +// Overlaps move_cursor_to_position() in PokemonFRLG_StartMenuNavigation.h. +// Upstream only has fixed-menu overloads (Start, Safari, NoDex); ours takes a row count, +// so it also fits the 5-row menu before the starter. +// Could be unified with upstream if needed. bool move_start_cursor(ConsoleHandle& console, ProControllerContext& context, int rows, int row){ const std::optional current = start_cursor_row(console, context, rows); if (!current){ @@ -134,6 +135,9 @@ bool move_start_cursor(ConsoleHandle& console, ProControllerContext& context, in // The START menu's cursor onto SAVE, in a menu of any length: up past the // top wraps to EXIT, the last row, whose place gives the length; SAVE is // two above it. +// Overlaps move_cursor_to_position(SelectionArrowPositionStartMenu::SAVE) in PokemonFRLG_StartMenuNavigation.h. +// Upstream's SAVE position only fits the full menu; ours finds the menu length first, so it fits any menu. +// Could be unified with upstream if needed. bool move_start_cursor_to_save(ConsoleHandle& console, ProControllerContext& context){ const int most = start_menu_rows(StartMenu::FULL); const std::optional current = start_cursor_row(console, context, most); @@ -154,6 +158,9 @@ bool move_start_cursor_to_save(ConsoleHandle& console, ProControllerContext& con return true; } +// Overlaps open_start_menu() and move_cursor_to_position() in PokemonFRLG_StartMenuNavigation.h. +// Ours wraps open_start_menu() and then moves the cursor by row for any START menu variant. +// Could be unified with upstream if needed. void open_start_menu_row(ConsoleHandle& console, ProControllerContext& context, StartMenu menu, int row){ open_start_menu(console, context); if (!move_start_cursor(console, context, start_menu_rows(menu), row)){ @@ -880,19 +887,6 @@ void set_options(ConsoleHandle& console, ProControllerContext& context, StartMen mash_until_overworld(console, context, 20000ms); } -void heal_at_center(ConsoleHandle& console, ProControllerContext& context){ - console.log("Healing at the Pokemon Center."); - // The nurse's YES/NO isn't seen by the selection detector (console B, - // 2026-11-01); YES is the default, so A after her lines is YES. - // "Welcome ... We heal your POKEMON ... Shall we heal?" is 3 lines. - press(context, BUTTON_A, 1500ms); - press(context, BUTTON_A, 1500ms); - press(context, BUTTON_A, 2500ms); - press(context, BUTTON_A, 1000ms); - pbf_wait(context, HEAL_TIME); - mash_until_overworld(console, context, 30000ms); -} - // A picture of the Mart screen for the run's record: the list with the // cursor, the quantity, the bag after. static void mart_shot(ConsoleHandle& console, ProControllerContext& context, const std::string& label){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h index 4b813e3f77..79034b19fb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h @@ -52,8 +52,6 @@ std::optional option_right_presses( // presses, fails with a screenshot and leaves the menu open. void set_options(ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language); -// Facing the nurse: A, YES, the heal, and the text to its end. -void heal_at_center(ConsoleHandle& console, ProControllerContext& context); // One line of a Mart's BUY list: the row (from 0) and how many. struct MartOrder{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index 01cdc9797a..4541571a9c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -29,6 +29,8 @@ #include "PokemonFRLG_AutoStoryBattleData.h" #include "PokemonFRLG_AutoStoryBattleDecisions.h" #include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryHealing.h" +#include "PokemonFRLG_AutoStoryHealingSteps.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -209,6 +211,10 @@ bool use_item( } // RUN, bottom right of the battle menu. +// Overlaps flee_battle() in PokemonFRLG_Navigation.h. +// Ours is one blind turn that resets the cursor first, since the battle loop reads the result itself; +// upstream needs the cursor on FIGHT and assumes the run always works. +// Could be unified with upstream if needed. void run_away(ProControllerContext& context){ tap(context, DPAD_LEFT); tap(context, DPAD_UP); @@ -567,6 +573,7 @@ class BattleLoop{ m_supplies.hurt = status.hp_red || status.hp_yellow; m_supplies.hp_red = status.hp_red; m_supplies.hp_fill = status.hp_fill; + measured_hp(m_supplies, status.hp_fill); } m_supplies.status = status.status; } @@ -586,6 +593,17 @@ class BattleLoop{ m_last_press = now; } + void log_turn(const PartyStatus& status, const TurnAction& action){ + m_console.log(std::format( + "Battle: turn {}, HP {} ({:.0f}% of the bar), {}, {} Potions, {} Antidotes, {} Parlyz Heals, {} Awakenings.", + m_decisions.turns(), status.hp_red ? "red" : status.hp_yellow ? "yellow" : "green", 100 * status.hp_fill, + status_name(status.status), m_supplies.potions, m_supplies.antidotes, m_supplies.parlyz_heals, m_supplies.awakenings + )); + if (!action.heal_reason.empty()){ + m_console.log("Battle: " + action.heal_reason + "."); + } + } + void take_turn(const ImageViewRGB32& screen){ m_faint_polls = 0; if (m_kind != BattleKind::TRAINER && m_decisions.turns() == 0){ @@ -601,14 +619,7 @@ class BattleLoop{ const PartyStatus status = read_party_status(screen); const TurnAction action = m_decisions.turn(status); m_evolution.turn_taken(action.choice); - m_console.log(std::format( - "Battle: turn {}, HP {} ({:.0f}% of the bar), {}, {} Potions, {} Antidotes, {} Parlyz Heals, {} Awakenings.", - m_decisions.turns(), status.hp_red ? "red" : status.hp_yellow ? "yellow" : "green", 100 * status.hp_fill, - status_name(status.status), m_supplies.potions, m_supplies.antidotes, m_supplies.parlyz_heals, m_supplies.awakenings - )); - if (!action.heal_reason.empty()){ - m_console.log("Battle: " + action.heal_reason + "."); - } + log_turn(status, action); dump_debug_image(m_console, "AutoStory/battle", std::format("turn{}-menu", m_decisions.turns()), screen); switch (action.choice){ case TurnChoice::RUN: @@ -624,6 +635,9 @@ class BattleLoop{ case TurnChoice::AWAKENING: m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, m_supplies, "awakening", ItemTarget::PARTY_MEMBER, m_checks, m_language))); return; + case TurnChoice::MEDICINE: + m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, m_supplies, action.item, ItemTarget::PARTY_MEMBER, m_checks, m_language))); + return; case TurnChoice::BATTLE_ITEM: m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, m_supplies, action.item, ItemTarget::POKEMON_OUT, m_checks, m_language))); return; @@ -673,6 +687,9 @@ class BattleLoop{ // From the overworld: the bag open on the Items pocket, cursor on its top. +// Overlaps open_bag_from_overworld() in PokemonFRLG_Navigation.h. +// Ours wraps it, then waits for the bag to slide in and moves the cursor to the top of the Items pocket. +// Could be unified with upstream if needed. void open_items_pocket(ConsoleHandle& console, ProControllerContext& context){ open_bag_from_overworld(console, context); // The bag ignores presses while it slides in. @@ -895,26 +912,25 @@ std::vector read_items_pocket(ConsoleHandle& console, ProControllerConte return rows; } +bool use_recovery_item( + ConsoleHandle& console, ProControllerContext& context, + const std::string& item, Pokemon::StoryCheckLevel checks, Language language, Supplies& supplies +){ + // The row before the count drops: a counted item with none left takes + // no row. + if (!use_item_on_overworld(console, context, supplies, item, checks, language)){ + return false; + } + took_recovery_item(supplies, item); + return true; +} + void recover_after_battle( ConsoleHandle& console, ProControllerContext& context, Supplies& supplies, Pokemon::StoryCheckLevel checks, Language language ){ for (const std::string& item : recovery_items(supplies)){ - // The row before the count drops: a counted item with none left - // takes no row. - if (!use_item_on_overworld(console, context, supplies, item, checks, language)){ - continue; - } - spend_item(supplies, item); - if (item == "potion"){ - // One Potion (20 HP) takes a starter of these levels from red - // to green; the bar can't be read again on the overworld. - supplies.hurt = false; - supplies.hp_red = false; - supplies.hp_fill = 1.0; - }else{ - supplies.status = StatusCondition::NONE; - } + use_recovery_item(console, context, item, checks, language, supplies); } if (supplies.status != StatusCondition::NONE){ console.log(std::format( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.cpp index fda6bae066..f94589be80 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.cpp @@ -142,6 +142,32 @@ size_t type_effectiveness(PokemonType attack, PokemonType defend){ return it == CHART.end() ? 10 : it->second; } +PokemonType ability_immunity(std::string_view species){ + struct Immunity{ + std::string_view species; + PokemonType type; + }; + // Gen 3 species with one ability only, so the foe has it for sure. + static constexpr Immunity IMMUNITIES[] = { + {"gastly", PokemonType::GROUND}, {"haunter", PokemonType::GROUND}, {"gengar", PokemonType::GROUND}, + {"koffing", PokemonType::GROUND}, {"weezing", PokemonType::GROUND}, + {"vulpix", PokemonType::FIRE}, {"ninetales", PokemonType::FIRE}, {"flareon", PokemonType::FIRE}, + {"jolteon", PokemonType::ELECTRIC}, + {"vaporeon", PokemonType::WATER}, + }; + for (const Immunity& immunity : IMMUNITIES){ + if (immunity.species == species){ + return immunity.type; + } + } + return PokemonType::NONE; +} + +bool takes_two_turns(std::string_view move){ + static constexpr std::string_view TWO_TURN_MOVES[] = {"dig", "fly", "solar-beam", "skull-bash", "razor-wind", "sky-attack"}; + return std::ranges::find(TWO_TURN_MOVES, move) != std::end(TWO_TURN_MOVES); +} + std::string read_trainer_foe(Logger& logger, Language language, const ImageViewRGB32& screen, const std::vector& party){ if (language == Language::None || party.empty()){ return ""; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp index 246f7c3d72..a503ed7ee1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp @@ -10,6 +10,8 @@ #include #include #include "PokemonFRLG_AutoStoryBattleDecisions.h" +#include "PokemonFRLG_AutoStoryHealing.h" +#include "PokemonFRLG_AutoStoryItemsPocket.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -60,6 +62,24 @@ constexpr uint8_t MAX_LEVELS_IN_BATTLE = 3; // The HP a Potion heals (pret src/data/items.h). constexpr double POTION_HP = 20; +// An item used: the story's count of it goes down, and an item it doesn't +// count takes its row with the last one. +void spend_bag_item(Supplies& supplies, const std::string& item){ + const auto count = supplies.other_counts.find(item); + if (count == supplies.other_counts.end()){ + spend_item(supplies, item); + return; + } + if (--count->second > 0){ + return; + } + supplies.other_counts.erase(count); + const auto row = std::find(supplies.pocket.begin(), supplies.pocket.end(), item); + if (row != supplies.pocket.end()){ + supplies.pocket.erase(row); + } +} + // A trainer's battle: the plan's attack, else the best type matchup // (attack_slot_against()) against the foe out as read at the battle // menu, else against the whole party its plan lists. @@ -118,6 +138,7 @@ void healed_by_nurse(Supplies& supplies){ supplies.hurt = false; supplies.hp_red = false; supplies.hp_fill = 1.0; + measured_hp(supplies, 1.0); supplies.status = StatusCondition::NONE; restore_pp(supplies.lead); } @@ -160,6 +181,10 @@ BattleDecisions::BattleDecisions(Supplies& supplies, BattleKind kind) if (supplies.lead.level > 0){ m_level_cap = static_cast(std::min(battle_level(supplies.lead) + MAX_LEVELS_IN_BATTLE, 255)); } + // The policy needs the lead's HP and Speed, which its stats give. + if (kind == BattleKind::TRAINER && supplies.policy.kind != BattlePolicyKind::NONE && supplies.lead.stats){ + m_policy.emplace(supplies.policy); + } } TurnAction BattleDecisions::turn(const PartyStatus& status){ @@ -185,6 +210,7 @@ TurnAction BattleDecisions::lead_turn(const PartyStatus& status){ m_supplies.hurt = hurt; if (status.hp_seen){ m_supplies.hp_fill = status.hp_fill; + measured_hp(m_supplies, status.hp_fill); } m_supplies.status = status.status; m_psn_reads = status.status == StatusCondition::POISON ? m_psn_reads + 1 : 0; @@ -198,6 +224,9 @@ TurnAction BattleDecisions::lead_turn(const PartyStatus& status){ return TurnAction{.choice = TurnChoice::RUN}; } see_hit(status); + if (m_policy){ + return policy_turn(status, {}); + } // Awakenings are kept for trainers: a wild battle with a status is run from. const int awakenings = m_kind == BattleKind::TRAINER ? m_supplies.awakenings : 0; const ItemTurn items = m_items_off ? ItemTurn{} : item_turn(m_supplies, status, m_seen_hit, awakenings); @@ -217,6 +246,40 @@ TurnAction BattleDecisions::lead_turn(const PartyStatus& status){ return action; } +size_t BattleDecisions::track_foe(){ + const std::vector& foes = m_supplies.foes; + for (size_t index = m_foe_index; index < foes.size() && !m_supplies.foe_out.empty(); index++){ + if (foes[index] == m_supplies.foe_out){ + m_foe_index = index; + break; + } + } + return m_foe_index; +} + +TurnAction BattleDecisions::policy_turn(const PartyStatus& status, std::string heal_reason){ + const std::optional hp = lead_hp(m_supplies, status); + const PolicyView view{ + .hp = hp.value_or(static_cast(m_supplies.lead.stats->hp)), + .max_hp = static_cast(m_supplies.lead.stats->hp), + .status = status.status, + .speed = m_supplies.lead.stats->speed, + .foe_index = track_foe(), + }; + std::optional item = m_items_off ? std::nullopt : m_policy->choose(m_supplies, view); + if (!item){ + TurnAction action = move_turn(); + action.heal_reason = std::move(heal_reason); + return action; + } + m_planned_item = item->item; + return TurnAction{ + .choice = item->party_member ? TurnChoice::MEDICINE : TurnChoice::BATTLE_ITEM, + .heal_reason = "policy: " + item->why, + .item = std::move(item->item), + }; +} + void BattleDecisions::see_hit(const PartyStatus& status){ if (m_supplies.foe_out != m_hit_by){ m_seen_hit = 0; @@ -224,13 +287,13 @@ void BattleDecisions::see_hit(const PartyStatus& status){ } const std::optional hp = lead_hp(m_supplies, status); if (hp && m_last_hp){ - const double taken = *m_last_hp + (m_healed ? POTION_HP : 0) - *hp; + const double taken = *m_last_hp + m_healed_hp - *hp; if (taken > 0){ m_seen_hit = taken; } } m_last_hp = hp; - m_healed = false; + m_healed_hp = 0; } // The plan's attack with PP left, or against known foes (a trainer's @@ -275,15 +338,15 @@ void BattleDecisions::planned_item_used(){ break; } } - const auto count = m_supplies.other_counts.find(m_planned_item); - if (count == m_supplies.other_counts.end() || --count->second > 0){ - return; - } - m_supplies.other_counts.erase(count); - const auto row = std::find(m_supplies.pocket.begin(), m_supplies.pocket.end(), m_planned_item); - if (row != m_supplies.pocket.end()){ - m_supplies.pocket.erase(row); - } + spend_bag_item(m_supplies, m_planned_item); +} + +void BattleDecisions::policy_item_used(){ + spend_bag_item(m_supplies, m_planned_item); + m_policy->item_used(m_planned_item); + // A medicine heals up to the bar's end. + const double room = static_cast(m_supplies.lead.stats->hp) - m_last_hp.value_or(0); + m_healed_hp = std::min(medicine_hp(m_planned_item), std::max(0.0, room)); } void BattleDecisions::count_down_refused(){ @@ -325,7 +388,7 @@ void BattleDecisions::turn_done(TurnChoice choice, TurnResult result){ } switch (choice){ case TurnChoice::POTION: - m_healed = true; + m_healed_hp = POTION_HP; m_supplies.potions--; m_supplies.hurt = false; m_supplies.hp_red = false; @@ -337,8 +400,15 @@ void BattleDecisions::turn_done(TurnChoice choice, TurnResult result){ m_supplies.awakenings--; m_supplies.status = StatusCondition::NONE; return; + case TurnChoice::MEDICINE: + policy_item_used(); + return; case TurnChoice::BATTLE_ITEM: - planned_item_used(); + if (m_policy){ + policy_item_used(); + }else{ + planned_item_used(); + } return; case TurnChoice::RUN: case TurnChoice::MOVE: diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h index 167dd3c9ab..e0949c3b13 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h @@ -28,6 +28,7 @@ #include "Common/Cpp/Time.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryBattlePolicy.h" #include "PokemonFRLG_AutoStoryParty.h" #include "PokemonFRLG_AutoStoryBattleTurns.h" @@ -79,6 +80,13 @@ class BattleDecisions{ // The plan's battle item chosen last was used: its quantity and count // go down, and its pocket row goes with the last one the bag had. void planned_item_used(); + // The policy's item chosen last was used. + void policy_item_used(); + // The battle policy's turn, with the lead's HP and speed known: its + // item, or an attack. + TurnAction policy_turn(const PartyStatus& status, std::string heal_reason); + // The foe out, as an index into the step's foes. + size_t track_foe(); // The HP the lead lost since the last turn, from the bar. void see_hit(const PartyStatus& status); void count_down_refused(); @@ -94,6 +102,9 @@ class BattleDecisions{ bool m_items_off = false; // The plan's battle item chosen last. std::string m_planned_item; + // The step's battle policy, if it has one and the lead's stats are read. + std::optional m_policy; + size_t m_foe_index = 0; bool m_lost = false; // NO was answered to "Delete a move?": "Stop learning?" comes next. bool m_declined_delete = false; @@ -103,10 +114,10 @@ class BattleDecisions{ // A YES/NO before the next turn means nothing was forgotten. std::optional m_before_forget; std::optional m_last_move_slot; - // The lead's HP at the last turn, from the bar, and whether a Potion - // was used on it since. + // The lead's HP at the last turn, from the bar, and the HP the + // medicine used on it since heals. std::optional m_last_hp; - bool m_healed = false; + double m_healed_hp = 0; // The HP the last hit seen took, from the foe out `m_hit_by`; 0 if none // was seen. double m_seen_hit = 0; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp new file mode 100644 index 0000000000..df51967657 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp @@ -0,0 +1,387 @@ +/* AutoStory Battle Policy + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "PokemonFRLG_AutoStoryBattlePolicy.h" +#include "PokemonFRLG_AutoStoryItemsPocket.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// Thunder Badge: Speed x1.1. Every fight a policy is written for is after Lt. Surge. +constexpr double THUNDER_BADGE = 1.1; +// Guard Spec's Mist lasts this many turns, the one it is used on included. +constexpr int MIST_TURNS = 5; +constexpr int MAX_STAGE = 6; +constexpr double WHOLE_HP = std::numeric_limits::infinity(); + +// The HP medicines, smallest first (the doc's HEALS table). +struct Medicine{ + std::string_view item; + double hp; +}; +constexpr Medicine MEDICINES[] = { + {"potion", 20}, {"super-potion", 50}, {"hyper-potion", 200}, {"max-potion", WHOLE_HP}, {"full-restore", WHOLE_HP}, +}; + +// The cure for a status, by the doc's CURES table; "" for none. +std::string_view cure_of(StatusCondition status){ + switch (status){ + case StatusCondition::SLEEP: + return "awakening"; + case StatusCondition::POISON: + return "antidote"; + case StatusCondition::PARALYSIS: + return "parlyz-heal"; + case StatusCondition::NONE: + case StatusCondition::OTHER: + return ""; + } + return ""; +} + +// A Full Restore (a heal and a cure in one) is used only when it also heals +// at least half of max HP; below that a cheap cure or a smaller medicine does. +bool full_restore_worth_it(const PolicyView& view){ + return view.max_hp - view.hp >= view.max_hp / 2; +} + +double stage_multiplier(int stage){ + return stage >= 0 ? (2.0 + stage) / 2.0 : 2.0 / (2.0 - stage); +} + +PolicyItem medicine_item(const std::string& item, std::string why){ + return PolicyItem{.item = item, .party_member = true, .why = std::move(why)}; +} + +PolicyItem setup_item_of(const std::string& item, std::string why){ + return PolicyItem{.item = item, .party_member = false, .why = std::move(why)}; +} + +} // namespace + + +std::optional battle_policy_kind(std::string_view word){ + if (word == "solo-recovery"){ + return BattlePolicyKind::SOLO_RECOVERY; + } + if (word == "goal-based-setup"){ + return BattlePolicyKind::GOAL_BASED_SETUP; + } + return std::nullopt; +} + +std::optional> foe_threats_of(const std::vector>& rows){ + constexpr size_t COLUMNS = 7; + std::vector foes; + for (const std::vector& row : rows){ + if (row.size() != COLUMNS){ + return std::nullopt; + } + foes.push_back(FoeThreat{ + .speed = static_cast(row[0]), + .likely = static_cast(row[1]), + .mean = static_cast(row[2]), + .max = static_cast(row[3]), + .normal_max = static_cast(row[4]), + .lowers_accuracy = row[5] != 0, + .explodes = row[6] != 0, + }); + } + return foes; +} + +BattlePolicy battle_policy_of(const Pokemon::StoryActionArgs& args){ + const std::optional kind = battle_policy_kind(Pokemon::story_arg(args, "policy")); + if (!kind){ + return {}; + } + BattlePolicy policy; + policy.kind = *kind; + policy.goals = SetupGoals{ + .spa = static_cast(Pokemon::story_arg(args, "setup_spa")), + .accuracy = static_cast(Pokemon::story_arg(args, "setup_accuracy")), + .outspeed = Pokemon::story_arg(args, "setup_outspeed"), + .guard_accuracy = Pokemon::story_arg(args, "setup_guard_accuracy"), + .torrent_power = Pokemon::story_arg(args, "setup_torrent_power"), + }; + if (std::optional> foes = foe_threats_of(Pokemon::story_arg>>(args, "foe_threats"))){ + policy.foes = std::move(*foes); + } + return policy; +} + +void end_trainer_battle(Supplies& supplies){ + supplies.foes.clear(); + supplies.trainer.clear(); + supplies.foe_out.clear(); + supplies.battle_items.clear(); + supplies.policy = {}; +} + +int bag_count(const Supplies& supplies, std::string_view item){ + const std::string name(item); + const auto other = supplies.other_counts.find(name); + return other != supplies.other_counts.end() ? other->second : item_count(supplies, name); +} + +double medicine_hp(std::string_view item){ + for (const Medicine& medicine : MEDICINES){ + if (medicine.item == item){ + return medicine.hp; + } + } + return 0; +} + + +PolicyState::PolicyState(const BattlePolicy& policy) + : m_policy(policy) +{} + +const FoeThreat* PolicyState::foe(const PolicyView& view) const{ + return view.foe_index < m_policy.foes.size() ? &m_policy.foes[view.foe_index] : nullptr; +} + +PolicyState::Danger PolicyState::danger(const PolicyView& view) const{ + // A poisoned lead also loses 1/8 of its HP to the poison each turn. + const double residual = view.status == StatusCondition::POISON ? std::floor(view.max_hp / 8) : 0; + const FoeThreat* threat = foe(view); + if (threat == nullptr){ + return {residual, residual, residual, residual}; + } + return { + residual + threat->likely, residual + threat->mean, residual + threat->max, residual + threat->normal_max, + }; +} + +int PolicyState::own_speed(const PolicyView& view) const{ + const int badged = static_cast(std::floor(view.speed * THUNDER_BADGE)); + return static_cast(std::floor(badged * stage_multiplier(m_speed))); +} + +bool PolicyState::outsped(const PolicyView& view) const{ + const int own = own_speed(view); + for (size_t index = view.foe_index; index < m_policy.foes.size(); index++){ + if (m_policy.foes[index].speed >= own){ + return false; + } + } + return true; +} + +int PolicyState::spa_goal(const PolicyView& view) const{ + const int target = m_policy.goals.spa; + const bool torrent = view.hp * 3 <= view.max_hp; + if (!m_policy.goals.torrent_power || torrent){ + return target; + } + // The stage whose multiplier makes up for Torrent's 1.5. + const double wanted = 1.5 * (2.0 + target) / 2.0; + for (int stage = target; stage <= MAX_STAGE; stage++){ + if ((2.0 + stage) / 2.0 >= wanted){ + return stage; + } + } + return MAX_STAGE; +} + +int PolicyState::accuracy_goal() const{ + return std::min(MAX_STAGE, m_policy.goals.accuracy + std::max(0, m_foe_evasion)); +} + +std::optional PolicyState::cure(const Supplies& supplies, const PolicyView& view, const Danger& danger) const{ + if (view.hp <= danger.likely){ + return std::nullopt; + } + const std::string_view own_cure = cure_of(view.status); + std::vector candidates; + if (!own_cure.empty()){ + candidates = {own_cure, "full-heal"}; + }else if (view.status == StatusCondition::OTHER){ + candidates = {"full-heal"}; + } + if (!candidates.empty() && full_restore_worth_it(view)){ + candidates.push_back("full-restore"); + } + for (const std::string_view item : candidates){ + if (bag_count(supplies, item) > 0){ + return medicine_item(std::string(item), std::format("{} for {}", item, status_name(view.status))); + } + } + return std::nullopt; +} + +std::optional PolicyState::heal(const Supplies& supplies, const PolicyView& view, const Danger& danger) const{ + if (view.hp > std::max(view.max_hp / 2, danger.max)){ + return std::nullopt; + } + const double missing = view.max_hp - view.hp; + for (const Medicine& medicine : MEDICINES){ + const double gained = std::min(medicine.hp, missing); + if (medicine.item == "full-restore" && !full_restore_worth_it(view)){ + continue; + } + if (bag_count(supplies, medicine.item) > 0 && gained > danger.likely && gained > 0){ + return medicine_item(std::string(medicine.item), std::format( + "{}: HP {:.0f}/{:.0f}, a turn's loss up to {:.0f}", medicine.item, view.hp, view.max_hp, danger.max + )); + } + } + return std::nullopt; +} + +int PolicyState::setup_turns(const Supplies& supplies, const PolicyView& view, bool guard) const{ + int count = std::min(bag_count(supplies, "x-special"), std::max(0, spa_goal(view) - m_spa)); + count += std::min(bag_count(supplies, "x-accuracy"), std::max(0, accuracy_goal() - m_accuracy)); + if (m_policy.goals.outspeed && !outsped(view) && bag_count(supplies, "x-speed") > 0){ + count++; + } + if (guard){ + count++; + } + return std::max(1, count); +} + +std::optional PolicyState::setup(const Supplies& supplies, const PolicyView& view) const{ + const bool special = m_spa < spa_goal(view) && bag_count(supplies, "x-special") > 0; + const bool speed = m_policy.goals.outspeed && bag_count(supplies, "x-speed") > 0 + && m_speed < MAX_STAGE && !outsped(view); + const bool accuracy = m_accuracy < accuracy_goal() && bag_count(supplies, "x-accuracy") > 0; + if (!special && !speed && !accuracy){ + return std::nullopt; + } + const FoeThreat* threat = foe(view); + if (m_policy.goals.guard_accuracy && bag_count(supplies, "guard-spec") > 0 && m_mist_turns <= 0 + && threat != nullptr && threat->lowers_accuracy + ){ + return setup_item_of("guard-spec", "Guard Spec: the foe lowers accuracy and setup is pending"); + } + if (special){ + return setup_item_of("x-special", std::format("X Special: Sp. Atk +{} of +{}", m_spa, spa_goal(view))); + } + if (speed){ + return setup_item_of("x-speed", std::format("X Speed: Speed {} against the foes left", own_speed(view))); + } + return setup_item_of("x-accuracy", std::format("X Accuracy: accuracy {:+} of {:+}", m_accuracy, accuracy_goal())); +} + +std::optional PolicyState::planning_heal( + const Supplies& supplies, const PolicyView& view, const Danger& danger, int turns, std::string_view waiting_on +) const{ + // An HP reserve for the setup turns ahead. + const double reserve = std::min(view.max_hp * 0.75, danger.normal_max + std::max(0, turns - 1) * danger.mean); + if (view.hp > danger.normal_max && view.hp >= reserve){ + return std::nullopt; + } + struct Option{ + bool sufficient; + double expected; + double restored; + std::string_view item; + }; + std::vector