diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index ebdcabe09f..9606924bbe 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -66,6 +66,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_MapData(ret); Pokemon::add_tests_StoryEvents(ret); Pokemon::add_tests_StorySegments(ret); + Pokemon::add_tests_StorySteps(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h index 00087fcd95..3c663a7ae8 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h @@ -21,6 +21,7 @@ void add_tests_LegWalker(UnitTestDatabase& database); void add_tests_MapData(UnitTestDatabase& database); void add_tests_StoryEvents(UnitTestDatabase& database); void add_tests_StorySegments(UnitTestDatabase& database); +void add_tests_StorySteps(UnitTestDatabase& database); // (name, JSON text) of each map in Pokemon/Navigation/TestMaps/, built into // the program by pa_embed_text_files() (cmake/EmbedTextFiles.cmake). diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySegments.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySegments.cpp index e80ff4915f..ad072e3411 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySegments.cpp @@ -83,21 +83,67 @@ Outcome reload(RunState& state, SegmentHooks& hooks){ return outcome_ok(); } +// The policy's in-place recovery, after each event's own: the game's +// recover hook, if any, then the event again. Counts into `used`. +void add_policy_recoveries(Checkpoint& checkpoint, const SegmentPolicy& policy, SegmentHooks& hooks, size_t& used){ + if (policy.recoveries_per_event == 0){ + return; + } + for (Event& event : checkpoint.events){ + Recovery recovery; + recovery.kind = RecoveryKind::REANCHOR; + recovery.attempts = policy.recoveries_per_event; + recovery.why = "the segment's policy: recover in place before reloading"; + recovery.prepare = [&hooks, &used, name = event.name](RunState& state){ + used++; + return hooks.recover ? hooks.recover(state, name) : outcome_ok(); + }; + event.recoveries.push_back(std::move(recovery)); + } +} + +std::string resets_text(size_t attempts){ + if (attempts == 1){ + return "one-shot"; + } + return std::format("{} reset{}", attempts - 1, attempts == 2 ? "" : "s"); +} + // One row to success, reloading and rebuilding after each failed attempt. -// Returns the last attempt's report, or the reload's failure. +// Returns the last attempt's report, or the reload's failure; `run` says +// how many attempts and recoveries it took. CheckpointReport run_row( RunState& state, const Segment& segment, CheckpointSpec& spec, - const SegmentPolicy& policy, SegmentHooks& hooks, SegmentReport& report + const SegmentPolicy& policy, SegmentHooks& hooks, SegmentReport& report, CheckpointRun& run ){ for (size_t attempt = 1; ; attempt++){ + run.attempts = attempt; Checkpoint checkpoint = spec.build(); if (spec.saves && !checkpoint.save){ checkpoint.save = [&hooks](RunState& state){ return hooks.save ? hooks.save(state) : outcome_failed("no_save_hook"); }; } + add_policy_recoveries(checkpoint, policy, hooks, run.recoveries); CheckpointReport result = run_checkpoint(state, checkpoint, hooks.log); - if (result.completed || attempt >= policy.attempts_per_checkpoint){ + if (result.completed){ + run.passed = true; + hooks.log(std::format( + "[Checkpoint] {}: passed on attempt {} ({}){}", + spec.id, attempt, resets_text(attempt), + run.recoveries == 0 ? "" : std::format(", {} in place", run.recoveries) + )); + return result; + } + if (policy.stop_at_first_failure){ + hooks.log(std::format( + "[Segment] {}: {} failed; stopping at the first failure, the game stays where it failed", + segment.id, spec.id + )); + report.stopped_at_first_failure = true; + return result; + } + if (attempt >= policy.attempts_per_checkpoint){ return result; } hooks.log(std::format( @@ -128,6 +174,19 @@ SegmentReport stop_segment(SegmentReport& report, SegmentHooks& hooks, const std } +bool CheckpointRun::one_shot() const{ + return passed && attempts == 1 && recoveries == 0; +} + +size_t SegmentReport::one_shot_passes() const{ + size_t count = 0; + for (const CheckpointRun& run : runs){ + count += run.one_shot() ? 1 : 0; + } + return count; +} + + SegmentReport run_segment( RunState& state, Segment& segment, const SegmentRange& range, const SegmentPolicy& policy, SegmentHooks& hooks @@ -141,7 +200,8 @@ SegmentReport run_segment( for (size_t c = selected.first; c <= selected.last; c++){ CheckpointSpec& spec = segment.checkpoints[c]; report.checkpoints_run++; - CheckpointReport result = run_row(state, segment, spec, policy, hooks, report); + report.runs.push_back(CheckpointRun{.id = spec.id}); + CheckpointReport result = run_row(state, segment, spec, policy, hooks, report, report.runs.back()); if (!result.completed){ report.failed_checkpoint = spec.id; report.failed_event = result.failed_name; @@ -149,6 +209,7 @@ SegmentReport run_segment( } } report.completed = true; + hooks.log(std::format("[Segment] {}: {} of {} checkpoints one-shot", segment.id, report.one_shot_passes(), report.checkpoints_run)); hooks.log(std::format("[Segment] {}: done, {} checkpoints", segment.id, report.checkpoints_run)); return report; } diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySegments.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySegments.h index 69e181ef57..5e6bf66e55 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySegments.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySegments.h @@ -46,15 +46,28 @@ struct Segment{ // What the game lends the runner: how to save, how to reload the last save // (the run state is emptied first; the reload's Outcome says where the // player stands), and where to log. +// `recover`, if set, is the game's way of recovering in place from a failed +// event (re-anchor on a landmark, close a stray dialogue) before the event +// is tried again; see SegmentPolicy::recoveries_per_event. struct SegmentHooks{ Act save; Act reload; EventLogger log; + MoveOnlyFunction recover; }; +// How hard a segment tries, for every game: the one place retries are set. struct SegmentPolicy{ - // Runs of one checkpoint, reloading between them, before the segment stops. + // Runs of one checkpoint, reloading its save between them, before the + // segment stops. size_t attempts_per_checkpoint = 3; + // Lab: stop at the first failed attempt without reloading, leaving the + // game where it failed for a look. + bool stop_at_first_failure = false; + // Times each event may recover in place (SegmentHooks::recover, then + // the event again) once its own recoveries are used up, before its + // checkpoint fails and is reloaded. 0 keeps a failure a reload. + size_t recoveries_per_event = 0; }; // The checkpoints to run, by id, both inclusive. An unset end is the @@ -65,8 +78,22 @@ struct SegmentRange{ }; +// How one checkpoint went: one attempt with no in-place recovery is a +// one-shot pass. +struct CheckpointRun{ + std::string id; + bool passed = false; + size_t attempts = 0; + // In-place recoveries (SegmentPolicy::recoveries_per_event) used, in all attempts. + size_t recoveries = 0; + + bool one_shot() const; +}; + struct SegmentReport{ bool completed = false; + // The run stopped at its first failure (SegmentPolicy::stop_at_first_failure). + bool stopped_at_first_failure = false; // Both empty when nothing failed; the event is empty when a start // check, an end check, a save or a reload failed. std::string failed_checkpoint; @@ -75,13 +102,21 @@ struct SegmentReport{ size_t checkpoints_run = 0; // Reloads after failed attempts. size_t reloads = 0; + // Each checkpoint run, in order, the failed one last. + std::vector runs; + + size_t one_shot_passes() const; }; // Runs the checkpoints in `range`, in order. Logs through `hooks.log`, // around the checkpoint lines: // [Segment] 00: start, 3 checkpoints // [Segment] 00: 00.02 failed, reloading for attempt 2/3 +// [Checkpoint] 00.02: passed on attempt 2 (1 reset) +// [Checkpoint] 00.03: passed on attempt 1 (one-shot) +// [Segment] 00: 2 of 3 checkpoints one-shot // [Segment] 00: done, 3 checkpoints +// [Segment] 00: 00.02 failed; stopping at the first failure, the game stays where it failed // [Segment] 00: failed at 00.02 talk_mom: expect_failed: dialogue opened SegmentReport run_segment( RunState& state, Segment& segment, const SegmentRange& range, diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySteps.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySteps.cpp new file mode 100644 index 0000000000..c9825391b0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySteps.cpp @@ -0,0 +1,278 @@ +/* Story Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Pokemon_StorySteps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const char* story_step_kind_name(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::NEW_GAME: + return "NEW_GAME"; + case StoryStepKind::OPTIONS: + return "OPTIONS"; + case StoryStepKind::ROUTE: + return "ROUTE"; + case StoryStepKind::LEGS: + return "LEGS"; + case StoryStepKind::STEP: + return "STEP"; + case StoryStepKind::TALK: + return "TALK"; + case StoryStepKind::ANSWER: + return "ANSWER"; + case StoryStepKind::MASH: + return "MASH"; + case StoryStepKind::BATTLE: + return "BATTLE"; + case StoryStepKind::TRAIN: + return "TRAIN"; + case StoryStepKind::HEAL: + return "HEAL"; + case StoryStepKind::SHOP: + return "SHOP"; + case StoryStepKind::SAVE: + return "SAVE"; + case StoryStepKind::READY: + return "READY"; + case StoryStepKind::GAME: + return "GAME"; + } + return "?"; +} + + +const char* story_checks_name(StoryChecks checks){ + switch (checks){ + case StoryChecks::THOROUGH: + return "thorough"; + case StoryChecks::FAST: + return "fast"; + } + return "?"; +} + + +Outcome unsupported_step(const StoryStep& step){ + return outcome_failed("unsupported_step", std::format("{} {}", story_step_kind_name(step.kind), step.name)); +} + +Outcome StoryStepExecutor::run(RunState& state, const StoryStep& step){ + return dispatch_story_step(*this, state, step); +} + +void StoryStepExecutor::begin_attempt(const StoryCheckpoint&){} + +bool StoryStepExecutor::holds(const std::string& condition, RunState& state){ + return state.flags.contains(condition); +} + +Outcome StoryStepExecutor::new_game(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::options(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::route(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::legs(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::step(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::talk(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::answer(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::mash(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::battle(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::train(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::heal(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::shop(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::save(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::ready(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::game(RunState&, const StoryStep& step){ + return unsupported_step(step); +} + +Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step){ + switch (step.kind){ + case StoryStepKind::NEW_GAME: + return executor.new_game(state, step); + case StoryStepKind::OPTIONS: + return executor.options(state, step); + case StoryStepKind::ROUTE: + return executor.route(state, step); + case StoryStepKind::LEGS: + return executor.legs(state, step); + case StoryStepKind::STEP: + return executor.step(state, step); + case StoryStepKind::TALK: + return executor.talk(state, step); + case StoryStepKind::ANSWER: + return executor.answer(state, step); + case StoryStepKind::MASH: + return executor.mash(state, step); + case StoryStepKind::BATTLE: + return executor.battle(state, step); + case StoryStepKind::TRAIN: + return executor.train(state, step); + case StoryStepKind::HEAL: + return executor.heal(state, step); + case StoryStepKind::SHOP: + return executor.shop(state, step); + case StoryStepKind::SAVE: + return executor.save(state, step); + case StoryStepKind::READY: + return executor.ready(state, step); + case StoryStepKind::GAME: + return executor.game(state, step); + } + return unsupported_step(step); +} + + +Event story_event(const StoryStep& step, StoryStepExecutor& executor){ + Event event; + event.name = step.name; + event.why = step.why; + for (const std::string& name : step.skip_if){ + event.skip_if.push_back(condition(name, [&executor, name](RunState& state){ + return executor.holds(name, state); + })); + } + event.act = [&executor, &step](RunState& state){ + return executor.run(state, step); + }; + event.pose_learned = step.pose_after; + return event; +} + +namespace{ + +// The first event of a checkpoint that starts from a save: where the save +// leaves the player, for a run that reloaded it. +Event from_save_event(const Pose& start){ + Event event; + event.name = "from_save"; + event.why = "where the checkpoint's save leaves the player"; + event.act = [](RunState&){ return outcome_ok(); }; + event.pose_learned = start; + return event; +} + +} + +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor){ + executor.begin_attempt(data); + Checkpoint checkpoint; + checkpoint.id = data.id; + if (data.start){ + checkpoint.events.push_back(from_save_event(*data.start)); + } + for (const StoryStep& step : data.steps){ + checkpoint.events.push_back(story_event(step, executor)); + } + return checkpoint; +} + + +namespace{ + +// What a step of its kind must have, or "" if it has it. +std::string missing_field(const StoryStep& step){ + switch (step.kind){ + case StoryStepKind::ROUTE: + case StoryStepKind::READY: + return step.target ? "" : "no target"; + case StoryStepKind::LEGS: + if (step.legs.empty()){ + return "no legs"; + } + for (const StoryLeg& leg : step.legs){ + if (leg.tiles <= 0){ + return "a leg of no tiles"; + } + } + return ""; + case StoryStepKind::TRAIN: + return step.battles > 0 ? "" : "no battles"; + case StoryStepKind::SHOP: + return step.items.empty() ? "no items" : ""; + case StoryStepKind::GAME: + return step.variant.empty() ? "no variant" : ""; + default: + return ""; + } +} + +} + +std::vector lint_story_checkpoint(const StoryCheckpoint& data){ + std::vector problems; + if (data.id.empty()){ + problems.emplace_back("a checkpoint has no id"); + } + std::set names; + for (size_t c = 0; c < data.steps.size(); c++){ + const StoryStep& step = data.steps[c]; + const std::string where = std::format("{} step {}", data.id, c + 1); + if (step.name.empty()){ + problems.emplace_back(where + ": no name"); + }else if (!names.insert(step.name).second){ + problems.emplace_back(std::format("{}: a second step named {}", where, step.name)); + } + const std::string missing = missing_field(step); + if (!missing.empty()){ + problems.emplace_back(std::format("{} {}: {} {}", where, step.name, story_step_kind_name(step.kind), missing)); + } + } + return problems; +} + + +Pose tile_pose(std::string map, std::vector tiles, std::optional facing){ + Pose pose; + pose.map = std::move(map); + pose.certainty = tiles.empty() ? PoseCertainty::UNKNOWN + : tiles.size() == 1 ? PoseCertainty::TILE : PoseCertainty::SET; + pose.where = std::make_shared(std::move(tiles), facing); + return pose; +} + +std::optional facing_of(const Pose& pose){ + const TilePose* tile_pose = dynamic_cast(pose.where.get()); + return tile_pose ? tile_pose->facing : std::nullopt; +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySteps.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySteps.h new file mode 100644 index 0000000000..84972ead25 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySteps.h @@ -0,0 +1,227 @@ +/* Story Steps + * + * From: https://github.com/PokemonAutomation/ + * + * One vocabulary of story steps for the tile games (FRLG, BDSP): a route, + * a fixed walk, a step onto a trigger, a talk, a YES/NO, a scene, a + * battle, the nurse, a shop, a save, and so on. A checkpoint is a list of + * such steps, plain data, so a game's story is a table its unit tests can + * plan without a console. + * + * build_story_checkpoint() turns a table row into engine events + * (Pokemon_StoryEvents.h). Each event's action asks the game's + * StoryStepExecutor to do its step: one virtual per kind, so a game + * implements the kinds it uses, and a step the game has no way of doing + * fails by name instead of doing something else. + * + * Steps never match dialogue or menu text: they look for screen state (a + * dialogue box, an arrow, a fade, a battle menu, colours, positions). The + * few reads that need text (item names in a shop or the Bag) take the + * game's language from the executor, and with no reader for it fall back + * to checks that need none (a row's position, digits, a changed screen), + * so a run never fails because its language is not supported. + * + * Poses are the game's own (Pose, with a TilePose for these games): a + * checkpoint's start, a scene's end and a route's target are poses, and + * an executor that knows where a step left the player says so in its + * Outcome, which the engine writes into the run. + * + */ + +#ifndef PokemonAutomation_Pokemon_StorySteps_H +#define PokemonAutomation_Pokemon_StorySteps_H + +#include +#include +#include +#include +#include "CommonFramework/Language.h" +#include "Pokemon_Grid.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_TilePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +enum class StoryStepKind{ + NEW_GAME, // title screen (no save) to the first room + OPTIONS, // the game's options as the story needs them + ROUTE, // plan and walk to `target` + LEGS, // walk `legs` as given + STEP, // one step `direction`: onto a trigger, into a door + TALK, // A at what the player faces + ANSWER, // text to a YES/NO, then `yes` + MASH, // text until the overworld is back: a scene + BATTLE, // text into a battle, fight it, text to the overworld + TRAIN, // fight `battles` wild battles where the player stands + HEAL, // the nurse, from in front of her or of the Center's door + SHOP, // `items` from a shop + SAVE, // save the game where the player stands + READY, // before a big battle: items, and the nurse at `target` if they can't + GAME, // a step only this game has, named by `variant` +}; +const char* story_step_kind_name(StoryStepKind kind); + +// How much a step reads the screen to confirm what it did. Each game +// decides what its steps check at each level. +enum class StoryChecks{ + // Confirm on screen: purchases, the Bag, status after battles, position. + THOROUGH, + // In a rush: trust counts and timings. + FAST, +}; +const char* story_checks_name(StoryChecks checks); + + +// A straight leg of a fixed walk. +struct StoryLeg{ + Direction direction = Direction::NORTH; + int tiles = 0; +}; + +// An item and how many to get. +struct StoryItem{ + std::string item; + size_t quantity = 0; +}; + +struct StoryStep{ + StoryStepKind kind = StoryStepKind::TALK; + std::string name; + std::string why; + + // ROUTE: where to go; with several tiles, any of them. READY: the nurse. + std::optional target; + // STEP + Direction direction = Direction::NORTH; + // LEGS + std::vector legs; + // ROUTE, LEGS: fight wild battles on the way instead of running. + bool fight_wild = false; + // ANSWER + bool yes = true; + // BATTLE: losing goes on (a rival's first battle). + bool may_lose = false; + // TRAIN + size_t battles = 0; + // SHOP + std::vector items; + // How this game does the kind, when it has more than one way: a + // route's plan costs, a door lined up by sight, the Mart lady instead + // of the clerk. Empty is the game's usual way. GAME: the step's name + // in the game's executor. + std::string variant; + + // Skipped when all of these hold (and there is at least one): names + // the game's executor answers (StoryStepExecutor::holds()), run flags + // unless the game reads them off the screen. + std::vector skip_if; + // Where the step leaves the player, when its action does not say: the + // end of a scene that moves the player. + std::optional pose_after; +}; + +struct StoryCheckpoint{ + std::string id; + std::string title; + // Where its starting save leaves the player; none for a new game. + std::optional start; + std::vector steps; +}; + + +// How a game does each kind of step. Every kind fails as unsupported +// unless the game overrides it. +class StoryStepExecutor{ +public: + virtual ~StoryStepExecutor() = default; + + // A checkpoint is being built for a new attempt: build_story_checkpoint() + // calls this first, so a game can start the attempt afresh (trainers + // who can see us again, the row's own settings). Does nothing by default. + virtual void begin_attempt(const StoryCheckpoint& data); + + // The checks level the program's options chose (StoryRunOptions); + // THOROUGH unless set. Steps read it to decide what to confirm. + StoryChecks checks() const{ + return m_checks; + } + void set_checks(StoryChecks checks){ + m_checks = checks; + } + // The game's language (StoryRunOptions), for the reads that need text; + // English unless set. A game with no reader for it uses language-free + // checks instead. + Language language() const{ + return m_language; + } + void set_language(Language language){ + m_language = language; + } + + // Runs `step`: dispatch_story_step() by default. A game overrides it + // to wrap every step, e.g. to turn a failed console step into a failed + // Outcome. + virtual Outcome run(RunState& state, const StoryStep& step); + + // Whether the condition named in a step's skip_if holds: by default, + // whether the run has the flag (set by an earlier step's action). + virtual bool holds(const std::string& condition, RunState& state); + + virtual Outcome new_game(RunState& state, const StoryStep& step); + virtual Outcome options(RunState& state, const StoryStep& step); + virtual Outcome route(RunState& state, const StoryStep& step); + virtual Outcome legs(RunState& state, const StoryStep& step); + virtual Outcome step(RunState& state, const StoryStep& step); + virtual Outcome talk(RunState& state, const StoryStep& step); + virtual Outcome answer(RunState& state, const StoryStep& step); + virtual Outcome mash(RunState& state, const StoryStep& step); + virtual Outcome battle(RunState& state, const StoryStep& step); + virtual Outcome train(RunState& state, const StoryStep& step); + virtual Outcome heal(RunState& state, const StoryStep& step); + virtual Outcome shop(RunState& state, const StoryStep& step); + virtual Outcome save(RunState& state, const StoryStep& step); + virtual Outcome ready(RunState& state, const StoryStep& step); + virtual Outcome game(RunState& state, const StoryStep& step); + +private: + StoryChecks m_checks = StoryChecks::THOROUGH; + Language m_language = Language::English; +}; + +// Calls the executor's method for the step's kind. +Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step); + +// "unsupported_step: TRAIN train_in_grass": what an executor without the kind returns. +Outcome unsupported_step(const StoryStep& step); + + +// The step as an event that runs it with `executor`. Both must outlive +// the event. +Event story_event(const StoryStep& step, StoryStepExecutor& executor); + +// The checkpoint `data` as events: "from_save" first when it has a start +// (the start pose, for a run that reloaded its save), then one event per +// step. `data` and `executor` must outlive the checkpoint. Saving is the +// game's: it sets the checkpoint's save, or adds a SAVE step. +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor); + +// Problems an author should fix before running: an empty id, unnamed or +// repeated steps, a route or READY without a target, empty legs, a GAME +// step without a variant, TRAIN without battles, SHOP without items. +std::vector lint_story_checkpoint(const StoryCheckpoint& data); + + +// A pose on one of `tiles` of `map`, facing `facing` if set: TILE for one +// tile, SET for several, UNKNOWN for none. +Pose tile_pose(std::string map, std::vector tiles, std::optional facing = std::nullopt); + +// The facing of a tile pose; nothing for another pose or none. +std::optional facing_of(const Pose& pose); + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySteps_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySteps_Tests.cpp new file mode 100644 index 0000000000..4e44b6e3b3 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StorySteps_Tests.cpp @@ -0,0 +1,570 @@ +/* Story Steps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Story tables built into checkpoints and run against a fake executor + * that writes down each step it is asked to do: the order of the events, + * skipped steps, the pose each step leaves, and how a failure is named. + * Nothing here belongs to one game. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Options/Pokemon_StoryRunOptions.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StorySegments.h" +#include "Pokemon_StorySteps.h" +#include "Pokemon_TilePose.h" +#include "Pokemon_Navigation_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// A world of two maps. Routes arrive on their target; a step moves a tile +// from the run's pose. Each step it does is written down as "KIND name", +// with the pose it started from when that is known. +class FakeExecutor : public StoryStepExecutor{ +public: + std::vector trace; + std::set conditions; + // Steps by name that always fail, and how. + std::set failing; + // Steps by name that fail this many more times, then pass. + std::map failures_left; + // The pose each step started from, by name. + std::vector> poses_seen; + // The checkpoints begun, one per attempt. + std::vector attempts; + + virtual void begin_attempt(const StoryCheckpoint& data) override{ + attempts.push_back(data.id); + } + + virtual Outcome run(RunState& state, const StoryStep& step) override{ + poses_seen.emplace_back(step.name, to_string(state.pose)); + trace.push_back(std::string(story_step_kind_name(step.kind)) + " " + step.name); + if (failing.contains(step.name)){ + return outcome_failed("blocked", step.name + " was blocked"); + } + size_t& left = failures_left[step.name]; + if (left > 0){ + left--; + return outcome_failed("blocked", step.name + " was blocked"); + } + return StoryStepExecutor::run(state, step); + } + virtual bool holds(const std::string& condition, RunState& state) override{ + return conditions.contains(condition) || StoryStepExecutor::holds(condition, state); + } + virtual Outcome route(RunState&, const StoryStep& step) override{ + return outcome_ok(*step.target); + } + virtual Outcome step(RunState& state, const StoryStep& step) override{ + const std::vector tiles = tiles_of(state.pose); + if (tiles.size() != 1){ + return outcome_failed("no_pose", to_string(state.pose)); + } + return outcome_ok(tile_pose(state.pose.map, {tiles[0].next(step.direction)}, step.direction)); + } + virtual Outcome talk(RunState&, const StoryStep&) override{ + return outcome_ok(); + } + virtual Outcome mash(RunState&, const StoryStep&) override{ + return outcome_ok(); + } + virtual Outcome battle(RunState&, const StoryStep& step) override{ + // The first battle is lost; a step that may lose goes on. + return step.may_lose ? outcome_ok() : outcome_failed("blackout"); + } + virtual Outcome shop(RunState&, const StoryStep& step) override{ + for (const StoryItem& item : step.items){ + trace.push_back(" bought " + std::to_string(item.quantity) + " " + item.item); + } + return outcome_ok(); + } + // A game step sets a run flag named for its variant. + virtual Outcome game(RunState& state, const StoryStep& step) override{ + trace.push_back(" game " + step.variant); + state.flags.insert(step.variant); + return outcome_ok(); + } +}; + +StoryStep make(StoryStepKind kind, std::string name){ + StoryStep step; + step.kind = kind; + step.name = std::move(name); + return step; +} + +StoryStep route_to(std::string name, Pose target){ + StoryStep step = make(StoryStepKind::ROUTE, std::move(name)); + step.target = std::move(target); + return step; +} + +StoryStep step_into(std::string name, Direction direction){ + StoryStep step = make(StoryStepKind::STEP, std::move(name)); + step.direction = direction; + return step; +} + +StoryStep scene(std::string name, std::optional pose_after){ + StoryStep step = make(StoryStepKind::MASH, std::move(name)); + step.pose_after = std::move(pose_after); + return step; +} + +// A lab checkpoint: to the table, a trigger, the scene into the lab, a +// talk, a shop, a game step. +StoryCheckpoint lab_checkpoint(){ + StoryStep shop = make(StoryStepKind::SHOP, "potions"); + shop.items = {{.item = "potion", .quantity = 5}, {.item = "antidote", .quantity = 3}}; + StoryStep game = make(StoryStepKind::GAME, "dance"); + game.variant = "dance"; + return StoryCheckpoint{ + .id = "00.03", + .title = "to the lab", + .start = tile_pose("Town", {{6, 8}}, Direction::SOUTH), + .steps = { + route_to("below_trigger", tile_pose("Town", {{12, 2}}, Direction::NORTH)), + step_into("trigger", Direction::NORTH), + scene("to_the_lab", tile_pose("Lab", {{6, 4}}, Direction::NORTH)), + make(StoryStepKind::TALK, "talk_oak"), + shop, + game, + }, + }; +} + +struct Run{ + CheckpointReport report; + RunState state; + std::vector lines; +}; + +Run run(const StoryCheckpoint& data, StoryStepExecutor& executor){ + Run ret; + Checkpoint checkpoint = build_story_checkpoint(data, executor); + EventLogger log = [&ret](const std::string& line){ ret.lines.push_back(line); }; + ret.report = run_checkpoint(ret.state, checkpoint, log); + return ret; +} + +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += "\n " + line; + } + return text; +} + + +UnitTestResult test_events_in_table_order(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + const Run result = run(data, executor); + const std::vector expected{ + "ROUTE below_trigger", + "STEP trigger", + "MASH to_the_lab", + "TALK talk_oak", + "SHOP potions", + " bought 5 potion", + " bought 3 antidote", + "GAME dance", + " game dance", + }; + if (!result.report.completed || executor.trace != expected){ + return "Expected the steps in table order:" + joined(expected) + "\nbut ran:" + joined(executor.trace); + } + // "from_save" is the engine's own event: the executor is not asked. + const std::string first = event_log_line("00.03", 1, "from_save", "start"); + if (result.lines.empty() || std::find(result.lines.begin(), result.lines.end(), first) == result.lines.end()){ + return "Expected the from_save event first:" + joined(result.lines); + } + return true; +} + +UnitTestResult test_skip_if(){ + StoryCheckpoint data = lab_checkpoint(); + data.steps[0].skip_if = {"has_parcel"}; + data.steps[3].skip_if = {"has_parcel", "talked"}; + FakeExecutor executor; + executor.conditions = {"has_parcel"}; + // The route is skipped; the talk needs both conditions, so it runs. + const Run result = run(data, executor); + if (!result.report.completed || result.report.events_skipped != 1){ + return "Expected one step skipped, got " + std::to_string(result.report.events_skipped) + ":" + joined(result.lines); + } + if (std::find(executor.trace.begin(), executor.trace.end(), "ROUTE below_trigger") != executor.trace.end()){ + return "Expected the route skipped:" + joined(executor.trace); + } + if (std::find(executor.trace.begin(), executor.trace.end(), "TALK talk_oak") == executor.trace.end()){ + return "Expected the talk run, one of its conditions not holding:" + joined(executor.trace); + } + + // By default a condition is a run flag: the game step "dance" sets + // one, and a talk after it that needs it is skipped. + StoryStep after = make(StoryStepKind::TALK, "talk_after_dance"); + after.skip_if = {"dance"}; + data = lab_checkpoint(); + data.steps.push_back(after); + FakeExecutor plain; + const Run flagged = run(data, plain); + if (!flagged.report.completed || flagged.report.events_skipped != 1 || plain.trace.back() != " game dance"){ + return "Expected the talk after the dance skipped on its flag:" + joined(plain.trace); + } + return true; +} + +UnitTestResult test_pose_propagation(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + const Run result = run(data, executor); + // Each step starts where the one before left the player: the save, the + // route's target, a tile north of it, the scene's end, and the scene's + // end again after a talk that says nothing of where it leaves us. + const std::vector> expected{ + {"below_trigger", "Town (6, 8) facing south (tile)"}, + {"trigger", "Town (12, 2) facing north (tile)"}, + {"to_the_lab", "Town (12, 1) facing north (tile)"}, + {"talk_oak", "Lab (6, 4) facing north (tile)"}, + {"potions", "Lab (6, 4) facing north (tile)"}, + {"dance", "Lab (6, 4) facing north (tile)"}, + }; + if (!result.report.completed || executor.poses_seen != expected){ + std::string text; + for (const auto& item : executor.poses_seen){ + text += "\n " + item.first + ": " + item.second; + } + return "Unexpected poses at the steps' starts:" + text; + } + if (to_string(result.state.pose) != "Lab (6, 4) facing north (tile)"){ + return "Expected the run to end at the scene's end, got " + to_string(result.state.pose); + } + return true; +} + +UnitTestResult test_failure_names_the_step(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + executor.failing = {"trigger"}; + const Run result = run(data, executor); + // Event 3: from_save is event 1. + if (result.report.completed || result.report.failed_event != 3 || result.report.failed_name != "trigger" + || result.report.failure.failure != "blocked" + ){ + return "Expected a failure at event 3 trigger, blocked:" + joined(result.lines); + } + if (executor.trace.size() != 2){ + return "Expected nothing run after the failed step:" + joined(executor.trace); + } + return true; +} + +UnitTestResult test_unsupported_and_lost_battles(){ + // The fake has no TRAIN, and loses battles a step may not lose. + StoryStep train = make(StoryStepKind::TRAIN, "train"); + train.battles = 3; + FakeExecutor executor; + Run result = run(StoryCheckpoint{.id = "01", .title = "", .start = std::nullopt, .steps = {train}}, executor); + if (result.report.completed || result.report.failure.failure != "unsupported_step" || result.report.failure.detail != "TRAIN train"){ + return "Expected TRAIN unsupported:" + joined(result.lines); + } + StoryStep rival = make(StoryStepKind::BATTLE, "rival"); + rival.may_lose = true; + StoryStep brock = make(StoryStepKind::BATTLE, "brock"); + result = run(StoryCheckpoint{.id = "02", .title = "", .start = std::nullopt, .steps = {rival, brock}}, executor); + if (result.report.completed || result.report.failed_name != "brock" || result.report.failure.failure != "blackout"){ + return "Expected the rival's battle passed and Brock's lost:" + joined(result.lines); + } + return true; +} + +UnitTestResult test_segment_of_tables(){ + // Two rows built into a segment, run with saves and a reload from the + // game's hooks: the second row's first attempt fails, its retry starts + // over from its start pose. + const std::vector tables{ + lab_checkpoint(), + StoryCheckpoint{ + .id = "00.04", + .title = "the parcel", + .start = tile_pose("Lab", {{6, 4}}, Direction::NORTH), + .steps = {make(StoryStepKind::TALK, "give_parcel")}, + }, + }; + FakeExecutor executor; + Segment segment; + segment.id = "00"; + for (const StoryCheckpoint& data : tables){ + segment.checkpoints.push_back(CheckpointSpec{ + .id = data.id, .title = data.title, .saves = true, + .build = [&data, &executor]{ return build_story_checkpoint(data, executor); }, + }); + } + std::vector lines; + SegmentHooks hooks; + hooks.save = [&executor](RunState&){ + executor.trace.push_back("save"); + return outcome_ok(); + }; + // Whatever blocked the talk has gone by the reload. + hooks.reload = [&executor](RunState&){ + executor.trace.push_back("reload"); + executor.failing.clear(); + return outcome_ok(); + }; + hooks.log = [&lines](const std::string& line){ lines.push_back(line); }; + executor.failing = {"give_parcel"}; + RunState state; + const SegmentReport report = run_segment(state, segment, SegmentRange{}, SegmentPolicy{}, hooks); + const std::vector tail{"save", "TALK give_parcel", "reload", "TALK give_parcel", "save"}; + const bool tail_matches = executor.trace.size() >= tail.size() + && std::equal(tail.begin(), tail.end(), executor.trace.end() - (std::ptrdiff_t)tail.size()); + if (!report.completed || report.reloads != 1 || !tail_matches){ + return "Expected 00.04 reloaded once and passed:" + joined(executor.trace) + joined(lines); + } + // Each attempt is begun anew: 00.03 once, 00.04 twice. + if (executor.attempts != std::vector{"00.03", "00.04", "00.04"}){ + return "Expected the executor told of each attempt:" + joined(executor.attempts); + } + // The report and the log tell a one-shot pass from a retried one. + const bool runs_ok = report.runs.size() == 2 + && report.runs[0].one_shot() && report.runs[0].attempts == 1 + && !report.runs[1].one_shot() && report.runs[1].attempts == 2 && report.runs[1].passed + && report.one_shot_passes() == 1; + const auto has = [&lines](const std::string& line){ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + }; + if (!runs_ok + || !has("[Checkpoint] 00.03: passed on attempt 1 (one-shot)") + || !has("[Checkpoint] 00.04: passed on attempt 2 (1 reset)") + || !has("[Segment] 00: 1 of 2 checkpoints one-shot") + ){ + return "Expected 00.03 one-shot and 00.04 passed on attempt 2:" + joined(lines); + } + return true; +} + + +// The two tables of test_segment_of_tables() as a segment run by `executor`, +// with hooks that write saves, reloads and recoveries into its trace. +struct PolicyLab{ + std::vector tables{ + lab_checkpoint(), + StoryCheckpoint{ + .id = "00.04", + .title = "the parcel", + .start = tile_pose("Lab", {{6, 4}}, Direction::NORTH), + .steps = {make(StoryStepKind::TALK, "give_parcel")}, + }, + }; + FakeExecutor executor; + std::vector lines; + + SegmentReport run(const SegmentPolicy& policy){ + Segment segment; + segment.id = "00"; + for (const StoryCheckpoint& data : tables){ + segment.checkpoints.push_back(CheckpointSpec{ + .id = data.id, .title = data.title, .saves = true, + .build = [&data, this]{ return build_story_checkpoint(data, executor); }, + }); + } + SegmentHooks hooks; + hooks.save = [this](RunState&){ + executor.trace.push_back("save"); + return outcome_ok(); + }; + hooks.reload = [this](RunState&){ + executor.trace.push_back("reload"); + return outcome_ok(); + }; + hooks.recover = [this](RunState&, const std::string& event){ + executor.trace.push_back("recover " + event); + return outcome_ok(); + }; + hooks.log = [this](const std::string& line){ lines.push_back(line); }; + RunState state; + return run_segment(state, segment, SegmentRange{}, policy, hooks); + } + bool has(const std::string& line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + size_t count(const std::string& item) const{ + return (size_t)std::count(executor.trace.begin(), executor.trace.end(), item); + } +}; + +UnitTestResult test_policy_attempts_then_fail(){ + // Three attempts by default, then the segment stops on the last one's failure. + PolicyLab lab; + lab.executor.failing = {"give_parcel"}; + const SegmentReport report = lab.run(SegmentPolicy{}); + if (report.completed || report.reloads != 2 || lab.count("TALK give_parcel") != 3 + || report.runs.size() != 2 || report.runs[1].passed || report.runs[1].attempts != 3 + || report.failed_checkpoint != "00.04" || report.failure.failure != "blocked" + ){ + return "Expected 00.04 tried 3 times, then failed:" + joined(lab.executor.trace) + joined(lab.lines); + } + return true; +} + +UnitTestResult test_policy_stop_at_first_failure(){ + PolicyLab lab; + lab.executor.failing = {"give_parcel"}; + const SegmentReport report = lab.run(SegmentPolicy{.stop_at_first_failure = true}); + if (report.completed || !report.stopped_at_first_failure || report.reloads != 0 || lab.count("reload") != 0 + || lab.count("TALK give_parcel") != 1 + || !lab.has("[Segment] 00: 00.04 failed; stopping at the first failure, the game stays where it failed") + ){ + return "Expected a stop at the first failure, with no reload:" + joined(lab.executor.trace) + joined(lab.lines); + } + return true; +} + +UnitTestResult test_policy_recovers_in_place(){ + // The talk fails twice; two recoveries in place get it through + // without a reload, but not one-shot. + PolicyLab lab; + lab.executor.failures_left = {{"give_parcel", 2}}; + const SegmentReport report = lab.run(SegmentPolicy{.recoveries_per_event = 2}); + if (!report.completed || report.reloads != 0 || lab.count("recover give_parcel") != 2 + || report.runs.size() != 2 || report.runs[1].recoveries != 2 || report.runs[1].one_shot() + || !lab.has("[Checkpoint] 00.04: passed on attempt 1 (one-shot), 2 in place") + ){ + return "Expected 00.04 recovered in place twice:" + joined(lab.executor.trace) + joined(lab.lines); + } + // Past the budget, the checkpoint is reloaded as before. + PolicyLab reloaded; + reloaded.executor.failures_left = {{"give_parcel", 2}}; + const SegmentReport second = reloaded.run(SegmentPolicy{.recoveries_per_event = 1}); + if (!second.completed || second.reloads != 1 || second.runs[1].attempts != 2){ + return "Expected a reload once the in-place budget was used:" + joined(reloaded.executor.trace) + joined(reloaded.lines); + } + return true; +} + +// The checks level: THOROUGH by default, and what the program sets is +// what a step reads. +UnitTestResult test_checks_level(){ + class CheckingExecutor : public FakeExecutor{ + public: + std::vector seen; + virtual Outcome talk(RunState&, const StoryStep& step) override{ + seen.push_back(step.name + " " + story_checks_name(checks())); + return outcome_ok(); + } + }; + StoryCheckpoint data = lab_checkpoint(); + CheckingExecutor executor; + run(data, executor); + executor.set_checks(StoryChecks::FAST); + executor.set_language(Language::Korean); + run(data, executor); + if (executor.language() != Language::Korean){ + return "Expected the language set on the executor."; + } + if (executor.seen != std::vector{"talk_oak thorough", "talk_oak fast"}){ + return "Expected the talk to read thorough, then fast:" + joined(executor.seen); + } + return true; +} + +// The program's option group: 3 attempts, no stop, Thorough, by default; +// Fast when chosen. +UnitTestResult test_run_options(){ + StoryRunOptions options; + const SegmentPolicy policy = options.policy(); + if (policy.attempts_per_checkpoint != 3 || policy.stop_at_first_failure || options.checks() != StoryChecks::THOROUGH){ + return "Expected 3 attempts, no stop at the first failure, and Thorough checks by default."; + } + options.CHECKS.set(StoryChecks::FAST); + if (options.checks() != StoryChecks::FAST){ + return "Expected Fast checks once chosen."; + } + // Every game language can be chosen, read or not. + if (options.language() != Language::English){ + return "Expected English by default."; + } + options.LANGUAGE.set(Language::Japanese); + if (options.language() != Language::Japanese || !options.check_validity().empty()){ + return "Expected Japanese to be chosen and valid, reader or not."; + } + return true; +} + +UnitTestResult test_lint(){ + StoryStep no_target = make(StoryStepKind::ROUTE, "walk"); + StoryStep again = make(StoryStepKind::TALK, "walk"); + StoryStep bad_legs = make(StoryStepKind::LEGS, "legs"); + bad_legs.legs = {{.direction = Direction::NORTH, .tiles = 0}}; + StoryStep no_variant = make(StoryStepKind::GAME, ""); + const StoryCheckpoint data{.id = "", .title = "", .start = std::nullopt, .steps = {no_target, again, bad_legs, no_variant}}; + const std::vector expected{ + "a checkpoint has no id", + " step 1 walk: ROUTE no target", + " step 2: a second step named walk", + " step 3 legs: LEGS a leg of no tiles", + " step 4: no name", + " step 4 : GAME no variant", + }; + const std::vector problems = lint_story_checkpoint(data); + if (problems != expected){ + return "Unexpected lint:" + joined(problems); + } + if (!lint_story_checkpoint(lab_checkpoint()).empty()){ + return "Expected the lab checkpoint to lint clean:" + joined(lint_story_checkpoint(lab_checkpoint())); + } + return true; +} + + +class Test_StorySteps : public UnitTest{ +public: + Test_StorySteps(std::string name, std::function body) + : UnitTest("Pokemon::StorySteps - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_body(); + } + +private: + std::function m_body; +}; + +} + + +void add_tests_StorySteps(UnitTestDatabase& database){ + database.add("steps run in table order", test_events_in_table_order); + database.add("skip_if asks the executor", test_skip_if); + database.add("each step starts where the last left the player", test_pose_propagation); + database.add("a failure names its step", test_failure_names_the_step); + database.add("unsupported kinds and lost battles", test_unsupported_and_lost_battles); + database.add("tables as a segment, with a reload", test_segment_of_tables); + database.add("lint", test_lint); + database.add("the checks level reaches the steps", test_checks_level); + database.add("the run options' defaults", test_run_options); + database.add("policy: attempts per checkpoint, then fail", test_policy_attempts_then_fail); + database.add("policy: stop at the first failure", test_policy_stop_at_first_failure); + database.add("policy: recover in place before reloading", test_policy_recovers_in_place); +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp new file mode 100644 index 0000000000..c68a783002 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp @@ -0,0 +1,87 @@ +/* Story Run Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryRunOptions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const EnumDropdownDatabase& StoryChecks_Database(){ + static const EnumDropdownDatabase database({ + {StoryChecks::THOROUGH, "thorough", "Thorough: confirm purchases, the Bag, status and position on screen"}, + {StoryChecks::FAST, "fast", "Fast: trust counts and timings"}, + }); + return database; +} + +const EnumDropdownDatabase& StoryLanguage_Database(){ + static const EnumDropdownDatabase database({ + {Language::English, "en", "English"}, + {Language::Japanese, "ja", "Japanese"}, + {Language::Spanish, "es", "Spanish"}, + {Language::French, "fr", "French"}, + {Language::German, "de", "German"}, + {Language::Italian, "it", "Italian"}, + {Language::Korean, "ko", "Korean"}, + {Language::ChineseSimplified, "zh-Hans", "Chinese (Simplified)"}, + {Language::ChineseTraditional, "zh-Hant", "Chinese (Traditional)"}, + }); + return database; +} + + +StoryRunOptions::StoryRunOptions() + : GroupOption("Checkpoint Retries", LockMode::LOCK_WHILE_RUNNING) + , ATTEMPTS_PER_CHECKPOINT( + "Attempts per checkpoint:
A failed checkpoint reloads its save and runs again, up to this many times in all.", + LockMode::LOCK_WHILE_RUNNING, + 3, 1, 20 + ) + , STOP_AT_FIRST_FAILURE( + "Stop at the first failure:
Stop without reloading, leaving the game where it failed for a look.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , CHECKS( + "Checks:
Thorough reads the screen to confirm what each step did; Fast trusts counts and timings, for a run in a rush.", + StoryChecks_Database(), + LockMode::LOCK_WHILE_RUNNING, + StoryChecks::THOROUGH + ) + , LANGUAGE( + "Game language:
For the few reads that need text (item names in a shop or the Bag). " + "Story steps never match dialogue text; with no reader for this language they check positions, digits and the screen instead.", + StoryLanguage_Database(), + LockMode::LOCK_WHILE_RUNNING, + Language::English + ) +{ + PA_ADD_OPTION(ATTEMPTS_PER_CHECKPOINT); + PA_ADD_OPTION(STOP_AT_FIRST_FAILURE); + PA_ADD_OPTION(CHECKS); + PA_ADD_OPTION(LANGUAGE); +} + +SegmentPolicy StoryRunOptions::policy() const{ + SegmentPolicy policy; + policy.attempts_per_checkpoint = ATTEMPTS_PER_CHECKPOINT; + policy.stop_at_first_failure = STOP_AT_FIRST_FAILURE; + return policy; +} + +StoryChecks StoryRunOptions::checks() const{ + return CHECKS; +} + +Language StoryRunOptions::language() const{ + return LANGUAGE; +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h new file mode 100644 index 0000000000..4f9a3a506b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h @@ -0,0 +1,52 @@ +/* Story Run Options + * + * From: https://github.com/PokemonAutomation/ + * + * The options every AutoStory program shows for how hard to try and how + * much to check: the same group in each game, read into the shared + * SegmentPolicy (Pokemon/Navigation/Pokemon_StorySegments.h) and the + * executor's checks level (Pokemon_StorySteps.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRunOptions_H +#define PokemonAutomation_Pokemon_StoryRunOptions_H + +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Pokemon/Navigation/Pokemon_StorySegments.h" +#include "Pokemon/Navigation/Pokemon_StorySteps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class StoryRunOptions : public GroupOption{ +public: + StoryRunOptions(); + + // The policy these options set. In-place recoveries are the game's to + // set, not the user's. + SegmentPolicy policy() const; + // The checks level for the game's story step executor (set_checks()). + StoryChecks checks() const; + // The game's language, for the executor (set_language()). + Language language() const; + +public: + SimpleIntegerOption ATTEMPTS_PER_CHECKPOINT; + BooleanCheckBoxOption STOP_AT_FIRST_FAILURE; + EnumDropdownOption CHECKS; + // Any language the game has, whether or not a reader supports it: + // steps without one use language-free checks, so none is refused. + EnumDropdownOption LANGUAGE; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index ddec042740..74dd158bb5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -299,6 +299,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_OverworldRecovery(database); add_tests_PlayerFacingReader(database); add_tests_AutoStory(database); + add_tests_AutoStorySimulation(database); add_tests_AutoStoryItems(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 3946f96427..544dcb6e39 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -51,22 +51,6 @@ AutoStory::AutoStory() LockMode::LOCK_WHILE_RUNNING, true ) - , ATTEMPTS_PER_CHECKPOINT( - "Attempts per checkpoint:
A failed checkpoint reloads its save and runs again, up to this many times in all.", - LockMode::LOCK_WHILE_RUNNING, - 1, 5, 2, 2 - ) - , CHECKS( - "Checks:
Thorough reads the screen before acting and confirms after: the item on a Mart row " - "before buying it, the bag's Items pocket after shopping (its counts are the ones kept), and an item's name " - "in the bag before using it. Fast trusts the counts it keeps and the timings.", - { - {StoryChecks::THOROUGH, "thorough", "Thorough"}, - {StoryChecks::FAST, "fast", "Fast"}, - }, - LockMode::LOCK_WHILE_RUNNING, - StoryChecks::THOROUGH - ) , NOTIFICATIONS({ &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_FATAL, @@ -75,8 +59,7 @@ AutoStory::AutoStory() PA_ADD_OPTION(START_CHECKPOINT); PA_ADD_OPTION(END_CHECKPOINT); PA_ADD_OPTION(NEW_GAME_FROM_TITLE); - PA_ADD_OPTION(ATTEMPTS_PER_CHECKPOINT); - PA_ADD_OPTION(CHECKS); + PA_ADD_OPTION(RETRIES); PA_ADD_OPTION(NOTIFICATIONS); } @@ -92,14 +75,19 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex throw UserSetupError(env.console, "Checkpoint 00.01 starts a new game: start on the title screen with no save."); } - StoryEnv story{env.console, context, checkpoints[first].supplies, checkpoints[first].supplies, false, CHECKS}; + StoryEnv story{env.console, context, checkpoints[first].supplies, checkpoints[first].supplies, false, RETRIES.checks()}; if (!(first == 0 && NEW_GAME_FROM_TITLE)){ env.console.log("Loading the save for " + checkpoints[first].id + "."); soft_reset(env.console, context); story.has_save = true; } - Pokemon::Segment segment = make_story_segment(checkpoints, story); + StoryExecutor executor(story); + executor.set_checks(RETRIES.checks()); + // For #120's item-name reads (read_item_list_name()), which still read + // English; no other step reads text. + executor.set_language(RETRIES.language()); + Pokemon::Segment segment = make_story_segment(checkpoints, executor); Pokemon::SegmentHooks hooks; hooks.reload = [&story](Pokemon::RunState&){ if (!story.has_save){ @@ -116,8 +104,7 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex hooks.log = [&env](const std::string& line){ env.console.log(line); }; - Pokemon::SegmentPolicy policy; - policy.attempts_per_checkpoint = ATTEMPTS_PER_CHECKPOINT; + const Pokemon::SegmentPolicy policy = RETRIES.policy(); Pokemon::RunState state; const Pokemon::SegmentReport report = run_segment( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h index eed050ea88..b5652767ba 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h @@ -5,7 +5,7 @@ * Plays FireRed from a new game to the Boulder Badge, as the story * checkpoints of PokemonFRLG_AutoStoryTable.h run by the shared story * engine. Each checkpoint saves at its end; one that fails is retried from - * that save. + * that save, as the shared retry options say. * */ @@ -17,6 +17,7 @@ #include "Common/Cpp/Options/SimpleIntegerOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_StoryRunOptions.h" #include "PokemonFRLG_AutoStoryActions.h" namespace PokemonAutomation{ @@ -43,8 +44,7 @@ class AutoStory : public SingleSwitchProgramInstance{ SimpleIntegerOption START_CHECKPOINT; SimpleIntegerOption END_CHECKPOINT; BooleanCheckBoxOption NEW_GAME_FROM_TITLE; - SimpleIntegerOption ATTEMPTS_PER_CHECKPOINT; - EnumDropdownOption CHECKS; + Pokemon::StoryRunOptions RETRIES; EventNotificationsOption NOTIFICATIONS; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h index ec2f5fa80a..8e9b555e37 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h @@ -21,21 +21,20 @@ #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon/Navigation/Pokemon_StorySteps.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ -// How much the story checks the screen before and after it acts. -// THOROUGH: reads a Mart row's item before buying it, the bag's Items +// How much the story checks the screen before and after it acts: the +// shared level (Pokemon_StorySteps.h, set by StoryRunOptions). For FRLG, +// THOROUGH reads a Mart row's item before buying it, the bag's Items // pocket after shopping (the counts the story then keeps), and an item's // name in the bag before using it. FAST trusts the counts it keeps and the // timings. -enum class StoryChecks{ - THOROUGH, - FAST, -}; +using StoryChecks = Pokemon::StoryChecks; // The START menu as the story grows it. Before the starter: BAG, the // player, SAVE, OPTION, EXIT; the starter adds POKEMON on top, the Pokedex diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index bcdb5e82b7..4d419193ee 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -21,6 +21,7 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ using namespace std::chrono_literals; +using Pokemon::facing_of; using Pokemon::Outcome; using Pokemon::RunState; @@ -44,11 +45,6 @@ Outcome guarded(Body&& body){ } } -std::optional facing_of(const Pokemon::Pose& pose){ - const Pokemon::TilePose* tile_pose = dynamic_cast(pose.where.get()); - return tile_pose ? tile_pose->facing : std::nullopt; -} - const MapData* find_story_map(const std::string& name){ for (const MapData& map : story_maps()){ if (map.name == name){ @@ -86,7 +82,11 @@ Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step){ if (!facing){ return Pokemon::outcome_failed("unknown_facing", to_string(start)); } - const RouteGoal goal{{step.target.map, step.target.tile}, step.target.facing}; + const std::optional target = step.target ? story_pose(*step.target) : std::nullopt; + if (!target){ + return Pokemon::outcome_failed("bad_target", step.target ? Pokemon::to_string(*step.target) : "none"); + } + const RouteGoal goal{{target->map, target->tile}, target->facing}; const std::optional> route = plan_overworld_route( story_maps(), start, goal, default_route_costs(), facing ); @@ -99,7 +99,7 @@ Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step){ const RoutePlanning planning{&story_maps(), default_route_costs()}; walk_overworld_route(env.console, env.context, *route, facing, interrupts, &planning); const std::optional end_facing = route->empty() ? facing : std::optional(route->back().facing_after); - return Pokemon::outcome_ok(to_pose(StoryPose{step.target.map, step.target.tile, end_facing})); + return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, end_facing})); } Outcome walk_legs(StoryEnv& env, RunState& state, const StoryStep& step){ @@ -169,14 +169,41 @@ Outcome get_ready(StoryEnv& env, RunState& state, const StoryStep& step){ return walked; } -Outcome shop(StoryEnv& env){ - // Viridian Mart before the Boulder Badge (pokefirered ViridianCity_Mart_Items): - // POKE BALL, POTION (300), ANTIDOTE (100), PARLYZ HEAL (200). 2000 of the - // 3000 a new game starts with, plus the rival's prize. - buy_items(env.console, env.context, {{1, 5, "potion"}, {2, 3, "antidote"}, {3, 1, "parlyz-heal"}}, env.checks); - env.supplies.potions += 5; - env.supplies.antidotes += 3; - env.supplies.parlyz_heals += 1; +// Viridian Mart before the Boulder Badge (pokefirered ViridianCity_Mart_Items): +// POKE BALL, POTION (300), ANTIDOTE (100), PARLYZ HEAL (200). Each item +// the story buys: its row, and where the bag's count is kept. +struct MartItem{ + const char* item; + int row; + int Supplies::* count; + // The name the item list reader reads (read_item_list_name()). + const char* slug; +}; +constexpr MartItem VIRIDIAN_MART_ITEMS[] = { + {.item = "potion", .row = 1, .count = &Supplies::potions, .slug = "potion"}, + {.item = "antidote", .row = 2, .count = &Supplies::antidotes, .slug = "antidote"}, + {.item = "parlyz_heal", .row = 3, .count = &Supplies::parlyz_heals, .slug = "parlyz-heal"}, +}; + +const MartItem* viridian_mart_item(const std::string& name){ + for (const MartItem& item : VIRIDIAN_MART_ITEMS){ + if (name == item.item){ + return &item; + } + } + return nullptr; +} + +Outcome shop(StoryEnv& env, const StoryStep& step){ + const std::optional> orders = viridian_mart_orders(step.items); + if (!orders){ + return Pokemon::outcome_failed("unknown_item", step.name); + } + // 2000 of the 3000 a new game starts with, plus the rival's prize. + buy_items(env.console, env.context, *orders, env.checks); + for (const Pokemon::StoryItem& item : step.items){ + env.supplies.*viridian_mart_item(item.item)->count += (int)item.quantity; + } if (env.checks == StoryChecks::FAST){ return Pokemon::outcome_ok(); } @@ -191,83 +218,36 @@ Outcome shop(StoryEnv& env){ return Pokemon::outcome_ok(); } -Outcome run_step(StoryEnv& env, RunState& state, const StoryStep& step, StartMenu menu){ - switch (step.kind){ - case StoryStepKind::NEW_GAME: - play_new_game_intro(env.console, env.context); - return Pokemon::outcome_ok(); - case StoryStepKind::SET_OPTIONS: - set_options(env.console, env.context, menu); - return Pokemon::outcome_ok(); - case StoryStepKind::ROUTE: - return walk_route(env, state, step); - case StoryStepKind::LEGS: - return walk_legs(env, state, step); - case StoryStepKind::STEP: - return take_step(env, state, step); - case StoryStepKind::TALK: - pbf_press_button(env.context, BUTTON_A, 160ms, 800ms); - return Pokemon::outcome_ok(); - case StoryStepKind::ANSWER: - answer_yes_no(env.console, env.context, step.yes, BUTTON_B, YES_NO_TIMEOUT); - return Pokemon::outcome_ok(); - case StoryStepKind::MASH: - mash_until_overworld(env.console, env.context, SCENE_TIMEOUT); - return Pokemon::outcome_ok(); - case StoryStepKind::BATTLE: - return battle(env, step); - case StoryStepKind::HEAL: - heal_at_center(env.console, env.context); - env.supplies.hurt = false; - env.supplies.hp_red = false; - env.supplies.status = StatusCondition::NONE; - return Pokemon::outcome_ok(); - case StoryStepKind::READY: - return get_ready(env, state, step); - case StoryStepKind::SHOP: - return shop(env); - } - return Pokemon::outcome_failed("unknown_step"); -} - -Pokemon::Event make_event(const StoryStep& step, StoryEnv& env, StartMenu menu){ - Pokemon::Event event; - event.name = step.name; - event.why = step.why; - event.act = [&env, &step, menu](RunState& state){ - return guarded([&]{ return run_step(env, state, step, menu); }); - }; - if (step.pose_after){ - event.pose_learned = to_pose(*step.pose_after); - } - return event; } -// The first event of a checkpoint that starts from a save: where the save -// leaves the player, for a run that reloaded it. -Pokemon::Event from_save_event(const StoryPose& start){ - Pokemon::Event event; - event.name = "from_save"; - event.why = "where the checkpoint's save leaves the player"; - event.act = [](RunState&){ return Pokemon::outcome_ok(); }; - event.pose_learned = to_pose(start); - return event; -} +std::optional> viridian_mart_orders(const std::vector& items){ + std::vector orders; + for (const Pokemon::StoryItem& wanted : items){ + const MartItem* found = viridian_mart_item(wanted.item); + if (found == nullptr){ + return std::nullopt; + } + orders.push_back(MartOrder{found->row, (int)wanted.quantity, found->slug}); + } + return orders; } - const std::vector& story_maps(){ static const std::vector maps = overworld_maps(map_flag_set(overworld_maps(), "after_hall_of_fame")); return maps; } Pokemon::Pose to_pose(const StoryPose& pose){ - Pokemon::Pose ret; - ret.map = pose.map; - ret.certainty = Pokemon::PoseCertainty::TILE; - ret.where = std::make_shared(std::vector{pose.tile}, pose.facing); - return ret; + return Pokemon::tile_pose(pose.map, {pose.tile}, pose.facing); +} + +std::optional story_pose(const Pokemon::Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + if (tiles.size() != 1){ + return std::nullopt; + } + return StoryPose{pose.map, tiles[0], facing_of(pose)}; } std::optional> fixed_route( @@ -315,15 +295,76 @@ std::optional wall_beside(const MapData& map, const TilePos& tile){ return std::nullopt; } -Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryEnv& env){ - Pokemon::Checkpoint checkpoint; - checkpoint.id = data.id; - if (data.start){ - checkpoint.events.push_back(from_save_event(*data.start)); - } - for (const StoryStep& step : data.steps){ - checkpoint.events.push_back(make_event(step, env, data.menu)); - } +StoryExecutor::StoryExecutor(StoryEnv& env) + : m_env(env) +{} + +Outcome StoryExecutor::run(RunState& state, const StoryStep& step){ + return guarded([&]{ return Pokemon::StoryStepExecutor::run(state, step); }); +} + +Outcome StoryExecutor::new_game(RunState&, const StoryStep&){ + play_new_game_intro(m_env.console, m_env.context); + return Pokemon::outcome_ok(); +} + +Outcome StoryExecutor::options(RunState&, const StoryStep&){ + set_options(m_env.console, m_env.context, m_menu); + return Pokemon::outcome_ok(); +} + +Outcome StoryExecutor::route(RunState& state, const StoryStep& step){ + return walk_route(m_env, state, step); +} + +Outcome StoryExecutor::legs(RunState& state, const StoryStep& step){ + return walk_legs(m_env, state, step); +} + +Outcome StoryExecutor::step(RunState& state, const StoryStep& step){ + return take_step(m_env, state, step); +} + +Outcome StoryExecutor::talk(RunState&, const StoryStep&){ + pbf_press_button(m_env.context, BUTTON_A, 160ms, 800ms); + return Pokemon::outcome_ok(); +} + +Outcome StoryExecutor::answer(RunState&, const StoryStep& step){ + answer_yes_no(m_env.console, m_env.context, step.yes, BUTTON_B, YES_NO_TIMEOUT); + return Pokemon::outcome_ok(); +} + +Outcome StoryExecutor::mash(RunState&, const StoryStep&){ + mash_until_overworld(m_env.console, m_env.context, SCENE_TIMEOUT); + return Pokemon::outcome_ok(); +} + +Outcome StoryExecutor::battle(RunState&, const StoryStep& step){ + return PokemonFRLG::battle(m_env, step); +} + +Outcome StoryExecutor::heal(RunState&, const StoryStep&){ + heal_at_center(m_env.console, m_env.context); + m_env.supplies.hurt = false; + m_env.supplies.hp_red = false; + m_env.supplies.status = StatusCondition::NONE; + return Pokemon::outcome_ok(); +} + +Outcome StoryExecutor::shop(RunState&, const StoryStep& step){ + return PokemonFRLG::shop(m_env, step); +} + +Outcome StoryExecutor::ready(RunState& state, const StoryStep& step){ + return get_ready(m_env, state, step); +} + + +Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryExecutor& executor){ + executor.set_menu(data.menu); + Pokemon::Checkpoint checkpoint = Pokemon::build_story_checkpoint(data, executor); + StoryEnv& env = executor.env(); const StartMenu menu = data.menu; checkpoint.save = [&env, menu](RunState&){ return guarded([&]{ @@ -336,13 +377,13 @@ Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryEnv& env) return checkpoint; } -Pokemon::Segment make_story_segment(const std::vector& checkpoints, StoryEnv& env){ +Pokemon::Segment make_story_segment(const std::vector& checkpoints, StoryExecutor& executor){ Pokemon::Segment segment; segment.id = "00"; for (const StoryCheckpoint& data : checkpoints){ segment.checkpoints.push_back(Pokemon::CheckpointSpec{ data.id, data.title, false, - [&data, &env]{ return build_checkpoint(data, env); } + [&data, &executor]{ return build_checkpoint(data, executor); } }); } return segment; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index 8a4245561d..ae20a676f6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -4,12 +4,13 @@ * * The FRLG story as data for the shared story engine * (Pokemon/Navigation/Pokemon_StoryEvents.h, Pokemon_StorySegments.h). - * A checkpoint is a list of StorySteps, each one kind of FRLG event (a + * A checkpoint is a list of the shared StorySteps + * (Pokemon/Navigation/Pokemon_StorySteps.h), each one kind of event (a * route, a talk, text read to its end, a YES/NO, a battle, the nurse, the - * Mart); make_story_segment() turns the table into engine checkpoints whose - * events run them on the console. Routes plan from the pose the run - * carries and return where they leave the player; scenes that move the - * player say where in the table. + * Mart); StoryExecutor does each kind on the console, and + * make_story_segment() turns the table into engine checkpoints. Routes + * plan from the pose the run carries and return where they leave the + * player; scenes that move the player say where in the table. * * The table itself is in PokemonFRLG_AutoStoryTable.h; it is plain data, * so its routes are planned in unit tests without a console. @@ -26,6 +27,7 @@ #include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "Pokemon/Navigation/Pokemon_StoryEvents.h" #include "Pokemon/Navigation/Pokemon_StorySegments.h" +#include "Pokemon/Navigation/Pokemon_StorySteps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" #include "PokemonFRLG_AutoStoryActions.h" @@ -36,65 +38,25 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -// Where the player stands and faces. An unknown facing (after a scene that -// turns the player) is set before the next route by turning to a wall. +using Pokemon::StoryLeg; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; + +// Where the player stands and faces: the one-tile poses of FRLG's table +// and routes. An unknown facing (after a scene that turns the player) is +// set before the next route by turning to a wall. struct StoryPose{ std::string map; TilePos tile; std::optional facing; }; -enum class StoryStepKind{ - NEW_GAME, // title screen (no save) to the bedroom - SET_OPTIONS, // text speed FAST, battle style SET - ROUTE, // plan and walk to `target` - LEGS, // walk `legs` as given, on one map - STEP, // one step `direction`: onto a trigger, into a door - TALK, // A at what the player faces - ANSWER, // text with B to a YES/NO, then `yes` - MASH, // text with B until the overworld is back - BATTLE, // text with B into a battle, fight it, text to the overworld - HEAL, // facing the nurse - SHOP, // facing the Viridian Mart clerk: Potions and Antidotes - READY, // before a big battle: items for status and HP, the nurse at `target` if they can't -}; - -// A straight leg of a fixed walk. -struct StoryLeg{ - Direction direction = Direction::NORTH; - int tiles = 0; -}; - -struct StoryStep{ - StoryStepKind kind = StoryStepKind::TALK; - std::string name; - std::string why; - // ROUTE: the goal, and the way to face there if set. READY: the nurse. - StoryPose target; - // STEP - Direction direction = Direction::NORTH; - // LEGS - std::vector legs; - // ROUTE, LEGS: fight wild battles for EXP instead of running. - bool fight_wild = false; - // ANSWER - bool yes = true; - // BATTLE: the starter may faint without a blackout (the lab's rival). - bool may_lose = false; - // Where a scene leaves the player. - std::optional pose_after; -}; - -struct StoryCheckpoint{ - std::string id; - std::string title; - // Where its starting save leaves the player; none for the new game. - std::optional start; +// A shared checkpoint with what FRLG adds to it. +struct StoryCheckpoint : public Pokemon::StoryCheckpoint{ // The healing items at its start, for a run that loads its save. Supplies supplies; // The START menu at its end, when it saves. StartMenu menu = StartMenu::FULL; - std::vector steps; }; @@ -103,6 +65,8 @@ struct StoryCheckpoint{ const std::vector& story_maps(); Pokemon::Pose to_pose(const StoryPose& pose); +// `pose` as a StoryPose: nothing unless it is on one tile. +std::optional story_pose(const Pokemon::Pose& pose); // `legs` from `start` as route steps for the walker, each checked against // the map: nothing if a step is blocked or leaves the map. A leg ends "to @@ -116,6 +80,11 @@ std::optional> fixed_route( // into a sign would read it. std::optional wall_beside(const MapData& map, const TilePos& tile); +// `items` as orders at the Viridian Mart before the Boulder Badge: the +// rows of POKE BALL, POTION, ANTIDOTE, PARLYZ HEAL. Nothing if it does +// not sell one of them. +std::optional> viridian_mart_orders(const std::vector& items); + // What the story's events act on. `supplies` are what the bag holds now, // `saved_supplies` what the last save holds. @@ -129,11 +98,46 @@ struct StoryEnv{ StoryChecks checks = StoryChecks::THOROUGH; }; +// Does FRLG's kinds of story step on the console. A console step that +// fails is a failed Outcome, which the segment answers by reloading. +class StoryExecutor : public Pokemon::StoryStepExecutor{ +public: + explicit StoryExecutor(StoryEnv& env); + + StoryEnv& env(){ + return m_env; + } + // The START menu SET_OPTIONS leaves: the checkpoint's being built. + void set_menu(StartMenu menu){ + m_menu = menu; + } + + virtual Pokemon::Outcome run(Pokemon::RunState& state, const StoryStep& step) override; + + virtual Pokemon::Outcome new_game(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome options(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome route(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome legs(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome step(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome talk(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome answer(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome mash(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome battle(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome heal(Pokemon::RunState& state, const StoryStep& step) override; + // The Viridian Mart, before the Boulder Badge: Potions, Antidotes and Parlyz Heals. + virtual Pokemon::Outcome shop(Pokemon::RunState& state, const StoryStep& step) override; + virtual Pokemon::Outcome ready(Pokemon::RunState& state, const StoryStep& step) override; + +private: + StoryEnv& m_env; + StartMenu m_menu = StartMenu::FULL; +}; + // The checkpoint `data` as events, saving at its end. -Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryEnv& env); +Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryExecutor& executor); // `checkpoints` (kept alive by the caller) as a segment for run_segment(). -Pokemon::Segment make_story_segment(const std::vector& checkpoints, StoryEnv& env); +Pokemon::Segment make_story_segment(const std::vector& checkpoints, StoryExecutor& executor); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp new file mode 100644 index 0000000000..0534dcee3c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -0,0 +1,360 @@ +/* AutoStory Simulation Tests + * + * From: https://github.com/PokemonAutomation/ + * + * A run of the whole story table, new game to the Boulder Badge, without + * the console: story_checkpoints() built into engine checkpoints by the + * shared builder, saving at each end as the program does, run by the + * shared runner with the program's retry policy, against a fake game. + * The fake plans each ROUTE on the story maps from where the run's pose + * says we stand (turning to a wall when the facing is unknown, as the + * program does), walks each LEGS on them, steps onto triggers, and passes + * every other step unless told to fail it. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Navigation/Pokemon_StorySegments.h" +#include "Pokemon/Navigation/Pokemon_StorySteps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +using Pokemon::Outcome; +using Pokemon::RunState; + +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += "\n " + line; + } + return text; +} + +const MapData* map_named(const std::string& name){ + for (const MapData& map : story_maps()){ + if (map.name == name){ + return ↦ + } + } + return nullptr; +} + +// Where the run stands, with a facing: a wall beside it when unknown. +struct Standing{ + MapPosition position; + Direction facing = Direction::NORTH; + std::string error; +}; +Standing standing(const Pokemon::Pose& pose){ + const std::optional at = story_pose(pose); + if (!at){ + return {{}, Direction::NORTH, "no one-tile pose: " + Pokemon::to_string(pose)}; + } + std::optional facing = at->facing; + if (!facing){ + const MapData* map = map_named(at->map); + facing = map ? wall_beside(*map, at->tile) : std::nullopt; + } + if (!facing){ + return {{}, Direction::NORTH, "facing unknown and no wall beside " + to_string(MapPosition{at->map, at->tile})}; + } + return {{at->map, at->tile}, *facing, ""}; +} + +class FakeGame : public Pokemon::StoryStepExecutor{ +public: + struct Failure{ + std::string failure; + size_t times = 0; + }; + + std::vector trace; + std::map failures; + // What the Mart sold, by its list's names. + std::map bag; + + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + trace.push_back("begin " + data.id); + } + virtual Outcome run(RunState& state, const StoryStep& step) override{ + const std::string key = m_row + "/" + step.name; + trace.push_back(key); + auto failure = failures.find(key); + if (failure != failures.end() && failure->second.times > 0){ + failure->second.times--; + return Pokemon::outcome_failed(failure->second.failure, key); + } + return Pokemon::StoryStepExecutor::run(state, step); + } + virtual Outcome route(RunState& state, const StoryStep& step) override{ + return walk_to(state.pose, step); + } + virtual Outcome legs(RunState& state, const StoryStep& step) override{ + const Standing at = standing(state.pose); + if (!at.error.empty()){ + return Pokemon::outcome_failed("no_pose", at.error); + } + const std::optional> route = fixed_route(story_maps(), at.position, step.legs); + if (!route || route->empty()){ + return Pokemon::outcome_failed("bad_legs", to_string(at.position)); + } + return Pokemon::outcome_ok(to_pose(StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after})); + } + virtual Outcome step(RunState& state, const StoryStep& step) override{ + const std::optional at = story_pose(state.pose); + if (!at){ + return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); + } + return Pokemon::outcome_ok(to_pose(StoryPose{at->map, at->tile.next(step.direction), step.direction})); + } + // The nurse's way must plan too, but the run goes on from where it stands. + virtual Outcome ready(RunState& state, const StoryStep& step) override{ + const Outcome to_nurse = walk_to(state.pose, step); + return to_nurse.succeeded() ? Pokemon::outcome_ok() : to_nurse; + } + virtual Outcome new_game(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } + virtual Outcome options(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } + virtual Outcome talk(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } + virtual Outcome answer(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } + virtual Outcome mash(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } + virtual Outcome battle(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } + virtual Outcome heal(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } + // The Viridian Mart's list as the game shows it. After a purchase the + // cursor stays on the row bought (console B, 2026-11-01), so each + // order moves it from there, as buy_items() does since ad5d40885. + virtual Outcome shop(RunState&, const StoryStep& step) override{ + static const std::vector LIST{"poke_ball", "potion", "antidote", "parlyz_heal", "cancel"}; + const std::optional> orders = viridian_mart_orders(step.items); + if (!orders){ + return Pokemon::outcome_failed("unknown_item", step.name); + } + int cursor = 0; + for (size_t c = 0; c < orders->size(); c++){ + const MartOrder& order = (*orders)[c]; + // The presses: down or up from where the cursor is. + cursor += order.row - cursor; + if (cursor < 0 || cursor >= (int)LIST.size() || LIST[cursor] == "cancel"){ + return Pokemon::outcome_failed("mart_cancel", std::format("order {} ends on row {}", c + 1, cursor + 1)); + } + if (LIST[cursor] != step.items[c].item){ + return Pokemon::outcome_failed("wrong_item", std::format("{} instead of {}", LIST[cursor], step.items[c].item)); + } + bag[LIST[cursor]] += order.quantity; + } + return Pokemon::outcome_ok(); + } + +private: + Outcome walk_to(const Pokemon::Pose& pose, const StoryStep& step){ + const Standing at = standing(pose); + if (!at.error.empty()){ + return Pokemon::outcome_failed("no_pose", at.error); + } + const std::optional target = story_pose(*step.target); + const RouteGoal goal{{target->map, target->tile}, target->facing}; + const std::optional> route = plan_overworld_route( + story_maps(), at.position, goal, default_route_costs(), at.facing + ); + if (!route){ + return Pokemon::outcome_failed("no_route", to_string(at.position) + " to " + to_string(goal.position)); + } + const MapPosition end = follow_overworld_route(story_maps(), at.position, *route); + if (!(end == goal.position)){ + return Pokemon::outcome_failed("wrong_end", to_string(end)); + } + const Direction facing = route->empty() ? at.facing : route->back().facing_after; + return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, facing})); + } + + std::string m_row; +}; + + +// One simulated run, segment built as the program builds it: each +// checkpoint saves at its end (hooks.save stands for save_game()). +struct Simulation{ + FakeGame game; + std::vector lines; + // Where each save stood: the end of its checkpoint. + std::vector> saves; + Pokemon::SegmentPolicy policy; + + // A language no reader supports, so a step that needed text would show. + Pokemon::SegmentReport run(const Pokemon::SegmentRange& range){ + game.set_language(Language::Japanese); + Pokemon::Segment segment; + segment.id = "00"; + for (const StoryCheckpoint& data : story_checkpoints()){ + segment.checkpoints.push_back(Pokemon::CheckpointSpec{ + .id = data.id, .title = data.title, .saves = true, + .build = [this, &data]{ return Pokemon::build_story_checkpoint(data, game); }, + }); + } + Pokemon::SegmentHooks hooks; + hooks.save = [this](RunState& state){ + game.trace.push_back("save"); + saves.emplace_back(last_begun(), state.pose); + return Pokemon::outcome_ok(); + }; + hooks.reload = [this](RunState&){ + game.trace.push_back("reload"); + return Pokemon::outcome_ok(); + }; + hooks.log = [this](const std::string& line){ lines.push_back(line); }; + RunState state; + return Pokemon::run_segment(state, segment, range, policy, hooks); + } + std::string last_begun() const{ + for (auto it = game.trace.rbegin(); it != game.trace.rend(); ++it){ + if (it->starts_with("begin ")){ + return it->substr(6); + } + } + return ""; + } + std::vector begun() const{ + std::vector ids; + for (const std::string& item : game.trace){ + if (item.starts_with("begin ")){ + ids.push_back(item.substr(6)); + } + } + return ids; + } + size_t count(const std::string& item) const{ + return (size_t)std::count(game.trace.begin(), game.trace.end(), item); + } +}; + + +class Test_AutoStorySimulation : public UnitTest{ +public: + Test_AutoStorySimulation(std::string name, std::function body) + : UnitTest("PokemonFRLG::AutoStory - Simulation: " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +UnitTestResult test_whole_story(){ + Simulation sim; + const Pokemon::SegmentReport report = sim.run({}); + if (!report.completed){ + return "Expected the whole story through:" + joined(sim.lines); + } + std::vector ids; + for (const StoryCheckpoint& data : story_checkpoints()){ + ids.push_back(data.id); + } + if (sim.begun() != ids || sim.saves.size() != ids.size()){ + return "Expected each checkpoint once, in order, each saving at its end:" + joined(sim.game.trace); + } + // Each checkpoint starts where the save before it stands. + for (size_t c = 1; c < story_checkpoints().size(); c++){ + const StoryCheckpoint& data = story_checkpoints()[c]; + const std::optional start = story_pose(*data.start); + const std::optional saved = story_pose(sim.saves[c - 1].second); + const bool same = start && saved && start->map == saved->map && start->tile == saved->tile + && (!start->facing || start->facing == saved->facing); + if (!same){ + return std::format("{} starts at {}, but {} saved at {}.", data.id, + Pokemon::to_string(*data.start), sim.saves[c - 1].first, Pokemon::to_string(sim.saves[c - 1].second)); + } + } + if (report.one_shot_passes() != report.checkpoints_run){ + return "Expected every checkpoint one-shot:" + joined(sim.lines); + } + // 00.07's shopping, with the cursor staying on each row bought. + const std::map bought{{"potion", 5}, {"antidote", 3}, {"parlyz_heal", 1}}; + if (sim.game.bag != bought){ + std::string text; + for (const auto& item : sim.game.bag){ + text += std::format(" {} {}", item.second, item.first); + } + return "Expected 5 Potions, 3 Antidotes and 1 Parlyz Heal; bought" + text + "."; + } + return true; +} + +UnitTestResult test_start_and_end(){ + Simulation sim; + const Pokemon::SegmentReport report = sim.run({.from = "00.05", .to = "00.07"}); + if (!report.completed || sim.begun() != std::vector{"00.05", "00.06", "00.07"}){ + return "Expected 00.05 to 00.07 only:" + joined(sim.begun()); + } + return true; +} + +// A walk that fails once (a trainer the walker could not recover from): +// the checkpoint reloads its last save and runs again from its start. +UnitTestResult test_retry_from_save(){ + Simulation sim; + sim.game.failures["00.07/forest_north"] = {.failure = "operation_failed", .times = 1}; + const Pokemon::SegmentReport report = sim.run({.from = "00.07", .to = "00.08"}); + if (!report.completed || report.reloads != 1 || sim.begun() != std::vector{"00.07", "00.07", "00.08"} + || sim.count("00.07/mart_clerk") != 2 + ){ + return "Expected 00.07 reloaded once and run again from its start:" + joined(sim.game.trace); + } + if (std::find(sim.lines.begin(), sim.lines.end(), "[Checkpoint] 00.07: passed on attempt 2 (1 reset)") == sim.lines.end()){ + return "Expected the retried pass logged:" + joined(sim.lines); + } + return true; +} + +// Brock's battle lost every time: three attempts, then the stop. +UnitTestResult test_gives_up_after_attempts(){ + Simulation sim; + sim.game.failures["00.08/brock"] = {.failure = "blackout", .times = 10}; + const Pokemon::SegmentReport report = sim.run({.from = "00.08", .to = std::nullopt}); + if (report.completed || report.reloads != 2 || report.failed_checkpoint != "00.08" || report.failed_event != "brock" + || report.failure.failure != "blackout" || sim.count("00.08/brock") != 3 || !sim.saves.empty() + ){ + return "Expected 00.08 tried 3 times, then a stop on Brock:" + joined(sim.game.trace) + joined(sim.lines); + } + return true; +} + +} + + +void add_tests_AutoStorySimulation(UnitTestDatabase& database){ + const auto add = [&](std::string name, UnitTestResult (*body)()){ + database.add(std::move(name), body); + }; + add("new game to Brock, in order, each start where the last save stood", test_whole_story); + add("start and end checkpoints", test_start_and_end); + add("a failed walk reloads its checkpoint's save", test_retry_from_save); + add("a battle lost every time stops after 3 attempts", test_gives_up_after_attempts); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index b8cbbce1e8..72427a3772 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -29,8 +29,22 @@ const char* const FOREST_GATE = "Route2_ViridianForest_NorthEntrance"; const char* const PEWTER_CENTER = "PewterCity_PokemonCenter_1F"; const char* const GYM = "PewterCity_Gym"; -StoryPose at(const char* map, int x, int y, std::optional facing = std::nullopt){ - return StoryPose{map, {x, y}, facing}; +Pokemon::Pose at(const char* map, int x, int y, std::optional facing = std::nullopt){ + return to_pose(StoryPose{map, {x, y}, facing}); +} + +StoryCheckpoint row( + std::string id, std::string title, std::optional start, + Supplies supplies, StartMenu menu, std::vector steps +){ + StoryCheckpoint checkpoint; + checkpoint.id = std::move(id); + checkpoint.title = std::move(title); + checkpoint.start = std::move(start); + checkpoint.steps = std::move(steps); + checkpoint.supplies = supplies; + checkpoint.menu = menu; + return checkpoint; } StoryStep make(StoryStepKind kind, std::string name, std::string why){ @@ -41,7 +55,7 @@ StoryStep make(StoryStepKind kind, std::string name, std::string why){ return step; } -StoryStep route(std::string name, StoryPose target, std::string why, bool fight_wild = false){ +StoryStep route(std::string name, Pokemon::Pose target, std::string why, bool fight_wild = false){ StoryStep step = make(StoryStepKind::ROUTE, std::move(name), std::move(why)); step.target = std::move(target); step.fight_wild = fight_wild; @@ -60,13 +74,13 @@ StoryStep answer(std::string name, bool yes, std::string why){ return step; } -StoryStep scene(std::string name, std::optional pose_after, std::string why){ +StoryStep scene(std::string name, std::optional pose_after, std::string why){ StoryStep step = make(StoryStepKind::MASH, std::move(name), std::move(why)); step.pose_after = std::move(pose_after); return step; } -StoryStep battle(std::string name, StoryPose pose_after, bool may_lose, std::string why){ +StoryStep battle(std::string name, Pokemon::Pose pose_after, bool may_lose, std::string why){ StoryStep step = make(StoryStepKind::BATTLE, std::move(name), std::move(why)); step.pose_after = std::move(pose_after); step.may_lose = may_lose; @@ -80,7 +94,7 @@ StoryStep legs(std::string name, std::vector legs, std::string why, bo return step; } -StoryStep new_game_intro(StoryPose pose_after, std::string why){ +StoryStep new_game_intro(Pokemon::Pose pose_after, std::string why){ StoryStep step = make(StoryStepKind::NEW_GAME, "intro", std::move(why)); step.pose_after = std::move(pose_after); return step; @@ -90,7 +104,7 @@ StoryStep talk(std::string name, std::string why){ return make(StoryStepKind::TALK, std::move(name), std::move(why)); } -StoryStep ready(std::string name, StoryPose nurse, std::string why){ +StoryStep ready(std::string name, Pokemon::Pose nurse, std::string why){ StoryStep step = make(StoryStepKind::READY, std::move(name), std::move(why)); step.target = std::move(nurse); return step; @@ -100,32 +114,38 @@ StoryStep heal(std::string name){ return make(StoryStepKind::HEAL, std::move(name), "full HP"); } +StoryStep shop(std::string name, std::vector items, std::string why){ + StoryStep step = make(StoryStepKind::SHOP, std::move(name), std::move(why)); + step.items = std::move(items); + return step; +} + StoryCheckpoint new_game(){ - return StoryCheckpoint{"00.01", "new game to the bedroom", std::nullopt, {}, StartMenu::BEFORE_POKEMON, { + return row("00.01", "new game to the bedroom", std::nullopt, {}, StartMenu::BEFORE_POKEMON, { // new_game.c: the bedroom at (6, 6), facing the TV. new_game_intro(at(BEDROOM, 6, 6, NORTH), "Oak's speech, BOY, default names, rival GREEN"), - make(StoryStepKind::SET_OPTIONS, "options", "fast text; no switch prompt between a trainer's Pokemon"), - }}; + make(StoryStepKind::OPTIONS, "options", "fast text; no switch prompt between a trainer's Pokemon"), + }); } StoryCheckpoint leave_house(){ - return StoryCheckpoint{"00.02", "bedroom to Pallet Town", at(BEDROOM, 6, 6, NORTH), {}, StartMenu::BEFORE_POKEMON, { + return row("00.02", "bedroom to Pallet Town", at(BEDROOM, 6, 6, NORTH), {}, StartMenu::BEFORE_POKEMON, { route("front_door", at(PALLET, 6, 8), "down the stairs and out of the house"), - }}; + }); } StoryCheckpoint oaks_trigger(){ - return StoryCheckpoint{"00.03", "Oak stops the player and walks them to the lab", at(PALLET, 6, 8, SOUTH), {}, StartMenu::BEFORE_POKEMON, { + return row("00.03", "Oak stops the player and walks them to the lab", at(PALLET, 6, 8, SOUTH), {}, StartMenu::BEFORE_POKEMON, { route("below_oaks_trigger", at(PALLET, 12, 2, NORTH), "below the north exit, short of Oak's trigger at (12, 1)"), step_into("oaks_trigger", NORTH, "the trigger: \"Don't go out!\""), // PlayerEnter walks the player up 8 tiles from the lab's door. scene("to_the_lab", at(LAB, 6, 4, NORTH), "Oak walks the player into the lab; the scene ends at the table"), - }}; + }); } StoryCheckpoint starter(){ - return StoryCheckpoint{"00.04", "Squirtle, then the rival's battle", at(LAB, 6, 4, NORTH), {}, StartMenu::BEFORE_POKEDEX, { + return row("00.04", "Squirtle, then the rival's battle", at(LAB, 6, 4, NORTH), {}, StartMenu::BEFORE_POKEDEX, { route("below_squirtle", at(LAB, 9, 5, NORTH), "under Squirtle's ball (9, 4)"), talk("squirtle_ball", "\"So, you want the WATER POKEMON SQUIRTLE?\""), answer("choose_squirtle", true, "take Squirtle"), @@ -135,30 +155,31 @@ StoryCheckpoint starter(){ step_into("rival_trigger", SOUTH, "\"Wait, let's check out our POKEMON!\""), // The rival leaves; PlayerWatchRivalExitAfterBattleRight ends facing down. battle("rival_battle", at(LAB, 7, 8, SOUTH), true, "the tutorial battle; losing goes on too"), - }}; + }); } StoryCheckpoint parcel(){ - return StoryCheckpoint{"00.05", "Route 1 to Viridian Mart: Oak's Parcel", at(LAB, 7, 8, SOUTH), {}, StartMenu::BEFORE_POKEDEX, { + return row("00.05", "Route 1 to Viridian Mart: Oak's Parcel", at(LAB, 7, 8, SOUTH), {}, StartMenu::BEFORE_POKEDEX, { route("below_mart_door", at(VIRIDIAN, 36, 20, NORTH), "Route 1, running from wild battles"), step_into("mart_door", NORTH, "the clerk's scene starts on entering"), // ApproachCounter: up 4 from the mat, then faces the clerk. scene("parcel_from_clerk", at(VIRIDIAN_MART, 4, 3, WEST), "the clerk gives OAK'S PARCEL"), - }}; + }); } StoryCheckpoint pokedex(){ - return StoryCheckpoint{"00.06", "Oak's Parcel to the Pokedex", at(VIRIDIAN_MART, 4, 3, WEST), {}, StartMenu::FULL, { + return row("00.06", "Oak's Parcel to the Pokedex", at(VIRIDIAN_MART, 4, 3, WEST), {}, StartMenu::FULL, { route("below_oak", at(LAB, 6, 4, NORTH), "back down Route 1 to Oak"), talk("give_parcel", "Oak takes the parcel"), scene("pokedex_scene", at(LAB, 6, 4, SOUTH), "the rival comes in, Pokedexes from the desk; the player ends facing south (console B, 2026-11-01)"), - }}; + }); } StoryCheckpoint forest(){ - return StoryCheckpoint{"00.07", "Viridian shopping to Pewter Center", at(LAB, 6, 4, SOUTH), {}, StartMenu::FULL, { + return row("00.07", "Viridian shopping to Pewter Center", at(LAB, 6, 4, SOUTH), {}, StartMenu::FULL, { route("mart_clerk", at(VIRIDIAN_MART, 4, 3, WEST), "Route 1 again"), - make(StoryStepKind::SHOP, "potions_and_antidotes", "5 Potions, 3 Antidotes, 1 Parlyz Heal"), + // 2000 of the 3000 a new game starts with, plus the rival's prize. + shop("potions_and_antidotes", {{"potion", 5}, {"antidote", 3}, {"parlyz_heal", 1}}, "5 Potions, 3 Antidotes, 1 Parlyz Heal"), route("viridian_nurse", at(VIRIDIAN_CENTER, 7, 4, NORTH), "heal before the forest"), heal("heal_viridian"), route("below_old_man_trigger", at(VIRIDIAN, 20, 9, NORTH), "short of the tutorial trigger (20, 8)"), @@ -186,12 +207,12 @@ StoryCheckpoint forest(){ // Out of the forest, wild battles are run from; trainers are still fought. route("pewter_nurse", at(PEWTER_CENTER, 7, 4, NORTH), "Route 2 north to Pewter's Center"), heal("heal_pewter"), - }}; + }); } StoryCheckpoint brock(){ // The by-hand save: 2 Potions and 1 Antidote left after the forest. - return StoryCheckpoint{"00.08", "Pewter Gym: Camper Liam, then Brock", at(PEWTER_CENTER, 7, 4, NORTH), {2, 1}, StartMenu::FULL, { + return row("00.08", "Pewter Gym: Camper Liam, then Brock", at(PEWTER_CENTER, 7, 4, NORTH), {2, 1}, StartMenu::FULL, { // Camper Liam (3, 8) always faces east (MOVEMENT_TYPE_FACE_RIGHT, sight // 4) and sees (4..7, 8): walking north up column 6 from the door, // the step onto (6, 8) starts his battle. He walks up to the player, @@ -205,7 +226,7 @@ StoryCheckpoint brock(){ route("before_brock", at(GYM, 6, 6, NORTH), "below Brock (6, 5); Liam, beaten, stands at (5, 8)"), talk("challenge_brock", "Brock's speech"), battle("brock", at(GYM, 6, 6, NORTH), false, "Geodude and Onix, with Bubble; Boulder Badge and TM39"), - }}; + }); } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h index 4c107c9874..cbf6fadbc3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h @@ -25,6 +25,8 @@ const std::vector& story_checkpoints(); void add_tests_AutoStory(UnitTestDatabase& database); +// The table run end to end against a fake game (PokemonFRLG_AutoStorySimulation_Tests.cpp). +void add_tests_AutoStorySimulation(UnitTestDatabase& database); 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 6fcced4acc..26a49f07ef 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -62,6 +62,15 @@ std::string describe(const StoryPose& pose){ + (pose.facing ? std::string(" facing ") + direction_name(*pose.facing) : ""); } +// A table pose as a StoryPose; FRLG's table has one-tile poses only. +StoryPose one_tile(const Pokemon::Pose& pose){ + const std::optional ret = story_pose(pose); + if (!ret){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Not a one-tile pose: " + Pokemon::to_string(pose)); + } + return *ret; +} + Direction reverse(Direction direction){ switch (direction){ case Direction::NORTH: @@ -133,7 +142,11 @@ UnitTestResult check_route(StoryPose& pose, const StoryStep& step){ return step.name + ": the facing is unknown at " + describe(pose) + " and no wall is beside it."; } } - const RouteGoal goal{{step.target.map, step.target.tile}, step.target.facing}; + if (!step.target){ + return step.name + ": no target."; + } + const StoryPose target = one_tile(*step.target); + const RouteGoal goal{{target.map, target.tile}, target.facing}; const std::optional> route = plan_overworld_route(story_maps(), start, goal, default_route_costs(), facing); if (!route){ return step.name + ": no route from " + to_string(start) + " to " + to_string(goal.position) + "."; @@ -158,7 +171,7 @@ UnitTestResult check_route(StoryPose& pose, const StoryStep& step){ } } } - pose = StoryPose{step.target.map, step.target.tile, route->empty() ? facing : route->back().facing_after}; + pose = StoryPose{target.map, target.tile, route->empty() ? facing : route->back().facing_after}; return true; } @@ -183,7 +196,7 @@ UnitTestResult check_checkpoint(const StoryCheckpoint& checkpoint, StoryPose& po pose = StoryPose{pose.map, pose.tile.next(step.direction), step.direction}; } if (step.pose_after){ - pose = *step.pose_after; + pose = one_tile(*step.pose_after); } } return true; @@ -198,7 +211,7 @@ UnitTestResult test_routes_and_chain(){ for (size_t c = 0; c < checkpoints.size(); c++){ const StoryCheckpoint& checkpoint = checkpoints[c]; if (c > 0){ - const StoryPose& start = *checkpoint.start; + const StoryPose start = one_tile(*checkpoint.start); const bool same_facing = !start.facing || start.facing == pose.facing; if (start.map != pose.map || !(start.tile == pose.tile) || !same_facing){ return checkpoint.id + " starts at " + describe(start) + ", but " + checkpoints[c - 1].id + " ends at " + describe(pose) + "."; @@ -278,6 +291,16 @@ UnitTestResult test_pewter_gym_walks(){ ); } +UnitTestResult test_lint(){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + const std::vector problems = Pokemon::lint_story_checkpoint(checkpoint); + if (!problems.empty()){ + return problems[0]; + } + } + return true; +} + UnitTestResult test_unique_names(){ for (const StoryCheckpoint& checkpoint : story_checkpoints()){ for (size_t i = 0; i < checkpoint.steps.size(); i++){ @@ -297,6 +320,7 @@ UnitTestResult test_unique_names(){ void add_tests_AutoStory(UnitTestDatabase& database){ database.add("every route plans, and checkpoints chain", test_routes_and_chain); database.add("step names are unique per checkpoint", test_unique_names); + database.add("every checkpoint lints clean", test_lint); database.add("Pewter Gym walks", test_pewter_gym_walks); } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 8ddec70b10..383e0a6ebf 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1459,6 +1459,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_StorySegments.cpp Source/Pokemon/Navigation/Pokemon_StorySegments.h Source/Pokemon/Navigation/Pokemon_StorySegments_Tests.cpp + Source/Pokemon/Navigation/Pokemon_StorySteps.cpp + Source/Pokemon/Navigation/Pokemon_StorySteps.h + Source/Pokemon/Navigation/Pokemon_StorySteps_Tests.cpp Source/Pokemon/Navigation/Pokemon_TilePose.cpp Source/Pokemon/Navigation/Pokemon_TilePose.h Source/Pokemon/Options/Pokemon_BoxSortingTable.cpp @@ -1474,6 +1477,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Options/Pokemon_NameSelectWidget.h Source/Pokemon/Options/Pokemon_StatsHuntFilter.cpp Source/Pokemon/Options/Pokemon_StatsHuntFilter.h + Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp + Source/Pokemon/Options/Pokemon_StoryRunOptions.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp @@ -1804,6 +1809,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_EliteFourFarmer.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_EliteFourFarmer.h