diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp index e6401a1b11..f99277ac70 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp @@ -223,6 +223,9 @@ Outcome verify_pass(const std::string& id, SegmentHooks& hooks, RunState& state) } if (hooks.verify_pass){ const Outcome passed = hooks.verify_pass(id, state); + if (passed.failure == VERIFY_UNREAD){ + return passed; + } if (!passed.succeeded()){ return outcome_failed("verify_no_pass", to_string(passed)); } @@ -290,8 +293,9 @@ class VerifyRow{ }else{ set_save(m_row, m_policy, m_hooks, checkpoint); } - checkpoint.save = [save = std::move(checkpoint.save), id = m_row.spec.id, &hooks = m_hooks](RunState& state) mutable{ + checkpoint.save = [save = std::move(checkpoint.save), id = m_row.spec.id, &hooks = m_hooks, &unread = m_unread](RunState& state) mutable{ const Outcome passed = verify_pass(id, hooks, state); + unread = passed.failure == VERIFY_UNREAD; if (!passed.succeeded() || !save){ return passed; } @@ -302,7 +306,7 @@ class VerifyRow{ // One try, reloading the start save first after the first; whether it // passed, or none when the loop stops (no reload, the start check - // failed, the game is not running). + // or a step's precondition failed, the game is not running). std::optional try_once(size_t phase, size_t index, size_t of){ const std::string& id = m_row.spec.id; if (m_run.attempts > 0){ @@ -314,6 +318,7 @@ class VerifyRow{ } } m_run.attempts++; + m_unread = false; Checkpoint checkpoint = build(phase); EventLogger log = [&hooks = m_hooks](const std::string& line){ say(line, hooks); }; m_result = run_checkpoint(m_state, checkpoint, log); @@ -321,11 +326,18 @@ class VerifyRow{ say(std::format("[Verify] {}: phase {} try {}/{} passed", id, phase, index, of), m_hooks); return true; } + if (m_unread){ + say(std::format("[Verify] {}: the pass check couldn't read the game; no save, stopping", id), m_hooks); + m_result = failed_report(outcome_failed(std::string(VERIFY_UNREAD), to_string(m_result.failure))); + return std::nullopt; + } say(std::format( "[Verify] {}: phase {} try {}/{} failed{}: {}", id, phase, index, of, m_result.failed_name.empty() ? "" : std::format(" at {}", m_result.failed_name), to_string(m_result.failure) ), m_hooks); - if (m_result.failure.failure == "start_failed" || m_result.failure.failure == GAME_NOT_RUNNING){ + if (m_result.failure.failure == "start_failed" || m_result.failure.failure == "precondition_failed" + || m_result.failure.failure == GAME_NOT_RUNNING + ){ say(std::format("[Verify] {}: stopping", id), m_hooks); return std::nullopt; } @@ -340,6 +352,8 @@ class VerifyRow{ CheckpointRun& m_run; RunState& m_state; CheckpointReport m_result; + // The last try's pass check couldn't read the game (VERIFY_UNREAD). + bool m_unread = false; }; SegmentReport stop_segment(const std::string& id, Outcome failure, SegmentHooks& hooks, SegmentReport& report){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h index ae0ddf1b58..49d82fa373 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h @@ -69,7 +69,10 @@ struct SegmentHooks{ MoveOnlyFunction check_postconditions; // Optional: whether a verify row's try that completed passes, by the // game's own measure (FRLG's League: the items a fight spent within - // its caps). Run after check_postconditions. + // its caps). Run after check_postconditions, right before the save; + // either failing blocks the save. A failure named VERIFY_UNREAD (the + // game couldn't read what it checks) stops the loop: never a save, + // nor another try, on a guess. MoveOnlyFunction verify_pass; }; @@ -78,10 +81,10 @@ struct SegmentHooks{ // 1's tries save nothing and reload between them; below min_pass the // segment stops ("verify_below_min_pass"); phase 2 reloads and tries // again until a try passes, which saves, or stops after reset_budget -// ("verify_out_of_budget"). A try whose start check fails stops the loop -// at once: the save does not meet the row's preconditions. Logs through -// `hooks.log`, -// around the checkpoint lines: +// ("verify_out_of_budget"). A try whose start check fails, or whose step +// fails "precondition_failed" (FRLG's League top-up and entry contract), +// stops the loop at once: the save does not meet the row's preconditions. +// Logs through `hooks.log`, around the checkpoint lines: // [Segment] 00: start, 3 checkpoints // [Checkpoint] 00.02: failed, resetting for attempt 2/3 // [Checkpoint] 00.02: passed on attempt 2 (1 reset) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.cpp index 0019825c46..4786e899bb 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.cpp @@ -60,6 +60,9 @@ struct FakeFight{ int saved_potions = 0; int potions = 0; std::vector tries; + // The game's postcondition check holds; its pass check reads the game. + bool postconditions_hold = true; + bool pass_readable = true; int fights = 0; int saves = 0; int reloads = 0; @@ -103,7 +106,13 @@ struct FakeFight{ potions = saved_potions; return outcome_ok(); }; + hooks.check_postconditions = [this](const std::string&, RunState&){ + return postconditions_hold ? outcome_ok() : outcome_failed("postconditions", "the bag is short of the next fight's entry"); + }; hooks.verify_pass = [this](const std::string&, RunState&){ + if (!pass_readable){ + return outcome_failed(std::string(VERIFY_UNREAD), "the bag wasn't read"); + } return spent <= POTION_CAP ? outcome_ok() : outcome_failed("over_cap", std::format("{} potions", spent)); }; hooks.log = [&lines](const std::string& line){ lines.push_back(line); }; @@ -117,6 +126,8 @@ struct VerifyRowCase{ StoryVerify verify = {}; int potions = POTIONS_NEEDED; std::vector tries = {}; + bool postconditions_hold = true; + bool pass_readable = true; }; struct Expectation{ bool completed = false; @@ -139,7 +150,10 @@ class Test_StoryVerifyRow : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - FakeFight game{.saved_potions = m_case.input.potions, .potions = m_case.input.potions, .tries = m_case.input.tries}; + FakeFight game{ + .saved_potions = m_case.input.potions, .potions = m_case.input.potions, .tries = m_case.input.tries, + .postconditions_hold = m_case.input.postconditions_hold, .pass_readable = m_case.input.pass_readable, + }; Segment segment; segment.id = "20"; segment.checkpoints.push_back(game.spec(m_case.input.verify)); @@ -200,6 +214,16 @@ const VerifyRowCase VERIFY_ROW_CASES[] = { .input = {.potions = POTIONS_NEEDED - 1, .tries = {win()}}, .expectation = {.failure = "start_failed", .fights = 0, .saves = 0, .reloads = 0}, }, + { + .name = "a won try whose postcondition check fails right before the save: never saved", + .input = {.verify = {.tries = 2, .min_pass = 0, .reset_budget = 2}, .tries = {win()}, .postconditions_hold = false}, + .expectation = {.failure = "verify_out_of_budget", .fights = 4, .saves = 0, .reloads = 3}, + }, + { + .name = "the pass check can't read the game: no save, the loop stops at once", + .input = {.tries = {win()}, .pass_readable = false}, + .expectation = {.failure = "postcondition_unread", .fights = 1, .saves = 0, .reloads = 0}, + }, { .name = "min_pass 0 of 2: straight to phase 2", .input = {.verify = {.tries = 2, .min_pass = 0, .reset_budget = 1}, .tries = {lose(), lose(), win()}}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryVerify.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryVerify.h index f9b67f4cad..547a92cfd8 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryVerify.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryVerify.h @@ -16,11 +16,16 @@ #define PokemonAutomation_Pokemon_StoryVerify_H #include +#include namespace PokemonAutomation{ namespace Pokemon{ +// A verify pass check that couldn't read the game +// (SegmentHooks::verify_pass): the loop stops, with no save. +inline constexpr std::string_view VERIFY_UNREAD = "postcondition_unread"; + // The verification loop's figures. struct StoryVerify{ size_t tries = 10; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 32c4e980fa..54ce1fd891 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -35,7 +35,7 @@ #include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryFailureClasses.h" #include "PokemonFRLG_AutoStoryLaunch.h" -#include "PokemonFRLG_AutoStoryLeagueRows.h" +#include "PokemonFRLG_AutoStoryLeagueSteps.h" #include "PokemonFRLG_AutoStoryRngLoop.h" #include "PokemonFRLG_AutoStoryTable.h" #include "PokemonFRLG_AutoStory.h" @@ -558,11 +558,13 @@ static void run_story_rows( Pokemon::StoryGameHooks game = story_game(env, story); Pokemon::SegmentHooks hooks = Pokemon::story_segment_hooks(game); // A verify row's try passes by the League's item caps, counted from - // its start save (the loop reloads it before each try). + // its start save (the loop reloads it before each try), and by our + // side as read off the console meeting the next fight's entry + // contract: checked right before the save, never on a guess. hooks.verify_pass = [&story, &rows](const std::string& id, Pokemon::RunState&){ for (const StoryCheckpoint& row : rows){ if (row.id == id){ - return league_row_pass(row, story.saved_supplies, story.supplies); + return check_league_save(story, row, story.saved_supplies); } } return Pokemon::outcome_ok(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp index 9b58ae7e6b..6e195a3da3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp @@ -209,12 +209,6 @@ BattleDecisions::BattleDecisions(Supplies& supplies, BattleKind kind) if (!m_planned && kind == BattleKind::TRAINER && supplies.policy.kind != BattlePolicyKind::NONE && supplies.lead.stats){ m_policy.emplace(supplies.policy); } - // A League fight spends its plan's budget and what the fights before - // left (end_trainer_battle() rolls it forward). - const LeagueFightPlan* league = supplies.league ? league_fight(supplies.league->plan, supplies.trainer) : nullptr; - if (kind == BattleKind::TRAINER && league != nullptr){ - supplies.budget = add_budgets(league->budget, supplies.league->carried); - } } TurnAction BattleDecisions::turn(const PartyStatus& status){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp index 40390abe25..8260b05880 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.cpp @@ -261,9 +261,6 @@ BattlePolicy battle_policy_of(const Pokemon::StoryActionArgs& args){ } void end_trainer_battle(Supplies& supplies){ - if (supplies.league && supplies.budget){ - supplies.league->carried = *supplies.budget; - } supplies.budget.reset(); supplies.foes.clear(); supplies.trainer.clear(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.h index 47d1a581c0..1d97d319de 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy.h @@ -56,7 +56,7 @@ * min(75% max HP, D + (setup turns - 1) x mean hit) first heals * within the budget, else the setup is dropped; * 10. attack. - * The budget comes from the League plan (PokemonFRLG_AutoStoryLeaguePlan.h); + * The budget is the battle's Supplies::budget (none: no cap); * every turn's state and choice is logged on one line (state_line()). * */ @@ -122,7 +122,7 @@ struct PolicyStages{ }; // A trainer battle's plan is over: its party, items and policy go from -// `supplies`; a League fight's budget left rolls forward to the next. +// `supplies`. void end_trainer_battle(Supplies& supplies); // The lead's side of the battle as the policy tracks it: the stages and diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy_Tests.cpp index 5be0f43524..f9c4e8b1d3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattlePolicy_Tests.cpp @@ -598,12 +598,12 @@ UnitTestResult test_plan_blaine(){ } UnitTestResult test_plan_bruno(){ - const UnitTestResult result = check_policy_step("20.01", "bruno", {.spa = 2, .outspeed = true, .guard_accuracy = true}, /*policy=*/"budgeted-setup"); + const UnitTestResult result = check_policy_step("20.02", "bruno", {.spa = 2, .outspeed = true, .guard_accuracy = true}, /*policy=*/"budgeted-setup"); if (result.result != UnitTestResult::PASSED){ return result; } - if (arg_of(battle_step("20.01", "bruno"), "setup_target_torrent") != true){ - return "20.01 bruno: expected the doc's target_torrent."; + if (arg_of(battle_step("20.02", "bruno"), "setup_target_torrent") != true){ + return "20.02 bruno: expected the doc's target_torrent."; } return true; } @@ -778,14 +778,14 @@ struct LeagueTurnCase{ // out. Setup only where it pays: not against a foe the best attack KOs, // nor one that phazes; still against Lorelei's Dewgong. const LeagueTurnCase LEAGUE_TURN_CASES[] = { - {"Bruno's Onix at +0, 71% HP: Surf", {"20.01", "bruno", 0, 0, 117}, {"", "surf"}}, - {"Bruno's Onix at +2: Surf", {"20.01", "bruno", 0, 2, 165}, {"", "surf"}}, - {"Bruno's Onix at +4: Surf", {"20.01", "bruno", 0, 4, 165}, {"", "surf"}}, - {"Bruno's second Onix at +0: Surf", {"20.01", "bruno", 3, 0, 165}, {"", "surf"}}, - {"Bruno's Hitmonchan at +0: X Special", {"20.01", "bruno", 1, 0, 165}, {"x-special", ""}}, + {"Bruno's Onix at +0, 71% HP: Surf", {"20.02", "bruno", 0, 0, 117}, {"", "surf"}}, + {"Bruno's Onix at +2: Surf", {"20.02", "bruno", 0, 2, 165}, {"", "surf"}}, + {"Bruno's Onix at +4: Surf", {"20.02", "bruno", 0, 4, 165}, {"", "surf"}}, + {"Bruno's second Onix at +0: Surf", {"20.02", "bruno", 3, 0, 165}, {"", "surf"}}, + {"Bruno's Hitmonchan at +0: X Special", {"20.02", "bruno", 1, 0, 165}, {"x-special", ""}}, {"Lorelei's Dewgong at +0: X Special", {"20.01", "lorelei", 0, 0, 165}, {"x-special", ""}}, - {"the Champion's Pidgeot (Whirlwind): no X item", {"20.01", "champion", 0, 0, 165}, {"", ""}}, - {"the Champion's Arcanine (Roar): no X item", {"20.01", "champion", 4, 0, 165}, {"", ""}}, + {"the Champion's Pidgeot (Whirlwind): no X item", {"20.05", "champion", 0, 0, 165}, {"", ""}}, + {"the Champion's Arcanine (Roar): no X item", {"20.05", "champion", 4, 0, 165}, {"", ""}}, }; UnitTestResult test_league_turns(){ @@ -923,7 +923,7 @@ const std::vector AUTO_STORY_BATTLE_POLICY_CASES = { .expectation = {.description = "4 in the opening, 2 with Torrent, on a later foe or a lone one"}, }, { - .input = {.name = "plan: 20.01 bruno names budgeted-setup, its goals and target_torrent", .body = test_plan_bruno}, + .input = {.name = "plan: 20.02 bruno names budgeted-setup, its goals and target_torrent", .body = test_plan_bruno}, .expectation = {.description = "the policy, goals, target_torrent and 5 foe rows"}, }, { diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocketChange.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocketChange.cpp index 0518046b11..70c49cc76c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocketChange.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocketChange.cpp @@ -98,8 +98,7 @@ const std::vector& items_pocket_change_rows(){ {StoryStepKind::GAME, RESTORE_PP, ItemsPocketChange::COUNTED}, {StoryStepKind::GAME, CHECK_FULL_HP_ACTION, ItemsPocketChange::NONE}, {StoryStepKind::GAME, BAG_CHECK_ACTION, ItemsPocketChange::NONE}, - {StoryStepKind::GAME, LEAGUE_START_ACTION, ItemsPocketChange::COUNTED}, - {StoryStepKind::GAME, LEAGUE_BETWEEN_FIGHTS_ACTION, ItemsPocketChange::COUNTED}, + {StoryStepKind::GAME, LEAGUE_TOP_UP_ACTION, ItemsPocketChange::COUNTED}, }; return ROWS; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop.cpp deleted file mode 100644 index e00ddf8817..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/* AutoStory League Loop - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "PokemonFRLG_AutoStoryLeagueLoop.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -namespace{ - -std::string_view end_name(LeagueBattleEnd end){ - switch (end){ - case LeagueBattleEnd::WON: - return "won"; - case LeagueBattleEnd::LOST: - return "lost"; - case LeagueBattleEnd::ROARED: - return "reset on a Roar or Whirlwind"; - case LeagueBattleEnd::EARLY_RESET: - return "early reset"; - } - return ""; -} - -std::string counts_text(const SlugCounts& counts){ - std::string text; - for (const auto& [name, count] : counts){ - if (count != 0){ - text += std::format("{}{} {}", text.empty() ? "" : ", ", name, count); - } - } - return text.empty() ? std::string("nothing") : text; -} - -// The first of `floors` that `counts` is below, as a line; none if none. -std::optional below_floor(std::string_view what, const SlugCounts& counts, const SlugCounts& floors){ - for (const auto& [name, floor] : floors){ - const int have = count_of(counts, name); - if (have < floor){ - return std::format("{} {}: {}, at least {}", what, name, have, floor); - } - } - return std::nullopt; -} - -// What `before` has more of than `after`. -SlugCounts spent(const SlugCounts& before, const SlugCounts& after){ - SlugCounts used; - for (const auto& [item, count] : before){ - const int less = count - count_of(after, item); - if (less > 0){ - used[item] = less; - } - } - return used; -} - -class FightLoop{ -public: - FightLoop(const LeagueFightData& fight, const LeagueFightRunner& runner) - : m_fight(fight) - , m_runner(runner) - {} - - LeagueFightReport run(){ - if (!m_fight.pass){ - m_runner.log(std::format("League {}: the plan has no pass figures; stopping.", m_fight.name)); - return std::move(m_report); - } - const LeaguePassFigures& figures = *m_fight.pass; - for (int c = 0; c < figures.min_pass_of; c++){ - if (!try_once(1, c, figures.min_pass_of)){ - return std::move(m_report); - } - m_report.phase1_passes += m_report.tries.back().passes ? 1 : 0; - } - if (m_report.phase1_passes < figures.min_pass){ - return stop(LeagueFightVerdict::BELOW_MIN_PASS, std::format( - "phase 1 passed {} of {}, under {}", m_report.phase1_passes, figures.min_pass_of, figures.min_pass - )); - } - for (int c = 0; c < figures.reset_budget; c++){ - if (!try_once(2, c, figures.reset_budget)){ - return std::move(m_report); - } - if (m_report.tries.back().passes){ - m_runner.save(); - m_runner.log(std::format("League {}: saved after phase 2 try {}.", m_fight.name, c + 1)); - m_report.verdict = LeagueFightVerdict::SAVED; - return std::move(m_report); - } - } - return stop(LeagueFightVerdict::OUT_OF_BUDGET, std::format("no pass in {} phase 2 tries", figures.reset_budget)); - } - -private: - LeagueFightReport stop(LeagueFightVerdict verdict, std::string detail){ - m_runner.log(std::format("League {}: {}; stopping.", m_fight.name, detail)); - m_report.verdict = verdict; - m_report.detail = std::move(detail); - return std::move(m_report); - } - - // One try from the start save; false if the entry contract broke. - bool try_once(int phase, int index, int of){ - m_runner.load_start(); - const LeagueSide start = m_runner.read_side(); - LeagueTryRecord record{.phase = phase, .top_up = m_runner.top_up()}; - const LeagueSide entry = m_runner.read_side(); - if (std::optional broken = entry_broken(entry)){ - stop(LeagueFightVerdict::PRECONDITION_FAILED, std::format("entry contract: {}", *broken)); - return false; - } - record.end = m_runner.fight(); - std::optional after; - if (record.end == LeagueBattleEnd::WON){ - const LeagueSide end = m_runner.read_side(); - record.used = spent(start.bag, end.bag); - after = below_floor("item", end.bag, m_fight.reserve_items); - after = after ? after : below_floor("PP", end.pp, m_fight.reserve_pp); - } - record.passes = !after && league_try_passes(m_fight, LeagueTry{ - .won = record.end == LeagueBattleEnd::WON, - .roared = record.end == LeagueBattleEnd::ROARED, - .early_reset = record.end == LeagueBattleEnd::EARLY_RESET, - .used = record.used, - }); - m_runner.log(std::format( - "League {}: phase {} try {}/{}: HP {}/{}, top-up [{}], {}, used {}{}: {}.", - m_fight.name, phase, index + 1, of, entry.hp, entry.max_hp, counts_text(counted(record.top_up)), - end_name(record.end), counts_text(record.used), after ? std::format(", {}", *after) : "", - record.passes ? "pass" : "no pass" - )); - if (after){ - m_report.detail = *after; - } - m_report.tries.push_back(std::move(record)); - return true; - } - - // The entry contract: every item at least its count (hard); a move's - // PP under its count only logged. - std::optional entry_broken(const LeagueSide& entry) const{ - if (std::optional pp = below_floor("PP", entry.pp, m_fight.entry_pp)){ - m_runner.log(std::format("League {}: entry {}; fighting on.", m_fight.name, *pp)); - } - return below_floor("item", entry.bag, m_fight.entry_items); - } - - static SlugCounts counted(const std::vector& items){ - SlugCounts counts; - for (const std::string& item : items){ - counts[item]++; - } - return counts; - } - - const LeagueFightData& m_fight; - const LeagueFightRunner& m_runner; - LeagueFightReport m_report; -}; - -} // namespace - - -LeagueFightReport run_league_fight(const LeagueFightData& fight, const LeagueFightRunner& runner){ - return FightLoop(fight, runner).run(); -} - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop.h deleted file mode 100644 index 1c410f95f0..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop.h +++ /dev/null @@ -1,114 +0,0 @@ -/* AutoStory League Loop - * - * From: https://github.com/PokemonAutomation/ - * - * The League fight by fight (the user's design, 2026-11-17): each fight - * starts from its own save, where the fight before it was won. A try - * loads that save, tops our side up (planned_between()), checks the - * fight's entry contract, fights, and passes on a win that spends no item - * over the fight's caps and leaves its reserves. - * - * Phase 1: the plan's min_pass_of tries (10), none saved. Fewer passes - * than min_pass: the run stops. Phase 2: up to reset_budget more tries, - * until one passes, which is saved. A try that a Roar, a Whirlwind or the - * plan's early reset ended is a try that didn't pass. - * - * The loop drives a LeagueFightRunner: the console's, or a fake one that - * plays scripted battles (PokemonFRLG_AutoStoryLeagueLoop_Tests.cpp). - * - */ - -#ifndef PokemonAutomation_PokemonFRLG_AutoStoryLeagueLoop_H -#define PokemonAutomation_PokemonFRLG_AutoStoryLeagueLoop_H - -#include -#include -#include -#include -#include "PokemonFRLG_AutoStoryLeagueFightData.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -// Our side as the loop reads it: the lead's HP, its moves' PP and the bag. -struct LeagueSide{ - int hp = 0; - int max_hp = 0; - SlugCounts pp = {}; - SlugCounts bag = {}; -}; - -// How a try's battle ended. -enum class LeagueBattleEnd{ - WON, - LOST, - // A Roar or Whirlwind landed in a fight that resets on one; the game - // was soft reset. - ROARED, - // The plan's early reset (Bruno's after Onix #1); the game was soft reset. - EARLY_RESET, -}; - -// Where the loop's lines go. -using LeagueLog = std::function; - -// What the loop drives. -struct LeagueFightRunner{ - // Back to the fight's start save. - std::function load_start; - // The top-ups before the fight (planned_between()); the items used. - std::function()> top_up; - // Our side as it is now. - std::function read_side; - // The fight, to its end. - std::function fight; - // Saves the game where it is. - std::function save; - LeagueLog log; -}; - -// How the loop left a fight. -enum class LeagueFightVerdict{ - // A phase 2 try passed and was saved: on to the next fight. - SAVED, - // Phase 1 passed fewer than the plan's min_pass. - BELOW_MIN_PASS, - // No phase 2 try passed within the reset budget. - OUT_OF_BUDGET, - // A try's side broke the fight's entry contract, before fighting. - PRECONDITION_FAILED, - // The plan has no pass figures for the fight. - NO_FIGURES, -}; - -// One try. -struct LeagueTryRecord{ - int phase = 1; - std::vector top_up = {}; - LeagueBattleEnd end = LeagueBattleEnd::LOST; - // Every item the try spent, the top-ups included; empty unless won. - SlugCounts used = {}; - bool passes = false; -}; - -// The tries of a fight and how the loop left it. -struct LeagueFightReport{ - LeagueFightVerdict verdict = LeagueFightVerdict::NO_FIGURES; - std::vector tries = {}; - int phase1_passes = 0; - // What broke the entry contract, or the postcondition of the last try. - std::string detail = {}; -}; - -// `fight` through phases 1 and 2 on `runner`, every try logged with its -// counts. -LeagueFightReport run_league_fight(const LeagueFightData& fight, const LeagueFightRunner& runner); - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop_Tests.cpp deleted file mode 100644 index 5ca96e9d18..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop_Tests.cpp +++ /dev/null @@ -1,366 +0,0 @@ -/* AutoStory League Loop Tests - * - * From: https://github.com/PokemonAutomation/ - * - * The League loop (PokemonFRLG_AutoStoryLeagueLoop.h) on a fake runner: - * each try's battle is scripted as how it ended and the items it spent, - * and the top-ups between fights are planned_between()'s. The cases check - * the phases, the saves, the entry contract and the top-ups. - * - */ - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/TestRunners/UnitTest.h" -#include "PokemonFRLG_AutoStoryLeagueFightData.h" -#include "PokemonFRLG_AutoStoryLeagueLoop.h" -#include "PokemonFRLG_AutoStoryLeagueLoop_Tests.h" -#include "PokemonFRLG_AutoStoryPlannedBetween.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -namespace{ - -constexpr int OUR_MAX_HP = 171; -const SlugCounts FULL_PP = {{"bite", 25}, {"surf", 15}, {"blizzard", 5}, {"strength", 15}}; - -// The bag the League starts with (PokemonSimulation BAG_NOW). -SlugCounts league_bag(){ - return { - {"full-restore", 8}, {"x-special", 15}, {"x-speed", 5}, {"x-accuracy", 3}, {"guard-spec", 2}, - {"max-elixir", 1}, {"elixir", 1}, {"super-potion", 6}, {"full-heal", 2}, {"parlyz-heal", 2}, {"antidote", 1}, - }; -} - -// A try's battle: how it ended and the items it spent. -struct ScriptedBattle{ - LeagueBattleEnd end = LeagueBattleEnd::LOST; - SlugCounts used = {}; -}; - -// A win on no items. -ScriptedBattle win(){ - return ScriptedBattle{.end = LeagueBattleEnd::WON}; -} -// A win on two Full Restores, over Lorelei's cap of one. -ScriptedBattle win_on_two_full_restores(){ - return ScriptedBattle{.end = LeagueBattleEnd::WON, .used = {{"full-restore", 2}}}; -} -ScriptedBattle lost(){ - return ScriptedBattle{.end = LeagueBattleEnd::LOST}; -} -ScriptedBattle roared(){ - return ScriptedBattle{.end = LeagueBattleEnd::ROARED, .used = {{"x-speed", 1}}}; -} -ScriptedBattle early_reset(){ - return ScriptedBattle{.end = LeagueBattleEnd::EARLY_RESET, .used = {{"x-speed", 3}}}; -} - -std::vector repeated(size_t count, const ScriptedBattle& battle){ - return std::vector(count, battle); -} -std::vector joined(std::vector first, const std::vector& then){ - first.insert(first.end(), then.begin(), then.end()); - return first; -} - -// The fight's start save: full HP and PP, `bag`. -LeagueSide full_side(SlugCounts bag){ - return LeagueSide{.hp = OUR_MAX_HP, .max_hp = OUR_MAX_HP, .pp = FULL_PP, .bag = std::move(bag)}; -} - -SlugCounts changed(SlugCounts counts, const SlugCounts& set){ - for (const auto& [name, count] : set){ - counts[name] = count; - } - return counts; -} - -std::string items_text(const std::vector& items){ - std::string text; - for (const std::string& item : items){ - text += text.empty() ? item : std::format(", {}", item); - } - return text; -} - -// The fight's start save, and each try's battle in order (the last one -// repeats). -class FakeLeagueRunner{ -public: - FakeLeagueRunner(const LeagueFightData& fight, LeagueSide save, std::vector battles) - : m_fight(fight) - , m_save(std::move(save)) - , m_battles(std::move(battles)) - {} - - LeagueFightRunner runner(){ - return LeagueFightRunner{ - .load_start = [this]{ m_now = m_save; }, - .top_up = [this]{ return top_up(); }, - .read_side = [this]{ return m_now; }, - .fight = [this]{ return fight(); }, - .save = [this]{ m_saves++; }, - .log = [](std::string_view){}, - }; - } - int saves() const{ - return m_saves; - } - int fights() const{ - return m_fights; - } - -private: - std::vector top_up(){ - PlannedCarry carry{.hp = m_now.hp, .max_hp = m_now.max_hp, .pp = m_now.pp, .full_pp = FULL_PP, .bag = m_now.bag}; - std::vector used = planned_between(carry, m_fight); - m_now.hp = carry.hp; - m_now.pp = carry.pp; - m_now.bag = carry.bag; - return used; - } - LeagueBattleEnd fight(){ - const ScriptedBattle& battle = m_battles[std::min(m_fights, m_battles.size() - 1)]; - m_fights++; - for (const auto& [item, count] : battle.used){ - m_now.bag[item] -= count; - } - return battle.end; - } - - const LeagueFightData& m_fight; - LeagueSide m_save; - LeagueSide m_now; - std::vector m_battles; - int m_saves = 0; - int m_fights = 0; -}; - -std::string_view verdict_name(LeagueFightVerdict verdict){ - switch (verdict){ - case LeagueFightVerdict::SAVED: - return "saved"; - case LeagueFightVerdict::BELOW_MIN_PASS: - return "below min_pass"; - case LeagueFightVerdict::OUT_OF_BUDGET: - return "out of budget"; - case LeagueFightVerdict::PRECONDITION_FAILED: - return "precondition failed"; - case LeagueFightVerdict::NO_FIGURES: - return "no figures"; - } - return ""; -} - -struct LoopCase{ - struct Input{ - std::string fight = {}; - LeagueSide save = {}; - std::vector battles = {}; - }; - struct Expectation{ - LeagueFightVerdict verdict = LeagueFightVerdict::SAVED; - int phase1_passes = 0; - int fights = 0; - int saves = 0; - // The first try's top-ups, when checked. - std::optional> top_up = std::nullopt; - // The last try's end, when checked. - std::optional last_end = std::nullopt; - }; - - std::string name = {}; - Input input = {}; - Expectation expectation = {}; -}; - -class Test_LeagueLoop : public UnitTest{ -public: - explicit Test_LeagueLoop(LoopCase test_case) - : UnitTest(std::format("PokemonFRLG::AutoStoryLeagueLoop - fake runner: {}", test_case.name)) - , m_case(std::move(test_case)) - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const LeagueFightData* fight = league_fight_data(league_plan_data(), m_case.input.fight); - if (fight == nullptr){ - return std::format("no fight {}.", m_case.input.fight); - } - FakeLeagueRunner fake(*fight, m_case.input.save, m_case.input.battles); - const LeagueFightReport report = run_league_fight(*fight, fake.runner()); - const LoopCase::Expectation& want = m_case.expectation; - if (report.verdict != want.verdict || report.phase1_passes != want.phase1_passes - || fake.fights() != want.fights || fake.saves() != want.saves - ){ - return std::format("{}, phase 1 passes {}, fights {}, saves {}; expected {}, {}, {}, {}.", - verdict_name(report.verdict), report.phase1_passes, fake.fights(), fake.saves(), - verdict_name(want.verdict), want.phase1_passes, want.fights, want.saves); - } - if (want.top_up && (report.tries.empty() || report.tries.front().top_up != *want.top_up)){ - return std::format("top-up [{}]; expected [{}].", - report.tries.empty() ? std::string() : items_text(report.tries.front().top_up), items_text(*want.top_up)); - } - if (want.last_end && (report.tries.empty() || report.tries.back().end != *want.last_end)){ - return "the last try ended otherwise."; - } - return true; - } - -private: - LoopCase m_case; -}; - -// Bruno's start save: Lorelei won on her caps (a Full Restore, six X Specials). -SlugCounts bruno_bag(){ - return changed(league_bag(), {{"full-restore", 7}, {"x-special", 9}}); -} - -const LoopCase LOOP_CASES[] = { - { - .name = "Lorelei: ten passes, saved on the first phase 2 try", - .input = {.fight = "lorelei", .save = full_side(league_bag()), .battles = {win()}}, - .expectation = {.verdict = LeagueFightVerdict::SAVED, .phase1_passes = 10, .fights = 11, .saves = 1}, - }, - { - .name = "Lorelei: four passes in phase 1, under min_pass 5: stop", - .input = {.fight = "lorelei", .save = full_side(league_bag()), .battles = joined(repeated(4, win()), {lost()})}, - .expectation = {.verdict = LeagueFightVerdict::BELOW_MIN_PASS, .phase1_passes = 4, .fights = 10, .saves = 0}, - }, - { - .name = "Lorelei: phase 2 passes on its third try: saved", - .input = { - .fight = "lorelei", - .save = full_side(league_bag()), - .battles = joined(joined(repeated(5, win()), repeated(7, lost())), {win()}), - }, - .expectation = {.verdict = LeagueFightVerdict::SAVED, .phase1_passes = 5, .fights = 13, .saves = 1}, - }, - { - .name = "Lorelei: no pass in the reset budget of 5: stop", - .input = {.fight = "lorelei", .save = full_side(league_bag()), .battles = joined(repeated(5, win()), {lost()})}, - .expectation = {.verdict = LeagueFightVerdict::OUT_OF_BUDGET, .phase1_passes = 5, .fights = 15, .saves = 0}, - }, - { - .name = "Lorelei: phase 2 wins over the Full Restore cap: never saved", - .input = { - .fight = "lorelei", - .save = full_side(league_bag()), - .battles = joined(repeated(5, win()), {win_on_two_full_restores()}), - }, - .expectation = { - .verdict = LeagueFightVerdict::OUT_OF_BUDGET, .phase1_passes = 5, .fights = 15, .saves = 0, - .last_end = LeagueBattleEnd::WON, - }, - }, - { - .name = "Bruno: a Roar, then early resets after Onix: tries that don't pass", - .input = {.fight = "bruno", .save = full_side(bruno_bag()), .battles = {roared(), early_reset()}}, - .expectation = { - .verdict = LeagueFightVerdict::BELOW_MIN_PASS, .phase1_passes = 0, .fights = 10, .saves = 0, - .last_end = LeagueBattleEnd::EARLY_RESET, - }, - }, - { - .name = "Lorelei's save is a Full Restore short of the entry contract: stop before fighting", - .input = {.fight = "lorelei", .save = full_side(changed(league_bag(), {{"full-restore", 7}})), .battles = {win()}}, - .expectation = {.verdict = LeagueFightVerdict::PRECONDITION_FAILED, .phase1_passes = 0, .fights = 0, .saves = 0}, - }, - { - .name = "before Bruno, 40 HP missing: one Super Potion", - .input = { - .fight = "bruno", - .save = LeagueSide{.hp = OUR_MAX_HP - 40, .max_hp = OUR_MAX_HP, .pp = FULL_PP, .bag = bruno_bag()}, - .battles = {lost()}, - }, - .expectation = { - .verdict = LeagueFightVerdict::BELOW_MIN_PASS, .phase1_passes = 0, .fights = 10, .saves = 0, - .top_up = std::vector{"super-potion"}, - }, - }, - { - .name = "before Bruno, 90 HP missing and two Super Potions spare: two", - .input = { - .fight = "bruno", - .save = LeagueSide{ - .hp = OUR_MAX_HP - 90, .max_hp = OUR_MAX_HP, .pp = FULL_PP, .bag = changed(bruno_bag(), {{"super-potion", 7}}), - }, - .battles = {lost()}, - }, - .expectation = { - .verdict = LeagueFightVerdict::BELOW_MIN_PASS, .phase1_passes = 0, .fights = 10, .saves = 0, - .top_up = std::vector{"super-potion", "super-potion"}, - }, - }, - { - .name = "before Bruno, 120 HP missing: a Full Restore", - .input = { - .fight = "bruno", - .save = LeagueSide{.hp = OUR_MAX_HP - 120, .max_hp = OUR_MAX_HP, .pp = FULL_PP, .bag = bruno_bag()}, - .battles = {lost()}, - }, - .expectation = { - .verdict = LeagueFightVerdict::BELOW_MIN_PASS, .phase1_passes = 0, .fights = 10, .saves = 0, - .top_up = std::vector{"full-restore"}, - }, - }, - { - .name = "before the Champion, Surf 5 and Blizzard 2: the Elixir", - .input = { - .fight = "champion", - .save = LeagueSide{ - .hp = OUR_MAX_HP, .max_hp = OUR_MAX_HP, - .pp = changed(FULL_PP, {{"surf", 5}, {"blizzard", 2}}), - .bag = { - {"full-restore", 2}, {"x-special", 2}, {"x-speed", 1}, {"x-accuracy", 3}, {"guard-spec", 2}, - {"elixir", 1}, {"max-elixir", 1}, - }, - }, - .battles = {lost()}, - }, - .expectation = { - .verdict = LeagueFightVerdict::BELOW_MIN_PASS, .phase1_passes = 0, .fights = 10, .saves = 0, - .top_up = std::vector{"elixir"}, - }, - }, - { - .name = "before Lance, Surf 3: no Elixir", - .input = { - .fight = "lance", - .save = LeagueSide{ - .hp = OUR_MAX_HP, .max_hp = OUR_MAX_HP, - .pp = changed(FULL_PP, {{"surf", 3}}), - .bag = { - {"full-restore", 4}, {"x-special", 4}, {"x-speed", 1}, {"x-accuracy", 3}, {"guard-spec", 2}, - {"super-potion", 2}, {"elixir", 1}, {"max-elixir", 1}, - }, - }, - .battles = {lost()}, - }, - .expectation = { - .verdict = LeagueFightVerdict::BELOW_MIN_PASS, .phase1_passes = 0, .fights = 10, .saves = 0, - .top_up = std::vector{}, - }, - }, -}; - -} // namespace - - -void add_tests_AutoStoryLeagueLoop(UnitTestDatabase& database){ - for (const LoopCase& test_case : LOOP_CASES){ - database.add(test_case); - } -} - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop_Tests.h deleted file mode 100644 index 124d06f754..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop_Tests.h +++ /dev/null @@ -1,28 +0,0 @@ -/* AutoStory League Loop Tests - * - * From: https://github.com/PokemonAutomation/ - * - * Registration of the League loop's tests on a fake runner - * (PokemonFRLG_AutoStoryLeagueLoop_Tests.cpp). - * - */ - -#ifndef PokemonAutomation_PokemonFRLG_AutoStoryLeagueLoop_Tests_H -#define PokemonAutomation_PokemonFRLG_AutoStoryLeagueLoop_Tests_H - -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -// Registers the League loop's tests. -void add_tests_AutoStoryLeagueLoop(UnitTestDatabase& database); - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan.cpp deleted file mode 100644 index dbf6d832c4..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan.cpp +++ /dev/null @@ -1,245 +0,0 @@ -/* AutoStory League Plan - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "PokemonFRLG_AutoStoryLeaguePlan.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -namespace{ - -// The bag the League is restocked to (20.01a's Mart and earlier rows): -// the bag of 2026-11-16, plus Full Heals for the fights' budgets. Not a -// precondition: the League is planned from whatever the bag holds (user, -// 2026-11-16: no money left for the next run). -struct MinimumRow{ - std::string_view item; - int count; -}; -constexpr MinimumRow LEAGUE_MINIMUM[] = { - {"full-restore", 8}, - {"x-special", 15}, - {"x-speed", 5}, - {"x-accuracy", 3}, - {"guard-spec", 2}, - {"max-elixir", 1}, - {"elixir", 1}, - {"super-potion", 6}, - {"full-heal", 6}, -}; - -// The Champion keeps at least this many Full Restores (at most half the -// bag): its fight is where the sim's chains end. -constexpr int CHAMPION_FULL_RESTORES = 3; - -// One fight's row: its Full Restore weight (the sim's median spend in -// tenths), the setup items it wants (the note's budgeted-C2 table, X Sp / -// X Spe / X Acc), Guard Spec and Elixirs, its entry HP and PP, and the -// Hyper (or Max) Potions and Full Heals it wants: two each against -// Lorelei's Lapras (user, 2026-11-16), Full Heals against Agatha's -// Hypnosis. -struct FightRow{ - std::string_view trainer; - std::string_view name; - int full_restore_weight; - int x_special; - int x_speed; - int x_accuracy; - int guard_spec; - int elixir; - int entry_hp_percent; - int surf_pp_floor; - int blizzard_pp_floor; - int hyper_potion; - int full_heal; -}; -constexpr size_t FIGHTS = 5; -constexpr std::array LEAGUE_FIGHTS = {{ - // Full HP from Indigo Plateau's nurse. - {"TRAINER_ELITE_FOUR_LORELEI", "lorelei", 6, 4, 1, 0, 0, 0, 100, 0, 0, 2, 2}, - // 80%: PokeGuy's 130/162; a 30% floor lost 26% of the sim's chains here. - {"TRAINER_ELITE_FOUR_BRUNO", "bruno", 15, 4, 5, 0, 0, 0, 80, 7, 0, 1, 0}, - // 27%: PokeGuy's 45/165, Torrent on. - {"TRAINER_ELITE_FOUR_AGATHA", "agatha", 2, 2, 1, 0, 0, 0, 27, 6, 0, 1, 2}, - {"TRAINER_ELITE_FOUR_LANCE", "lance", 30, 3, 1, 1, 0, 1, 100, 6, 5, 2, 1}, - {"TRAINER_CHAMPION_FIRST_BULBASAUR", "champion", 22, 4, 2, 2, 1, 1, 100, 8, 2, 2, 1}, -}}; - -using Split = std::array; - -int held(const BagCounts& bag, std::string_view item){ - const auto found = bag.find(item); - return found == bag.end() ? 0 : std::max(0, found->second); -} - -// `total` split in proportion to `weights` (largest remainder, ties to -// the later fight); all zero if the weights are. -Split split_by_weight(int total, const Split& weights, size_t count = FIGHTS){ - Split out{}; - int sum = 0; - for (size_t c = 0; c < count; c++){ - sum += weights[c]; - } - if (sum <= 0 || total <= 0){ - return out; - } - int given = 0; - std::array remainder{}; - for (size_t c = 0; c < count; c++){ - out[c] = total * weights[c] / sum; - remainder[c] = total * weights[c] % sum; - given += out[c]; - } - for (; given < total; given++){ - size_t best = 0; - for (size_t c = 0; c < count; c++){ - if (remainder[c] >= remainder[best]){ - best = c; - } - } - out[best]++; - remainder[best] = -1; - } - return out; -} - -// `total` against each fight's wanted count: all of it when the bag -// covers them (the rest spare), else the Champion first and the rest in -// proportion. -Split split_wanted(int total, const Split& wanted, int& spare){ - int sum = 0; - for (const int count : wanted){ - sum += count; - } - if (total >= sum){ - spare = total - sum; - return wanted; - } - spare = 0; - const int champion = std::min(wanted[FIGHTS - 1], total); - Split out = split_by_weight(total - champion, wanted, FIGHTS - 1); - out[FIGHTS - 1] = champion; - return out; -} - -Split split_full_restores(int total){ - Split weights{}; - for (size_t c = 0; c < FIGHTS; c++){ - weights[c] = LEAGUE_FIGHTS[c].full_restore_weight; - } - Split out = split_by_weight(total, weights); - const int reserve = std::min(CHAMPION_FULL_RESTORES, total / 2); - for (size_t c = 0; c + 1 < FIGHTS && out[FIGHTS - 1] < reserve; c++){ - const int moved = std::min(out[c], reserve - out[FIGHTS - 1]); - out[c] -= moved; - out[FIGHTS - 1] += moved; - } - return out; -} - -// The fights' wanted counts of one item: `member` of each row. -Split wanted_of(int FightRow::* member){ - Split out{}; - for (size_t c = 0; c < FIGHTS; c++){ - out[c] = LEAGUE_FIGHTS[c].*member; - } - return out; -} - -} // namespace - - -std::optional league_shortfalls(const BagCounts& bag){ - std::string out; - for (const MinimumRow& row : LEAGUE_MINIMUM){ - const int count = held(bag, row.item); - if (count < row.count){ - out += std::format("{}{} {} of {}", out.empty() ? "" : ", ", row.item, count, row.count); - } - } - if (out.empty()){ - return std::nullopt; - } - return out; -} - -LeaguePlan plan_league(const BagCounts& bag){ - int spare_special = 0; - int spare_speed = 0; - int spare_accuracy = 0; - int spare_guard = 0; - int spare_elixir = 0; - int spare_hyper = 0; - int spare_full_heal = 0; - const Split full_restore = split_full_restores(held(bag, "full-restore")); - const Split special = split_wanted(held(bag, "x-special"), wanted_of(&FightRow::x_special), spare_special); - const Split speed = split_wanted(held(bag, "x-speed"), wanted_of(&FightRow::x_speed), spare_speed); - const Split accuracy = split_wanted(held(bag, "x-accuracy"), wanted_of(&FightRow::x_accuracy), spare_accuracy); - const Split guard = split_wanted(held(bag, "guard-spec"), wanted_of(&FightRow::guard_spec), spare_guard); - const Split elixir = split_wanted( - held(bag, "elixir") + held(bag, "max-elixir"), wanted_of(&FightRow::elixir), spare_elixir - ); - const Split hyper = split_wanted( - held(bag, "hyper-potion") + held(bag, "max-potion"), wanted_of(&FightRow::hyper_potion), spare_hyper - ); - const Split full_heal = split_wanted(held(bag, "full-heal"), wanted_of(&FightRow::full_heal), spare_full_heal); - LeaguePlan plan; - for (size_t c = 0; c < FIGHTS; c++){ - const FightRow& row = LEAGUE_FIGHTS[c]; - plan.fights.push_back(LeagueFightPlan{ - .trainer = std::string(row.trainer), - .name = std::string(row.name), - .budget = { - .full_restore = full_restore[c], .x_special = special[c], .x_speed = speed[c], - .x_accuracy = accuracy[c], .guard_spec = guard[c], .elixir = elixir[c], - .hyper_potion = hyper[c], .full_heal = full_heal[c], - }, - .entry_hp_percent = row.entry_hp_percent, - .surf_pp_floor = row.surf_pp_floor, - .blizzard_pp_floor = row.blizzard_pp_floor, - }); - } - plan.spare = FightBudget{ - .full_restore = 0, .x_special = spare_special, .x_speed = spare_speed, - .x_accuracy = spare_accuracy, .guard_spec = spare_guard, .elixir = spare_elixir, - .hyper_potion = spare_hyper, .full_heal = spare_full_heal, - }; - return plan; -} - -std::vector league_plan_lines(const LeaguePlan& plan){ - std::vector lines; - for (const LeagueFightPlan& fight : plan.fights){ - lines.push_back(std::format( - "League plan: {}: {}; enter at {}% HP, Surf >= {}, Blizzard >= {}.", - fight.name, budget_text(fight.budget), fight.entry_hp_percent, fight.surf_pp_floor, fight.blizzard_pp_floor - )); - } - lines.push_back("League plan: spare: " + budget_text(plan.spare) + "."); - return lines; -} - -const LeagueFightPlan* league_fight(const LeaguePlan& plan, std::string_view trainer){ - for (const LeagueFightPlan& fight : plan.fights){ - if (fight.trainer == trainer){ - return &fight; - } - } - return nullptr; -} - - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan.h deleted file mode 100644 index bc59a8e2d7..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan.h +++ /dev/null @@ -1,100 +0,0 @@ -/* AutoStory League Plan - * - * From: https://github.com/PokemonAutomation/ - * - * The Elite Four and the Champion are one checkpoint with no save between - * the fights (user, 2026-11-16), so the bag read at the League's start is - * all five fights get. This plans it out: a pure function from the bag's - * counts to an item budget per fight, and the rules between the fights. - * - * The planner (plan_league()): - * - LEAGUE_MINIMUM is the bag the League is restocked to; - * league_shortfalls() names what is short, for the log. The League - * is planned from whatever the bag holds (user, 2026-11-16). - * - Full Restores are spread over the five fights by the median each - * fight spends in PokemonSimulation's budgeted-C2 League chains - * (sim/frlg-e4-replica, ~/BDSPLab/notes/frlg-e4-replica-policy.md): - * Lance and the Champion take the most. The Champion keeps a reserve - * of at least CHAMPION_FULL_RESTORES (half the bag at most), taken - * from the earliest fights. - * - X Special, X Speed, X Accuracy, Guard Spec, the Elixirs, Hyper (and - * Max) Potions and Full Heals go by - * each fight's wanted count (the note's budgeted-C2 table); a bag - * short of the sum gives the Champion its count first and splits the - * rest in proportion. A bag with more than the sum keeps the extra - * as spare, which the KO-risk rules may still use. - * - Every split is largest-remainder, ties to the later fight. - * - What a fight leaves of its budget rolls forward to the next. - * - * Between the fights: between_fight_action() (PokemonFRLG_AutoStoryLeagueSteps.h) - * from each fight's entry HP and PP floors. - * - * The in-battle rules that spend the budget are in - * PokemonFRLG_AutoStoryBattlePolicy.h (BUDGETED_SETUP). - * - */ - -#ifndef PokemonAutomation_PokemonFRLG_AutoStoryLeaguePlan_H -#define PokemonAutomation_PokemonFRLG_AutoStoryLeaguePlan_H - -#include -#include -#include -#include -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "PokemonFRLG_AutoStoryLeagueBudget.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -// One League fight in the plan. -struct LeagueFightPlan{ - // The battle step's trainer ("TRAINER_ELITE_FOUR_LORELEI"). - std::string trainer; - // "lorelei". - std::string name; - FightBudget budget; - // The HP the lead enters with, in percent of its maximum. - int entry_hp_percent = 100; - // The PP the lead enters with, at least. - int surf_pp_floor = 0; - int blizzard_pp_floor = 0; -}; - -// The League's plan: the fights in order, and what the bag holds beyond -// their budgets. -struct LeaguePlan{ - std::vector fights; - FightBudget spare; -}; - -// The items `bag` holds less of than LEAGUE_MINIMUM, as "full-restore 7 -// of 8, max-elixir 0 of 1"; none when it holds enough. -std::optional league_shortfalls(const BagCounts& bag); - -// The budgets and between-fight rows for the five fights from `bag`. -LeaguePlan plan_league(const BagCounts& bag); - -// The plan, one line per fight, for the log. -std::vector league_plan_lines(const LeaguePlan& plan); - -// The fight in `plan` whose trainer is `trainer`, none if it isn't one. -const LeagueFightPlan* league_fight(const LeaguePlan& plan, std::string_view trainer); - -// A League run: the plan, and what the fights before have left of theirs. -struct LeagueRun{ - LeaguePlan plan; - FightBudget carried; -}; - -// Registers the League plan tests. -void add_tests_AutoStoryLeaguePlan(UnitTestDatabase& database); - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.cpp index 19f6a3f3fd..54a2a89991 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.cpp @@ -129,17 +129,23 @@ LeaguePassFigures pass_of(const JsonObject& pass){ }; } -void read_contract(const JsonObject& contract, LeagueFightData& fight){ +// `lead_max_hp`: the HP hp_sim counts out of (the plan's entry_hp); none +// leaves the fight without an HP floor. +void read_contract(const JsonObject& contract, std::optional lead_max_hp, LeagueFightData& fight){ if (const JsonObject* pass = contract.get_object("pass")){ fight.pass = pass_of(*pass); } if (const JsonObject* entry = contract.get_object("entry")){ fight.entry_items = counts_of(entry->get_object("items"), true); fight.entry_pp = counts_of(entry->get_object("pp"), false); + const JsonObject* hp = entry->get_object("hp_sim"); + if (hp != nullptr && lead_max_hp && *lead_max_hp > 0){ + fight.entry_hp_share = static_cast(hp->get_integer_throw("p10")) / *lead_max_hp; + } } } -LeagueFightData fight_of(const std::string& name, const JsonObject& object){ +LeagueFightData fight_of(const std::string& name, const JsonObject& object, std::optional lead_max_hp){ LeagueFightData fight{.name = name, .goal = object.get_string_default("goal")}; for (const JsonValue& foe : object.get_array_throw("foes")){ fight.foes.push_back(foe_of(foe.to_object_throw())); @@ -160,7 +166,7 @@ LeagueFightData fight_of(const std::string& name, const JsonObject& object){ read_reset(*reset, fight); } if (const JsonObject* contract = object.get_object("contract")){ - read_contract(*contract, fight); + read_contract(*contract, lead_max_hp, fight); } return fight; } @@ -174,12 +180,16 @@ LeaguePlanData parse_league_plan(std::string_view json){ throw ParseException(std::format("{}.json: not a {} plan.", PLAN_FILE, PLAN_FORMAT)); } LeaguePlanData plan; + std::optional lead_max_hp; + if (const JsonObject* entry_hp = root.get_object("entry_hp")){ + lead_max_hp = static_cast(entry_hp->get_integer_throw("lead_max_hp")); + } const JsonObject& fights = root.get_object_throw("fights"); // In the League's order, whatever the file's. for (const TrainerFight& trainer : TRAINER_FIGHTS){ const std::string name(trainer.fight); if (const JsonObject* fight = fights.get_object(name)){ - plan.fights.push_back(fight_of(name, *fight)); + plan.fights.push_back(fight_of(name, *fight, lead_max_hp)); } } return plan; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.h index 1c421e7fb1..b39c73055a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.h @@ -74,6 +74,11 @@ struct LeagueFightData{ // done. SlugCounts entry_items = {}; SlugCounts entry_pp = {}; + // The least HP our side starts the fight with, as a share of its + // maximum: contract.entry.hp_sim.p10 over the plan's entry_hp + // lead_max_hp. That convention awaits the user's confirmation (see + // entry_hp in frlg-league-plan.json). None: no floor. + std::optional entry_hp_share = std::nullopt; // PP this fight must not spend, by move, and the items it must leave // in the bag. SlugCounts reserve_pp = {}; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan_Tests.cpp index 18d47d3a6e..3cea3fb3a6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan_Tests.cpp @@ -2,14 +2,11 @@ * * From: https://github.com/PokemonAutomation/ * - * The League planner (PokemonFRLG_AutoStoryLeaguePlan.h) on the bag of - * 2026-11-16, a smaller and a larger one; the minimum check; the items - * between the fights (PokemonFRLG_AutoStoryLeagueSteps.h); and the - * budgeted C2 policy's turns (PokemonFRLG_AutoStoryBattlePolicy.h). + * The budgeted C2 policy's turns (PokemonFRLG_AutoStoryBattlePolicy.h) + * in the League rows' battles (20.01 to 20.05). * */ -#include #include #include #include @@ -18,8 +15,7 @@ #include "Common/Cpp/TestRunners/UnitTest.h" #include "PokemonFRLG_AutoStoryBattlePolicy.h" #include "PokemonFRLG_AutoStoryItemsPocket.h" -#include "PokemonFRLG_AutoStoryLeaguePlan.h" -#include "PokemonFRLG_AutoStoryLeagueSteps.h" +#include "PokemonFRLG_AutoStoryRows20_Tests.h" #include "PokemonFRLG_AutoStoryTable.h" namespace PokemonAutomation{ @@ -29,399 +25,6 @@ namespace PokemonFRLG{ namespace{ -// The bag at the League's start on console B, 2026-11-16. -const BagCounts BAG_NOW = { - {"full-restore", 8}, {"x-special", 15}, {"x-speed", 5}, {"x-accuracy", 3}, {"guard-spec", 2}, - {"max-elixir", 1}, {"elixir", 1}, {"super-potion", 6}, {"full-heal", 2}, {"parlyz-heal", 2}, -}; - - -struct LeaguePlanInput{ - BagCounts bag; -}; - -struct LeaguePlanExpectation{ - // Lorelei, Bruno, Agatha, Lance, the Champion. - std::array budgets; - FightBudget spare; -}; - -struct LeaguePlanCase{ - std::string name; - LeaguePlanInput input; - LeaguePlanExpectation expectation; -}; - -class Test_LeaguePlan : public UnitTest{ -public: - explicit Test_LeaguePlan(LeaguePlanCase test_case) - : UnitTest(std::format("PokemonFRLG::AutoStory - League plan: {}", test_case.name)) - , m_case(std::move(test_case)) - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const LeaguePlan plan = plan_league(m_case.input.bag); - if (plan.fights.size() != m_case.expectation.budgets.size()){ - return std::format("expected {} fights, planned {}", m_case.expectation.budgets.size(), plan.fights.size()); - } - for (size_t c = 0; c < plan.fights.size(); c++){ - if (plan.fights[c].budget != m_case.expectation.budgets[c]){ - return std::format( - "{}: expected {}, planned {}", - plan.fights[c].name, budget_text(m_case.expectation.budgets[c]), budget_text(plan.fights[c].budget) - ); - } - } - if (plan.spare != m_case.expectation.spare){ - return std::format("spare: expected {}, planned {}", budget_text(m_case.expectation.spare), budget_text(plan.spare)); - } - return true; - } - -private: - LeaguePlanCase m_case; -}; - -FightBudget budget(int full_restore, int x_special, int x_speed, int x_accuracy, int guard_spec, int elixir){ - return FightBudget{ - .full_restore = full_restore, .x_special = x_special, .x_speed = x_speed, - .x_accuracy = x_accuracy, .guard_spec = guard_spec, .elixir = elixir, - }; -} - -// `base` with its Hyper (and Max) Potions and Full Heals. -FightBudget with_heals(FightBudget base, int hyper_potion, int full_heal){ - base.hyper_potion = hyper_potion; - base.full_heal = full_heal; - return base; -} - -const LeaguePlanCase LEAGUE_PLAN_CASES[] = { - { - .name = "the bag of 2026-11-16", - .input = {.bag = BAG_NOW}, - // Full Restores by the sim's medians, the Champion's reserve of 3 - // taken from Lorelei; 15 X Specials against 17 wanted, the - // Champion's 4 first. - .expectation = { - .budgets = { - budget(/*full_restore=*/0, /*x_special=*/3, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - budget(/*full_restore=*/2, /*x_special=*/3, /*x_speed=*/2, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - with_heals(budget(/*full_restore=*/0, /*x_special=*/2, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), /*hyper_potion=*/0, /*full_heal=*/1), - budget(/*full_restore=*/3, /*x_special=*/3, /*x_speed=*/1, /*x_accuracy=*/1, /*guard_spec=*/0, /*elixir=*/1), - with_heals(budget(/*full_restore=*/3, /*x_special=*/4, /*x_speed=*/2, /*x_accuracy=*/2, /*guard_spec=*/1, /*elixir=*/1), /*hyper_potion=*/0, /*full_heal=*/1), - }, - .spare = budget(/*full_restore=*/0, /*x_special=*/0, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/1, /*elixir=*/0), - }, - }, - { - .name = "a smaller bag", - .input = {.bag = { - {"full-restore", 4}, {"x-special", 10}, {"x-speed", 3}, {"x-accuracy", 2}, {"guard-spec", 1}, {"elixir", 1}, - }}, - // The Champion's Full Restore reserve is half the bag, 2. - .expectation = { - .budgets = { - budget(/*full_restore=*/0, /*x_special=*/2, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - budget(/*full_restore=*/0, /*x_special=*/2, /*x_speed=*/1, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - budget(/*full_restore=*/0, /*x_special=*/1, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - budget(/*full_restore=*/2, /*x_special=*/1, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - budget(/*full_restore=*/2, /*x_special=*/4, /*x_speed=*/2, /*x_accuracy=*/2, /*guard_spec=*/1, /*elixir=*/1), - }, - .spare = {}, - }, - }, - { - .name = "a larger bag (the note's buy)", - .input = {.bag = { - {"full-restore", 12}, {"x-special", 18}, {"x-speed", 9}, {"x-accuracy", 3}, {"guard-spec", 2}, - {"max-elixir", 1}, {"elixir", 1}, {"super-potion", 6}, - }}, - // Every X Special wanted, one spare; Lance and the Champion take - // the extra Full Restores. - .expectation = { - .budgets = { - budget(/*full_restore=*/1, /*x_special=*/4, /*x_speed=*/1, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - budget(/*full_restore=*/2, /*x_special=*/4, /*x_speed=*/4, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - budget(/*full_restore=*/0, /*x_special=*/2, /*x_speed=*/1, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - budget(/*full_restore=*/5, /*x_special=*/3, /*x_speed=*/1, /*x_accuracy=*/1, /*guard_spec=*/0, /*elixir=*/1), - budget(/*full_restore=*/4, /*x_special=*/4, /*x_speed=*/2, /*x_accuracy=*/2, /*guard_spec=*/1, /*elixir=*/1), - }, - .spare = budget(/*full_restore=*/0, /*x_special=*/1, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/1, /*elixir=*/0), - }, - }, - { - .name = "the bag after the 2026-11-16 15:35 run, no restock", - .input = {.bag = { - {"full-restore", 7}, {"x-special", 10}, {"x-speed", 5}, {"x-accuracy", 3}, {"guard-spec", 2}, - {"max-elixir", 1}, {"full-heal", 2}, - }}, - // The Champion's 4 X Specials first; its Full Heal first, the - // other to Agatha (Hypnosis). - .expectation = { - .budgets = { - budget(/*full_restore=*/0, /*x_special=*/2, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - budget(/*full_restore=*/1, /*x_special=*/2, /*x_speed=*/2, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), - with_heals(budget(/*full_restore=*/0, /*x_special=*/1, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/0, /*elixir=*/0), /*hyper_potion=*/0, /*full_heal=*/1), - budget(/*full_restore=*/3, /*x_special=*/1, /*x_speed=*/1, /*x_accuracy=*/1, /*guard_spec=*/0, /*elixir=*/0), - with_heals(budget(/*full_restore=*/3, /*x_special=*/4, /*x_speed=*/2, /*x_accuracy=*/2, /*guard_spec=*/1, /*elixir=*/1), /*hyper_potion=*/0, /*full_heal=*/1), - }, - .spare = budget(/*full_restore=*/0, /*x_special=*/0, /*x_speed=*/0, /*x_accuracy=*/0, /*guard_spec=*/1, /*elixir=*/0), - }, - }, - { - .name = "Hyper Potions and Full Heals for every fight", - .input = {.bag = {{"hyper-potion", 6}, {"max-potion", 2}, {"full-heal", 6}}}, - // Two of each against Lorelei's Lapras; a Max Potion counts as a Hyper Potion. - .expectation = { - .budgets = { - with_heals(FightBudget{}, /*hyper_potion=*/2, /*full_heal=*/2), - with_heals(FightBudget{}, /*hyper_potion=*/1, /*full_heal=*/0), - with_heals(FightBudget{}, /*hyper_potion=*/1, /*full_heal=*/2), - with_heals(FightBudget{}, /*hyper_potion=*/2, /*full_heal=*/1), - with_heals(FightBudget{}, /*hyper_potion=*/2, /*full_heal=*/1), - }, - .spare = {}, - }, - }, -}; - - -struct LeagueMinimumInput{ - BagCounts bag; -}; - -struct LeagueMinimumExpectation{ - // league_shortfalls()'s list, none when the bag is enough. - std::optional shortfalls; -}; - -struct LeagueMinimumCase{ - std::string name; - LeagueMinimumInput input; - LeagueMinimumExpectation expectation; -}; - -class Test_LeagueMinimum : public UnitTest{ -public: - explicit Test_LeagueMinimum(LeagueMinimumCase test_case) - : UnitTest(std::format("PokemonFRLG::AutoStory - League minimum: {}", test_case.name)) - , m_case(std::move(test_case)) - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::optional found = league_shortfalls(m_case.input.bag); - if (found != m_case.expectation.shortfalls){ - return std::format( - "expected {}, read {}", - m_case.expectation.shortfalls.value_or("nothing short"), found.value_or("nothing short") - ); - } - return true; - } - -private: - LeagueMinimumCase m_case; -}; - -const LeagueMinimumCase LEAGUE_MINIMUM_CASES[] = { - { - .name = "the bag of 2026-11-16 lacks only Full Heals", - .input = {.bag = BAG_NOW}, - .expectation = {.shortfalls = "full-heal 2 of 6"}, - }, - { - .name = "one Full Restore and the Max Elixir short", - .input = {.bag = { - {"full-restore", 7}, {"x-special", 15}, {"x-speed", 5}, {"x-accuracy", 3}, {"guard-spec", 2}, - {"elixir", 1}, {"super-potion", 6}, {"full-heal", 6}, - }}, - .expectation = {.shortfalls = "full-restore 7 of 8, max-elixir 0 of 1"}, - }, - { - .name = "more than the minimum is enough", - .input = {.bag = { - {"full-restore", 12}, {"x-special", 18}, {"x-speed", 9}, {"x-accuracy", 3}, {"guard-spec", 2}, - {"max-elixir", 1}, {"elixir", 1}, {"super-potion", 10}, {"full-heal", 8}, - }}, - .expectation = {.shortfalls = std::nullopt}, - }, -}; - - -struct BetweenFightsInput{ - BetweenFightView lead; - BagCounts bag; - // The next fight, by its plan row's name. - std::string next; -}; - -struct BetweenFightsExpectation{ - BetweenFightAction action; -}; - -struct BetweenFightsCase{ - std::string name; - BetweenFightsInput input; - BetweenFightsExpectation expectation; -}; - -std::string action_text(const BetweenFightAction& action){ - switch (action.move){ - case BetweenFightMove::READY: - return "ready"; - case BetweenFightMove::USE_ITEM: - return std::format("the {}", action.item.value_or("?")); - case BetweenFightMove::READ_HP: - return "read the HP"; - case BetweenFightMove::HP_UNKNOWN: - return "HP unknown"; - } - return "?"; -} - -class Test_BetweenFights : public UnitTest{ -public: - explicit Test_BetweenFights(BetweenFightsCase test_case) - : UnitTest(std::format("PokemonFRLG::AutoStory - League between fights: {}", test_case.name)) - , m_case(std::move(test_case)) - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const LeaguePlan plan = plan_league(BAG_NOW); - const LeagueFightPlan* next = nullptr; - for (const LeagueFightPlan& fight : plan.fights){ - if (fight.name == m_case.input.next){ - next = &fight; - } - } - if (next == nullptr){ - return "no fight " + m_case.input.next; - } - const BetweenFightAction action = between_fight_action(m_case.input.lead, m_case.input.bag, *next); - if (action != m_case.expectation.action){ - return std::format("expected {}, chose {}", action_text(m_case.expectation.action), action_text(action)); - } - return true; - } - -private: - BetweenFightsCase m_case; -}; - -BetweenFightView lead_at(std::optional hp, int max_hp, int surf_pp = 15, int blizzard_pp = 5){ - return BetweenFightView{ - .hp = hp, .max_hp = max_hp, .hp_reread = false, .cure = "", - .surf_pp = surf_pp, .surf_max_pp = 15, .blizzard_pp = blizzard_pp, .blizzard_max_pp = 5, - }; -} - -// `lead` after its HP was read again (READ_HP). -BetweenFightView reread(BetweenFightView lead){ - lead.hp_reread = true; - return lead; -} - -BetweenFightView with_cure(BetweenFightView lead, std::string cure){ - lead.cure = std::move(cure); - return lead; -} - -BetweenFightAction use(std::string item){ - return BetweenFightAction{.move = BetweenFightMove::USE_ITEM, .item = std::move(item)}; -} - -const BetweenFightAction READY{.move = BetweenFightMove::READY}; - -const BetweenFightsCase BETWEEN_FIGHTS_CASES[] = { - { - .name = "into Bruno at 117/165: a Super Potion up to 80%", - .input = {.lead = lead_at(/*hp=*/117, /*max_hp=*/165), .bag = BAG_NOW, .next = "bruno"}, - .expectation = {.action = use("super-potion")}, - }, - { - .name = "into Bruno at 140/165: nothing", - .input = {.lead = lead_at(/*hp=*/140, /*max_hp=*/165), .bag = BAG_NOW, .next = "bruno"}, - .expectation = {.action = READY}, - }, - { - .name = "into Agatha at 48/165: nothing, above 27%", - .input = {.lead = lead_at(/*hp=*/48, /*max_hp=*/165), .bag = BAG_NOW, .next = "agatha"}, - .expectation = {.action = READY}, - }, - { - .name = "into Lance at 48/168: a Super Potion, not a Full Restore", - .input = {.lead = lead_at(/*hp=*/48, /*max_hp=*/168), .bag = BAG_NOW, .next = "lance"}, - .expectation = {.action = use("super-potion")}, - }, - { - .name = "into Lance at 98/168, no Super Potion left: a Full Restore", - .input = {.lead = lead_at(/*hp=*/98, /*max_hp=*/168), .bag = {{"full-restore", 5}}, .next = "lance"}, - .expectation = {.action = use("full-restore")}, - }, - { - .name = "into Lance at 48/168, no Super Potion, Hyper Potions held: a Hyper Potion, not a Full Restore", - .input = {.lead = lead_at(/*hp=*/48, /*max_hp=*/168), .bag = {{"hyper-potion", 2}, {"full-restore", 5}}, .next = "lance"}, - .expectation = {.action = use("hyper-potion")}, - }, - { - .name = "paralysed: a Parlyz Heal first", - .input = { - .lead = with_cure(lead_at(/*hp=*/60, /*max_hp=*/168), "parlyz-heal"), - .bag = BAG_NOW, .next = "lance", - }, - .expectation = {.action = use("parlyz-heal")}, - }, - { - .name = "into the Champion with Surf 3, Blizzard 0: the Elixir", - .input = {.lead = lead_at(/*hp=*/171, /*max_hp=*/171, /*surf_pp=*/3, /*blizzard_pp=*/0), .bag = BAG_NOW, .next = "champion"}, - .expectation = {.action = use("elixir")}, - }, - { - .name = "into Lance with Blizzard 0 and no Elixir: the Max Elixir", - .input = { - .lead = lead_at(/*hp=*/168, /*max_hp=*/168, /*surf_pp=*/9, /*blizzard_pp=*/0), - .bag = {{"max-elixir", 1}}, .next = "lance", - }, - .expectation = {.action = use("max-elixir")}, - }, - { - .name = "HP unknown: read it again, no Full Restore", - .input = {.lead = lead_at(/*hp=*/std::nullopt, /*max_hp=*/165), .bag = BAG_NOW, .next = "bruno"}, - .expectation = {.action = {.move = BetweenFightMove::READ_HP}}, - }, - { - .name = "read again at 117/165: a Super Potion up to Bruno's 80%", - .input = {.lead = reread(lead_at(/*hp=*/117, /*max_hp=*/165)), .bag = BAG_NOW, .next = "bruno"}, - .expectation = {.action = use("super-potion")}, - }, - { - .name = "read again at 140/165: ready for Bruno", - .input = {.lead = reread(lead_at(/*hp=*/140, /*max_hp=*/165)), .bag = BAG_NOW, .next = "bruno"}, - .expectation = {.action = READY}, - }, - { - .name = "still unknown after reading it again: stop, no Full Restore", - .input = {.lead = reread(lead_at(/*hp=*/std::nullopt, /*max_hp=*/165)), .bag = BAG_NOW, .next = "bruno"}, - .expectation = {.action = {.move = BetweenFightMove::HP_UNKNOWN}}, - }, - { - .name = "poisoned, no Antidote or Full Heal: a Full Restore", - .input = { - .lead = with_cure(lead_at(/*hp=*/150, /*max_hp=*/168), "antidote"), - .bag = {{"full-restore", 5}, {"super-potion", 6}}, .next = "lance", - }, - .expectation = {.action = use("full-restore")}, - }, - { - .name = "poisoned with HP unknown: the Antidote before reading the HP", - .input = { - .lead = with_cure(lead_at(/*hp=*/std::nullopt, /*max_hp=*/168), "antidote"), - .bag = {{"antidote", 1}, {"full-restore", 5}}, .next = "lance", - }, - .expectation = {.action = use("antidote")}, - }, -}; - - - // The League's budgeted C2 (budgeted-setup) at one turn of a League // fight (Bruno's unless named): the foe out and its bar, the lead's HP, // status and Surf PP, and the fight's budget. The lead is the one into @@ -463,12 +66,12 @@ struct BudgetedTurnCase{ const Pokemon::StoryStep& league_battle(std::string_view name){ for (const StoryCheckpoint& row : story_checkpoints()){ for (const Pokemon::StoryStep& step : row.steps){ - if (row.id == "20.01" && step.kind == Pokemon::StoryStepKind::BATTLE && step.name == name){ + if (row.id.starts_with("20.") && step.kind == Pokemon::StoryStepKind::BATTLE && step.name == name){ return step; } } } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No battle {} in 20.01.", name)); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No League battle {}.", name)); } Supplies league_turn_supplies(const BudgetedTurnInput& input){ @@ -506,7 +109,7 @@ class Test_BudgetedTurn : public UnitTest{ const BudgetedTurnInput& input = m_case.input; const Supplies supplies = league_turn_supplies(input); if (supplies.policy.kind != BattlePolicyKind::BUDGETED_SETUP){ - return std::format("20.01 {}: expected budgeted-setup.", input.battle); + return std::format("{}: expected budgeted-setup.", input.battle); } PolicyState state(supplies.policy); state.foe_evasion_raised(input.foe_evasion); @@ -630,15 +233,6 @@ const BudgetedTurnCase BUDGETED_TURN_CASES[] = { void add_tests_AutoStoryLeaguePlan(UnitTestDatabase& database){ - for (const LeaguePlanCase& item : LEAGUE_PLAN_CASES){ - database.add(item); - } - for (const LeagueMinimumCase& item : LEAGUE_MINIMUM_CASES){ - database.add(item); - } - for (const BetweenFightsCase& item : BETWEEN_FIGHTS_CASES){ - database.add(item); - } for (const BudgetedTurnCase& item : BUDGETED_TURN_CASES){ database.add(item); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.cpp index 60dcb47750..97361e4d78 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.cpp @@ -9,6 +9,7 @@ #include #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "PokemonFRLG_AutoStoryLeagueFightData.h" +#include "PokemonFRLG_AutoStoryPlannedBetween.h" #include "PokemonFRLG_AutoStoryLeagueRows.h" namespace PokemonAutomation{ @@ -18,8 +19,26 @@ namespace PokemonFRLG{ namespace{ -// The League fight of `row`'s battle; none if it has none. -const LeagueFightData* row_fight(const StoryCheckpoint& row){ +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += std::format("{}{}", text.empty() ? "" : ", ", line); + } + return text.empty() ? std::string("nothing") : text; +} + +// `wanted` of `what` against `had`, logged; short of it noted. +void compare(std::string_view what, int had, int wanted, LeagueEntryCheck& check){ + check.compared.push_back(std::format("{} {}/{}", what, had, wanted)); + if (had < wanted){ + check.short_of.push_back(std::format("{} {} of {}", what, had, wanted)); + } +} + +} // namespace + + +const LeagueFightData* league_row_fight(const StoryCheckpoint& row){ for (const Pokemon::StoryStep& step : row.steps){ if (step.kind != Pokemon::StoryStepKind::BATTLE || !step.args.contains("trainer")){ continue; @@ -32,8 +51,17 @@ const LeagueFightData* row_fight(const StoryCheckpoint& row){ return nullptr; } -// The supplies' counts by bag slug. -SlugCounts counts_of(const Supplies& supplies){ +const LeagueFightData* next_league_fight(const LeagueFightData& fight){ + const std::vector& fights = league_plan_data().fights; + for (size_t c = 0; c + 1 < fights.size(); c++){ + if (fights[c].name == fight.name){ + return &fights[c + 1]; + } + } + return nullptr; +} + +SlugCounts supplies_counts(const Supplies& supplies){ SlugCounts counts(supplies.other_counts.begin(), supplies.other_counts.end()); counts["potion"] = supplies.potions; counts["super-potion"] = supplies.super_potions; @@ -44,29 +72,51 @@ SlugCounts counts_of(const Supplies& supplies){ return counts; } -} // namespace - +LeagueEntryCheck league_entry_check(const LeagueFightData& next, LeagueSide side){ + LeagueEntryCheck check; + PlannedCarry carry{.hp = side.hp, .max_hp = side.max_hp, .pp = side.pp, .full_pp = side.full_pp, .bag = side.bag}; + check.topped_up = planned_between(carry, next); + for (const auto& [item, least] : next.entry_items){ + compare(item, count_of(carry.bag, item), least, check); + } + if (next.entry_hp_share){ + compare("HP", carry.hp, static_cast(carry.max_hp * *next.entry_hp_share + 0.999), check); + } + for (const auto& [move, least] : next.entry_pp){ + compare(std::format("{} PP", move), count_of(carry.pp, move), least, check); + } + return check; +} -Pokemon::Outcome league_row_pass(const StoryCheckpoint& row, const Supplies& start, const Supplies& end){ - const LeagueFightData* fight = row_fight(row); +Pokemon::Outcome league_row_pass(const StoryCheckpoint& row, const SlugCounts& start_bag, const LeagueSide& end){ + const LeagueFightData* fight = league_row_fight(row); if (fight == nullptr){ return Pokemon::outcome_ok(); } - const SlugCounts before = counts_of(start); - const SlugCounts after = counts_of(end); SlugCounts used; - std::string text; - for (const auto& [item, count] : before){ - const int less = count - count_of(after, item); + std::vector spent; + for (const auto& [item, count] : start_bag){ + const int less = count - count_of(end.bag, item); if (less > 0){ used[item] = less; - text += std::format("{}{} {}", text.empty() ? "" : ", ", item, less); + spent.push_back(std::format("{} {}", item, less)); } } - if (league_try_passes(*fight, LeagueTry{.won = true, .used = used})){ + if (!league_try_passes(*fight, LeagueTry{.won = true, .used = used})){ + return Pokemon::outcome_failed("league_over_caps", std::format("{} spent {}", fight->name, joined(spent))); + } + const LeagueFightData* next = next_league_fight(*fight); + if (next == nullptr){ return Pokemon::outcome_ok(); } - return Pokemon::outcome_failed("league_over_caps", std::format("{} spent {}", fight->name, text.empty() ? "nothing" : text)); + const LeagueEntryCheck check = league_entry_check(*next, end); + if (!check.short_of.empty()){ + return Pokemon::outcome_failed("league_next_entry", std::format( + "{} spent {}; after the top-up [{}] before {}, read vs wanted: {}; short of {}", + fight->name, joined(spent), joined(check.topped_up), next->name, joined(check.compared), joined(check.short_of) + )); + } + return Pokemon::outcome_ok(); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.h index 3d34c17428..928c2c1062 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.h @@ -6,7 +6,9 @@ * is its own checkpoint, run as the shared engine's verification loop * from its start save. FRLG's part is the pass predicate: the fight the * row's battle names, won (the battle step fails otherwise) spending no - * item over the plan's caps (league_try_passes()). + * item over the plan's caps (league_try_passes()), leaving our side, as + * read off the console, able to start the next fight: its entry contract + * met after the heal rule's top-up (league_entry_check()). * */ @@ -14,7 +16,10 @@ #define PokemonAutomation_PokemonFRLG_AutoStoryLeagueRows_H #include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include +#include #include "PokemonFRLG_AutoStoryCheckpoints.h" +#include "PokemonFRLG_AutoStoryLeaguePlanData.h" #include "PokemonFRLG_AutoStorySupplies.h" namespace PokemonAutomation{ @@ -22,10 +27,46 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -// Whether a try of `row` that completed passes: for a row whose battle is -// a League fight, the items spent from `start` (the start save's -// supplies) to `end` within the fight's caps; any other row passes. -Pokemon::Outcome league_row_pass(const StoryCheckpoint& row, const Supplies& start, const Supplies& end); +// The League fight of `row`'s battle; none if it has none. +const LeagueFightData* league_row_fight(const StoryCheckpoint& row); + +// The fight after `fight` in the League's order; none after the Champion. +const LeagueFightData* next_league_fight(const LeagueFightData& fight); + +// Our side as read off the console: the lead's HP, its moves' PP and the +// bag, by slug. +struct LeagueSide{ + int hp = 0; + int max_hp = 0; + SlugCounts pp = {}; + SlugCounts full_pp = {}; + SlugCounts bag = {}; +}; + +// `side` against `next`'s entry contract once the heal rule's top-up +// before it (planned_between()) is done: every item of contract.entry +// at least its count, the HP at least entry_hp_share of its maximum, each +// move's PP at least contract.entry's. `compared` logs each value, +// wanted against had; `short_of` names what falls short (a shopping list +// for the items). +struct LeagueEntryCheck{ + std::vector topped_up = {}; + std::vector compared = {}; + std::vector short_of = {}; +}; + +// `side` checked against `next`'s entry contract (LeagueEntryCheck above). +LeagueEntryCheck league_entry_check(const LeagueFightData& next, LeagueSide side); + +// Whether a won try of `row`, its side read as `end`, passes and may be +// saved: for a row whose battle is a League fight, the items spent from +// `start_bag` (the start save's) within the fight's caps, and `end` able +// to start the next fight (league_entry_check()). Any other row passes. +// The failure's detail logs every value compared. +Pokemon::Outcome league_row_pass(const StoryCheckpoint& row, const SlugCounts& start_bag, const LeagueSide& end); + +// The supplies' counts by bag slug. +SlugCounts supplies_counts(const Supplies& supplies); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows_Tests.cpp new file mode 100644 index 0000000000..8bb5d8b678 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows_Tests.cpp @@ -0,0 +1,530 @@ +/* AutoStory League Rows Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The League's fight rows 20.01 to 20.05, with their verify blocks, run + * through the shared engine (run_segment()) against a fake game: each + * try's battle is scripted (won or lost, the items spent), the reload + * goes back to the bag of the last save, and a try passes by + * league_row_pass(): the fight's item caps, and the side it leaves able + * to start the next fight after its top-up. And the top-up before a + * fight (planned_between(), the console's league_top_up): one Super + * Potion, two, or a Full Restore, and the Elixir only before the + * Champion. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "PokemonFRLG_AutoStoryLeagueFightData.h" +#include "PokemonFRLG_AutoStoryLeagueRows.h" +#include "PokemonFRLG_AutoStoryPlannedBetween.h" +#include "PokemonFRLG_AutoStoryRows20_Tests.h" +#include "PokemonFRLG_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +constexpr std::string_view FIGHT_ROWS[] = {"20.01", "20.02", "20.03", "20.04", "20.05"}; + +const StoryCheckpoint& fight_row(std::string_view id){ + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id == id){ + return row; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No checkpoint {}.", id)); +} + +constexpr int MAX_HP = 165; + +// One try's battle: won or lost, the items it spent, the HP and Surf PP +// it left. +struct ScriptedTry{ + bool won = true; + SlugCounts used = {}; + int hp_left = MAX_HP; + int surf_spent = 0; +}; + +ScriptedTry win(SlugCounts used = {}, int hp_left = MAX_HP, int surf_spent = 0){ + return ScriptedTry{.won = true, .used = std::move(used), .hp_left = hp_left, .surf_spent = surf_spent}; +} +ScriptedTry lose(){ + return ScriptedTry{.won = false}; +} + +// The bag of "Enter Lorelei" (her entry contract), which 20.01a buys. +SlugCounts lorelei_bag(){ + return { + {"full-restore", 8}, {"x-special", 15}, {"x-speed", 5}, {"x-accuracy", 3}, {"guard-spec", 2}, + {"super-potion", 6}, {"elixir", 1}, {"max-elixir", 1}, + }; +} + +// Our side at full HP and PP with `bag`. +LeagueSide full_side(SlugCounts bag){ + const SlugCounts full_pp = {{"bite", 25}, {"strength", 15}, {"surf", 15}, {"blizzard", 5}}; + return LeagueSide{.hp = MAX_HP, .max_hp = MAX_HP, .pp = full_pp, .full_pp = full_pp, .bag = std::move(bag)}; +} + +// The fake game: our side now and at the last save, and each row's tries +// in order (the last repeats; a row with none wins spending nothing). A +// try first tops up as the console's league_top_up does and checks the +// fight's entry contract (failing "precondition_failed"), then plays its +// battle. Each save's side is checked against the next fight's entry +// contract after its top-up, which no save may break. +class FakeLeague{ +public: + using Script = std::function; + + FakeLeague(SlugCounts bag, Script script) + : m_side(full_side(std::move(bag))) + , m_saved(m_side) + , m_script(std::move(script)) + {} + + Pokemon::Segment segment(){ + Pokemon::Segment segment; + segment.id = "20"; + for (std::string_view id : FIGHT_ROWS){ + const StoryCheckpoint& row = fight_row(id); + Pokemon::CheckpointSpec spec; + spec.id = row.id; + spec.title = row.title; + spec.verify = row.verify; + spec.build = [this, id = row.id]{ + return checkpoint(id); + }; + segment.checkpoints.push_back(std::move(spec)); + } + return segment; + } + + Pokemon::SegmentHooks hooks(){ + Pokemon::SegmentHooks hooks; + hooks.reload = [this](Pokemon::RunState&){ + m_side = m_saved; + return Pokemon::outcome_ok(); + }; + hooks.verify_pass = [this](const std::string& id, Pokemon::RunState&){ + return league_row_pass(fight_row(id), m_saved.bag, m_side); + }; + hooks.log = [this](const std::string& line){ + log += std::format("\n {}", line); + }; + return hooks; + } + + int full_restores_saved() const{ + return count_of(m_saved.bag, "full-restore"); + } + + int fights = 0; + int saves = 0; + // Saves after which the next fight's entry contract failed. + std::vector broken_saves; + std::string log; + +private: + Pokemon::Checkpoint checkpoint(const std::string& id){ + Pokemon::Checkpoint checkpoint; + checkpoint.id = id; + Pokemon::Event fight; + fight.name = "fight"; + fight.act = [this, id](Pokemon::RunState&){ + const LeagueFightData& data = *league_row_fight(fight_row(id)); + const LeagueEntryCheck entry = top_up(data); + if (!entry.short_of.empty()){ + return Pokemon::outcome_failed("precondition_failed", entry.short_of.front()); + } + const ScriptedTry one = m_script(id); + fights++; + if (!one.won){ + return Pokemon::outcome_failed("blackout"); + } + for (const auto& [item, count] : one.used){ + m_side.bag[item] -= count; + } + m_side.hp = std::clamp(one.hp_left, 1, MAX_HP); + m_side.pp["surf"] = std::max(0, m_side.pp["surf"] - one.surf_spent); + return Pokemon::outcome_ok(); + }; + checkpoint.events.push_back(std::move(fight)); + checkpoint.save = [this, id](Pokemon::RunState&){ + saves++; + m_saved = m_side; + if (const LeagueFightData* next = next_league_fight(*league_row_fight(fight_row(id)))){ + const LeagueEntryCheck check = league_entry_check(*next, m_saved); + if (!check.short_of.empty()){ + broken_saves.push_back(std::format("{}: {}", id, check.short_of.front())); + } + } + return Pokemon::outcome_ok(); + }; + return checkpoint; + } + + // The heal rule's top-up before `fight`, on our side. + LeagueEntryCheck top_up(const LeagueFightData& fight){ + PlannedCarry carry{.hp = m_side.hp, .max_hp = MAX_HP, .pp = m_side.pp, .full_pp = m_side.full_pp, .bag = m_side.bag}; + planned_between(carry, fight); + m_side.hp = carry.hp; + m_side.pp = carry.pp; + m_side.bag = carry.bag; + return league_entry_check(fight, m_side); + } + + LeagueSide m_side; + LeagueSide m_saved; + Script m_script; +}; + +// Each row's tries in order, the last repeating; a row with none wins. +FakeLeague::Script scripted(std::map, std::less<>> tries){ + auto played = std::make_shared>(); + return [tries = std::move(tries), played](const std::string& row){ + const auto found = tries.find(row); + if (found == tries.end() || found->second.empty()){ + return win(); + } + size_t& count = (*played)[row]; + const ScriptedTry& one = found->second[std::min(count, found->second.size() - 1)]; + count++; + return one; + }; +} + +std::vector repeated(size_t count, const ScriptedTry& one){ + return std::vector(count, one); +} +std::vector joined(std::vector first, const std::vector& then){ + first.insert(first.end(), then.begin(), then.end()); + return first; +} + + +struct LeagueRunCase{ + struct Input{ + // The row the run starts at, and the bag of its start save. + std::string first = "20.01"; + SlugCounts bag = lorelei_bag(); + // Each row's tries, by row id. + std::map, std::less<>> tries = {}; + }; + struct Expectation{ + bool completed = false; + std::string failure = {}; + std::string failed_row = {}; + int fights = 0; + int saves = 0; + // The Full Restores the last save holds. + int full_restores_saved = 0; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_LeagueRows : public UnitTest{ +public: + explicit Test_LeagueRows(LeagueRunCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStoryLeagueRows - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeLeague game(m_case.input.bag, scripted(m_case.input.tries)); + Pokemon::Segment segment = game.segment(); + Pokemon::SegmentHooks hooks = game.hooks(); + Pokemon::RunState state; + const Pokemon::SegmentReport report = Pokemon::run_segment( + Pokemon::SegmentRange{m_case.input.first, "20.05"}, Pokemon::SegmentPolicy{}, segment, hooks, state + ); + const LeagueRunCase::Expectation& want = m_case.expectation; + const std::string failure = report.completed ? "" : report.failure.failure; + if (report.completed != want.completed || failure != want.failure || report.failed_checkpoint != want.failed_row + || game.fights != want.fights || game.saves != want.saves || game.full_restores_saved() != want.full_restores_saved + || !game.broken_saves.empty() + ){ + return std::format( + "{} \"{}\" at \"{}\", fights {}, saves {} ({} broken), Full Restores saved {}; expected {} \"{}\" at \"{}\", {}, {}, {}:{}", + report.completed ? "completed" : "failed", failure, report.failed_checkpoint, + game.fights, game.saves, game.broken_saves.size(), game.full_restores_saved(), + want.completed ? "completed" : "failed", want.failure, want.failed_row, + want.fights, want.saves, want.full_restores_saved, game.log + ); + } + return true; + } + +private: + LeagueRunCase m_case; +}; + +// Each fight row plays its 10 phase 1 tries and one phase 2 try when +// every try passes. +constexpr int TRIES_ALL_PASS = 11; + +const LeagueRunCase LEAGUE_RUN_CASES[] = { + { + .name = "every try a win within the caps: 20.01 to 20.05 each saved once", + .input = {}, + .expectation = {.completed = true, .fights = 5 * TRIES_ALL_PASS, .saves = 5, .full_restores_saved = 8}, + }, + { + .name = "Bruno's first phase 2 win spends 3 Full Restores, over his cap of 2: not saved; the next win is", + .input = {.tries = { + {"20.02", joined(joined(repeated(10, win()), {win({{"full-restore", 3}})}), {win({{"full-restore", 1}})})}, + }}, + .expectation = {.completed = true, .fights = 5 * TRIES_ALL_PASS + 1, .saves = 5, .full_restores_saved = 7}, + }, + { + .name = "Lorelei passes 4 of phase 1's 10, under min_pass 5: the run stops before Bruno, nothing saved", + .input = {.tries = {{"20.01", joined(repeated(4, win()), {lose()})}}}, + .expectation = {.failure = "verify_below_min_pass", .failed_row = "20.01", .fights = 10, .saves = 0, .full_restores_saved = 8}, + }, + { + .name = "Lorelei wins with 2 Full Restores, over her cap of 1, every time: phase 1 passes none, the run stops", + .input = {.tries = {{"20.01", {win({{"full-restore", 2}})}}}}, + .expectation = {.failure = "verify_below_min_pass", .failed_row = "20.01", .fights = 10, .saves = 0, .full_restores_saved = 8}, + }, + { + .name = "the bag at the Indigo Plateau Center short of a Full Restore: 20.01 stops before the League's door", + .input = {.bag = { + {"full-restore", 7}, {"x-special", 15}, {"x-speed", 5}, {"x-accuracy", 3}, {"guard-spec", 2}, + {"super-potion", 6}, {"elixir", 1}, {"max-elixir", 1}, + }}, + .expectation = {.failure = "precondition_failed", .failed_row = "20.01", .fights = 0, .saves = 0, .full_restores_saved = 7}, + }, + { + .name = "from Lance's entry bag, a win within his cap of 2 Full Restores at 45 HP: the Champion's heal takes a third, leaving 1 of his 2: never saved", + .input = { + .first = "20.04", + .bag = { + {"full-restore", 4}, {"x-special", 4}, {"x-speed", 1}, {"x-accuracy", 3}, {"guard-spec", 2}, + {"super-potion", 2}, {"elixir", 1}, {"max-elixir", 1}, + }, + .tries = {{"20.04", {win({{"full-restore", 2}}, /*hp_left=*/45)}}}, + }, + .expectation = {.failure = "verify_below_min_pass", .failed_row = "20.04", .fights = 10, .saves = 0, .full_restores_saved = 4}, + }, + { + .name = "Agatha wins leaving Surf at 2, under Lance's 3: never saved", + .input = {.tries = {{"20.03", {win(/*used=*/{}, MAX_HP, /*surf_spent=*/13)}}}}, + .expectation = {.failure = "verify_below_min_pass", .failed_row = "20.03", .fights = 2 * TRIES_ALL_PASS + 10, .saves = 2, .full_restores_saved = 8}, + }, +}; + + +// Random fights within the caps: whatever they leave, no save breaks the +// next fight's entry contract. +struct RandomRunCase{ + struct Input{ + // Runs from Lorelei, seeded 1 to `runs`. + uint32_t runs; + // The share of tries lost, in tenths. + uint32_t losses_in_ten; + }; + struct Expectation{ + size_t broken_saves; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +// Seeded tries: a loss `losses_in_ten` in ten, else a win spending up to +// each of the fight's caps, at a random HP and Surf PP. +FakeLeague::Script random_tries(uint32_t seed, uint32_t losses_in_ten){ + auto random = std::make_shared(seed); + return [random, losses_in_ten](const std::string& row){ + std::mt19937& next = *random; + const LeagueFightData& fight = *league_row_fight(fight_row(row)); + if (next() % 10 < losses_in_ten){ + return lose(); + } + SlugCounts used; + for (const auto& [item, cap] : fight.caps){ + if (cap > 0){ + used[item] = static_cast(next() % (cap + 1)); + } + } + return win(std::move(used), /*hp_left=*/1 + static_cast(next() % MAX_HP), /*surf_spent=*/static_cast(next() % 16)); + }; +} + +class Test_LeagueRowsRandom : public UnitTest{ +public: + explicit Test_LeagueRowsRandom(RandomRunCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStoryLeagueRows - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + size_t broken = 0; + int saves = 0; + std::string first_broken; + for (uint32_t seed = 1; seed <= m_case.input.runs; seed++){ + FakeLeague game(lorelei_bag(), random_tries(seed, m_case.input.losses_in_ten)); + Pokemon::Segment segment = game.segment(); + Pokemon::SegmentHooks hooks = game.hooks(); + Pokemon::RunState state; + Pokemon::run_segment(/*range=*/{}, Pokemon::SegmentPolicy{}, segment, hooks, state); + if (!game.broken_saves.empty() && first_broken.empty()){ + first_broken = std::format("seed {}: saved {}", seed, game.broken_saves.front()); + } + broken += game.broken_saves.size(); + saves += game.saves; + } + if (saves == 0){ + return "No run saved anything: the check proves nothing."; + } + if (broken != m_case.expectation.broken_saves){ + return std::format("{} broken saves, expected {}; first: {}.", broken, m_case.expectation.broken_saves, first_broken); + } + return true; + } + +private: + RandomRunCase m_case; +}; + +const RandomRunCase RANDOM_RUN_CASES[] = { + { + .name = "random wins within the caps: every save meets the next fight's entry contract", + .input = {.runs = 200, .losses_in_ten = 3}, + .expectation = {.broken_saves = 0}, + }, +}; + + +// The top-up before a fight (planned_between()) from our side at the +// fight's start: Blastoise at HP 165, Surf and Blizzard as given. +struct TopUpCase{ + struct Input{ + std::string_view fight = "bruno"; + int missing_hp = 0; + int super_potions = 7; + int full_restores = 7; + int surf_pp = 15; + }; + struct Expectation{ + std::vector items = {}; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_LeagueTopUp : public UnitTest{ +public: + explicit Test_LeagueTopUp(TopUpCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStoryLeagueRows - top-up: {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const TopUpCase::Input& input = m_case.input; + const LeagueFightData* fight = league_fight_data(league_plan_data(), input.fight); + if (fight == nullptr){ + return std::format("No League fight {}.", input.fight); + } + PlannedCarry carry{ + .hp = MAX_HP - input.missing_hp, .max_hp = MAX_HP, + .pp = {{"surf", input.surf_pp}, {"blizzard", 5}}, + .full_pp = {{"surf", 15}, {"blizzard", 5}}, + .bag = {{"super-potion", input.super_potions}, {"full-restore", input.full_restores}, {"elixir", 1}}, + }; + const std::vector items = planned_between(carry, *fight); + if (items != m_case.expectation.items){ + std::string text; + for (const std::string& item : items){ + text += std::format(" {}", item); + } + return std::format("Used [{} ].", text); + } + return true; + } + +private: + TopUpCase m_case; +}; + +// Bruno's reserve is 5 Super Potions and 5 Full Restores: 7 Super +// Potions leave two spare, 6 one. +const TopUpCase TOP_UP_CASES[] = { + { + .name = "40 HP missing: one Super Potion", + .input = {.missing_hp = 40}, + .expectation = {.items = {"super-potion"}}, + }, + { + .name = "90 HP missing, two Super Potions spare: two", + .input = {.missing_hp = 90}, + .expectation = {.items = {"super-potion", "super-potion"}}, + }, + { + .name = "90 HP missing, one Super Potion spare: a Full Restore", + .input = {.missing_hp = 90, .super_potions = 6}, + .expectation = {.items = {"full-restore"}}, + }, + { + .name = "120 HP missing: a Full Restore", + .input = {.missing_hp = 120}, + .expectation = {.items = {"full-restore"}}, + }, + { + .name = "full HP: nothing", + .input = {}, + .expectation = {.items = {}}, + }, + { + .name = "Surf at 3 before Lance: no Elixir", + .input = {.fight = "lance", .surf_pp = 3}, + .expectation = {.items = {}}, + }, + { + .name = "Surf at 3 before the Champion, under his floor of 8: the Elixir", + .input = {.fight = "champion", .surf_pp = 3}, + .expectation = {.items = {"elixir"}}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryLeagueRows(UnitTestDatabase& database){ + for (const LeagueRunCase& test_case : LEAGUE_RUN_CASES){ + database.add(test_case); + } + for (const RandomRunCase& test_case : RANDOM_RUN_CASES){ + database.add(test_case); + } + for (const TopUpCase& test_case : TOP_UP_CASES){ + database.add(test_case); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.cpp index 1abaf4aea4..facadf9044 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.cpp @@ -7,24 +7,22 @@ #include #include #include -#include #include "Common/Cpp/Color.h" -#include "Common/Cpp/Exceptions.h" -#include "PokemonFRLG_AutoStoryBag.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" #include "PokemonFRLG_AutoStoryBagUse.h" #include "PokemonFRLG_AutoStoryBattlePolicy.h" #include "PokemonFRLG_AutoStoryGameArgs.h" #include "PokemonFRLG_AutoStoryHealing.h" #include "PokemonFRLG_AutoStoryHealingSteps.h" #include "PokemonFRLG_AutoStoryItemsPocket.h" -#include "PokemonFRLG_AutoStoryLeaguePlan.h" -#include "PokemonFRLG_AutoStoryLeagueSteps.h" -#include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryLeagueFightData.h" -#include "PokemonFRLG_AutoStoryLeaguePlanData.h" -#include "PokemonFRLG_AutoStoryParty.h" +#include "PokemonFRLG_AutoStoryLeagueSteps.h" +#include "PokemonFRLG_AutoStoryPartyMember.h" #include "PokemonFRLG_AutoStoryPlannedBetween.h" #include "PokemonFRLG_AutoStoryStartMenu.h" +#include "PokemonFRLG_AutoStorySummary.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -35,6 +33,14 @@ using Pokemon::StoryStep; namespace{ +std::string joined_lines(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += std::format("{}{}", text.empty() ? "" : ", ", line); + } + return text.empty() ? std::string("nothing") : text; +} + // `item` (is_lead_recovery_item()) on the lead from the bag, found by // reading the pocket: taken into the supplies if used. ItemUseEnd use_lead_item_from_bag(StoryEnv& env, const StoryStep& step, const std::string& item){ @@ -46,24 +52,9 @@ ItemUseEnd use_lead_item_from_bag(StoryEnv& env, const StoryStep& step, const st return end; } -int held_count(const BagCounts& bag, std::string_view item){ - const auto found = bag.find(item); - return found == bag.end() ? 0 : std::max(0, found->second); -} - -// A budgeted item (a Full Restore, Hyper or Max Potion, Full Heal, Elixir -// or Max Elixir) used between fights comes out of the next fight's -// budget (it may go below 0 here: the budget planned for that fight is -// added to it). -void charge_next_fight(FightBudget& carried, std::string_view item){ - if (int* count = budget_count(item, carried)){ - (*count)--; - } -} - // The League's items as the story counts them. -BagCounts league_bag(const Supplies& supplies){ - BagCounts bag; +SlugCounts league_bag(const Supplies& supplies){ + SlugCounts bag; for (const std::string_view item : { "full-restore", "x-special", "x-speed", "x-accuracy", "guard-spec", "max-elixir", "elixir", "super-potion", "full-heal", "parlyz-heal", "antidote", "awakening", "max-potion", "hyper-potion", @@ -73,78 +64,6 @@ BagCounts league_bag(const Supplies& supplies){ return bag; } -// LEAGUE_START_ACTION: the Items pocket read, checked against the -// League's minimum and planned. -Outcome league_start(StoryEnv& env, const StoryStep& step){ - const std::vector rows = read_items_pocket(env.console, env.context, env.language); - if (rows.empty()){ - return Pokemon::outcome_failed("bag_unread", step.name); - } - set_from_bag(env.supplies, rows); - env.supplies.counts_read = true; - const BagCounts bag = league_bag(env.supplies); - if (const std::optional short_items = league_shortfalls(bag)){ - env.console.log(std::format( - "Story: {}: the bag is short of the League's restock list: {}. Planning from the bag as it is.", - step.name, *short_items - ), COLOR_ORANGE); - } - LeagueRun run{.plan = plan_league(bag), .carried = {}}; - for (const std::string& line : league_plan_lines(run.plan)){ - env.console.log(line); - } - env.supplies.league = std::move(run); - // The row starts after Indigo Plateau's nurse (20.01a) and nothing - // hurts the lead before Lorelei; a fresh program has measured nothing. - if (!missing_hp(env.supplies, 1)){ - env.console.log(std::format("Story: {}: HP unknown since the load; full from the nurse before this row.", step.name), COLOR_ORANGE); - measured_hp(env.supplies, 1.0); - } - return Pokemon::outcome_ok(); -} - -// The lead's move `move`: its PP and full PP, 0 and 0 if it doesn't know it. -std::pair move_pp(const PartyMember& lead, std::string_view move){ - for (const KnownMove& known : lead.moves){ - if (known.move == move){ - return {known.pp, max_pp(move)}; - } - } - return {0, 0}; -} - -// The lead's state between fights, as between_fight_action() reads it -// (`hp_reread`: READ_HP was done this step), its move for `next`, and the -// line that logs both. -BetweenFightAction logged_between_action( - StoryEnv& env, std::string_view step, const LeagueFightPlan& next, int max_hp, bool hp_reread -){ - const std::pair surf = move_pp(env.supplies.lead, "surf"); - const std::pair blizzard = move_pp(env.supplies.lead, "blizzard"); - const StatusCondition status = env.supplies.status; - const std::optional missing = missing_hp(env.supplies, max_hp); - const BetweenFightView lead{ - .hp = missing ? std::optional(max_hp - std::max(0, *missing)) : std::nullopt, - .max_hp = max_hp, - .hp_reread = hp_reread, - .cure = status == StatusCondition::NONE ? std::string() - : !cure_of(status).empty() ? std::string(cure_of(status)) : std::string("full-heal"), - .surf_pp = surf.first, .surf_max_pp = surf.second, - .blizzard_pp = blizzard.first, .blizzard_max_pp = blizzard.second, - }; - const BetweenFightAction action = between_fight_action(lead, league_bag(env.supplies), next); - const std::string what = action.move == BetweenFightMove::USE_ITEM ? std::format("the {}", action.item.value_or("?")) - : action.move == BetweenFightMove::READ_HP ? std::string("read the HP again") - : action.move == BetweenFightMove::HP_UNKNOWN ? std::string("HP still unknown") - : std::string("ready"); - env.console.log(std::format( - "Story: {}: before {}: HP {}/{}, {}, Surf {}/{}, Blizzard {}/{}: {}.", - step, next.name, lead.hp ? std::to_string(*lead.hp) : std::string("?"), max_hp, status_name(status), - surf.first, surf.second, blizzard.first, blizzard.second, what - ), action.move == BetweenFightMove::READY || action.move == BetweenFightMove::USE_ITEM ? COLOR_BLACK : COLOR_RED); - return action; -} - PlannedStatus carry_status(StatusCondition status){ switch (status){ case StatusCondition::POISON: @@ -161,9 +80,8 @@ PlannedStatus carry_status(StatusCondition status){ return PlannedStatus::NONE; } -// Our side between fights as planned_between() reads it; none while the -// HP is unknown. -std::optional between_carry(const Supplies& supplies, int max_hp){ +// Our side as planned_between() reads it; none while the HP is unknown. +std::optional top_up_carry(const Supplies& supplies, int max_hp){ const std::optional missing = missing_hp(supplies, max_hp); if (!missing){ return std::nullopt; @@ -173,27 +91,49 @@ std::optional between_carry(const Supplies& supplies, int max_hp){ carry.pp[known.move] = known.pp; carry.full_pp[known.move] = max_pp(known.move); } - for (const auto& [item, count] : league_bag(supplies)){ - carry.bag[item] = count; - } + carry.bag = league_bag(supplies); return carry; } -// The planned policy's top-ups before `next` (planned_between()), one -// item at a time from the lead's state, until none is left; the PP is -// read off the lead's summary again after a PP item. False if the HP is -// unknown. -bool planned_between_fights(StoryEnv& env, const StoryStep& step, const LeagueFightData& next, int max_hp){ +// The lead's HP, when the story lost count of it since the save: read off +// its summary (POKEMON SKILLS); else, with `full_if_unknown` (a row that +// starts after the nurse), taken as full. False if still unknown. +bool know_lead_hp(StoryEnv& env, const StoryStep& step, int max_hp, bool full_if_unknown){ + if (missing_hp(env.supplies, max_hp)){ + return true; + } + const std::optional summary = read_party_summary( + env.console, env.context, step_start_menu(step.args), env.language, /*slot=*/0 + ); + const std::optional hp = summary ? summary_current_hp(summary->hp_digits, max_hp) : std::nullopt; + if (hp){ + env.console.log(std::format("Story: {}: the summary reads HP {}/{}.", step.name, *hp, max_hp)); + measured_hp(env.supplies, static_cast(*hp) / max_hp); + return true; + } + if (full_if_unknown){ + env.console.log(std::format("Story: {}: HP unread; full from the nurse before this row.", step.name), COLOR_ORANGE); + measured_hp(env.supplies, 1.0); + return true; + } + return false; +} + +// The plan's top-ups before `fight` (planned_between()), one item at a +// time from the lead's state, until none is left; the PP is read off the +// lead's summary again after a PP item. False if an item couldn't be +// used. +bool top_up(StoryEnv& env, const StoryStep& step, const LeagueFightData& fight, int max_hp){ constexpr int MAX_ITEMS = 10; for (int c = 0; c < MAX_ITEMS; c++){ - std::optional carry = between_carry(env.supplies, max_hp); + std::optional carry = top_up_carry(env.supplies, max_hp); if (!carry){ return false; } const int hp = carry->hp; - const std::vector items = planned_between(*carry, next); + const std::vector items = planned_between(*carry, fight); env.console.log(std::format( - "Story: {}: before {}: HP {}/{}, {}: {}.", step.name, next.name, hp, max_hp, + "Story: {}: before {}: HP {}/{}, {}: {}.", step.name, fight.name, hp, max_hp, status_name(env.supplies.status), items.empty() ? std::string("ready") : std::format("the {}", items.front()) )); if (items.empty()){ @@ -204,11 +144,8 @@ bool planned_between_fights(StoryEnv& env, const StoryStep& step, const LeagueFi ? use_lead_item_from_bag(env, step, item) == ItemUseEnd::USED : use_recovery_item(env.console, env.context, item, env.checks, env.language, env.supplies); if (!used){ - env.console.log(std::format("Story: {}: couldn't use the {}; going on.", step.name, item), COLOR_RED); - return true; - } - if (env.supplies.league){ - charge_next_fight(env.supplies.league->carried, item); + env.console.log(std::format("Story: {}: couldn't use the {}.", step.name, item), COLOR_RED); + return false; } if (item == "elixir" || item == "max-elixir"){ read_lead_moves(env, step_start_menu(step.args)); @@ -217,126 +154,177 @@ bool planned_between_fights(StoryEnv& env, const StoryStep& step, const LeagueFi return true; } -// LEAGUE_BETWEEN_FIGHTS_ACTION: between_fight_action()'s moves until it is -// READY, each item used from the bag; a Full Restore, Elixir or Max Elixir -// counts against the next fight's budget. READ_HP: no overworld reader -// has the lead's current HP yet (the summary's POKEMON SKILLS read keeps -// only its maximum), so the HP stays unknown and the step fails before -// the fight. -Outcome league_between_fights(StoryEnv& env, const StoryStep& step, int fallback_max_hp){ - constexpr int MAX_MOVES = 10; - const std::string* trainer = game_arg(step.args, "next"); - if (trainer == nullptr || !env.supplies.league){ - return Pokemon::outcome_failed("bad_args", std::format("{}{}", step.name, env.supplies.league ? "" : ": no League plan (league_start)")); +// LEAGUE_TOP_UP_ACTION. +Outcome league_top_up(StoryEnv& env, const StoryStep& step){ + const std::string* name = game_arg(step.args, "fight"); + const int64_t* fallback_max_hp = game_arg(step.args, "max_hp"); + const LeagueFightData* fight = name ? league_fight_data(league_plan_data(), *name) : nullptr; + if (fight == nullptr || fallback_max_hp == nullptr){ + return Pokemon::outcome_failed("bad_args", std::format("{}: no League fight {}", step.name, name ? *name : "named")); } - const LeagueFightPlan* next = league_fight(env.supplies.league->plan, *trainer); - if (next == nullptr){ - return Pokemon::outcome_failed("bad_args", std::format("{}: no League fight {}", step.name, *trainer)); + const bool* full_if_unknown = game_arg(step.args, "full_if_unknown"); + const int max_hp = env.supplies.lead.stats && env.supplies.lead.stats->hp > 0 + ? env.supplies.lead.stats->hp + : static_cast(*fallback_max_hp); + + const std::vector rows = read_items_pocket(env.console, env.context, env.language); + if (rows.empty()){ + return Pokemon::outcome_failed("precondition_failed", std::format("{}: the Items pocket wasn't read", step.name)); } - const int max_hp = env.supplies.lead.stats && env.supplies.lead.stats->hp > 0 ? env.supplies.lead.stats->hp : fallback_max_hp; - // The planned policy's targets (frlg-league-plan.json's between rows). - const std::optional fight = league_fight_name(*trainer); - if (const LeagueFightData* planned = fight ? league_fight_data(league_plan_data(), *fight) : nullptr){ - return planned_between_fights(env, step, *planned, max_hp) - ? Pokemon::outcome_ok() - : Pokemon::outcome_failed("hp_unknown", std::format("{}: before {}", step.name, planned->name)); + set_from_bag(env.supplies, rows); + env.supplies.counts_read = true; + // Read right after the reload, before any item is used: the start + // save's bag, which the save check counts the try's spending from. + set_from_bag(env.saved_supplies, rows); + + if (!know_lead_hp(env, step, max_hp, full_if_unknown != nullptr && *full_if_unknown)){ + return Pokemon::outcome_failed("precondition_failed", std::format("{}: the lead's HP is unknown before {}", step.name, fight->name)); } - bool hp_reread = false; - for (int c = 0; c < MAX_MOVES; c++){ - const BetweenFightAction action = logged_between_action(env, step.name, *next, max_hp, hp_reread); - switch (action.move){ - case BetweenFightMove::READY: - return Pokemon::outcome_ok(); - case BetweenFightMove::READ_HP: - hp_reread = true; - continue; - case BetweenFightMove::HP_UNKNOWN: - // Never into a fight on an HP the story doesn't know (Bruno, - // console B, 2026-11-16: entered at 71% after "HP unknown"). - return Pokemon::outcome_failed("hp_unknown", std::format("{}: before {}", step.name, next->name)); - case BetweenFightMove::USE_ITEM: - break; - } - const std::string item = action.item.value_or(""); - const bool used = is_lead_recovery_item(item) - ? use_lead_item_from_bag(env, step, item) == ItemUseEnd::USED - : use_recovery_item(env.console, env.context, item, env.checks, env.language, env.supplies); - if (!used){ - env.console.log(std::format("Story: {}: couldn't use the {}; going on.", step.name, item), COLOR_RED); - return Pokemon::outcome_ok(); - } - charge_next_fight(env.supplies.league->carried, item); + if (!top_up(env, step, *fight, max_hp)){ + return Pokemon::outcome_failed("precondition_failed", std::format("{}: the top-up before {} didn't finish", step.name, fight->name)); + } + std::optional carry = top_up_carry(env.supplies, max_hp); + const LeagueEntryCheck check = league_entry_check(*fight, LeagueSide{ + .hp = carry->hp, .max_hp = carry->max_hp, .pp = carry->pp, .full_pp = carry->full_pp, .bag = carry->bag, + }); + env.console.log(std::format("Story: {}: {}'s entry contract, had/wanted: {}.", step.name, fight->name, joined_lines(check.compared))); + if (!check.short_of.empty()){ + // Before Lorelei this is the Indigo Plateau Center, where the Mart + // still sells: the shopping list, and never into the League. + return Pokemon::outcome_failed("precondition_failed", std::format( + "{}: {}'s entry contract is short of {}", step.name, fight->name, joined_lines(check.short_of) + )); } return Pokemon::outcome_ok(); } -} // namespace - +// Fails "postcondition_unread" for `what`, keeping the screen. +Outcome unread(StoryEnv& env, std::string_view row, std::string_view what){ + if (VideoSnapshot screen = env.console.video().snapshot()){ + dump_debug_image(env.console.logger(), "AutoStory/league", "postcondition_unread", screen); + } + env.console.log(std::format("Story: {}: no save: {}.", row, what), COLOR_RED); + return Pokemon::outcome_failed(std::string(Pokemon::VERIFY_UNREAD), std::format("{}: {}", row, what)); +} -BetweenFightAction between_fight_action( - const BetweenFightView& lead, const BagCounts& bag, const LeagueFightPlan& next -){ - // The PP an Elixir restores to each move (pokefirered items.json). - constexpr int ELIXIR_PP = 10; - const auto first_held = [&](std::initializer_list items) -> std::optional{ - for (const std::string_view item : items){ - if (held_count(bag, item) > 0){ - return BetweenFightAction{.move = BetweenFightMove::USE_ITEM, .item = std::string(item)}; +// The row's top-up step's max_hp; 0 if it has none. +int row_max_hp(const StoryCheckpoint& row){ + for (const StoryStep& step : row.steps){ + if (step.action == LEAGUE_TOP_UP_ACTION){ + if (const int64_t* max_hp = game_arg(step.args, "max_hp")){ + return static_cast(*max_hp); } } - return std::nullopt; - }; - if (!lead.cure.empty()){ - if (std::optional cure = first_held({lead.cure, "full-heal", "full-restore"})){ - return *cure; + } + return 0; +} + +// The lead's HP and moves' PP off its summary into `side`; the failure +// (VERIFY_UNREAD) if a read failed or is unsure. +std::optional read_lead(StoryEnv& env, const StoryCheckpoint& row, const LeagueFightData& fight, LeagueSide& side){ + const int max_hp = env.supplies.lead.stats && env.supplies.lead.stats->hp > 0 ? env.supplies.lead.stats->hp : row_max_hp(row); + const std::optional summary = read_party_summary(env.console, env.context, row.menu, env.language, /*slot=*/0); + if (!summary){ + return unread(env, row.id, "the lead's summary wasn't read"); + } + const std::optional hp = summary_current_hp(summary->hp_digits, max_hp); + if (!hp){ + return unread(env, row.id, std::format("the lead's HP wasn't read (\"{}\" against max {})", summary->hp_digits, max_hp)); + } + side.hp = *hp; + side.max_hp = max_hp; + for (const SummaryMove& move : summary->moves){ + if (move.move.empty() || move.pp < 0){ + return unread(env, row.id, std::format("a move's PP wasn't read ({})", move.move.empty() ? "?" : move.move)); } + side.pp[move.move] = move.pp; + side.full_pp[move.move] = move.max_pp > 0 ? move.max_pp : max_pp(move.move); } - if (!lead.hp){ - return BetweenFightAction{.move = lead.hp_reread ? BetweenFightMove::HP_UNKNOWN : BetweenFightMove::READ_HP}; + if (const LeagueFightData* next = next_league_fight(fight)){ + for (const auto& [move, least] : next->entry_pp){ + if (!side.pp.contains(move)){ + return unread(env, row.id, std::format("{}'s PP wasn't read", move)); + } + } + } + return std::nullopt; +} + +// The Items pocket off the bag into `now`; the failure (VERIFY_UNREAD) if +// it wasn't read or a row is unsure. +std::optional read_bag(StoryEnv& env, const StoryCheckpoint& row, Supplies& now){ + const std::vector rows = read_items_pocket(env.console, env.context, env.language); + if (rows.empty()){ + return unread(env, row.id, "the Items pocket wasn't read"); } - const int target = (lead.max_hp * next.entry_hp_percent + 99) / 100; - if (*lead.hp < target){ - if (std::optional heal = first_held({"super-potion", "hyper-potion", "max-potion", "full-restore"})){ - return *heal; + for (const BagRow& read : rows){ + if (read.item.empty() || read.count < 0){ + return unread(env, row.id, std::format("an Items pocket row is unsure ({} x{})", read.item.empty() ? "?" : read.item, read.count)); } } - const bool surf_low = lead.surf_max_pp > 0 && lead.surf_pp < next.surf_pp_floor; - const bool blizzard_low = lead.blizzard_max_pp > 0 && lead.blizzard_pp < next.blizzard_pp_floor; - if (!surf_low && !blizzard_low){ - return BetweenFightAction{}; + set_from_bag(now, rows); + return std::nullopt; +} + +// What was read before the save, and the next fight's entry contract +// against it, for the log. +void log_save_read(StoryEnv& env, const StoryCheckpoint& row, const LeagueFightData& fight, const LeagueSide& side){ + std::string read_pp; + for (const auto& [move, pp] : side.pp){ + read_pp += std::format(" {} {}/{}", move, pp, count_of(side.full_pp, move)); + } + env.console.log(std::format("Story: {}: read before the save: HP {}/{}, PP{}.", row.id, side.hp, side.max_hp, read_pp)); + if (const LeagueFightData* next = next_league_fight(fight)){ + const LeagueEntryCheck check = league_entry_check(*next, side); + env.console.log(std::format( + "Story: {}: {}'s entry contract after the top-up [{}], had/wanted: {}.", + row.id, next->name, joined_lines(check.topped_up), joined_lines(check.compared) + )); } - const bool elixir_reaches = - std::min(lead.surf_pp + ELIXIR_PP, lead.surf_max_pp) >= std::min(next.surf_pp_floor, lead.surf_max_pp) - && std::min(lead.blizzard_pp + ELIXIR_PP, lead.blizzard_max_pp) >= std::min(next.blizzard_pp_floor, lead.blizzard_max_pp); - const std::optional pp = elixir_reaches - ? first_held({"elixir", "max-elixir"}) - : first_held({"max-elixir", "elixir"}); - return pp.value_or(BetweenFightAction{}); } +} // namespace + + +Outcome check_league_save(StoryEnv& env, const StoryCheckpoint& row, const Supplies& start){ + const LeagueFightData* fight = league_row_fight(row); + if (fight == nullptr){ + return Pokemon::outcome_ok(); + } + Supplies now = env.supplies; + if (std::optional failed = read_bag(env, row, now)){ + return *failed; + } + LeagueSide side{.bag = league_bag(now)}; + if (std::optional failed = read_lead(env, row, *fight, side)){ + return *failed; + } + log_save_read(env, row, *fight, side); + const Outcome passed = league_row_pass(row, supplies_counts(start), side); + if (passed.succeeded()){ + // The story's counts are the console's from here. + env.supplies = std::move(now); + env.supplies.counts_read = true; + measured_hp(env.supplies, static_cast(side.hp) / side.max_hp); + } + return passed; +} std::vector league_action_specs(){ return { - {.kind = Pokemon::StoryStepKind::GAME, .name = LEAGUE_START_ACTION, .args = {}}, - {.kind = Pokemon::StoryStepKind::GAME, .name = LEAGUE_BETWEEN_FIGHTS_ACTION, .args = { + {.kind = Pokemon::StoryStepKind::GAME, .name = LEAGUE_TOP_UP_ACTION, .args = { + required_arg("fight", Pokemon::StoryArgType::WORD, "the row's fight, as the League plan names it"), required_arg("max_hp", Pokemon::StoryArgType::INTEGER, "the lead's maximum HP when its summary wasn't read"), - required_arg("next", Pokemon::StoryArgType::WORD, "the next fight's trainer, as its battle step names it"), + optional_arg("full_if_unknown", Pokemon::StoryArgType::BOOLEAN, false, "the HP is full when unread: the row starts after the nurse"), }}, }; } std::optional run_league_step(StoryEnv& env, const StoryStep& step){ - if (step.action == LEAGUE_START_ACTION){ - return league_start(env, step); - } - if (step.action != LEAGUE_BETWEEN_FIGHTS_ACTION){ + if (step.action != LEAGUE_TOP_UP_ACTION){ return std::nullopt; } - const int64_t* max_hp = game_arg(step.args, "max_hp"); - if (max_hp == nullptr){ - return Pokemon::outcome_failed("bad_args", step.action); - } - return league_between_fights(env, step, static_cast(*max_hp)); + return league_top_up(env, step); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.h index 04ffbe7158..f4ded9cef4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.h @@ -2,19 +2,21 @@ * * From: https://github.com/PokemonAutomation/ * - * The League's own steps (one checkpoint from Lorelei's door to the Hall - * of Fame, no save between; PokemonFRLG_AutoStoryLeaguePlan.h plans it): + * The League's own step. Each fight is its own row (20.01 to 20.05), run + * as a verification loop from its start save (Pokemon_StoryVerify.h). * - * league_start: reads the Items pocket, logs what the bag lacks of the - * League's restock list, and logs and keeps the plan made from the bag - * as it is; the fights' battles spend its budgets (Supplies::budget). - * - * league_between_fights (next WORD, the next fight's trainer; max_hp - * INTEGER, the lead's maximum HP when its summary wasn't read): does - * between_fight_action()'s moves one at a time from the lead's state. A - * budgeted item (Full Restore, Hyper or Max Potion, Full Heal, Elixir, - * Max Elixir) counts against the next fight's budget. Never a fight on an unknown HP (Bruno, console B, 2026-11-16: - * entered at 71%), and never a Full Restore for a read failure. + * league_top_up (fight WORD, the plan's name of the row's fight; max_hp + * INTEGER, the lead's maximum HP when its summary wasn't read; + * full_if_unknown BOOLEAN, default false): the row's first step, after + * the reload and before the walk. It reads the Items pocket and the + * lead's HP (the story's own count since the save, else the summary's + * POKEMON SKILLS), uses the plan's top-up before the fight one item at a + * time (planned_between(): a Super Potion for up to 50 missing HP, two + * for up to 100 if two are spare, else a Full Restore; the Elixir only + * before the Champion), then checks the fight's entry contract. A broken + * contract or an HP still unknown fails with "precondition_failed": the + * save does not meet the row's start, and the loop stops. Never a fight + * on an unknown HP (Bruno, console B, 2026-11-16: entered at 71%). * */ @@ -28,75 +30,30 @@ #include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" #include "PokemonFRLG_AutoStoryEvents.h" -#include "PokemonFRLG_AutoStoryLeaguePlan.h" +#include "PokemonFRLG_AutoStoryLeagueRows.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ -// The GAME step at the League's start (league_start above). -inline const std::string LEAGUE_START_ACTION = "league_start"; -// The GAME step between two League fights (league_between_fights above). -inline const std::string LEAGUE_BETWEEN_FIGHTS_ACTION = "league_between_fights"; - -// The lead between two fights, as between_fight_action() reads it. -struct BetweenFightView{ - // None when no bar was measured since the load and no item healed it - // to a known HP. - std::optional hp = std::nullopt; - int max_hp = 0; - // Whether the HP was already read again this step (READ_HP). - bool hp_reread = false; - // The item that cures the lead's status ("parlyz-heal"; "full-heal" - // for one with no own cure), "" for none. - std::string cure; - int surf_pp = 0; - int surf_max_pp = 0; - int blizzard_pp = 0; - int blizzard_max_pp = 0; -}; - -// What league_between_fights does next (between_fight_action()). -enum class BetweenFightMove{ - // Into the fight. - READY, - // The action's item on the lead. - USE_ITEM, - // Read the lead's HP again. - READ_HP, - // The HP is still unknown after reading it again: stop before the fight. - HP_UNKNOWN, -}; - -// between_fight_action()'s move, with its item. -struct BetweenFightAction{ - BetweenFightMove move = BetweenFightMove::READY; - // USE_ITEM's item (a bag slug). - std::optional item = std::nullopt; - - bool operator==(const BetweenFightAction&) const = default; -}; +// The GAME step at a League fight row's start (league_top_up above). +inline const std::string LEAGUE_TOP_UP_ACTION = "league_top_up"; -// The next move before `next`, from the lead's state, in this order: -// 1. a status: its own cure, else a Full Heal, else a Full Restore; -// 2. HP unknown: read it again; still unknown: HP_UNKNOWN (a Full -// Restore is never spent on a read failure); -// 3. HP below the fight's entry target: the cheapest heal held, a -// Super Potion, then a Hyper Potion, a Max Potion, a Full Restore -// last; -// 4. Surf or Blizzard below the fight's PP floor: an Elixir when it -// reaches the floor, else a Max Elixir, else the Elixir anyway; -// 5. READY (also when the bag has nothing that helps). -BetweenFightAction between_fight_action( - const BetweenFightView& lead, const BagCounts& bag, const LeagueFightPlan& next -); +// On the console, before a League fight row's save: whether the try may +// be saved (league_row_pass()), from our side as read off the console +// now, not the story's own counts: the Items pocket, the lead's HP +// (summary_current_hp()) and its moves' PP (the summary's KNOWN MOVES). +// `start` is the start save's supplies. Every value compared is logged, +// wanted against read. A read that fails or is unsure fails +// "postcondition_unread" (the loop stops: never a save on a guess), with +// the screen kept in DebugDumps/AutoStory/league. +Pokemon::Outcome check_league_save(StoryEnv& env, const StoryCheckpoint& row, const Supplies& start); -// LEAGUE_START_ACTION's and LEAGUE_BETWEEN_FIGHTS_ACTION's specs. +// LEAGUE_TOP_UP_ACTION's spec. std::vector league_action_specs(); -// On the console, a LEAGUE_START_ACTION or LEAGUE_BETWEEN_FIGHTS_ACTION -// step; nothing for another. +// On the console, a LEAGUE_TOP_UP_ACTION step; nothing for another. std::optional run_league_step(StoryEnv& env, const Pokemon::StoryStep& step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeague_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeague_Tests.cpp index 40662bdf62..618a9ea6d9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeague_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeague_Tests.cpp @@ -2,11 +2,11 @@ * * From: https://github.com/PokemonAutomation/ * - * Rows 20.01a and 20.01 (StoryData/frlg-20.01*.plan.json) on the - * overworld sim: Indigo Plateau's Mart, the Elite Four's rooms one way - * north, the Champion's door, all in 20.01 (one checkpoint, no save - * between the fights); the battles' foe rows against their generator; and - * the League plan's steps around the fights. + * Rows 20.01a to 20.05 (StoryData/frlg-20.0*.plan.json) on the overworld + * sim: Indigo Plateau's Mart, then one row per League fight (20.01 + * Lorelei to 20.05 the Champion), the rooms one way north; the battles' + * foe rows against their generator; and each fight row's top-up and + * verification figures against the League plan. * */ @@ -22,12 +22,14 @@ #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/AutoStory/Pokemon_StoryPostconditionCheck.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_AutoStoryBattlePolicy.h" #include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryItemsPocket.h" -#include "PokemonFRLG_AutoStoryLeaguePlan.h" +#include "PokemonFRLG_AutoStoryLeagueFightData.h" +#include "PokemonFRLG_AutoStoryLeagueSteps.h" #include "PokemonFRLG_AutoStoryPoses.h" #include "PokemonFRLG_AutoStoryRowSim.h" #include "PokemonFRLG_AutoStoryRows20_Tests.h" @@ -137,14 +139,13 @@ UnitTestResult walk_to_room(std::string_view id, std::string_view until, std::st return true; } -// Walks 20.01 from in front of the trainer its battle step `battle` beat -// (the step's declared pose) round them to below their door, up to the -// step `door` into it. The map pack draws the door closed (a wall: the +// Walks row `id` from in front of the trainer its battle step `battle` +// beat (the step's declared pose) round them to below their door, up to +// the step `door` into it (to the row's end if empty). The map pack draws the door closed (a wall: the // game opens it with setmetatile when the trainer is beaten, // PokemonLeague_EventScript_OpenDoor), so the step through it and the // next room's walk are the console's. -UnitTestResult walk_to_door(std::string_view battle, std::string_view door, const MapPosition& below){ - const std::string_view id = "20.01"; +UnitTestResult walk_to_door(std::string_view id, std::string_view battle, std::string_view door, const MapPosition& below){ const StoryCheckpoint& row = league_row(id); const StoryStep& beaten = league_step(id, battle); if (!beaten.pose_after){ @@ -217,28 +218,28 @@ std::vector league_fights(){ {110, 22, 10, 48, 24, 0, 0}, // Jynx {94, 28, 12, 62, 31, 0, 0}, // Lapras }}, - {"20.01", "bruno", { + {"20.02", "bruno", { {81, 26, 16, 63, 31, 0, 0, 1}, // Onix (Roar) {101, 43, 24, 108, 54, 0, 0}, // Hitmonchan {113, 54, 44, 114, 57, 0, 0}, // Hitmonlee {96, 33, 33, 69, 34, 0, 0}, // Onix {83, 0, 4, 150, 75, 0, 0}, // Machamp }}, - {"20.01", "agatha", { + {"20.03", "agatha", { {126, 0, 3, 60, 30, 0, 0}, // Gengar {129, 28, 17, 60, 30, 0, 0}, // Golbat {108, 0, 0, 0, 41, 0, 0}, // Haunter {111, 51, 31, 108, 54, 0, 0}, // Arbok {150, 40, 24, 84, 42, 0, 0}, // Gengar }}, - {"20.01", "lance", { + {"20.04", "lance", { {112, 40, 31, 40, 80, 0, 0}, // Gyarados {96, 40, 16, 78, 53, 0, 0}, // Dragonair {96, 0, 0, 0, 53, 0, 0}, // Dragonair {173, 41, 41, 84, 67, 0, 0}, // Aerodactyl {107, 56, 19, 126, 98, 0, 0}, // Dragonite }}, - {"20.01", "champion", { + {"20.05", "champion", { {130, 35, 24, 75, 37, 1, 0, 1}, // Pidgeot (Sand Attack, Whirlwind) {159, 70, 64, 144, 72, 0, 0}, // Alakazam {70, 0, 8, 183, 91, 0, 0}, // Rhydon @@ -290,7 +291,7 @@ const VenusaurTurnCase VENUSAUR_TURN_CASES[] = { // Console B's Blastoise (Lv54, 2026-11-16) at full HP against Venusaur. UnitTestResult test_venusaur_charge(){ - const StoryStep& step = league_step("20.01", "champion"); + const StoryStep& step = league_step("20.05", "champion"); constexpr size_t VENUSAUR = 5; for (const VenusaurTurnCase& test : VENUSAUR_TURN_CASES){ Supplies supplies; @@ -332,45 +333,56 @@ size_t step_index(const StoryCheckpoint& row, std::string_view name){ return index; } -// The League plan's steps in 20.01: league_start before the League's -// door, and before each fight after Lorelei's a league_between_fights -// for that fight's trainer, after the fight before it. -UnitTestResult test_league_plan_steps(){ - const StoryCheckpoint& row = league_row("20.01"); - const size_t start = step_index(row, "league_start"); - if (start >= step_index(row, "league_door") || row.steps[start].action != "league_start"){ - return "20.01: expected league_start before the League's door."; - } - struct Between{ - std::string_view after; - std::string_view step; - std::string_view battle; - std::string_view trainer; - }; - const Between betweens[] = { - {"lorelei", "items_before_bruno", "bruno", "TRAINER_ELITE_FOUR_BRUNO"}, - {"bruno", "items_before_agatha", "agatha", "TRAINER_ELITE_FOUR_AGATHA"}, - {"agatha", "items_before_lance", "lance", "TRAINER_ELITE_FOUR_LANCE"}, - {"lance", "items_before_champion", "champion", "TRAINER_CHAMPION_FIRST_BULBASAUR"}, - }; - for (const Between& between : betweens){ - const size_t at = step_index(row, between.step); - if (at <= step_index(row, between.after) || at >= step_index(row, between.battle) - || row.steps[at].action != "league_between_fights" - || Pokemon::story_arg(row.steps[at].args, "next") != between.trainer - ){ - return std::format("20.01: expected {} (league_between_fights, next {}) between {} and {}.", between.step, between.trainer, between.after, between.battle); - } - if (Pokemon::story_arg(league_step("20.01", between.battle).args, "trainer") != between.trainer){ - return std::format("20.01 {}: expected trainer {}.", between.battle, between.trainer); - } - } - return true; -} - +// The League's fight rows, in order: each starts where the one before +// ends; its first steps are the level check and the top-up for its own +// fight (league_top_up), before any walk; its battle is that fight; and +// its verify block is the plan's pass figures (frlg-league-plan.json's +// contract.pass: tries = min_pass.of, min_pass = min_pass.k, +// reset_budget). +UnitTestResult test_league_fight_rows(){ + const std::string_view rows[][2] = { + {"20.01", "lorelei"}, {"20.02", "bruno"}, {"20.03", "agatha"}, {"20.04", "lance"}, {"20.05", "champion"}, + }; + const StoryCheckpoint* before = &league_row("20.01a"); + for (const auto& [id, fight_name] : rows){ + const StoryCheckpoint& row = league_row(id); + const std::optional before_end = Pokemon::checkpoint_end_pose(*before); + if (!row.start || !before_end || !(Pokemon::grid_pose_of(*row.start) == *before_end)){ + return std::format("{}: doesn't start where {} ends.", id, before->id); + } + before = &row; + if (row.steps.size() < 2 || row.steps[0].action != "level" || row.steps[1].action != LEAGUE_TOP_UP_ACTION + || Pokemon::story_arg(row.steps[1].args, "fight") != fight_name + ){ + return std::format("{}: expected the level check, then league_top_up for {}, first.", id, fight_name); + } + const std::optional battle = league_fight_name(Pokemon::story_arg(league_step(id, fight_name).args, "trainer")); + if (battle != fight_name){ + return std::format("{} {}: its trainer is not the plan's {}.", id, fight_name, fight_name); + } + const LeagueFightData* fight = league_fight_data(league_plan_data(), fight_name); + if (fight == nullptr || !fight->pass){ + return std::format("{}: the League plan has no pass figures for {}.", id, fight_name); + } + const Pokemon::StoryVerify plan{ + .tries = (size_t)fight->pass->min_pass_of, + .min_pass = (size_t)fight->pass->min_pass, + .reset_budget = (size_t)fight->pass->reset_budget, + }; + if (row.verify != plan){ + return std::format( + "{}: verify {}, the plan's {} {} {}.", id, + row.verify ? std::format("{} {} {}", row.verify->tries, row.verify->min_pass, row.verify->reset_budget) : std::string("none"), + plan.tries, plan.min_pass, plan.reset_budget + ); + } + } + return true; +} + const AutoStoryLeagueCase AUTO_STORY_LEAGUE_CASES[] = { { - .name = "20.01 the Champion's Venusaur: Solar Beam is a KO risk only charged or in sun", + .name = "20.05 the Champion's Venusaur: Solar Beam is a KO risk only charged or in sun", .input = {.body = test_venusaur_charge}, .expectation = {.description = "X Special until it charges or the sun is out, then an attack"}, }, @@ -389,40 +401,40 @@ const AutoStoryLeagueCase AUTO_STORY_LEAGUE_CASES[] = { { .name = "20.01 around Lorelei to below her door", .input = {.body = []{ - return walk_to_door("lorelei", "loreleis_door", MapPosition{"PokemonLeague_LoreleisRoom", {6, 3}}); + return walk_to_door("20.01", "lorelei", "loreleis_door", MapPosition{"PokemonLeague_LoreleisRoom", {6, 3}}); }}, .expectation = {.description = "Lorelei's room (6, 3) facing north"}, }, { - .name = "20.01 around Bruno to below his door", + .name = "20.02 around Bruno to below his door", .input = {.body = []{ - return walk_to_door("bruno", "brunos_door", MapPosition{"PokemonLeague_BrunosRoom", {6, 3}}); + return walk_to_door("20.02", "bruno", "brunos_door", MapPosition{"PokemonLeague_BrunosRoom", {6, 3}}); }}, .expectation = {.description = "Bruno's room (6, 3) facing north"}, }, { - .name = "20.01 around Agatha to below her door", + .name = "20.03 around Agatha to below her door", .input = {.body = []{ - return walk_to_door("agatha", "agathas_door", MapPosition{"PokemonLeague_AgathasRoom", {6, 3}}); + return walk_to_door("20.03", "agatha", "agathas_door", MapPosition{"PokemonLeague_AgathasRoom", {6, 3}}); }}, .expectation = {.description = "Agatha's room (6, 3) facing north"}, }, { - .name = "20.01 around Lance to below the Champion's door", + .name = "20.04 around Lance to below the Champion's door, where the row ends", .input = {.body = []{ - return walk_to_door("lance", "champions_door", MapPosition{"PokemonLeague_LancesRoom", {6, 6}}); + return walk_to_door("20.04", "lance", /*door=*/"", MapPosition{"PokemonLeague_LancesRoom", {6, 6}}); }}, .expectation = {.description = "Lance's room (6, 6) facing north"}, }, { - .name = "20.01 the League's foe rows are the generator's", + .name = "20.01 to 20.05 the League's foe rows are the generator's", .input = {.body = test_foe_threats_are_the_generators}, .expectation = {.description = "PokemonSimulation planning_risk() rows"}, }, { - .name = "20.01 the League plan's steps: league_start, then the items before each fight", - .input = {.body = test_league_plan_steps}, - .expectation = {.description = "league_start before the door; league_between_fights before Bruno, Agatha, Lance and the Champion"}, + .name = "20.01 to 20.05 one row per fight: chained, topped up first, verify figures as the League plan's", + .input = {.body = test_league_fight_rows}, + .expectation = {.description = "each row starts where the one before ends, league_top_up for its fight first, verify = contract.pass"}, }, }; @@ -434,6 +446,7 @@ void add_tests_AutoStoryLeague(UnitTestDatabase& database){ database.add(item); } add_tests_AutoStoryLeaguePlan(database); + add_tests_AutoStoryLeagueRows(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden20.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden20.h index 3a61d07daf..8f2ee799bc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden20.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden20.h @@ -35,27 +35,27 @@ inline constexpr std::string_view FRLG_PLAN_GOLDEN_20[] = { "20.01 walk north 3 (to wall) -> PokemonLeague_LoreleisRoom (7, 3) [walk only]", "20.01 walk west 1 -> PokemonLeague_LoreleisRoom (6, 3) [walk only]", "20.01 face north -> PokemonLeague_LoreleisRoom (6, 3) [walk only]", - "20.01 before_bruno from PokemonLeague_BrunosRoom (6, 7) facing north to PokemonLeague_BrunosRoom (6, 6) facing north", - "20.01 walk north 1 (to wall) -> PokemonLeague_BrunosRoom (6, 6) [walk only]", - "20.01 below_brunos_door from PokemonLeague_BrunosRoom (6, 6) facing north to PokemonLeague_BrunosRoom (6, 3) facing north", - "20.01 walk east 1 -> PokemonLeague_BrunosRoom (7, 6) [walk only]", - "20.01 walk north 3 (to wall) -> PokemonLeague_BrunosRoom (7, 3) [walk only]", - "20.01 walk west 1 -> PokemonLeague_BrunosRoom (6, 3) [walk only]", - "20.01 face north -> PokemonLeague_BrunosRoom (6, 3) [walk only]", - "20.01 before_agatha from PokemonLeague_AgathasRoom (6, 7) facing north to PokemonLeague_AgathasRoom (6, 6) facing north", - "20.01 walk north 1 (to wall) -> PokemonLeague_AgathasRoom (6, 6) [walk only]", - "20.01 below_agathas_door from PokemonLeague_AgathasRoom (6, 6) facing north to PokemonLeague_AgathasRoom (6, 3) facing north", - "20.01 walk east 1 -> PokemonLeague_AgathasRoom (7, 6) [walk only]", - "20.01 walk north 3 (to wall) -> PokemonLeague_AgathasRoom (7, 3) [walk only]", - "20.01 walk west 1 -> PokemonLeague_AgathasRoom (6, 3) [walk only]", - "20.01 face north -> PokemonLeague_AgathasRoom (6, 3) [walk only]", - "20.01 before_lance from PokemonLeague_LancesRoom (6, 10) facing north to PokemonLeague_LancesRoom (6, 9) facing north", - "20.01 walk north 1 (to wall) -> PokemonLeague_LancesRoom (6, 9) [walk only]", - "20.01 below_champions_door from PokemonLeague_LancesRoom (6, 9) facing north to PokemonLeague_LancesRoom (6, 6) facing north", - "20.01 walk east 1 -> PokemonLeague_LancesRoom (7, 9) [walk only]", - "20.01 walk north 3 (to wall) -> PokemonLeague_LancesRoom (7, 6) [walk only]", - "20.01 walk west 1 -> PokemonLeague_LancesRoom (6, 6) [walk only]", - "20.01 face north -> PokemonLeague_LancesRoom (6, 6) [walk only]", + "20.02 before_bruno from PokemonLeague_BrunosRoom (6, 7) facing north to PokemonLeague_BrunosRoom (6, 6) facing north", + "20.02 walk north 1 (to wall) -> PokemonLeague_BrunosRoom (6, 6) [walk only]", + "20.02 below_brunos_door from PokemonLeague_BrunosRoom (6, 6) facing north to PokemonLeague_BrunosRoom (6, 3) facing north", + "20.02 walk east 1 -> PokemonLeague_BrunosRoom (7, 6) [walk only]", + "20.02 walk north 3 (to wall) -> PokemonLeague_BrunosRoom (7, 3) [walk only]", + "20.02 walk west 1 -> PokemonLeague_BrunosRoom (6, 3) [walk only]", + "20.02 face north -> PokemonLeague_BrunosRoom (6, 3) [walk only]", + "20.03 before_agatha from PokemonLeague_AgathasRoom (6, 7) facing north to PokemonLeague_AgathasRoom (6, 6) facing north", + "20.03 walk north 1 (to wall) -> PokemonLeague_AgathasRoom (6, 6) [walk only]", + "20.03 below_agathas_door from PokemonLeague_AgathasRoom (6, 6) facing north to PokemonLeague_AgathasRoom (6, 3) facing north", + "20.03 walk east 1 -> PokemonLeague_AgathasRoom (7, 6) [walk only]", + "20.03 walk north 3 (to wall) -> PokemonLeague_AgathasRoom (7, 3) [walk only]", + "20.03 walk west 1 -> PokemonLeague_AgathasRoom (6, 3) [walk only]", + "20.03 face north -> PokemonLeague_AgathasRoom (6, 3) [walk only]", + "20.04 before_lance from PokemonLeague_LancesRoom (6, 10) facing north to PokemonLeague_LancesRoom (6, 9) facing north", + "20.04 walk north 1 (to wall) -> PokemonLeague_LancesRoom (6, 9) [walk only]", + "20.04 below_champions_door from PokemonLeague_LancesRoom (6, 9) facing north to PokemonLeague_LancesRoom (6, 6) facing north", + "20.04 walk east 1 -> PokemonLeague_LancesRoom (7, 9) [walk only]", + "20.04 walk north 3 (to wall) -> PokemonLeague_LancesRoom (7, 6) [walk only]", + "20.04 walk west 1 -> PokemonLeague_LancesRoom (6, 6) [walk only]", + "20.04 face north -> PokemonLeague_LancesRoom (6, 6) [walk only]", }; } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows20_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows20_Tests.h index 024ecda089..ed08d4a595 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows20_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows20_Tests.h @@ -17,9 +17,17 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -// Rows 20.01a and 20.01 on the overworld sim (PokemonFRLG_AutoStoryLeague_Tests.cpp). +// Rows 20.01a to 20.05 on the overworld sim (PokemonFRLG_AutoStoryLeague_Tests.cpp). void add_tests_AutoStoryLeague(UnitTestDatabase& database); +// The budgeted C2 policy's turns in the League's battles +// (PokemonFRLG_AutoStoryLeaguePlan_Tests.cpp). +void add_tests_AutoStoryLeaguePlan(UnitTestDatabase& database); + +// The League's fight rows through the engine's verification loop, and the +// top-up before each (PokemonFRLG_AutoStoryLeagueRows_Tests.cpp). +void add_tests_AutoStoryLeagueRows(UnitTestDatabase& database); + } // namespace PokemonFRLG } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp index 8661a7786a..e0f4e8a237 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp @@ -145,7 +145,7 @@ class Test_RunPlan : public UnitTest{ const RunPlanScenario m_scenario; }; -const std::string TODAY = "01.01 01.03 01.04 01.05 02.01 02.02 02.03 03.01 03.02 03.03 04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 16.02 16.03 16.03b 16.05 16.05b 16.06 16.06b 18.01 18.02 18.02b 18.03 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.04b 19.04c 19.04d 19.05 20.01a 20.01"; +const std::string TODAY = "01.01 01.03 01.04 01.05 02.01 02.02 02.03 03.01 03.02 03.03 04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 16.02 16.03 16.03b 16.05 16.05b 16.06 16.06b 18.01 18.02 18.02b 18.03 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.04b 19.04c 19.04d 19.05 20.01a 20.01 20.02 20.03 20.04 20.05"; const RunPlanScenario RUN_PLAN_CASES[] = { { @@ -236,11 +236,11 @@ const RunPlanScenario RUN_PLAN_CASES[] = { }, { .input = {.name = "Gift RNG off: 04.03 is passed over", .first = "04.01"}, - .expectation = {.expected_ids = "04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 16.02 16.03 16.03b 16.05 16.05b 16.06 16.06b 18.01 18.02 18.02b 18.03 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.04b 19.04c 19.04d 19.05 20.01a 20.01"}, + .expectation = {.expected_ids = "04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 16.02 16.03 16.03b 16.05 16.05b 16.06 16.06b 18.01 18.02 18.02b 18.03 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.04b 19.04c 19.04d 19.05 20.01a 20.01 20.02 20.03 20.04 20.05"}, }, { .input = {.name = "Gift RNG off: 04.03 runs when started at", .first = "04.03"}, - .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 16.02 16.03 16.03b 16.05 16.05b 16.06 16.06b 18.01 18.02 18.02b 18.03 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.04b 19.04c 19.04d 19.05 20.01a 20.01"}, + .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 16.02 16.03 16.03b 16.05 16.05b 16.06 16.06b 18.01 18.02 18.02b 18.03 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.04b 19.04c 19.04d 19.05 20.01a 20.01 20.02 20.03 20.04 20.05"}, }, { .input = { .name = "Gift RNG: started at 04.03, from the save beside the salesman", @@ -279,7 +279,7 @@ const RunPlanScenario RUN_PLAN_CASES[] = { }, { .input = {.name = "Starter RNG alone: 04.03 runs when started at", .first = "04.03", .handoffs = {.starter_rng = true}}, - .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 16.02 16.03 16.03b 16.05 16.05b 16.06 16.06b 18.01 18.02 18.02b 18.03 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.04b 19.04c 19.04d 19.05 20.01a 20.01"}, + .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 16.02 16.03 16.03b 16.05 16.05b 16.06 16.06b 18.01 18.02 18.02b 18.03 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.04b 19.04c 19.04d 19.05 20.01a 20.01 20.02 20.03 20.04 20.05"}, }, { .input = { .name = "Starter RNG first, with both on", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp index 7e0e6fce5f..913b2d61fe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp @@ -25,7 +25,6 @@ #include "PokemonFRLG_AutoStoryRooms.h" #include "PokemonFRLG_AutoStoryBattleBag.h" #include "PokemonFRLG_AutoStoryBattleTrack.h" -#include "PokemonFRLG_AutoStoryLeagueLoop_Tests.h" #include "PokemonFRLG_AutoStoryLeagueParity_Tests.h" #include "PokemonFRLG_AutoStoryPlannedBattle.h" #include "PokemonFRLG_AutoStoryPlannedPolicy.h" @@ -344,7 +343,6 @@ void add_tests_AutoStoryStepTable(UnitTestDatabase& database){ add_tests_AutoStoryPlannedPolicy(database); add_tests_AutoStoryPlannedBattle(database); add_tests_AutoStoryPlannedBattleFake(database); - add_tests_AutoStoryLeagueLoop(database); add_tests_AutoStoryLeagueParity(database); add_tests_AutoStoryBattleTrack(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp index 01285bf2a4..82d80d21c1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp @@ -11,7 +11,9 @@ #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_PartyDialogs.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_DigitReader.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_StatsReader.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "PokemonFRLG_AutoStorySummary.h" @@ -77,6 +79,15 @@ bool open_summary(ConsoleHandle& console, ProControllerContext& context){ return true; } +// POKEMON SKILLS' HP box (StatsReader's) as its digits read; empty if +// none were. +std::string skills_hp_digits(Logger& logger, const ImageViewRGB32& screen){ + const ImageFloatBox HP_BOX(0.805274, 0.131247, 0.183790, 0.066639); + const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); + const int digits = read_digits_waterfill_template(logger, extract_box_reference(game, HP_BOX), DigitTemplateType::StatBox); + return digits < 0 ? std::string() : std::to_string(digits); +} + // From the party menu with the cursor on the member: its summary, read. std::optional read_open_summary(ConsoleHandle& console, ProControllerContext& context, Language language){ if (!open_summary(console, context)){ @@ -101,6 +112,7 @@ std::optional read_open_summary(ConsoleHandle& console, ProControll } if (VideoSnapshot page = console.video().snapshot()){ read.stats = skills_stats(console, language, page); + read.hp_digits = skills_hp_digits(console, page); } SummaryPage3Watcher moves(COLOR_RED); tap(context, DPAD_RIGHT, 0ms); @@ -265,6 +277,25 @@ SpeciesFinder console_species_finder( }; } +std::optional summary_current_hp(std::string_view hp_digits, int max_hp){ + const std::string max = std::to_string(max_hp); + if (max_hp <= 0 || hp_digits.size() <= max.size() || !hp_digits.ends_with(max)){ + return std::nullopt; + } + std::string_view current = hp_digits.substr(0, hp_digits.size() - max.size()); + for (int c = 0; c < 2 && !current.empty(); c++){ + const int hp = std::stoi(std::string(current)); + if (hp <= max_hp){ + return hp; + } + if (!current.ends_with('2')){ + return std::nullopt; + } + current.remove_suffix(1); + } + return std::nullopt; +} + std::optional read_party_summary( ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language, size_t slot ){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h index 6a8d0e3d90..a926ce5f0b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include "CommonFramework/Language.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" @@ -39,8 +40,18 @@ struct SummaryRead{ std::vector moves = {}; // POKEMON SKILLS (HP as its maximum), none unless all six were read. std::optional stats = std::nullopt; + // POKEMON SKILLS' HP box as its digits read: the current HP's, then + // the maximum's (the "/" between is usually not read); empty if not + // read. + std::string hp_digits = {}; }; +// The current HP in `hp_digits` (SummaryRead::hp_digits) of a member whose +// maximum HP is `max_hp`: the digits before the maximum's, else, when they +// are more than it, those without a last "2" (the "/" read as one). +// None if the digits don't end in the maximum or nothing fits. +std::optional summary_current_hp(std::string_view hp_digits, int max_hp); + // From the overworld: the party menu, party slot `slot`'s SUMMARY, its // first page (species, level), POKEMON SKILLS (stats) and KNOWN MOVES, // then back to the overworld. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h index 2d272bf5bb..b7bd30a58d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h @@ -20,7 +20,7 @@ #include "PokemonFRLG_AutoStoryActions.h" #include "PokemonFRLG_AutoStoryBattleData.h" #include "PokemonFRLG_AutoStoryBattlePolicyData.h" -#include "PokemonFRLG_AutoStoryLeaguePlan.h" +#include "PokemonFRLG_AutoStoryLeagueBudget.h" #include "PokemonFRLG_AutoStoryParty.h" #include "PokemonFRLG_AutoStoryStartMenu.h" @@ -110,11 +110,7 @@ struct Supplies{ // How that battle is fought by PokeGuy's policy, if its step names one // (BattlePolicyKind::NONE otherwise: the story's own recovery). BattlePolicy policy = {}; - // The League's plan and what its fights have left, from the bag read - // at its start (league_start); none outside the League. - std::optional league = std::nullopt; - // The items the battle going on may spend (its League budget plus - // what the fights before left); none: no cap. + // The items the battle going on may spend; none: no cap. std::optional budget = std::nullopt; // How carefully that battle is fought (default_battle_risk()). BattleRisk risk = BattleRisk::LOW; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index d27992c529..66303ffb00 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -250,7 +250,7 @@ constexpr std::string_view STORY_ORDER[] = { "14.03", "14.04", "14.04b", "15.01", "16.01", "16.02", "16.03", "16.03b", "16.04", "16.05", "16.05b", "16.06", "16.06b", "18.01", "18.02", "18.02b", "18.03", "17.02", "17.03", "17.04", "17.04b", "19.01a", "19.01", "19.02", "19.03", "19.04", "19.04b", "19.04c", "19.04d", "19.05", - "20.01a", "20.01", + "20.01a", "20.01", "20.02", "20.03", "20.04", "20.05", }; // Where checkpoint `id` plays in STORY_ORDER; past its end if it is not diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable_Tests.cpp index 10f725a5cc..b7c2659ce5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable_Tests.cpp @@ -38,7 +38,7 @@ const std::vector PINNED_ORDER = { "14.03", "14.04", "14.04b", "15.01", "16.01", "16.02", "16.03", "16.03b", "16.04", "16.05", "16.05b", "16.06", "16.06b", "18.01", "18.02", "18.02b", "18.03", "17.02", "17.03", "17.04", "17.04b", "19.01a", "19.01", "19.02", "19.03", "19.04", "19.04b", "19.04c", "19.04d", "19.05", - "20.01a", "20.01", + "20.01a", "20.01", "20.02", "20.03", "20.04", "20.05", }; // The marks of every authored row that has one, as before the shared diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index f7ecd9ce84..ed124192d9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -424,8 +424,8 @@ UnitTestResult check_checkpoint(const StoryCheckpoint& checkpoint, StoryPose& po // start: starts_after_unauthored_rows()), and adds the plans to `golden`. UnitTestResult chain_story_routes(std::vector& golden){ const std::vector& checkpoints = story_checkpoints(); - if (checkpoints.size() != 93 || checkpoints[0].start){ - return "Expected 93 checkpoints, the first from a new game."; + if (checkpoints.size() != 97 || checkpoints[0].start){ + return "Expected 97 checkpoints, the first from a new game."; } StoryPose pose; walk_state() = WalkGates{}; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.01.plan.json index 25aa0b7da2..2c131e9442 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.01.plan.json @@ -3,7 +3,7 @@ "game": "frlg", "checkpoint": { "id": "20.01", - "title": "The Elite Four and the Champion, then the Hall of Fame", + "title": "The League: Lorelei", "start": { "map": "IndigoPlateau_PokemonCenter_1F", "tiles": [ @@ -26,11 +26,15 @@ "why": "the precondition for Lorelei: the lead at least Lv51, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md lorelei; the Route 22 rival takes it from 49 to 51)" }, { - "id": "league_start", + "id": "top_up_before_lorelei", "kind": "game_action", - "action": "league_start", - "args": {}, - "why": "the Items pocket read once for the whole League: stops before the door if the bag holds less than the League's minimum (the bag of 2026-11-16, LEAGUE_MINIMUM), else plans each fight's item budget from it (plan_league()) and logs the plan" + "action": "league_top_up", + "args": { + "fight": "lorelei", + "max_hp": 165, + "full_if_unknown": true + }, + "why": "after the reload, before the walk: reads the lead's HP and the Items pocket, then the plan's top-up before the fight (planned_between(): a Super Potion for up to 50 missing HP, two for up to 100 if two are spare, else a Full Restore; the Elixir only before the Champion), then checks the fight's entry contract (contract.entry: the items it starts with); a broken contract fails the row's start; the HP unread is full: the save is after 20.01a's nurse" }, { "id": "below_league_door", @@ -202,26 +206,6 @@ }, "why": "Lorelei (TRAINER_ELITE_FOUR_LORELEI): Dewgong Lv52, Cloyster Lv51, Slowbro Lv52, Jynx Lv54, Lapras Lv54, two Full Restores; fought by budgeted C2 (budgeted-setup, the League plan's per-fight item budget; before that goal-based-setup: Sp. Atk +4 by X Specials, X Speed until faster, Guard Spec first against an accuracy drop; the doc's lorelei row, 94.3% at 159/159); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against console B's Lv54 Blastoise (171 HP, Def 135, Sp. Def 150) at full HP: the 80th percentile of the foe's move choice, its mean, its worst case and its worst normal hit. Lapras's worst case is 62. Cloyster's only hit, Dive, hides a turn first (its row's ninth column): no KO risk until it is underwater. Dewgong's worst normal hit is 30, not the generator's 18: console B, 2026-11-16, took 30 of 162 in one turn. foe_stats are each foe's Defense, Sp. Def and HP from the doc's table, for the damage each attack would do and whether the best one KOs (no X item then). Then her door north (6, 2) opens" }, - { - "id": "lead_lv52_for_bruno", - "kind": "game_action", - "action": "level", - "args": { - "slot": 1, - "min": 52 - }, - "why": "the precondition for Bruno: the lead at least Lv52, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md bruno; Lorelei's fight takes it a level up)" - }, - { - "id": "items_before_bruno", - "kind": "game_action", - "action": "league_between_fights", - "args": { - "next": "TRAINER_ELITE_FOUR_BRUNO", - "max_hp": 165 - }, - "why": "the League plan's rules between fights (PokemonFRLG_AutoStoryLeaguePlan.h, between_fight_item()): a status cured, Super Potions up to Bruno's entry HP, a Full Restore only when they run out, an Elixir or Max Elixir when Surf or Blizzard is under its PP floor. Replaces the per-checkpoint heal_to_full, whose HP was unknown after a load (Bruno entered at 71%, console B, 2026-11-16)" - }, { "id": "below_loreleis_door", "kind": "route", @@ -262,707 +246,22 @@ "facing": "north" }, "why": "the room's OnFrame script (PokemonLeague_EventScript_EnterRoom) walks the player five tiles north from (6, 12) to (6, 7) and closes the entrance behind; no text" - }, - { - "id": "before_bruno", - "kind": "route", - "action": "run", - "args": { - "target": { - "map": "PokemonLeague_BrunosRoom", - "tiles": [ - [ - 6, - 6 - ] - ], - "facing": "north" - } - }, - "why": "to (6, 6) facing Bruno (6, 5), planned from where the room's walk left the player: a tile north, or a step round if the walk ended a tile off" - }, - { - "id": "challenge_bruno", - "kind": "talk", - "why": "Bruno (6, 5): the intro, then the battle (trainerbattle_no_intro)" - }, - { - "id": "bruno", - "kind": "battle", - "args": { - "trainer": "TRAINER_ELITE_FOUR_BRUNO", - "foes": [ - "onix", - "hitmonchan", - "hitmonlee", - "onix", - "machamp" - ], - "policy": "budgeted-setup", - "setup_spa": 2, - "setup_accuracy": 0, - "setup_outspeed": true, - "setup_guard_accuracy": true, - "setup_target_torrent": true, - "foe_threats": [ - [ - 81, - 26, - 16, - 63, - 31, - 0, - 0, - 1 - ], - [ - 101, - 43, - 24, - 108, - 54, - 0, - 0 - ], - [ - 113, - 54, - 44, - 114, - 57, - 0, - 0 - ], - [ - 96, - 33, - 33, - 69, - 34, - 0, - 0 - ], - [ - 83, - 0, - 4, - 150, - 75, - 0, - 0 - ] - ], - "foe_stats": [ - [ - 183, - 72, - 112 - ], - [ - 104, - 137, - 131 - ], - [ - 77, - 137, - 131 - ], - [ - 194, - 75, - 118 - ], - [ - 111, - 117, - 183 - ] - ] - }, - "declared_after": { - "map": "PokemonLeague_BrunosRoom", - "tiles": [ - [ - 6, - 6 - ] - ], - "facing": "north" - }, - "why": "Bruno (TRAINER_ELITE_FOUR_BRUNO): Onix Lv51, Hitmonchan Lv53, Hitmonlee Lv53, Onix Lv54, Machamp Lv56, two Full Restores; fought by budgeted C2 (budgeted-setup, the League plan's per-fight item budget; before that goal-based-setup: Sp. Atk +2 by X Specials, X Speed until faster, Guard Spec first against an accuracy drop; the doc's bruno row, 95.9% at 130/162. The doc's target_torrent (stalling to Torrent in the opening) is the C++ policy's extra X Specials against the first Onix, up to +4 while Torrent is off; its weaker-move stall needs the foe's HP and is not modelled (PokemonFRLG_AutoStoryBattlePolicy.h)); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against console B's Lv54 Blastoise (171 HP, Def 135, Sp. Def 150) at full HP: Machamp's worst case (crit Cross Chop) is 150, Hitmonlee's 114. The first Onix has Roar (marked as phazing in its row): console B, 2026-11-16, its Roar sent Blastoise out after four X Specials. foe_stats are each foe's Defense, Sp. Def and HP from the doc's table: Surf KOs both Onix at +0, so no X item is spent on them and setup waits for Hitmonchan. Then the door north (6, 2) opens" - }, - { - "id": "lead_lv53_for_agatha", - "kind": "game_action", - "action": "level", - "args": { - "slot": 1, - "min": 53 - }, - "why": "the precondition for Agatha: the lead at least Lv53, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md agatha; Bruno's fight takes it a level up)" - }, - { - "id": "items_before_agatha", - "kind": "game_action", - "action": "league_between_fights", - "args": { - "next": "TRAINER_ELITE_FOUR_AGATHA", - "max_hp": 165 - }, - "why": "the League plan's rules between fights (PokemonFRLG_AutoStoryLeaguePlan.h, between_fight_item()): a status cured, Super Potions up to Agatha's entry HP, a Full Restore only when they run out, an Elixir or Max Elixir when Surf or Blizzard is under its PP floor. Replaces the per-checkpoint heal_to_full, whose HP was unknown after a load (Bruno entered at 71%, console B, 2026-11-16)" - }, - { - "id": "below_brunos_door", - "kind": "route", - "action": "run", - "args": { - "target": { - "map": "PokemonLeague_BrunosRoom", - "tiles": [ - [ - 6, - 3 - ] - ], - "facing": "north" - } - }, - "why": "from in front of Bruno (6, 5) around him to below his door (6, 2), open since his defeat" - }, - { - "id": "brunos_door", - "kind": "step", - "args": { - "direction": "north" - }, - "why": "into the door (6, 2), the warp into Agatha's room at its south entrance (6, 12)" - }, - { - "id": "enter_agathas_room", - "kind": "scene", - "declared_after": { - "map": "PokemonLeague_AgathasRoom", - "tiles": [ - [ - 6, - 7 - ] - ], - "facing": "north" - }, - "why": "the room's OnFrame script (PokemonLeague_EventScript_EnterRoom) walks the player five tiles north from (6, 12) to (6, 7) and closes the entrance behind; no text" - }, - { - "id": "before_agatha", - "kind": "route", - "action": "run", - "args": { - "target": { - "map": "PokemonLeague_AgathasRoom", - "tiles": [ - [ - 6, - 6 - ] - ], - "facing": "north" - } - }, - "why": "to (6, 6) facing Agatha (6, 5), planned from where the room's walk left the player: a tile north, or a step round if the walk ended a tile off" - }, - { - "id": "challenge_agatha", - "kind": "talk", - "why": "Agatha (6, 5): the intro, then the battle (trainerbattle_no_intro)" - }, - { - "id": "agatha", - "kind": "battle", - "args": { - "trainer": "TRAINER_ELITE_FOUR_AGATHA", - "foes": [ - "gengar", - "golbat", - "haunter", - "arbok", - "gengar" - ], - "policy": "budgeted-setup", - "setup_spa": 1, - "setup_accuracy": 0, - "setup_outspeed": true, - "setup_guard_accuracy": true, - "setup_torrent_power": true, - "foe_threats": [ - [ - 126, - 0, - 3, - 60, - 30, - 0, - 0 - ], - [ - 129, - 28, - 17, - 60, - 30, - 0, - 0 - ], - [ - 108, - 0, - 0, - 0, - 41, - 0, - 0 - ], - [ - 111, - 51, - 31, - 108, - 54, - 0, - 0 - ], - [ - 150, - 40, - 24, - 84, - 42, - 0, - 0 - ] - ], - "foe_stats": [ - [ - 86, - 102, - 145 - ], - [ - 96, - 91, - 161 - ], - [ - 68, - 86, - 126 - ], - [ - 108, - 110, - 150 - ], - [ - 92, - 109, - 155 - ] - ] - }, - "declared_after": { - "map": "PokemonLeague_AgathasRoom", - "tiles": [ - [ - 6, - 6 - ] - ], - "facing": "north" - }, - "why": "Agatha (TRAINER_ELITE_FOUR_AGATHA): Gengar Lv54, Golbat Lv54, Haunter Lv53, Arbok Lv56, Gengar Lv58, two Full Restores; fought by budgeted C2 (budgeted-setup, the League plan's per-fight item budget; before that goal-based-setup: Sp. Atk +1 by X Specials, +3 while Torrent is off (torrent_power), X Speed until faster, Guard Spec first against an accuracy drop; the doc's agatha row, 95.3% at 45/165, its opening a heal); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against console B's Lv54 Blastoise (171 HP, Def 135, Sp. Def 150) at full HP: Arbok's worst case is 108. foe_stats are each foe's Defense, Sp. Def and HP from the doc's table, for the damage each attack would do and whether the best one KOs (no X item then). Then the door north (6, 2) opens" - }, - { - "id": "items_before_lance", - "kind": "game_action", - "action": "league_between_fights", - "args": { - "next": "TRAINER_ELITE_FOUR_LANCE", - "max_hp": 168 - }, - "why": "the League plan's rules between fights (PokemonFRLG_AutoStoryLeaguePlan.h, between_fight_item()): a status cured, Super Potions up to Lance's entry HP, a Full Restore only when they run out, an Elixir or Max Elixir when Surf or Blizzard is under its PP floor. Replaces the per-checkpoint heal_to_full, whose HP was unknown after a load (Bruno entered at 71%, console B, 2026-11-16)" - }, - { - "id": "lead_lv54_for_lance", - "kind": "game_action", - "action": "level", - "args": { - "slot": 1, - "min": 54 - }, - "why": "the precondition for Lance: the lead at least Lv54, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md lance)" - }, - { - "id": "below_agathas_door", - "kind": "route", - "action": "run", - "args": { - "target": { - "map": "PokemonLeague_AgathasRoom", - "tiles": [ - [ - 6, - 3 - ] - ], - "facing": "north" - } - }, - "why": "from in front of Agatha (6, 5) around her to below her door (6, 2), open since her defeat" - }, - { - "id": "agathas_door", - "kind": "step", - "args": { - "direction": "north" - }, - "why": "into the door (6, 2), the warp into Lance's room at the east end of its corridor (23, 13)" - }, - { - "id": "lances_corridor", - "kind": "scene", - "declared_after": { - "map": "PokemonLeague_LancesRoom", - "tiles": [ - [ - 6, - 10 - ] - ], - "facing": "north" - }, - "why": "the room's OnFrame script walks the player through the corridor (PokemonLeague_LancesRoom_Movement_WalkThroughCorridor: 2 north, 6 west, 7 south, 11 west, 8 north) from (23, 13) to (6, 10) and closes the entrance behind; no text" - }, - { - "id": "before_lance", - "kind": "route", - "action": "run", - "args": { - "target": { - "map": "PokemonLeague_LancesRoom", - "tiles": [ - [ - 6, - 9 - ] - ], - "facing": "north" - } - }, - "why": "to (6, 9) facing Lance (6, 8), planned from where the room's walk left the player: a tile north, or a step round if the walk ended a tile off" - }, - { - "id": "challenge_lance", - "kind": "talk", - "why": "Lance (6, 8): the intro, then the battle (trainerbattle_no_intro)" - }, - { - "id": "lance", - "kind": "battle", - "args": { - "trainer": "TRAINER_ELITE_FOUR_LANCE", - "foes": [ - "gyarados", - "dragonair", - "dragonair", - "aerodactyl", - "dragonite" - ], - "policy": "budgeted-setup", - "setup_spa": 3, - "setup_accuracy": 2, - "setup_outspeed": true, - "setup_guard_accuracy": true, - "foe_threats": [ - [ - 112, - 40, - 31, - 40, - 80, - 0, - 0 - ], - [ - 96, - 40, - 16, - 78, - 53, - 0, - 0 - ], - [ - 96, - 0, - 0, - 0, - 53, - 0, - 0 - ], - [ - 173, - 41, - 41, - 84, - 67, - 0, - 0 - ], - [ - 107, - 56, - 19, - 126, - 98, - 0, - 0 - ] - ], - "foe_stats": [ - [ - 110, - 119, - 189 - ], - [ - 91, - 96, - 146 - ], - [ - 91, - 96, - 146 - ], - [ - 106, - 109, - 178 - ], - [ - 137, - 157, - 197 - ] - ] - }, - "declared_after": { - "map": "PokemonLeague_LancesRoom", - "tiles": [ - [ - 6, - 9 - ] - ], - "facing": "north" - }, - "why": "Lance (TRAINER_ELITE_FOUR_LANCE): Gyarados Lv56, Dragonair Lv54, Dragonair Lv54, Aerodactyl Lv58, Dragonite Lv60, two Full Restores; fought by budgeted C2 (budgeted-setup, the League plan's per-fight item budget; before that goal-based-setup: Sp. Atk +3 and Accuracy +2 by X Specials and X Accuracies, X Speed until faster, Guard Spec first against an accuracy drop; the doc's lance row, 99.2% at 168/168); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against console B's Lv54 Blastoise (171 HP, Def 135, Sp. Def 150) at full HP: Dragonite's worst case is 126 and its worst normal hit (Hyper Beam) 98. foe_stats are each foe's Defense, Sp. Def and HP from the doc's table, for the damage each attack would do and whether the best one KOs (no X item then). Then the Champion's door north (6, 5) opens" - }, - { - "id": "items_before_champion", - "kind": "game_action", - "action": "league_between_fights", - "args": { - "next": "TRAINER_CHAMPION_FIRST_BULBASAUR", - "max_hp": 171 - }, - "why": "the League plan's rules between fights (PokemonFRLG_AutoStoryLeaguePlan.h, between_fight_item()): a status cured, Super Potions up to the Champion's entry HP, a Full Restore only when they run out, an Elixir or Max Elixir when Surf or Blizzard is under its PP floor. Replaces the per-checkpoint heal_to_full, whose HP was unknown after a load (Bruno entered at 71%, console B, 2026-11-16)" - }, - { - "id": "lead_lv55_for_champion", - "kind": "game_action", - "action": "level", - "args": { - "slot": 1, - "min": 55 - }, - "why": "the precondition for the Champion: the lead at least Lv55, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md champion)" - }, - { - "id": "below_champions_door", - "kind": "route", - "action": "run", - "args": { - "target": { - "map": "PokemonLeague_LancesRoom", - "tiles": [ - [ - 6, - 6 - ] - ], - "facing": "north" - } - }, - "why": "from in front of Lance (6, 8) around him to below the Champion's door (6, 5), open since his defeat" - }, - { - "id": "champions_door", - "kind": "step", - "args": { - "direction": "north" - }, - "why": "into the door (6, 5), the warp into the Champion's room at its south end (6, 19). The room's OnFrame script walks the player ten tiles north to (6, 9), in front of the rival (6, 8), and his intro runs straight into the battle: no talk" - }, - { - "id": "champion", - "kind": "battle", - "args": { - "trainer": "TRAINER_CHAMPION_FIRST_BULBASAUR", - "foes": [ - "pidgeot", - "alakazam", - "rhydon", - "gyarados", - "arcanine", - "venusaur" - ], - "policy": "budgeted-setup", - "setup_spa": 2, - "setup_accuracy": 2, - "setup_outspeed": true, - "setup_guard_accuracy": true, - "foe_threats": [ - [ - 130, - 35, - 24, - 75, - 37, - 1, - 0, - 1 - ], - [ - 159, - 70, - 64, - 144, - 72, - 0, - 0 - ], - [ - 70, - 0, - 8, - 183, - 91, - 0, - 0 - ], - [ - 118, - 44, - 43, - 96, - 48, - 0, - 0 - ], - [ - 139, - 45, - 45, - 92, - 46, - 0, - 0, - 1 - ], - [ - 125, - 194, - 182, - 396, - 198, - 0, - 0, - 0, - 1 - ] - ], - "foe_stats": [ - [ - 111, - 105, - 185 - ], - [ - 73, - 130, - 147 - ], - [ - 147, - 76, - 211 - ], - [ - 127, - 141, - 199 - ], - [ - 121, - 108, - 199 - ], - [ - 129, - 135, - 193 - ] - ] - }, - "declared_after": { - "map": "PokemonLeague_ChampionsRoom", - "tiles": [ - [ - 6, - 9 - ] - ], - "facing": "north" - }, - "why": "the Champion (TRAINER_CHAMPION_FIRST_BULBASAUR for a player who took Squirtle): Pidgeot Lv59, Alakazam Lv57, Rhydon Lv59, Gyarados Lv59, Arcanine Lv61, Venusaur Lv63, four Full Restores; fought by budgeted C2 (budgeted-setup, the League plan's per-fight item budget; before that goal-based-setup: Sp. Atk +2 and Accuracy +2 by X Specials and X Accuracies, X Speed until faster, Guard Spec first against Pidgeot's Sand Attack; the doc's champion row, 95.6% at 171/171, its opening a Guard Spec); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against console B's Lv54 Blastoise (171 HP, Def 135, Sp. Def 150) at full HP, Pidgeot's row marked as lowering accuracy: Venusaur's Solar Beam worst normal hit is 198 (a one-hit KO from full), Rhydon's worst case 183; Solar Beam without sun charges a turn first (Venusaur's row's ninth column), so it is a KO risk only while Venusaur is charging or the sun is out (the battle text), else setup goes on; Pidgeot (Whirlwind) and Arcanine (Roar) are marked as phazing, so no X item is spent on them (their stages would go with a forced switch). foe_stats are each foe's Defense, Sp. Def and HP from the doc's table: Surf KOs Rhydon, so it is attacked at once" - }, - { - "id": "hall_of_fame", - "kind": "scene", - "declared_after": { - "map": "PokemonLeague_HallOfFame", - "tiles": [ - [ - 5, - 4 - ] - ], - "facing": "north" - }, - "why": "the rival's last words, Oak's entrance and his talk, and Oak leading the player out north (PokemonLeague_ChampionsRoom_Movement_PlayerExit) to the Hall of Fame (5, 12); its OnFrame script walks the player eight tiles north to (5, 4), Oak's congratulations, then the record (FLDEFF_HALL_OF_FAME_RECORD) and the Hall of Fame (special EnterHallOfFame), which saves the game itself and rolls the credits" } ] }, "execution": { "menu": "full", + "verify": { + "tries": 10, + "min_pass": 5, + "reset_budget": 5 + }, "notes": { "checkpoint": [ - "Starts at Indigo Plateau's Mart counter, where 20.01a ends. The whole League is one checkpoint, with no save between the fights until the Hall of Fame (user, 2026-11-16; overrides a boss battle per checkpoint): league_start reads the bag once and plans every fight's items from it (PokemonFRLG_AutoStoryLeaguePlan.h), and each battle spends its budget plus what the fights before left. A failed fight goes back to this row's start.", + "Starts at Indigo Plateau's Mart counter, where 20.01a ends, the party healed by its nurse. Ends in Bruno's room (6, 7), where its entrance scene leaves the player.", + "One League fight per row, each run as a verification loop from its start save (execution.verify, copied from frlg-league-plan.json's contract.pass: tries = min_pass.of, min_pass = min_pass.k, reset_budget): phase 1 plays it that many times saving none and stops the run under min_pass; phase 2 plays it until a try passes (won, within the fight's item caps: league_row_pass()) and saves that one.", "The League rooms are one-way: the entrance closes behind the player, and the next room's door opens only when the room's trainer is beaten.", - "PokeGuy's fights: Lorelei 1:46:37, Bruno 1:49:15, Agatha 1:51:12, Lance 1:53:07, the Champion 1:55:44 (docs/battles/pokeguy-conditions.md); his turns: ~/BDSPLab/notes/pokeguy-league-turns.md.", - "Ends in the Hall of Fame (5, 4) facing north. The Hall of Fame saves the game itself (respawn at Pallet Town) and the credits follow: the row's own save at its end is not one the game offers there." + "PokeGuy's fights: Lorelei 1:46:37, Bruno 1:49:15, Agatha 1:51:12, Lance 1:53:07, the Champion 1:55:44 (docs/battles/pokeguy-conditions.md); his turns: ~/BDSPLab/notes/pokeguy-league-turns.md." ] } }, @@ -970,11 +269,11 @@ "phase": "testing", "postconditions": { "position": { - "map": "PokemonLeague_HallOfFame", + "map": "PokemonLeague_BrunosRoom", "tiles": [ [ - 5, - 4 + 6, + 7 ] ], "facing": "north" diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.02.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.02.plan.json new file mode 100644 index 0000000000..f1d3e167cb --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.02.plan.json @@ -0,0 +1,241 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "20.02", + "title": "The League: Bruno", + "start": { + "map": "PokemonLeague_BrunosRoom", + "tiles": [ + [ + 6, + 7 + ] + ], + "facing": "north" + }, + "events": [ + { + "id": "lead_lv52_for_bruno", + "kind": "game_action", + "action": "level", + "args": { + "slot": 1, + "min": 52 + }, + "why": "the precondition for Bruno: the lead at least Lv52, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md bruno; Lorelei's fight takes it a level up)" + }, + { + "id": "top_up_before_bruno", + "kind": "game_action", + "action": "league_top_up", + "args": { + "fight": "bruno", + "max_hp": 165 + }, + "why": "after the reload, before the walk: reads the lead's HP and the Items pocket, then the plan's top-up before the fight (planned_between(): a Super Potion for up to 50 missing HP, two for up to 100 if two are spare, else a Full Restore; the Elixir only before the Champion), then checks the fight's entry contract (contract.entry: the items it starts with); a broken contract fails the row's start" + }, + { + "id": "before_bruno", + "kind": "route", + "action": "run", + "args": { + "target": { + "map": "PokemonLeague_BrunosRoom", + "tiles": [ + [ + 6, + 6 + ] + ], + "facing": "north" + } + }, + "why": "to (6, 6) facing Bruno (6, 5), planned from where the room's walk left the player: a tile north, or a step round if the walk ended a tile off" + }, + { + "id": "challenge_bruno", + "kind": "talk", + "why": "Bruno (6, 5): the intro, then the battle (trainerbattle_no_intro)" + }, + { + "id": "bruno", + "kind": "battle", + "args": { + "trainer": "TRAINER_ELITE_FOUR_BRUNO", + "foes": [ + "onix", + "hitmonchan", + "hitmonlee", + "onix", + "machamp" + ], + "policy": "budgeted-setup", + "setup_spa": 2, + "setup_accuracy": 0, + "setup_outspeed": true, + "setup_guard_accuracy": true, + "setup_target_torrent": true, + "foe_threats": [ + [ + 81, + 26, + 16, + 63, + 31, + 0, + 0, + 1 + ], + [ + 101, + 43, + 24, + 108, + 54, + 0, + 0 + ], + [ + 113, + 54, + 44, + 114, + 57, + 0, + 0 + ], + [ + 96, + 33, + 33, + 69, + 34, + 0, + 0 + ], + [ + 83, + 0, + 4, + 150, + 75, + 0, + 0 + ] + ], + "foe_stats": [ + [ + 183, + 72, + 112 + ], + [ + 104, + 137, + 131 + ], + [ + 77, + 137, + 131 + ], + [ + 194, + 75, + 118 + ], + [ + 111, + 117, + 183 + ] + ] + }, + "declared_after": { + "map": "PokemonLeague_BrunosRoom", + "tiles": [ + [ + 6, + 6 + ] + ], + "facing": "north" + }, + "why": "Bruno (TRAINER_ELITE_FOUR_BRUNO): Onix Lv51, Hitmonchan Lv53, Hitmonlee Lv53, Onix Lv54, Machamp Lv56, two Full Restores; fought by budgeted C2 (budgeted-setup, the League plan's per-fight item budget; before that goal-based-setup: Sp. Atk +2 by X Specials, X Speed until faster, Guard Spec first against an accuracy drop; the doc's bruno row, 95.9% at 130/162. The doc's target_torrent (stalling to Torrent in the opening) is the C++ policy's extra X Specials against the first Onix, up to +4 while Torrent is off; its weaker-move stall needs the foe's HP and is not modelled (PokemonFRLG_AutoStoryBattlePolicy.h)); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against console B's Lv54 Blastoise (171 HP, Def 135, Sp. Def 150) at full HP: Machamp's worst case (crit Cross Chop) is 150, Hitmonlee's 114. The first Onix has Roar (marked as phazing in its row): console B, 2026-11-16, its Roar sent Blastoise out after four X Specials. foe_stats are each foe's Defense, Sp. Def and HP from the doc's table: Surf KOs both Onix at +0, so no X item is spent on them and setup waits for Hitmonchan. Then the door north (6, 2) opens" + }, + { + "id": "below_brunos_door", + "kind": "route", + "action": "run", + "args": { + "target": { + "map": "PokemonLeague_BrunosRoom", + "tiles": [ + [ + 6, + 3 + ] + ], + "facing": "north" + } + }, + "why": "from in front of Bruno (6, 5) around him to below his door (6, 2), open since his defeat" + }, + { + "id": "brunos_door", + "kind": "step", + "args": { + "direction": "north" + }, + "why": "into the door (6, 2), the warp into Agatha's room at its south entrance (6, 12)" + }, + { + "id": "enter_agathas_room", + "kind": "scene", + "declared_after": { + "map": "PokemonLeague_AgathasRoom", + "tiles": [ + [ + 6, + 7 + ] + ], + "facing": "north" + }, + "why": "the room's OnFrame script (PokemonLeague_EventScript_EnterRoom) walks the player five tiles north from (6, 12) to (6, 7) and closes the entrance behind; no text" + } + ] + }, + "execution": { + "menu": "full", + "verify": { + "tries": 10, + "min_pass": 1, + "reset_budget": 9 + }, + "notes": { + "checkpoint": [ + "Starts in Bruno's room (6, 7), where 20.01 ends. Ends in Agatha's room (6, 7).", + "One League fight per row, each run as a verification loop from its start save (execution.verify, copied from frlg-league-plan.json's contract.pass: tries = min_pass.of, min_pass = min_pass.k, reset_budget): phase 1 plays it that many times saving none and stops the run under min_pass; phase 2 plays it until a try passes (won, within the fight's item caps: league_row_pass()) and saves that one.", + "The League rooms are one-way: the entrance closes behind the player, and the next room's door opens only when the room's trainer is beaten.", + "PokeGuy's fights: Lorelei 1:46:37, Bruno 1:49:15, Agatha 1:51:12, Lance 1:53:07, the Champion 1:55:44 (docs/battles/pokeguy-conditions.md); his turns: ~/BDSPLab/notes/pokeguy-league-turns.md." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": { + "map": "PokemonLeague_AgathasRoom", + "tiles": [ + [ + 6, + 7 + ] + ], + "facing": "north" + } + } + } +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.03.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.03.plan.json new file mode 100644 index 0000000000..be54d429d3 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.03.plan.json @@ -0,0 +1,240 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "20.03", + "title": "The League: Agatha", + "start": { + "map": "PokemonLeague_AgathasRoom", + "tiles": [ + [ + 6, + 7 + ] + ], + "facing": "north" + }, + "events": [ + { + "id": "lead_lv53_for_agatha", + "kind": "game_action", + "action": "level", + "args": { + "slot": 1, + "min": 53 + }, + "why": "the precondition for Agatha: the lead at least Lv53, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md agatha; Bruno's fight takes it a level up)" + }, + { + "id": "top_up_before_agatha", + "kind": "game_action", + "action": "league_top_up", + "args": { + "fight": "agatha", + "max_hp": 165 + }, + "why": "after the reload, before the walk: reads the lead's HP and the Items pocket, then the plan's top-up before the fight (planned_between(): a Super Potion for up to 50 missing HP, two for up to 100 if two are spare, else a Full Restore; the Elixir only before the Champion), then checks the fight's entry contract (contract.entry: the items it starts with); a broken contract fails the row's start" + }, + { + "id": "before_agatha", + "kind": "route", + "action": "run", + "args": { + "target": { + "map": "PokemonLeague_AgathasRoom", + "tiles": [ + [ + 6, + 6 + ] + ], + "facing": "north" + } + }, + "why": "to (6, 6) facing Agatha (6, 5), planned from where the room's walk left the player: a tile north, or a step round if the walk ended a tile off" + }, + { + "id": "challenge_agatha", + "kind": "talk", + "why": "Agatha (6, 5): the intro, then the battle (trainerbattle_no_intro)" + }, + { + "id": "agatha", + "kind": "battle", + "args": { + "trainer": "TRAINER_ELITE_FOUR_AGATHA", + "foes": [ + "gengar", + "golbat", + "haunter", + "arbok", + "gengar" + ], + "policy": "budgeted-setup", + "setup_spa": 1, + "setup_accuracy": 0, + "setup_outspeed": true, + "setup_guard_accuracy": true, + "setup_torrent_power": true, + "foe_threats": [ + [ + 126, + 0, + 3, + 60, + 30, + 0, + 0 + ], + [ + 129, + 28, + 17, + 60, + 30, + 0, + 0 + ], + [ + 108, + 0, + 0, + 0, + 41, + 0, + 0 + ], + [ + 111, + 51, + 31, + 108, + 54, + 0, + 0 + ], + [ + 150, + 40, + 24, + 84, + 42, + 0, + 0 + ] + ], + "foe_stats": [ + [ + 86, + 102, + 145 + ], + [ + 96, + 91, + 161 + ], + [ + 68, + 86, + 126 + ], + [ + 108, + 110, + 150 + ], + [ + 92, + 109, + 155 + ] + ] + }, + "declared_after": { + "map": "PokemonLeague_AgathasRoom", + "tiles": [ + [ + 6, + 6 + ] + ], + "facing": "north" + }, + "why": "Agatha (TRAINER_ELITE_FOUR_AGATHA): Gengar Lv54, Golbat Lv54, Haunter Lv53, Arbok Lv56, Gengar Lv58, two Full Restores; fought by budgeted C2 (budgeted-setup, the League plan's per-fight item budget; before that goal-based-setup: Sp. Atk +1 by X Specials, +3 while Torrent is off (torrent_power), X Speed until faster, Guard Spec first against an accuracy drop; the doc's agatha row, 95.3% at 45/165, its opening a heal); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against console B's Lv54 Blastoise (171 HP, Def 135, Sp. Def 150) at full HP: Arbok's worst case is 108. foe_stats are each foe's Defense, Sp. Def and HP from the doc's table, for the damage each attack would do and whether the best one KOs (no X item then). Then the door north (6, 2) opens" + }, + { + "id": "below_agathas_door", + "kind": "route", + "action": "run", + "args": { + "target": { + "map": "PokemonLeague_AgathasRoom", + "tiles": [ + [ + 6, + 3 + ] + ], + "facing": "north" + } + }, + "why": "from in front of Agatha (6, 5) around her to below her door (6, 2), open since her defeat" + }, + { + "id": "agathas_door", + "kind": "step", + "args": { + "direction": "north" + }, + "why": "into the door (6, 2), the warp into Lance's room at the east end of its corridor (23, 13)" + }, + { + "id": "lances_corridor", + "kind": "scene", + "declared_after": { + "map": "PokemonLeague_LancesRoom", + "tiles": [ + [ + 6, + 10 + ] + ], + "facing": "north" + }, + "why": "the room's OnFrame script walks the player through the corridor (PokemonLeague_LancesRoom_Movement_WalkThroughCorridor: 2 north, 6 west, 7 south, 11 west, 8 north) from (23, 13) to (6, 10) and closes the entrance behind; no text" + } + ] + }, + "execution": { + "menu": "full", + "verify": { + "tries": 10, + "min_pass": 5, + "reset_budget": 5 + }, + "notes": { + "checkpoint": [ + "Starts in Agatha's room (6, 7), where 20.02 ends. Ends in Lance's room (6, 10), at the end of its corridor.", + "One League fight per row, each run as a verification loop from its start save (execution.verify, copied from frlg-league-plan.json's contract.pass: tries = min_pass.of, min_pass = min_pass.k, reset_budget): phase 1 plays it that many times saving none and stops the run under min_pass; phase 2 plays it until a try passes (won, within the fight's item caps: league_row_pass()) and saves that one.", + "The League rooms are one-way: the entrance closes behind the player, and the next room's door opens only when the room's trainer is beaten.", + "PokeGuy's fights: Lorelei 1:46:37, Bruno 1:49:15, Agatha 1:51:12, Lance 1:53:07, the Champion 1:55:44 (docs/battles/pokeguy-conditions.md); his turns: ~/BDSPLab/notes/pokeguy-league-turns.md." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": { + "map": "PokemonLeague_LancesRoom", + "tiles": [ + [ + 6, + 10 + ] + ], + "facing": "north" + } + } + } +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.04.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.04.plan.json new file mode 100644 index 0000000000..da74fc1ab3 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.04.plan.json @@ -0,0 +1,216 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "20.04", + "title": "The League: Lance", + "start": { + "map": "PokemonLeague_LancesRoom", + "tiles": [ + [ + 6, + 10 + ] + ], + "facing": "north" + }, + "events": [ + { + "id": "lead_lv54_for_lance", + "kind": "game_action", + "action": "level", + "args": { + "slot": 1, + "min": 54 + }, + "why": "the precondition for Lance: the lead at least Lv54, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md lance)" + }, + { + "id": "top_up_before_lance", + "kind": "game_action", + "action": "league_top_up", + "args": { + "fight": "lance", + "max_hp": 168 + }, + "why": "after the reload, before the walk: reads the lead's HP and the Items pocket, then the plan's top-up before the fight (planned_between(): a Super Potion for up to 50 missing HP, two for up to 100 if two are spare, else a Full Restore; the Elixir only before the Champion), then checks the fight's entry contract (contract.entry: the items it starts with); a broken contract fails the row's start" + }, + { + "id": "before_lance", + "kind": "route", + "action": "run", + "args": { + "target": { + "map": "PokemonLeague_LancesRoom", + "tiles": [ + [ + 6, + 9 + ] + ], + "facing": "north" + } + }, + "why": "to (6, 9) facing Lance (6, 8), planned from where the room's walk left the player: a tile north, or a step round if the walk ended a tile off" + }, + { + "id": "challenge_lance", + "kind": "talk", + "why": "Lance (6, 8): the intro, then the battle (trainerbattle_no_intro)" + }, + { + "id": "lance", + "kind": "battle", + "args": { + "trainer": "TRAINER_ELITE_FOUR_LANCE", + "foes": [ + "gyarados", + "dragonair", + "dragonair", + "aerodactyl", + "dragonite" + ], + "policy": "budgeted-setup", + "setup_spa": 3, + "setup_accuracy": 2, + "setup_outspeed": true, + "setup_guard_accuracy": true, + "foe_threats": [ + [ + 112, + 40, + 31, + 40, + 80, + 0, + 0 + ], + [ + 96, + 40, + 16, + 78, + 53, + 0, + 0 + ], + [ + 96, + 0, + 0, + 0, + 53, + 0, + 0 + ], + [ + 173, + 41, + 41, + 84, + 67, + 0, + 0 + ], + [ + 107, + 56, + 19, + 126, + 98, + 0, + 0 + ] + ], + "foe_stats": [ + [ + 110, + 119, + 189 + ], + [ + 91, + 96, + 146 + ], + [ + 91, + 96, + 146 + ], + [ + 106, + 109, + 178 + ], + [ + 137, + 157, + 197 + ] + ] + }, + "declared_after": { + "map": "PokemonLeague_LancesRoom", + "tiles": [ + [ + 6, + 9 + ] + ], + "facing": "north" + }, + "why": "Lance (TRAINER_ELITE_FOUR_LANCE): Gyarados Lv56, Dragonair Lv54, Dragonair Lv54, Aerodactyl Lv58, Dragonite Lv60, two Full Restores; fought by budgeted C2 (budgeted-setup, the League plan's per-fight item budget; before that goal-based-setup: Sp. Atk +3 and Accuracy +2 by X Specials and X Accuracies, X Speed until faster, Guard Spec first against an accuracy drop; the doc's lance row, 99.2% at 168/168); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against console B's Lv54 Blastoise (171 HP, Def 135, Sp. Def 150) at full HP: Dragonite's worst case is 126 and its worst normal hit (Hyper Beam) 98. foe_stats are each foe's Defense, Sp. Def and HP from the doc's table, for the damage each attack would do and whether the best one KOs (no X item then). Then the Champion's door north (6, 5) opens" + }, + { + "id": "below_champions_door", + "kind": "route", + "action": "run", + "args": { + "target": { + "map": "PokemonLeague_LancesRoom", + "tiles": [ + [ + 6, + 6 + ] + ], + "facing": "north" + } + }, + "why": "from in front of Lance (6, 8) around him to below the Champion's door (6, 5), open since his defeat" + } + ] + }, + "execution": { + "menu": "full", + "verify": { + "tries": 10, + "min_pass": 2, + "reset_budget": 7 + }, + "notes": { + "checkpoint": [ + "Starts in Lance's room (6, 10), where 20.03 ends. Ends below the Champion's door (6, 6): the door itself starts the Champion's battle, which is 20.05's.", + "One League fight per row, each run as a verification loop from its start save (execution.verify, copied from frlg-league-plan.json's contract.pass: tries = min_pass.of, min_pass = min_pass.k, reset_budget): phase 1 plays it that many times saving none and stops the run under min_pass; phase 2 plays it until a try passes (won, within the fight's item caps: league_row_pass()) and saves that one.", + "The League rooms are one-way: the entrance closes behind the player, and the next room's door opens only when the room's trainer is beaten.", + "PokeGuy's fights: Lorelei 1:46:37, Bruno 1:49:15, Agatha 1:51:12, Lance 1:53:07, the Champion 1:55:44 (docs/battles/pokeguy-conditions.md); his turns: ~/BDSPLab/notes/pokeguy-league-turns.md." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": { + "map": "PokemonLeague_LancesRoom", + "tiles": [ + [ + 6, + 6 + ] + ], + "facing": "north" + } + } + } +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.05.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.05.plan.json new file mode 100644 index 0000000000..9c75f3fda2 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-20.05.plan.json @@ -0,0 +1,217 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "20.05", + "title": "The League: the Champion, then the Hall of Fame", + "start": { + "map": "PokemonLeague_LancesRoom", + "tiles": [ + [ + 6, + 6 + ] + ], + "facing": "north" + }, + "events": [ + { + "id": "lead_lv55_for_champion", + "kind": "game_action", + "action": "level", + "args": { + "slot": 1, + "min": 55 + }, + "why": "the precondition for the Champion: the lead at least Lv55, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md champion)" + }, + { + "id": "top_up_before_champion", + "kind": "game_action", + "action": "league_top_up", + "args": { + "fight": "champion", + "max_hp": 171 + }, + "why": "after the reload, before the walk: reads the lead's HP and the Items pocket, then the plan's top-up before the fight (planned_between(): a Super Potion for up to 50 missing HP, two for up to 100 if two are spare, else a Full Restore; the Elixir only before the Champion), then checks the fight's entry contract (contract.entry: the items it starts with); a broken contract fails the row's start" + }, + { + "id": "champions_door", + "kind": "step", + "args": { + "direction": "north" + }, + "why": "into the door (6, 5), the warp into the Champion's room at its south end (6, 19). The room's OnFrame script walks the player ten tiles north to (6, 9), in front of the rival (6, 8), and his intro runs straight into the battle: no talk" + }, + { + "id": "champion", + "kind": "battle", + "args": { + "trainer": "TRAINER_CHAMPION_FIRST_BULBASAUR", + "foes": [ + "pidgeot", + "alakazam", + "rhydon", + "gyarados", + "arcanine", + "venusaur" + ], + "policy": "budgeted-setup", + "setup_spa": 2, + "setup_accuracy": 2, + "setup_outspeed": true, + "setup_guard_accuracy": true, + "foe_threats": [ + [ + 130, + 35, + 24, + 75, + 37, + 1, + 0, + 1 + ], + [ + 159, + 70, + 64, + 144, + 72, + 0, + 0 + ], + [ + 70, + 0, + 8, + 183, + 91, + 0, + 0 + ], + [ + 118, + 44, + 43, + 96, + 48, + 0, + 0 + ], + [ + 139, + 45, + 45, + 92, + 46, + 0, + 0, + 1 + ], + [ + 125, + 194, + 182, + 396, + 198, + 0, + 0, + 0, + 1 + ] + ], + "foe_stats": [ + [ + 111, + 105, + 185 + ], + [ + 73, + 130, + 147 + ], + [ + 147, + 76, + 211 + ], + [ + 127, + 141, + 199 + ], + [ + 121, + 108, + 199 + ], + [ + 129, + 135, + 193 + ] + ] + }, + "declared_after": { + "map": "PokemonLeague_ChampionsRoom", + "tiles": [ + [ + 6, + 9 + ] + ], + "facing": "north" + }, + "why": "the Champion (TRAINER_CHAMPION_FIRST_BULBASAUR for a player who took Squirtle): Pidgeot Lv59, Alakazam Lv57, Rhydon Lv59, Gyarados Lv59, Arcanine Lv61, Venusaur Lv63, four Full Restores; fought by budgeted C2 (budgeted-setup, the League plan's per-fight item budget; before that goal-based-setup: Sp. Atk +2 and Accuracy +2 by X Specials and X Accuracies, X Speed until faster, Guard Spec first against Pidgeot's Sand Attack; the doc's champion row, 95.6% at 171/171, its opening a Guard Spec); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against console B's Lv54 Blastoise (171 HP, Def 135, Sp. Def 150) at full HP, Pidgeot's row marked as lowering accuracy: Venusaur's Solar Beam worst normal hit is 198 (a one-hit KO from full), Rhydon's worst case 183; Solar Beam without sun charges a turn first (Venusaur's row's ninth column), so it is a KO risk only while Venusaur is charging or the sun is out (the battle text), else setup goes on; Pidgeot (Whirlwind) and Arcanine (Roar) are marked as phazing, so no X item is spent on them (their stages would go with a forced switch). foe_stats are each foe's Defense, Sp. Def and HP from the doc's table: Surf KOs Rhydon, so it is attacked at once" + }, + { + "id": "hall_of_fame", + "kind": "scene", + "declared_after": { + "map": "PokemonLeague_HallOfFame", + "tiles": [ + [ + 5, + 4 + ] + ], + "facing": "north" + }, + "why": "the rival's last words, Oak's entrance and his talk, and Oak leading the player out north (PokemonLeague_ChampionsRoom_Movement_PlayerExit) to the Hall of Fame (5, 12); its OnFrame script walks the player eight tiles north to (5, 4), Oak's congratulations, then the record (FLDEFF_HALL_OF_FAME_RECORD) and the Hall of Fame (special EnterHallOfFame), which saves the game itself and rolls the credits" + } + ] + }, + "execution": { + "menu": "full", + "verify": { + "tries": 10, + "min_pass": 2, + "reset_budget": 8 + }, + "notes": { + "checkpoint": [ + "Starts below the Champion's door (6, 6), where 20.04 ends. Ends in the Hall of Fame (5, 4) facing north. The Hall of Fame saves the game itself (respawn at Pallet Town) and the credits follow: the row's own save at its end is not one the game offers there.", + "One League fight per row, each run as a verification loop from its start save (execution.verify, copied from frlg-league-plan.json's contract.pass: tries = min_pass.of, min_pass = min_pass.k, reset_budget): phase 1 plays it that many times saving none and stops the run under min_pass; phase 2 plays it until a try passes (won, within the fight's item caps: league_row_pass()) and saves that one.", + "The League rooms are one-way: the entrance closes behind the player, and the next room's door opens only when the room's trainer is beaten.", + "PokeGuy's fights: Lorelei 1:46:37, Bruno 1:49:15, Agatha 1:51:12, Lance 1:53:07, the Champion 1:55:44 (docs/battles/pokeguy-conditions.md); his turns: ~/BDSPLab/notes/pokeguy-league-turns.md." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": { + "map": "PokemonLeague_HallOfFame", + "tiles": [ + [ + 5, + 4 + ] + ], + "facing": "north" + } + } + } +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-league-plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-league-plan.json index 87948a1dd7..786bc27885 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-league-plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-league-plan.json @@ -1,5 +1,9 @@ { "format": "frlg-league-plan/1", + "entry_hp": { + "lead_max_hp": 171, + "why": "Each fight's contract.entry.hp_sim counts HP out of the sim's Lv54 Blastoise (171 max HP). The entry check before a fight (league_entry_check) wants our lead's HP at least hp_sim.p10 / lead_max_hp of its own maximum. This convention is the agents' reading, NOT confirmed: the user must confirm it (2026-11-17)." + }, "fights": { "lorelei": { "goal": "Win with <= 1 Full Restore: 6 X Special on Dewgong (+6), Bite/Surf through, Lapras Strength -> Bite -> Bite", diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 08ce71f927..1d36770b92 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2225,20 +2225,15 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueBudget.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueParity_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueParity_Tests.h - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan.cpp - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlan_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeaguePlanData.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueFightData.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueFightData.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueFoePlan.h - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop.cpp - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop.h - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop_Tests.cpp - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueLoop_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows13_Tests.h