diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp index 1175684067..c572844e3b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp @@ -15,7 +15,7 @@ namespace Pokemon{ namespace{ -constexpr std::string_view SHARED_FIELDS[] = {"save", "reload_when_chained", "dev_only"}; +constexpr std::string_view SHARED_FIELDS[] = {"save", "reload_when_chained", "dev_only", "verify"}; bool is_known_field(std::string_view key, std::initializer_list game_fields){ for (std::string_view field : SHARED_FIELDS){ @@ -74,6 +74,37 @@ bool read_dev_only(const JsonObject& execution, std::string_view where){ return true; } +// One of verify's figures: a whole number of at least `least`. +size_t read_verify_figure(const JsonObject& verify, std::string_view name, size_t least, std::string_view where){ + const int64_t value = verify.get_integer_throw(std::string(name), std::string(where)); + if (value < (int64_t)least){ + throw ParseException(std::format("{}: verify {} is {}, at least {}", where, name, value, least)); + } + return (size_t)value; +} + +std::optional read_verify(const JsonObject& execution, std::string_view where){ + const JsonValue* value = execution.get_value("verify"); + if (value == nullptr){ + return std::nullopt; + } + const JsonObject& verify = value->to_object_throw(std::string(where)); + for (const auto& [key, figure] : verify){ + if (key != "tries" && key != "min_pass" && key != "reset_budget"){ + throw ParseException(std::format("{}: unknown verify field {}", where, key)); + } + } + StoryVerify figures{ + .tries = read_verify_figure(verify, "tries", /*least=*/1, where), + .min_pass = read_verify_figure(verify, "min_pass", /*least=*/0, where), + .reset_budget = read_verify_figure(verify, "reset_budget", /*least=*/1, where), + }; + if (figures.min_pass > figures.tries){ + throw ParseException(std::format("{}: verify min_pass {} is more than its {} tries", where, figures.min_pass, figures.tries)); + } + return figures; +} + } // namespace @@ -89,6 +120,7 @@ StoryRowExecution read_story_row_execution( .autosave = read_autosave(execution, where), .reload = read_reload(execution, where), .dev_only = read_dev_only(execution, where), + .verify = read_verify(execution, where), }; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h index d820f0b6a1..ab73e9e634 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h @@ -17,12 +17,14 @@ #include #include +#include #include #include #include #include #include #include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryVerify.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -46,10 +48,13 @@ struct StoryRowExecution{ // "dev_only": true: a lab walk the story does not need (developer // mode lists and plays it, a user's run does not). bool dev_only = false; + // "verify": {"tries", "min_pass", "reset_budget"}: the row runs as a + // verification loop (Pokemon_StoryVerify.h). + std::optional verify = std::nullopt; }; -// The shared fields of `execution`: "save", "reload_when_chained" and -// "dev_only", each optional. Throws ParseException naming `where` for a +// The shared fields of `execution`: "save", "reload_when_chained", +// "dev_only" and "verify", each optional. Throws ParseException naming `where` for a // malformed one, and for a field that is neither shared nor one of // `game_fields`, which the game reads itself. StoryRowExecution read_story_row_execution( diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 12a663fb7d..9556e609d8 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -36,6 +36,7 @@ #include "Pokemon_StoryRun_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" +#include "Pokemon_StoryVerifyRows_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" #include "Pokemon_Transitions_Tests.h" #include "Types/Pokemon_StoryActionArg_Tests.h" @@ -57,6 +58,7 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryRangeOptions(database); add_tests_StoryEvents(database); add_tests_StorySegments(database); + add_tests_StoryVerifyRows(database); add_tests_StoryStepExecutor(database); add_tests_StoryStepJson(database); add_tests_StoryActionArg(database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp index c46ab2764e..e6401a1b11 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp @@ -212,6 +212,136 @@ CheckpointReport run_row( return result; } +// Whether a verify try that completed passes: the game's postcondition +// check, then its pass predicate. +Outcome verify_pass(const std::string& id, SegmentHooks& hooks, RunState& state){ + if (hooks.check_postconditions){ + const Outcome checked = hooks.check_postconditions(id, state); + if (!checked.succeeded()){ + return outcome_failed("postconditions_failed", to_string(checked)); + } + } + if (hooks.verify_pass){ + const Outcome passed = hooks.verify_pass(id, state); + if (!passed.succeeded()){ + return outcome_failed("verify_no_pass", to_string(passed)); + } + } + return outcome_ok(); +} + +// The verification loop of a row with `verify` (run_segment()). +class VerifyRow{ +public: + VerifyRow(const Row& row, const SegmentPolicy& policy, SegmentHooks& hooks, SegmentReport& report, CheckpointRun& run, RunState& state) + : m_row(row) + , m_verify(*row.spec.verify) + , m_policy(policy) + , m_hooks(hooks) + , m_report(report) + , m_run(run) + , m_state(state) + {} + + CheckpointReport run(){ + const std::string& id = m_row.spec.id; + say(std::format( + "[Verify] {}: phase 1, {} tries from one save, {} must pass; phase 2, up to {} tries, the first pass saved", + id, m_verify.tries, m_verify.min_pass, m_verify.reset_budget + ), m_hooks); + size_t passes = 0; + for (size_t c = 1; c <= m_verify.tries; c++){ + const std::optional passed = try_once(/*phase=*/1, c, m_verify.tries); + if (!passed){ + return std::move(m_result); + } + passes += *passed ? 1 : 0; + } + if (passes < m_verify.min_pass){ + return stop("verify_below_min_pass", std::format("phase 1 passed {} of {}, under {}", passes, m_verify.tries, m_verify.min_pass)); + } + for (size_t c = 1; c <= m_verify.reset_budget; c++){ + const std::optional passed = try_once(/*phase=*/2, c, m_verify.reset_budget); + if (!passed){ + return std::move(m_result); + } + if (*passed){ + m_run.passed = true; + say(std::format("[Verify] {}: phase 2 try {} passed and saved", id, c), m_hooks); + return std::move(m_result); + } + } + return stop("verify_out_of_budget", std::format("no pass in {} phase 2 tries", m_verify.reset_budget)); + } + +private: + CheckpointReport stop(std::string failure, std::string detail){ + say(std::format("[Verify] {}: {}; stopping", m_row.spec.id, detail), m_hooks); + m_result = failed_report(outcome_failed(std::move(failure), std::move(detail))); + return std::move(m_result); + } + + // The checkpoint built fresh; phase 1 checks the pass in place of a + // save, phase 2 before the save. + Checkpoint build(size_t phase){ + Checkpoint checkpoint = m_row.spec.build(); + if (phase == 1){ + checkpoint.save = nullptr; + }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{ + const Outcome passed = verify_pass(id, hooks, state); + if (!passed.succeeded() || !save){ + return passed; + } + return save(state); + }; + return checkpoint; + } + + // 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). + 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){ + m_report.reloads++; + Outcome reloaded = reload(m_state, m_hooks); + if (!reloaded.succeeded()){ + m_result = failed_report(std::move(reloaded)); + return std::nullopt; + } + } + m_run.attempts++; + Checkpoint checkpoint = build(phase); + EventLogger log = [&hooks = m_hooks](const std::string& line){ say(line, hooks); }; + m_result = run_checkpoint(m_state, checkpoint, log); + if (m_result.completed){ + say(std::format("[Verify] {}: phase {} try {}/{} passed", id, phase, index, of), m_hooks); + return true; + } + 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){ + say(std::format("[Verify] {}: stopping", id), m_hooks); + return std::nullopt; + } + return false; + } + + const Row& m_row; + const StoryVerify& m_verify; + const SegmentPolicy& m_policy; + SegmentHooks& m_hooks; + SegmentReport& m_report; + CheckpointRun& m_run; + RunState& m_state; + CheckpointReport m_result; +}; + SegmentReport stop_segment(const std::string& id, Outcome failure, SegmentHooks& hooks, SegmentReport& report){ std::string where; if (!report.failed_checkpoint.empty()){ @@ -246,7 +376,9 @@ SegmentReport run_segment( report.checkpoints_run++; report.runs.push_back(CheckpointRun{.id = spec.id}); const Row row{.spec = spec, .first = c == selected.first, .last = c == selected.last}; - CheckpointReport result = run_row(segment, row, policy, hooks, report, report.runs.back(), state); + CheckpointReport result = spec.verify + ? VerifyRow(row, policy, hooks, report, report.runs.back(), state).run() + : run_row(segment, row, policy, hooks, report, report.runs.back(), state); if (!result.completed){ report.failed_checkpoint = spec.id; report.failed_event = result.failed_name; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h index 280504487f..ae0ddf1b58 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h @@ -17,12 +17,14 @@ #define PokemonAutomation_Pokemon_StorySegments_H #include +#include #include #include #include "Common/Cpp/MoveOnlyFunction.h" #include "Pokemon_StoryEvents.h" #include "Pokemon_StoryLog.h" #include "Types/Pokemon_StorySegmentTypes.h" +#include "Types/Pokemon_StoryVerify.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -31,11 +33,14 @@ namespace Pokemon{ // One row of a segment. `build` makes the checkpoint anew for each attempt. // `saves` has the segment save the game (SegmentHooks::save) after the // checkpoint's end check, when the checkpoint has no save of its own. +// `verify` runs the row as a verification loop (Pokemon_StoryVerify.h) +// instead of the policy's attempts. struct CheckpointSpec{ std::string id; std::string title; bool saves = false; MoveOnlyFunction build; + std::optional verify = std::nullopt; }; // Collection of ordered checkpoints that make up a story segment. @@ -62,10 +67,20 @@ struct SegmentHooks{ // before a save in AFTER_VERIFICATION mode: one that failed stops the // save and fails the run. The game logs its lines. 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. + MoveOnlyFunction verify_pass; }; // Runs the checkpoints in `range`, in order, saving as `policy.save_mode` -// allows (story_save_allowed()). Logs through `hooks.log`, +// allows (story_save_allowed()). A row with `verify` runs its loop: phase +// 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: // [Segment] 00: start, 3 checkpoints // [Checkpoint] 00.02: failed, resetting for attempt 2/3 diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.cpp new file mode 100644 index 0000000000..0019825c46 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.cpp @@ -0,0 +1,222 @@ +/* Story Verify Rows Tests + * + * From: https://github.com/PokemonAutomation/ + * + * run_segment() on a row with a verify block, against a fake game: one + * fight from a save, whose tries are scripted (won or lost, the potions + * spent). The game's pass predicate is a cap on the potions a try spends; + * the row's start check is the potions the save must hold. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StorySegments.h" +#include "Pokemon_StoryVerifyRows_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +constexpr int POTION_CAP = 1; +constexpr int POTIONS_NEEDED = 2; + +// One try's fight. +struct ScriptedTry{ + bool won = true; + int potions_spent = 0; +}; + +// A try won on no potion: a pass. +ScriptedTry win(){ + return ScriptedTry{}; +} +ScriptedTry lose(){ + return ScriptedTry{.won = false}; +} +// Won on two potions, over the cap. +ScriptedTry win_over_cap(){ + return ScriptedTry{.potions_spent = 2}; +} + +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; +} + +// The fake game: the save's potions, the potions now, the tries in order +// (the last repeats). +struct FakeFight{ + int saved_potions = 0; + int potions = 0; + std::vector tries; + int fights = 0; + int saves = 0; + int reloads = 0; + int spent = 0; + + CheckpointSpec spec(StoryVerify verify){ + CheckpointSpec spec; + spec.id = "20.01"; + spec.title = "Lorelei"; + spec.verify = verify; + spec.build = [this]{ + Checkpoint checkpoint; + checkpoint.id = "20.01"; + checkpoint.start.push_back(condition("the potions the fight needs", [this](RunState&){ + return potions >= POTIONS_NEEDED; + })); + Event fight; + fight.name = "fight"; + fight.act = [this](RunState&){ + const ScriptedTry& one = tries[std::min(fights, tries.size() - 1)]; + fights++; + potions -= one.potions_spent; + spent = one.potions_spent; + return one.won ? outcome_ok() : outcome_failed("blackout"); + }; + checkpoint.events.push_back(std::move(fight)); + checkpoint.save = [this](RunState&){ + saves++; + saved_potions = potions; + return outcome_ok(); + }; + return checkpoint; + }; + return spec; + } + + SegmentHooks hooks(std::vector& lines){ + SegmentHooks hooks; + hooks.reload = [this](RunState&){ + reloads++; + potions = saved_potions; + return outcome_ok(); + }; + hooks.verify_pass = [this](const std::string&, RunState&){ + 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); }; + return hooks; + } +}; + + +struct VerifyRowCase{ + struct Input{ + StoryVerify verify = {}; + int potions = POTIONS_NEEDED; + std::vector tries = {}; + }; + struct Expectation{ + bool completed = false; + // The segment's failure; empty when it completed. + std::string failure = {}; + int fights = 0; + int saves = 0; + int reloads = 0; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_StoryVerifyRow : public UnitTest{ +public: + explicit Test_StoryVerifyRow(VerifyRowCase test_case) + : UnitTest(std::format("Pokemon::StoryVerifyRows - {}", test_case.name)) + , 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}; + Segment segment; + segment.id = "20"; + segment.checkpoints.push_back(game.spec(m_case.input.verify)); + std::vector lines; + SegmentHooks hooks = game.hooks(lines); + RunState state; + const SegmentReport report = run_segment({}, SegmentPolicy{}, segment, hooks, state); + const VerifyRowCase::Expectation& want = m_case.expectation; + const std::string failure = report.completed ? "" : report.failure.failure; + if (report.completed != want.completed || failure != want.failure + || game.fights != want.fights || game.saves != want.saves || game.reloads != want.reloads + ){ + std::string log; + for (const std::string& line : lines){ + log += std::format("\n {}", line); + } + return std::format( + "{} \"{}\", fights {}, saves {}, reloads {}; expected {} \"{}\", {}, {}, {}:{}", + report.completed ? "completed" : "failed", failure, game.fights, game.saves, game.reloads, + want.completed ? "completed" : "failed", want.failure, want.fights, want.saves, want.reloads, log + ); + } + return true; + } + +private: + VerifyRowCase m_case; +}; + +const VerifyRowCase VERIFY_ROW_CASES[] = { + { + .name = "ten passes: saved on the first phase 2 try", + .input = {.tries = {win()}}, + .expectation = {.completed = true, .fights = 11, .saves = 1, .reloads = 10}, + }, + { + .name = "four passes in phase 1, under min_pass 5: stop, no save", + .input = {.tries = joined(repeated(4, win()), {lose()})}, + .expectation = {.failure = "verify_below_min_pass", .fights = 10, .saves = 0, .reloads = 9}, + }, + { + .name = "phase 2 passes on its third try: saved once", + .input = {.tries = joined(joined(repeated(5, win()), repeated(7, lose())), {win()})}, + .expectation = {.completed = true, .fights = 13, .saves = 1, .reloads = 12}, + }, + { + .name = "no pass in the reset budget of 5: stop, no save", + .input = {.tries = joined(repeated(5, win()), {lose()})}, + .expectation = {.failure = "verify_out_of_budget", .fights = 15, .saves = 0, .reloads = 14}, + }, + { + .name = "wins over the game's cap don't pass: never saved", + .input = {.tries = joined(repeated(5, win()), {win_over_cap()})}, + .expectation = {.failure = "verify_out_of_budget", .fights = 15, .saves = 0, .reloads = 14}, + }, + { + .name = "the save is short of the start check: stop before fighting", + .input = {.potions = POTIONS_NEEDED - 1, .tries = {win()}}, + .expectation = {.failure = "start_failed", .fights = 0, .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()}}, + .expectation = {.completed = true, .fights = 3, .saves = 1, .reloads = 2}, + }, +}; + +} // namespace + + +void add_tests_StoryVerifyRows(UnitTestDatabase& database){ + for (const VerifyRowCase& test_case : VERIFY_ROW_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.h new file mode 100644 index 0000000000..3d5574a07c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.h @@ -0,0 +1,23 @@ +/* Story Verify Rows Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryVerifyRows_Tests_H +#define PokemonAutomation_Pokemon_StoryVerifyRows_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the tests of run_segment()'s verify rows on a fake game. +void add_tests_StoryVerifyRows(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h index cc3bf66ce3..7565488071 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -19,6 +19,7 @@ #include "Pokemon_StoryCheckpointMetadata.h" #include "Pokemon_StoryPostconditions.h" #include "Pokemon_StoryStep.h" +#include "Pokemon_StoryVerify.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -49,6 +50,9 @@ struct StoryCheckpoint{ // them in the story so far, which a reload loses ("card_key_held" in a // save made after the Card Key). JSON: "start_flags". std::vector start_flags = {}; + // Run as a verification loop (Pokemon_StoryVerify.h); none for a + // checkpoint played once. JSON: "execution": {"verify": ...}. + std::optional verify = std::nullopt; }; // The gate state of `checkpoint` once its first `steps_done` steps are done: diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryVerify.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryVerify.h new file mode 100644 index 0000000000..f9b67f4cad --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryVerify.h @@ -0,0 +1,37 @@ +/* Story Verify + * + * From: https://github.com/PokemonAutomation/ + * + * A checkpoint run as a verification loop (a plan's "execution": + * {"verify": {"tries": 10, "min_pass": 5, "reset_budget": 5}}): phase 1 + * plays it `tries` times from its start save, saving none, and stops the + * run when fewer than `min_pass` passed; phase 2 plays it again, up to + * `reset_budget` times, until one passes, and saves that one. A try + * passes when it completes, the game's postcondition check holds and the + * game's pass predicate holds (SegmentHooks, Pokemon_StorySegments.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryVerify_H +#define PokemonAutomation_Pokemon_StoryVerify_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The verification loop's figures. +struct StoryVerify{ + size_t tries = 10; + size_t min_pass = 5; + size_t reset_budget = 5; + + bool operator==(const StoryVerify&) const = default; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 2b2ccb1e51..32c4e980fa 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -35,6 +35,7 @@ #include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryFailureClasses.h" #include "PokemonFRLG_AutoStoryLaunch.h" +#include "PokemonFRLG_AutoStoryLeagueRows.h" #include "PokemonFRLG_AutoStoryRngLoop.h" #include "PokemonFRLG_AutoStoryTable.h" #include "PokemonFRLG_AutoStory.h" @@ -556,6 +557,16 @@ 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). + 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 Pokemon::outcome_ok(); + }; Pokemon::RunState state; Pokemon::SegmentReport report; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 4eddab3524..a51225d506 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -1027,7 +1027,7 @@ Pokemon::Segment make_story_segment(const std::vector& checkpoi for (const StoryCheckpoint& data : checkpoints){ segment.checkpoints.push_back(Pokemon::CheckpointSpec{ data.id, data.title, false, - [&data, &executor]{ return build_checkpoint(data, executor); } + [&data, &executor]{ return build_checkpoint(data, executor); }, data.verify, }); } return segment; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.cpp new file mode 100644 index 0000000000..60dcb47750 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.cpp @@ -0,0 +1,76 @@ +/* AutoStory League Rows + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "PokemonFRLG_AutoStoryLeagueFightData.h" +#include "PokemonFRLG_AutoStoryLeagueRows.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// The League fight of `row`'s battle; none if it has none. +const LeagueFightData* row_fight(const StoryCheckpoint& row){ + for (const Pokemon::StoryStep& step : row.steps){ + if (step.kind != Pokemon::StoryStepKind::BATTLE || !step.args.contains("trainer")){ + continue; + } + const std::optional name = league_fight_name(Pokemon::story_arg(step.args, "trainer")); + if (name){ + return league_fight_data(league_plan_data(), *name); + } + } + return nullptr; +} + +// The supplies' counts by bag slug. +SlugCounts counts_of(const Supplies& supplies){ + SlugCounts counts(supplies.other_counts.begin(), supplies.other_counts.end()); + counts["potion"] = supplies.potions; + counts["super-potion"] = supplies.super_potions; + counts["antidote"] = supplies.antidotes; + counts["parlyz-heal"] = supplies.parlyz_heals; + counts["awakening"] = supplies.awakenings; + counts["full-heal"] = supplies.full_heals; + return counts; +} + +} // namespace + + +Pokemon::Outcome league_row_pass(const StoryCheckpoint& row, const Supplies& start, const Supplies& end){ + const LeagueFightData* fight = 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); + if (less > 0){ + used[item] = less; + text += std::format("{}{} {}", text.empty() ? "" : ", ", item, less); + } + } + if (league_try_passes(*fight, LeagueTry{.won = true, .used = used})){ + return Pokemon::outcome_ok(); + } + return Pokemon::outcome_failed("league_over_caps", std::format("{} spent {}", fight->name, text.empty() ? "nothing" : text)); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.h new file mode 100644 index 0000000000..3d34c17428 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueRows.h @@ -0,0 +1,35 @@ +/* AutoStory League Rows + * + * From: https://github.com/PokemonAutomation/ + * + * The League's fights as verify rows (Pokemon_StoryVerify.h): each fight + * 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()). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryLeagueRows_H +#define PokemonAutomation_PokemonFRLG_AutoStoryLeagueRows_H + +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "PokemonFRLG_AutoStoryCheckpoints.h" +#include "PokemonFRLG_AutoStorySupplies.h" + +namespace PokemonAutomation{ +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); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index 14e9c0e63c..d27992c529 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -215,6 +215,7 @@ Pokemon::StoryFileRow read_story_file(const JsonValue& value, s static_cast(checkpoint) = Pokemon::read_authored_checkpoint( without_metadata(value, source), "frlg", source, read_execution, story_action_specs() ); + checkpoint.verify = shared.verify; for (const std::string& key : note_keys){ bool found = key == "checkpoint"; for (const StoryStep& step : checkpoint.steps){ diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a8a736828c..08ce71f927 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1696,6 +1696,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StorySegments.h Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryVerifyRows_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -1738,6 +1740,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryVerify.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp @@ -2234,6 +2237,8 @@ file(GLOB LIBRARY_SOURCES 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_AutoStoryLeagueSteps.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLeagueSteps.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows13_Tests.h