From 0b1057fd412567922778f9d83c438cf2ea994a4c Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 01:46:26 -0800 Subject: [PATCH 1/4] PokemonLZA AutoStory: the story game, its table and the built-in checkpoint files --- SerialPrograms/CMakeLists.txt | 2 + .../PokemonLZA/PokemonLZA_Tests.cpp | 7 + .../PokemonLZA_AutoStoryGateWalk_Tests.cpp | 278 +++++ .../PokemonLZA_AutoStoryGateWalk_Tests.h | 25 + .../PokemonLZA_AutoStoryEngine_Tests.cpp | 1108 +++++++++++++++++ .../PokemonLZA_AutoStoryEngine_Tests.h | 26 + .../AutoStory/PokemonLZA_AutoStoryGame.cpp | 984 +++++++++++++++ .../AutoStory/PokemonLZA_AutoStoryGame.h | 147 +++ .../PokemonLZA_AutoStorySceneMachine.h | 4 + ...PokemonLZA_AutoStorySceneMachine_Tests.cpp | 584 +++++++++ .../PokemonLZA_AutoStoryStoryFiles.cpp | 83 ++ .../PokemonLZA_AutoStoryStoryFiles.h | 74 ++ .../AutoStory/PokemonLZA_AutoStoryTable.cpp | 58 + .../AutoStory/PokemonLZA_AutoStoryTable.h | 60 + .../PokemonLZA_AutoStoryTable_Tests.cpp | 696 +++++++++++ .../PokemonLZA_AutoStoryTable_Tests.h | 26 + SerialPrograms/cmake/SourceFiles.cmake | 13 + 17 files changed, 4175 insertions(+) create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.h diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index f23153a8f7..f44a4e08c7 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -228,6 +228,8 @@ add_library(SerialProgramsLib STATIC ${CORE_LIBRARY_SOURCES} ${LIBRARY_SOURCES}) # Data files built into the program (see cmake/EmbedTextFiles.cmake). include(cmake/EmbedTextFiles.cmake) +pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonLZA/Programs/AutoStory/StoryData + VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h PokemonAutomation::NintendoSwitch::PokemonLZA autostory_checkpoint_json) pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonLZA/Programs/AutoStory/ReferenceData VideoGames/PokemonLZA/Programs/AutoStory/Detectors/PokemonLZA_AutoStoryPlatformArrivalDetector.h PokemonAutomation::NintendoSwitch::PokemonLZA autostory_reference_json) diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/PokemonLZA_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/PokemonLZA_Tests.cpp index 2a9ac60017..3e844b7058 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/PokemonLZA_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/PokemonLZA_Tests.cpp @@ -21,11 +21,13 @@ #include "Inference/PokemonLZA_OverworldPartySelectionDetector.h" #include "Inference/PokemonLZA_PartyBarDetector.h" #include "Inference/PokemonLZA_SelectionArrowDetector.h" +#include "Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.h" #include "Programs/AutoStory/PokemonLZA_AutoStoryFailures.h" #include "Programs/AutoStory/PokemonLZA_AutoStoryStartLoad_Tests.h" #include "Programs/AutoStory/Actions/PokemonLZA_AutoStoryCatchPlan_Tests.h" #include "Programs/AutoStory/Actions/PokemonLZA_AutoStoryCatchStop_Tests.h" #include "Programs/AutoStory/Actions/PokemonLZA_AutoStoryDialogs_Tests.h" +#include "Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.h" #include "Programs/AutoStory/Detectors/PokemonLZA_AutoStoryConfirmChoicesReader_Tests.h" #include "Programs/AutoStory/Detectors/PokemonLZA_AutoStoryDialogChoiceBox_Tests.h" #include "Programs/AutoStory/Detectors/PokemonLZA_AutoStoryDetectors_Tests.h" @@ -33,6 +35,7 @@ #include "Programs/AutoStory/Detectors/PokemonLZA_AutoStoryZoneGateReader_Tests.h" #include "Programs/AutoStory/PokemonLZA_AutoStorySceneMachine.h" #include "Programs/AutoStory/PokemonLZA_AutoStoryScreenEvents.h" +#include "Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -57,16 +60,20 @@ void add_tests(UnitTestDatabase& database){ add_tests_OverworldPartySelectionDetector(database); add_tests_PartyBarDetector(database); add_tests_SelectionArrowDetector(database); + add_tests_AutoStory_StoryTable(database); add_tests_AutoStoryScreenEvents(database); add_tests_AutoStoryDetectors(database); add_tests_AutoStoryConfirmChoicesReader(database); add_tests_AutoStoryDialogChoiceBox(database); add_tests_AutoStoryObjectiveMarkerReader(database); add_tests_AutoStoryZoneGateReader(database); + add_tests_AutoStoryGateWalk(database); add_tests_AutoStoryFailures(database); add_tests_AutoStoryCatchPlan(database); add_tests_AutoStoryCatchStop(database); add_tests_AutoStoryDialogs(database); + add_tests_AutoStorySceneMachine(database); + add_tests_AutoStoryEngine(database); add_tests_AutoStoryStartLoad(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.cpp new file mode 100644 index 0000000000..20788bcea2 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.cpp @@ -0,0 +1,278 @@ +/* PokemonLZA AutoStory - Walk to a wild zone's gate Tests + * + * From: https://github.com/PokemonAutomation/ + * + * walk_to_zone_gate_entrance() on the engine's scripted backend + * (FakeStoryBackend): each look carries the gate readings a console's + * zone_gate_reader() would set, and the A prompt. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h" +#include "PokemonLZA_AutoStoryGateWalk.h" +#include "PokemonLZA_AutoStoryGateWalk_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + +using namespace std::chrono_literals; +using Pokemon::Observation; +using Pokemon::ZonePose; + + +namespace{ + +using FakeBackend = Pokemon::FakeStoryBackend; + +// What a look shows. +struct Look{ + // The gate's middle, in thousandths of the width; none: no gate. + std::optional gate_x = std::nullopt; + bool prompt = false; + // The minimap's heading; none: not read. + std::optional heading = std::nullopt; +}; + +std::vector> looks_of(const std::vector& looks){ + std::vector> out; + const WallClock start = current_time(); + for (const Look& look : looks){ + Observation observation; + observation.when = start + Milliseconds(250) * out.size(); + if (look.gate_x){ + observation.readings[std::string(ZONE_GATE_X_READING)] = *look.gate_x; + observation.readings[std::string(ZONE_GATE_WIDTH_READING)] = 150; + } + if (look.heading){ + observation.readings[std::string(Pokemon::STORY_HEADING)] = *look.heading; + } + if (look.prompt){ + observation.events.set(ScreenEvent::INTERACT_PROMPT, true); + } + out.push_back(std::move(observation)); + } + return out; +} + +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += (text.empty() ? "" : ", ") + line; + } + return text; +} + +std::string slice(int degrees){ + return std::format("stick {}deg 250ms walk", degrees); +} + + +struct GateWalkCase{ + std::string name; + struct Input{ + // In order; the last repeats. + std::vector looks; + Milliseconds timeout = 1000ms; + }; + Input input; + struct Expectation{ + // The failure; none: the walk succeeds. + std::optional failure; + std::vector inputs; + // In the failure's message, when there is one. + std::string message = ""; + }; + Expectation expectation; +}; + +const GateWalkCase GATE_WALK_CASES[] = { + { + .name = "at the prompt already: no walk", + .input = {.looks = {{.gate_x = 500, .prompt = true}}}, + .expectation = {.failure = std::nullopt, .inputs = {}}, + }, + { + .name = "steers toward the gate until the prompt", + .input = {.looks = {{.gate_x = 700}, {.gate_x = 600}, {.gate_x = 505}, {.prompt = true}}}, + .expectation = {.failure = std::nullopt, .inputs = {slice(12), slice(6), slice(0)}}, + }, + { + .name = "a gate lost up close keeps the last angle", + .input = {.looks = {{.gate_x = 250}, {}, {}, {.prompt = true}}}, + .expectation = {.failure = std::nullopt, .inputs = {slice(-15), slice(-15), slice(-15)}}, + }, + { + .name = "no gate in the first 3 seconds fails", + .input = {.looks = {{}}, .timeout = 15000ms}, + .expectation = { + .failure = "gate_not_seen", .inputs = std::vector(12, slice(0)), + .message = "no gate on 13 looks", + }, + }, + { + .name = "a gate late in the first second is seen", + .input = {.looks = {{}, {}, {}, {.gate_x = 400}, {.prompt = true}}}, + .expectation = {.failure = std::nullopt, .inputs = {slice(0), slice(0), slice(0), slice(-6)}}, + }, + { + .name = "no prompt by the timeout fails with the last gate read", + .input = {.looks = {{.gate_x = 510}}, .timeout = 1000ms}, + .expectation = { + .failure = "no_prompt", .inputs = {slice(0), slice(0), slice(0), slice(0)}, + .message = "gate on 5 of 5 looks, last at x = 0.510 width 0.150", + }, + }, +}; + +UnitTestResult check_gate_walk(const GateWalkCase& test, CancellableScope& scope){ + FakeBackend backend(Pokemon::FakeStoryScript{ + .looks = looks_of(test.input.looks), .battle = Pokemon::outcome_ok(), .kind = Pokemon::StoryBackendKind::SCRIPT, + }, scope); + const Pokemon::Outcome outcome = walk_to_zone_gate_entrance( + backend, PlzaReader(), PlzaReader(), GateWalk{.heading = std::nullopt, .timeout = test.input.timeout} + ); + const std::optional failure = outcome.succeeded() ? std::nullopt : std::optional(outcome.failure); + if (failure != test.expectation.failure){ + return std::format("Expected {}, got {}.", test.expectation.failure.value_or("a pass"), to_string(outcome)); + } + if (failure && to_string(outcome).find(test.expectation.message) == std::string::npos){ + return std::format("Expected \"{}\" in {}.", test.expectation.message, to_string(outcome)); + } + if (backend.inputs() != test.expectation.inputs){ + return std::format("Expected inputs [{}], got [{}].", joined(test.expectation.inputs), joined(backend.inputs())); + } + return true; +} + + +// The step `name` of checkpoint `id`, alone in a checkpoint of its own; +// none when the story has no such step. +std::optional step_of(std::string_view id, std::string_view name){ + for (const Pokemon::StoryCheckpoint& row : story_checkpoints()){ + if (row.id != id){ + continue; + } + for (const Pokemon::StoryStep& step : row.steps){ + if (step.name == name){ + Pokemon::StoryCheckpoint one; + one.id = row.id; + one.title = row.title; + one.steps.push_back(step); + return one; + } + } + } + return std::nullopt; +} + +// A checkpoint's to_zone_1_gate through PLZA's engine, on looks that read +// 30 degrees left of the plan's heading, then the heading, then the gate +// dead ahead, then the prompt. +struct PlanStepCase{ + std::string name; + struct Input{ + std::string_view checkpoint; + }; + Input input; + struct Expectation{ + std::vector inputs; + }; + Expectation expectation; +}; + +// 03.06's step faces the plan's heading by the minimap first (a turn of 30, then L +// so the camera follows), then walk the gate's way until the prompt. +const PlanStepCase PLAN_STEP_CASES[] = { + { + .name = "03.06 to_zone_1_gate faces the street, then the gate", + .input = {.checkpoint = "03.06"}, + .expectation = {.inputs = {"press L", "stick 30deg 150ms walk, release 100ms", "press L", slice(0)}}, + }, +}; + +UnitTestResult check_plan_step(const PlanStepCase& test, CancellableScope& scope){ + const std::string_view id = test.input.checkpoint; + const std::optional row = step_of(id, "to_zone_1_gate"); + if (!row){ + return std::format("{} has no to_zone_1_gate step.", id); + } + const Pokemon::StoryStep& step = row->steps[0]; + const auto heading = step.args.find("heading"); + if (step.action != "walk_to_zone_gate_entrance" || heading == step.args.end()){ + return std::format("{}: expected walk_to_zone_gate_entrance with a heading, got {}.", id, step.action); + } + const int facing = (int)std::get(heading->second); + FakeBackend backend(Pokemon::FakeStoryScript{ + .looks = looks_of({{.heading = (facing + 330) % 360}, {.heading = facing}, {.gate_x = 500}, {.prompt = true}}), + .battle = Pokemon::outcome_ok(), .kind = Pokemon::StoryBackendKind::SCRIPT, + }, scope); + const Pokemon::StoryGame game = make_plza_story_game(StarterChoice::CHIKORITA); + Pokemon::StoryEngine engine(game, backend); + Pokemon::RunState state; + const Pokemon::StoryEngineReport report = engine.run_checkpoint(*row, Pokemon::SavePoint::RUN_END, state); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("{}: expected a pass, got {}.", id, to_string(report.run.failure)); + } + if (backend.inputs() != test.expectation.inputs){ + return std::format("{}: expected inputs [{}], got [{}].", id, joined(test.expectation.inputs), joined(backend.inputs())); + } + return true; +} + + +class Test_GateWalk : public UnitTest{ +public: + explicit Test_GateWalk(const GateWalkCase& test) + : UnitTest(std::format("PokemonLZA::AutoStory - walk_to_zone_gate_entrance: {}", test.name)) + , m_test(test) + {} + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + return check_gate_walk(m_test, scope); + } + +private: + const GateWalkCase& m_test; +}; + +class Test_GatePlanStep : public UnitTest{ +public: + explicit Test_GatePlanStep(const PlanStepCase& test) + : UnitTest(std::format("PokemonLZA::AutoStory - walk_to_zone_gate_entrance: {}", test.name)) + , m_test(test) + {} + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + return check_plan_step(m_test, scope); + } + +private: + const PlanStepCase& m_test; +}; + +} // namespace + + +void add_tests_AutoStoryGateWalk(UnitTestDatabase& database){ + for (const GateWalkCase& test : GATE_WALK_CASES){ + database.add(test); + } + for (const PlanStepCase& test : PLAN_STEP_CASES){ + database.add(test); + } +} + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.h new file mode 100644 index 0000000000..f230b8a3b3 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.h @@ -0,0 +1,25 @@ +/* PokemonLZA AutoStory - Walk to a wild zone's gate Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLZA_AutoStoryGateWalk_Tests_H +#define PokemonAutomation_PokemonLZA_AutoStoryGateWalk_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + + +// Registers walk_to_zone_gate_entrance()'s tests, on scripted looks. +void add_tests_AutoStoryGateWalk(UnitTestDatabase& database); + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.cpp new file mode 100644 index 0000000000..b73a1d6011 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.cpp @@ -0,0 +1,1108 @@ +/* PokemonLZA AutoStory - Engine Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The new game's and 01.01's scene steps and walks, and every checkpoint, through the shared + * story engine on its scripted backend (FakeStoryBackend). + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h" +#include "PokemonLZA_AutoStoryGame.h" +#include "PokemonLZA_AutoStoryLaunch.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryMoves.h" +#include "PokemonLZA_AutoStoryReadings.h" +#include "PokemonLZA_AutoStoryStoryFiles.h" +#include "PokemonLZA_AutoStoryEngine_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + +using namespace std::chrono_literals; +using Pokemon::Observation; +using Pokemon::StoryCheckpoint; +using Pokemon::StoryRunPolicy; +using Pokemon::StoryStep; +using Pokemon::ZonePose; +using EngineEvent = PokemonAutomation::ScreenEvent; + + +namespace{ + +using FakeBackend = Pokemon::FakeStoryBackend; + +// A scripted PLZA showing `looks` in order (the last repeats); `kind` +// CONSOLE runs the console_only actions' code. +FakeBackend fake_plza( + std::vector> looks, CancellableScope& scope, + Pokemon::StoryBackendKind kind = Pokemon::StoryBackendKind::SCRIPT +){ + return FakeBackend(Pokemon::FakeStoryScript{.looks = std::move(looks), .battle = Pokemon::outcome_ok(), .kind = kind}, scope); +} + +// A look at `at` after a fixed start showing `events`. +Observation look_at(Milliseconds at, std::initializer_list events = {}){ + static const WallClock START = current_time(); + Observation look; + look.when = START + at; + look.events = ScreenEvents(events); + return look; +} + +// The step `name` of checkpoint `id`, alone in a checkpoint of its own. +StoryCheckpoint step_of(std::string_view id, std::string_view name){ + const auto found = std::find_if(story_checkpoints().begin(), story_checkpoints().end(), [id](const StoryCheckpoint& row){ + return row.id == id; + }); + if (found == story_checkpoints().end()){ + return StoryCheckpoint{}; + } + const StoryCheckpoint& row = *found; + StoryCheckpoint one; + one.id = row.id; + one.title = row.title; + for (const StoryStep& step : row.steps){ + if (step.name == name){ + one.steps.push_back(step); + } + } + return one; +} + +// `checkpoint` on PLZA's engine over `backend`. +Pokemon::StoryEngineReport run_plza(FakeBackend& backend, const StoryCheckpoint& checkpoint){ + const Pokemon::StoryGame game = make_plza_story_game(StarterChoice::CHIKORITA); + Pokemon::StoryEngine engine(game, backend); + Pokemon::RunState state; + return engine.run_checkpoint(checkpoint, Pokemon::SavePoint::RUN_END, state); +} + +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += (text.empty() ? "" : ", ") + line; + } + return text; +} + +UnitTestResult expect_inputs(const FakeBackend& backend, const std::vector& expected){ + if (backend.inputs() != expected){ + return std::format("Expected inputs [{}], got [{}].", joined(expected), joined(backend.inputs())); + } + return true; +} + + +// `look` with the reading `name` on screen. +Observation with_reading(Observation look, std::string_view name){ + look.readings[std::string(name)] = 1; + return look; +} + +// The opening (opening_to_platform): no presses through the cutscene and +// its skip prompt; the platform before the autosave does not count; done +// on the second look in a row at the platform after the autosave badge. +UnitTestResult test_opening_waits_for_platform(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::FADE_BLACK}), + with_reading(look_at(300ms), SKIP_PROMPT_READING), + with_reading(look_at(600ms), PLATFORM_READING), + with_reading(look_at(900ms), PLATFORM_READING), + with_reading(with_reading(look_at(1200ms), PLATFORM_READING), AUTOSAVE_READING), + with_reading(look_at(1500ms), PLATFORM_READING), + with_reading(look_at(1800ms), PLATFORM_READING), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.00", "opening")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the opening to end at the platform: {}", to_string(report.run.failure)); + } + const auto logged = [&backend](std::string_view text){ + return std::any_of(backend.lines().begin(), backend.lines().end(), [text](const std::string& line){ + return line.find(text) != std::string::npos; + }); + }; + if (!logged("skip prompt") || !logged("autosave")){ + return "Expected the skip prompt and the autosave in the log."; + } + return expect_inputs(backend, std::vector(6, "wait 300ms")); +} + +// 01.01's start check: one look at the platform is not enough, and with +// no platform it fails within its 10 s, pressing nothing. +UnitTestResult test_start_check_needs_platform(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + with_reading(look_at(0ms), PLATFORM_READING), + look_at(500ms), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.01", "on_platform")); + if (report.run.completed || report.run.failure.failure != "platform_not_seen"){ + return std::format("Expected platform_not_seen, got {}", to_string(report.run.failure)); + } + for (const std::string& input : backend.inputs()){ + if (input != "wait 300ms"){ + return std::format("Expected only waits, got {}", input); + } + } + return true; +} + +// A walk starts only on free control: platform_to_plaza on a text box +// waits for it, then fails with no input but its waits. +UnitTestResult test_walk_needs_free_control(CancellableScope& scope){ + FakeBackend backend = fake_plza({look_at(0ms, {EngineEvent::DIALOG_BOX})}, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.01", "platform_to_plaza")); + if (report.run.completed || report.run.failure.failure != "walk_not_free"){ + return std::format("Expected walk_not_free, got {}", to_string(report.run.failure)); + } + for (const std::string& input : backend.inputs()){ + if (input != "wait 250ms"){ + return std::format("Expected only waits, got {}", input); + } + } + return true; +} + +// platform_to_plaza: the first leg, the turn (L, the stick tapped at 90 +// degrees) and L again, then the last leg held in slices until the white +// fade. Looks: 2 of free control, 3 around the legs' inputs, 1 per slice. +UnitTestResult test_walk_ends_on_white_fade(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms), look_at(150ms), look_at(250ms), look_at(4750ms), look_at(5000ms), + look_at(12000ms), look_at(12250ms), look_at(12500ms, {EngineEvent::FADE_WHITE}), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.01", "platform_to_plaza")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the walk to end on the white fade: {}", to_string(report.run.failure)); + } + return expect_inputs(backend, { + "wait 250ms", "hold north 4500ms walk", "press L", "stick 90deg 150ms walk, release 100ms", "press L", + "hold north 250ms walk", "hold north 250ms walk", "hold north 250ms walk", + }); +} + +// 02.01's battle_zone_to_brigitte, a held walk: +// 3 s for the NPCs to move off, the first leg held at its angle with no L, +// then L and the stick held at each later turning leg's angle. +UnitTestResult test_held_walk_inputs(CancellableScope& scope){ + FakeBackend backend = fake_plza({look_at(0ms), look_at(250ms)}, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("02.01", "battle_zone_to_brigitte")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the held walk to pass: {}", to_string(report.run.failure)); + } + return expect_inputs(backend, { + "wait 3000ms", "wait 250ms", "stick 10deg 4250ms walk", + "press L", "stick 90deg 6000ms walk", + "press L", "stick 90deg 6500ms walk", + }); +} + +// platform_to_plaza with no white fade fails once the last leg's 10 s are +// held: 40 slices. +UnitTestResult test_walk_fails_at_bound(CancellableScope& scope){ + FakeBackend backend = fake_plza({look_at(0ms)}, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.01", "platform_to_plaza")); + if (report.run.completed || report.run.failure.failure != "walk_no_end"){ + return std::format("Expected walk_no_end, got {}", to_string(report.run.failure)); + } + const size_t slices = (size_t)std::count(backend.inputs().begin(), backend.inputs().end(), "hold north 250ms walk"); + if (slices != 40){ + return std::format("Expected 40 slices of 250 ms, held {}.", slices); + } + return true; +} + +// The opening ends on "Your train has arrived in Lumiose City!", a text box +// with the advance arrow that waits for A (the run +// waited 100 s on it and failed platform_not_seen; one A by hand went on to +// the platform). One A per text, none while it is still up, then the platform. +UnitTestResult test_opening_presses_through_arrival_text(CancellableScope& scope){ + const auto arrival = [](Milliseconds at){ + return with_reading(look_at(at, {EngineEvent::DIALOG_BOX}), ADVANCE_ARROW_READING); + }; + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::FADE_BLACK}), + with_reading(look_at(300ms), AUTOSAVE_READING), + arrival(600ms), + arrival(900ms), + with_reading(look_at(1200ms), PLATFORM_READING), + with_reading(look_at(1500ms), PLATFORM_READING), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.00", "opening")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the opening to end at the platform: {}", to_string(report.run.failure)); + } + std::vector presses; + std::copy_if(backend.inputs().begin(), backend.inputs().end(), std::back_inserter(presses), [](const std::string& input){ + return input.starts_with("press"); + }); + if (presses != std::vector{"press A"}){ + return std::format("Expected one A at the arrival text, got [{}].", joined(backend.inputs())); + } + return true; +} + +// A look at `at` facing `heading`, as the minimap reads it. +Observation facing(Milliseconds at, int heading){ + Observation look = look_at(at); + look.readings[std::string(Pokemon::STORY_HEADING)] = heading; + return look; +} + +// face_heading() turns by the difference to the heading a look reads, +// stops once a look reads it within the tolerance and ends with L, so the +// camera looks where the player faces; with no heading read it fails +// before any input. +UnitTestResult test_face_heading(CancellableScope& scope){ + FakeBackend backend = fake_plza({facing(0ms, 0), facing(500ms, 88)}, scope); + const Pokemon::Outcome faced = face_heading(backend, PlzaReader(), 90, 10); + if (!faced.succeeded()){ + return std::format("Expected to face 90 degrees: {}", to_string(faced)); + } + const UnitTestResult turned = expect_inputs(backend, {"press L", "stick 90deg 150ms walk, release 100ms", "press L"}); + if (turned.result != UnitTestResult::PASSED){ + return turned; + } + FakeBackend blind = fake_plza({look_at(0ms)}, scope); + const Pokemon::Outcome unread = face_heading(blind, PlzaReader(), 90, 10); + if (unread.failure != "heading_unread"){ + return std::format("Expected heading_unread with no heading read, got {}", to_string(unread)); + } + return expect_inputs(blind, {}); +} + +// Pancham cornered (text_to_choice): B through the text, done at the +// choice without pressing it. +UnitTestResult test_text_to_choice(CancellableScope& scope){ + const Observation choice = look_at(2000ms, {EngineEvent::DIALOG_BOX, EngineEvent::CHOICE_BOX}); + FakeBackend backend = fake_plza({look_at(0ms, {EngineEvent::DIALOG_BOX}), choice}, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.02", "pancham_cornered")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the scene to end at the choice: {}", to_string(report.run.failure)); + } + return expect_inputs(backend, {"press B"}); +} + +// 01.01's arrival scenes (mash_to_move_hints): A at the text and at the +// choice (its top row), one blind A in a 20 s text-free flyover, done +// once the controls hint has shown a second. +UnitTestResult test_arrival_ends_on_controls_hint(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::DIALOG_BOX}), + look_at(1000ms), + look_at(21000ms), + look_at(22000ms, {EngineEvent::DIALOG_BOX, EngineEvent::CHOICE_BOX}), + look_at(23000ms), + with_reading(look_at(24000ms), CONTROLS_HINT_READING), + with_reading(look_at(24500ms), CONTROLS_HINT_READING), + with_reading(look_at(25100ms), CONTROLS_HINT_READING), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.01", "arrival_scenes")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the scenes to end on the controls hint: {}", to_string(report.run.failure)); + } + const auto presses = std::count_if(backend.inputs().begin(), backend.inputs().end(), [](const std::string& input){ + return input.starts_with("press"); + }); + const auto a_presses = std::count(backend.inputs().begin(), backend.inputs().end(), "press A"); + if (presses != 3 || a_presses != 3){ + return std::format("Expected A at the text, once in the flyover and at the choice, got [{}].", joined(backend.inputs())); + } + return true; +} + +// 01.01's ad : subtitles with no box. A at each +// advance chevron, a blind A once nothing has shown for 5 s, none once +// the controls hint shows; done when it has shown a second. +// 01.02's battle area (the console): A at the text, a +// fade, then free control with only the "A: Talk" prompt, no controls +// hint. The prompt held a second ends the step; no press at it. +UnitTestResult test_battle_area_ends_on_interact_prompt(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::DIALOG_BOX}), + look_at(1000ms, {EngineEvent::FADE_BLACK}), + look_at(3000ms), + look_at(3250ms, {EngineEvent::INTERACT_PROMPT}), + look_at(3750ms, {EngineEvent::INTERACT_PROMPT}), + look_at(4300ms, {EngineEvent::INTERACT_PROMPT}), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.02", "battle_area")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the battle area to end on the interact prompt: {}", to_string(report.run.failure)); + } + std::vector presses; + std::copy_if(backend.inputs().begin(), backend.inputs().end(), std::back_inserter(presses), [](const std::string& input){ + return input.starts_with("press"); + }); + if (presses != std::vector{"press A"}){ + return std::format("Expected one A at the text, got [{}].", joined(backend.inputs())); + } + return true; +} + +UnitTestResult test_arrival_presses_through_the_ad(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms), + with_reading(look_at(1000ms), ADVANCE_ARROW_READING), + with_reading(look_at(2000ms), ADVANCE_ARROW_READING), + look_at(2500ms), + look_at(6000ms), + look_at(7100ms), + with_reading(look_at(8000ms), CONTROLS_HINT_READING), + with_reading(look_at(8500ms), CONTROLS_HINT_READING), + with_reading(look_at(9100ms), CONTROLS_HINT_READING), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.01", "arrival_scenes")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the ad to end on the controls hint: {}", to_string(report.run.failure)); + } + std::vector presses; + std::copy_if(backend.inputs().begin(), backend.inputs().end(), std::back_inserter(presses), [](const std::string& input){ + return input.starts_with("press"); + }); + if (presses != std::vector{"press A", "press A", "press A"}){ + return std::format("Expected A at the two chevrons and one blind A, got [{}].", joined(backend.inputs())); + } + return true; +} + +// 01.01's arrival : A at the last box, then the +// "MAIN MISSION 01" banner on two looks ends the step, which returns +// once the banner has gone, with no press at it. A banner still up after +// 10 s (01.03's "MAIN MISSION 02") gets A 3 times, +// then the step returns all the same. +UnitTestResult test_arrival_ends_on_mission_banner(CancellableScope& scope){ + for (const bool goes : {true, false}){ + std::vector> looks{ + look_at(0ms, {EngineEvent::DIALOG_BOX}), + look_at(500ms), + with_reading(look_at(1000ms), MISSION_BANNER_READING), + with_reading(look_at(1250ms), MISSION_BANNER_READING), + with_reading(look_at(1500ms), MISSION_BANNER_READING), + }; + if (goes){ + looks.push_back(look_at(4000ms)); + } + FakeBackend backend = fake_plza(std::move(looks), scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.01", "arrival_scenes")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the scenes to end on the mission banner: {}", to_string(report.run.failure)); + } + const auto presses = std::count_if(backend.inputs().begin(), backend.inputs().end(), [](const std::string& input){ + return input.starts_with("press"); + }); + const auto expected = goes ? 1 : 4; + if (presses != expected){ + return std::format("Expected {} A presses, got [{}].", expected, joined(backend.inputs())); + } + } + return true; +} + +// 01.03's after_andi: A at the box, A at each +// look at the "MAIN MISSION 01 COMPLETE" card, then "MAIN MISSION 02" on +// two looks ends the step. A banner that goes by itself gets no press; one +// that stays past 10 s gets A 3 times. +UnitTestResult test_after_andi_presses_complete_card(CancellableScope& scope){ + for (const bool goes : {true, false}){ + std::vector> looks{ + look_at(0ms, {EngineEvent::DIALOG_BOX}), + with_reading(look_at(500ms), MISSION_COMPLETE_READING), + with_reading(look_at(1000ms), MISSION_COMPLETE_READING), + look_at(1500ms), + with_reading(look_at(2000ms), MISSION_BANNER_READING), + with_reading(look_at(2250ms), MISSION_BANNER_READING), + }; + if (goes){ + looks.push_back(look_at(2500ms)); + } + FakeBackend backend = fake_plza(std::move(looks), scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.03", "after_andi")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected after_andi to end on the mission banner: {}", to_string(report.run.failure)); + } + const auto presses = std::count_if(backend.inputs().begin(), backend.inputs().end(), [](const std::string& input){ + return input.starts_with("press"); + }); + const auto expected = goes ? 3 : 6; + if (presses != expected){ + return std::format("Expected {} A presses (the box, the card twice, the banner if it stays), got [{}].", + expected, joined(backend.inputs())); + } + } + return true; +} + +// 01.01's arrival scenes: a minute with nothing busy and no controls hint +// (a text-free cutscene, or control the detectors miss) fails the step +// instead of taking it for control. +UnitTestResult test_arrival_quiet_fails(CancellableScope& scope){ + FakeBackend backend = fake_plza({look_at(0ms), look_at(30000ms), look_at(61000ms)}, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.01", "arrival_scenes")); + if (report.verdict == Pokemon::CheckpointVerdict::PASSED || report.run.failure.failure != "scene_quiet"){ + return std::format("Expected a quiet minute to fail as scene_quiet, got {}", to_string(report.run.failure)); + } + return true; +} + +// 02.02's street scene (a "scene" step, A): A at each box and at the +// tutorial card, a wait while the party bar shows between lines, done once +// it has held a second (TalkOver's calm time, OVERWORLD_HOLD). +UnitTestResult test_scene_step_presses_to_overworld(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::DIALOG_BOX}), + with_reading(look_at(1000ms), TUTORIAL_CARD_READING), + look_at(2000ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(2500ms, {EngineEvent::DIALOG_BOX}), + look_at(3000ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(4000ms, {EngineEvent::PLAYER_CAN_MOVE}), + }, scope, Pokemon::StoryBackendKind::CONSOLE); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("02.02", "street_scene")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the scene to end in the overworld: {}", to_string(report.run.failure)); + } + return expect_inputs(backend, {"press A", "press A", "wait 250ms", "press A", "wait 250ms"}); +} + +// A scene step not at its scene's trigger (02.02 after the Brigitte +// battle): no box, choice or battle in the start +// window fails it, before an A mash talks to whoever stands in front. +UnitTestResult test_scene_step_never_started(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::FADE_BLACK}), + look_at(20000ms), + look_at(46000ms), + }, scope, Pokemon::StoryBackendKind::CONSOLE); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("02.02", "street_scene")); + if (report.verdict == Pokemon::CheckpointVerdict::PASSED || report.run.failure.failure != "scene_never_started"){ + return std::format("Expected a scene with no box to fail as scene_never_started, got {}", to_string(report.run.failure)); + } + return expect_inputs(backend, {"wait 250ms", "wait 250ms"}); +} + +// 03.10's to_lab_elevator, a walk with no end event: once its legs are +// in, one look, which on a console waits for them to run, so the step +// ends where the walk does (to_mable returned +// 0.4 s in, before its 3.5 s of legs). +UnitTestResult test_walk_looks_after_its_legs(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(250ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(1500ms, {EngineEvent::INTERACT_PROMPT}), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("03.10", "to_lab_elevator")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the walk to pass: {}", to_string(report.run.failure)); + } + const std::string_view expected = "to_lab_elevator: legs done, screen now: interact prompt"; + const bool logged = std::any_of(backend.lines().begin(), backend.lines().end(), [expected](const std::string& line){ + return line.find(expected) != std::string::npos; + }); + if (!logged){ + return std::format("Expected the line \"{}\", got [{}].", expected, joined(backend.lines())); + } + return expect_inputs(backend, {"wait 250ms", "hold north 1000ms walk"}); +} + +// 03.11's to_mable walks into Mable's talk: its last leg is held until her +// dialog box shows. +UnitTestResult test_walk_ends_in_mables_talk(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(250ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(3000ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(3250ms, {EngineEvent::DIALOG_BOX}), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("03.11", "to_mable")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the walk to end in Mable's talk: {}", to_string(report.run.failure)); + } + return expect_inputs(backend, { + "wait 250ms", + "press L", "stick -90deg 150ms walk, release 100ms", "press L", "hold north 900ms walk", + "press L", "stick 90deg 150ms walk, release 100ms", "press L", "hold north 1300ms walk", + "press L", "stick 90deg 150ms walk, release 100ms", "press L", + "hold north 250ms walk", "hold north 250ms walk", + }); +} + +// 03.11's to_mable when a black fade shows in the held last leg: the scene +// at the walk's end takes over, so the walk ends there, with no slice after +// the fade (Mable's box came over 5 s after the +// fade, past a camera pan). +UnitTestResult test_walk_ends_on_black_fade(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(250ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(3000ms, {EngineEvent::FADE_BLACK}), + look_at(3250ms), + }, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("03.11", "to_mable")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the walk to end on the black fade: {}", to_string(report.run.failure)); + } + return expect_inputs(backend, { + "wait 250ms", + "press L", "stick -90deg 150ms walk, release 100ms", "press L", "hold north 900ms walk", + "press L", "stick 90deg 150ms walk, release 100ms", "press L", "hold north 1300ms walk", + "press L", "stick 90deg 150ms walk, release 100ms", "press L", + "hold north 250ms walk", + }); +} + +// 03.11's mable_talk (a "talk" scene) on free control with no box or +// choice: control does not end it before her talk shows; the start window +// fails it, with no press (it had passed at once). +UnitTestResult test_talk_scene_needs_the_talk(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(20000ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(46000ms, {EngineEvent::PLAYER_CAN_MOVE}), + }, scope, Pokemon::StoryBackendKind::CONSOLE); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("03.11", "mable_talk")); + if (report.verdict == Pokemon::CheckpointVerdict::PASSED || report.run.failure.failure != "scene_never_started"){ + return std::format("Expected the talk scene to fail as scene_never_started, got {}", to_string(report.run.failure)); + } + return expect_inputs(backend, {"wait 250ms", "wait 250ms"}); +} + +// 03.11's mable_talk: B through her lines, A at her question's top answer, +// done once the party bar holds after the talk. +UnitTestResult test_talk_scene_ends_after_the_talk(CancellableScope& scope){ + FakeBackend backend = fake_plza({ + look_at(0ms, {EngineEvent::DIALOG_BOX}), + look_at(500ms, {EngineEvent::CHOICE_BOX}), + look_at(1000ms, {EngineEvent::DIALOG_BOX}), + look_at(2000ms, {EngineEvent::PLAYER_CAN_MOVE}), + look_at(3000ms, {EngineEvent::PLAYER_CAN_MOVE}), + }, scope, Pokemon::StoryBackendKind::CONSOLE); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("03.11", "mable_talk")); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the talk scene to end in the overworld: {}", to_string(report.run.failure)); + } + return expect_inputs(backend, {"press B", "press A", "press B", "wait 250ms"}); +} + +// What PLZA refuses: console actions fail as console_only off a console, +// and tile walks and unknown actions fail the lint. +UnitTestResult test_refused_steps(CancellableScope& scope){ + StoryCheckpoint legs; + legs.id = "probe"; + StoryStep step; + step.kind = Pokemon::StoryStepKind::LEGS; + step.name = "legs"; + step.args["legs"] = std::vector{{.direction = Pokemon::Direction::NORTH, .tiles = 1}}; + legs.steps.push_back(step); + if (plza_story_lint(legs).empty()){ + return "Expected a tile walk to fail the lint."; + } + FakeBackend backend = fake_plza({look_at(0ms)}, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, step_of("01.00", "confirm")); + if (report.run.failure.failure != "console_only"){ + return std::format("Expected Confirm Choices to need a console, got {}", to_string(report.run.failure)); + } + const std::vector> unknown{ + {Pokemon::StoryStepKind::MASH, "x"}, + {Pokemon::StoryStepKind::GAME, "no_such_move"}, + {Pokemon::StoryStepKind::GAME, "choose_starter"}, + {Pokemon::StoryStepKind::GAME, "choose_2"}, + }; + for (const auto& [kind, action] : unknown){ + StoryCheckpoint probe; + probe.id = "probe"; + StoryStep bad; + bad.kind = kind; + bad.name = "probe"; + bad.action = action; + probe.steps.push_back(bad); + if (plza_story_lint(probe).empty()){ + return std::format("Expected {} \"{}\" to fail the lint.", Pokemon::story_step_kind_name(kind), action); + } + } + return expect_inputs(backend, {}); +} + +// Every checkpoint through the engine with each action recording itself: +// its steps in order, each by its action, and no save while testing. The +// fake says it is a console, so the console_only actions run too. +UnitTestResult test_every_checkpoint_runs(CancellableScope& scope){ + FakeBackend backend = fake_plza({look_at(0ms)}, scope, Pokemon::StoryBackendKind::CONSOLE); + std::vector trace; + Pokemon::StoryGame game; + game.id = "plza"; + for (const Pokemon::StoryActionSpec& spec : plza_story_action_specs()){ + const std::string label = std::format("{}/{}", Pokemon::story_step_kind_name(spec.kind), spec.name); + game.actions.push_back({.spec = spec, .handler = [&trace, label](Pokemon::StoryBackend&, const Pokemon::StoryActionCall&, Pokemon::RunState&){ + trace.push_back(label); + return Pokemon::outcome_ok(); + }}); + } + size_t saves = 0; + game.save = [&saves](Pokemon::StoryBackend&, const StoryCheckpoint&){ + saves++; + return Pokemon::outcome_ok(); + }; + Pokemon::StoryEngine engine(game, backend); + std::vector expected; + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + const Pokemon::StoryActionSpec* spec = Pokemon::find_story_action(plza_story_specs(), step.kind, step.action); + expected.push_back(std::format("{}/{}", Pokemon::story_step_kind_name(step.kind), spec ? spec->name : "?")); + } + Pokemon::RunState state; + const Pokemon::StoryEngineReport report = engine.run_checkpoint(checkpoint, Pokemon::SavePoint::RUN_END, state); + if (report.verdict != Pokemon::CheckpointVerdict::PASSED || report.saved){ + return std::format("{}: expected a pass with no save, got {} ({}).", checkpoint.id, + report.verdict == Pokemon::CheckpointVerdict::PASSED ? "a save" : "a failure", to_string(report.run.failure)); + } + } + if (trace != expected){ + return std::format("Expected {} steps in order, ran {}.", expected.size(), trace.size()); + } + if (saves != 0){ + return std::format("Expected no save from testing checkpoints, saw {}.", saves); + } + return true; +} + + +// A row `id` whose one step is the platform start check (wait_for_platform). +StoryCheckpoint platform_row(std::string id){ + StoryCheckpoint row; + row.id = std::move(id); + row.steps.push_back(StoryStep{ + .kind = Pokemon::StoryStepKind::GAME, .name = "on_platform", .why = "test", .action = "wait_for_platform", + .args = {{"timeout_ms", int64_t(1000)}}, + }); + return row; +} + +// How a run of `ids` (platform rows) went, B reloading when chained. +struct BoundaryRun{ + Pokemon::SegmentReport report; + std::vector lines; + size_t reloads = 0; +}; + +// `ids` through run_plza_segment() with `boundary_reload` over looks with +// the platform on `platform` (by look index; the last look repeats); the +// game's reload counts itself. +BoundaryRun run_boundary( + std::vector ids, std::vector platform, CancellableScope& scope, + StoryRunPolicy::BoundaryReload boundary_reload = StoryRunPolicy::BoundaryReload::AT_PLAN_BOUNDARIES, + std::set> reload_always = {} +){ + std::vector> looks; + for (size_t i = 0; i < platform.size(); i++){ + const Observation look = look_at(Milliseconds(300 * (int64_t)i)); + looks.push_back(platform[i] ? with_reading(look, PLATFORM_READING) : look); + } + FakeBackend backend = fake_plza(std::move(looks), scope); + Pokemon::StoryGame game = make_plza_story_game(StarterChoice::CHIKORITA); + BoundaryRun run; + game.reload = [&run](Pokemon::StoryBackend& backend){ + run.reloads++; + backend.log("[Test] reload"); + return Pokemon::outcome_ok(); + }; + StoryData story; + story.reload_when_chained = {"B"}; + story.reload_always = std::move(reload_always); + std::vector rows; + for (std::string& id : ids){ + rows.push_back(platform_row(std::move(id))); + } + Pokemon::StoryEngine engine(game, backend); + Pokemon::RunState state; + run.report = run_plza_segment(game, story, rows, {.boundary_reload = boundary_reload}, engine, backend, state); + run.lines = backend.lines(); + return run; +} + +// The index of the first line of `lines` that holds `text`; the size when +// none does. +size_t line_index(const std::vector& lines, std::string_view text){ + return std::find_if(lines.begin(), lines.end(), [text](const std::string& line){ + return line.find(text) != std::string::npos; + }) - lines.begin(); +} + +// Run straight after A, B starts with the reload, logged as its own event +// between A's pass and B's start; then no platform on the looks after it. +UnitTestResult test_reload_when_chained(CancellableScope& scope){ + const BoundaryRun run = run_boundary({"A", "B"}, {true, true, false, false, false, false, true, true}, scope); + if (!run.report.completed || run.reloads != 1){ + return std::format("Expected A and B with one reload, got {} reloads: {}", run.reloads, joined(run.lines)); + } + const size_t a_passed = line_index(run.lines, "[Checkpoint] A: passed"); + const size_t reload = line_index(run.lines, "[Event] B/0 reload_at_boundary: start"); + const size_t reloaded = line_index(run.lines, "[Test] reload"); + const size_t done = line_index(run.lines, "[Event] B/0 reload_at_boundary: done"); + const size_t b_start = line_index(run.lines, "[Checkpoint] B: start"); + if (!(a_passed < reload && reload < reloaded && reloaded < done && done < b_start && b_start < run.lines.size())){ + return std::format("Expected A, the reload event, then B: {}", joined(run.lines)); + } + if (run.report.runs.size() != 2 || run.report.checkpoints_run != 2){ + return std::format("Expected both rows in one report, got {} runs.", run.report.runs.size()); + } + return true; +} + +// A run that starts at B (from B's save), or a row with no +// reload_when_chained after A, has no reload. +UnitTestResult test_no_reload_unless_chained(CancellableScope& scope){ + for (const std::vector& ids : {std::vector{"B"}, std::vector{"A", "C"}}){ + const BoundaryRun run = run_boundary(ids, {true}, scope); + if (!run.report.completed || run.reloads != 0 || line_index(run.lines, "reload_at_boundary") != run.lines.size()){ + return std::format("Expected no reload for {}: {}", joined(ids), joined(run.lines)); + } + } + return true; +} + +// Run straight through, a row that always reloads still reloads after the +// row before. +UnitTestResult test_straight_through_reloads_always(CancellableScope& scope){ + const BoundaryRun run = run_boundary( + {"A", "B"}, {true, true, false, false, false, false, true, true}, scope, + StoryRunPolicy::BoundaryReload::STRAIGHT_THROUGH, {"B"} + ); + if (!run.report.completed || run.reloads != 1){ + return std::format("Expected A and B with one reload, got {} reloads: {}", run.reloads, joined(run.lines)); + } + return true; +} + +// Run straight through, B runs on after A with no reload, though it is in +// reload_when_chained; both rows run in one segment. +UnitTestResult test_straight_through_has_no_reload(CancellableScope& scope){ + const BoundaryRun run = run_boundary({"A", "B", "C"}, {true}, scope, StoryRunPolicy::BoundaryReload::STRAIGHT_THROUGH); + if (!run.report.completed || run.reloads != 0 || line_index(run.lines, "reload_at_boundary") != run.lines.size()){ + return std::format("Expected A, B and C with no reload, got {} reloads: {}", run.reloads, joined(run.lines)); + } + if (run.report.runs.size() != 3 || run.report.checkpoints_run != 3){ + return std::format("Expected all three rows in one report, got {} runs.", run.report.runs.size()); + } + return true; +} + +// A reload that lands on the station platform loaded an older save: the +// run fails at the boundary, before any step of B. +UnitTestResult test_reload_lands_on_older_save(CancellableScope& scope){ + const BoundaryRun run = run_boundary({"A", "B"}, {true}, scope); + if (run.report.completed || run.report.failed_checkpoint != "B" || run.report.failed_event != "reload_at_boundary"){ + return std::format("Expected a failure at B's reload: {}", joined(run.lines)); + } + if (to_string(run.report.failure).find("did not land at B's start") == std::string::npos){ + return std::format("Expected the failure to say where it did not land: {}", to_string(run.report.failure)); + } + if (line_index(run.lines, "[Checkpoint] B: start") != run.lines.size()){ + return "Expected no step of B after the failed reload."; + } + return true; +} + + +// A walk_to_prompt step alone in a checkpoint. +StoryCheckpoint prompt_walk_row(){ + StoryCheckpoint row; + row.id = "02.02"; + row.steps.push_back(StoryStep{ + .kind = Pokemon::StoryStepKind::GAME, .name = "to_battle_zone_gate", .why = "test", .action = "walk_to_prompt", + .args = {{"timeout_ms", int64_t(1000)}}, + }); + return row; +} + +// walk_to_prompt: no walk when the A prompt shows already; slices of walk +// until it shows; a failure after its timeout without one. +UnitTestResult test_walk_to_prompt(CancellableScope& scope){ + const auto prompt = [](Milliseconds at){ + return look_at(at, {EngineEvent::INTERACT_PROMPT}); + }; + const std::string slice = "hold north 250ms walk"; + { + FakeBackend backend = fake_plza({prompt(0ms)}, scope); + if (run_plza(backend, prompt_walk_row()).verdict != Pokemon::CheckpointVerdict::PASSED || !backend.inputs().empty()){ + return std::format("At the prompt: expected no walk, got [{}].", joined(backend.inputs())); + } + } + { + FakeBackend backend = fake_plza({look_at(0ms), look_at(250ms), prompt(500ms)}, scope); + if (run_plza(backend, prompt_walk_row()).verdict != Pokemon::CheckpointVerdict::PASSED){ + return "Expected a pass once the prompt shows."; + } + UnitTestResult inputs = expect_inputs(backend, {slice, slice}); + if (inputs.result != UnitTestResult::PASSED){ + return inputs; + } + } + FakeBackend backend = fake_plza({look_at(0ms)}, scope); + const Pokemon::StoryEngineReport report = run_plza(backend, prompt_walk_row()); + if (report.verdict == Pokemon::CheckpointVerdict::PASSED || to_string(report.run.failure).find("no A prompt") == std::string::npos){ + return std::format("Expected no_prompt after the timeout: {}", to_string(report.run.failure)); + } + return expect_inputs(backend, std::vector(4, slice)); +} + + +// Breakpoints on legs: the walk pauses before each of its legs, after the +// step's own pause, each labelled with the leg's turn and walk. +UnitTestResult test_walk_pauses_before_each_leg(CancellableScope& scope){ + std::vector pauses; + Pokemon::StoryGame game = make_plza_story_game(StarterChoice::CHIKORITA); + game.breakpoints = Pokemon::StoryBreakpoints::LEGS; + game.pause_point = [&pauses](std::string_view label){ + pauses.emplace_back(label); + }; + const std::vector legs{{.turn = 0, .ms = 500}, {.turn = 90, .ms = 0}}; + StoryCheckpoint row; + row.id = "01.01"; + row.steps.push_back(StoryStep{.kind = Pokemon::StoryStepKind::GAME, .name = "chase", .why = "test", .action = "walk"}); + row.steps.back().args["legs"] = legs; + FakeBackend backend = fake_plza({look_at(0ms)}, scope); + Pokemon::StoryEngine engine(game, backend); + Pokemon::RunState state; + if (engine.run_checkpoint(row, Pokemon::SavePoint::RUN_END, state).verdict != Pokemon::CheckpointVerdict::PASSED){ + return std::format("Expected the walk to pass: {}", joined(backend.lines())); + } + const std::vector expected{ + "01.01/1 chase", "01.01/1 chase leg 1/2 turn 0 walk 500 ms", "01.01/1 chase leg 2/2 turn 90", + }; + if (pauses != expected){ + return std::format("Expected pauses [{}], got [{}].", joined(expected), joined(pauses)); + } + return true; +} + + +// The inputs of `backend` that start with `kind` ("hold", "press A"). +size_t count_inputs(const FakeBackend& backend, std::string_view kind){ + return (size_t)std::ranges::count_if(backend.inputs(), [kind](const std::string& input){ return input.starts_with(kind); }); +} + +// A walk's leg is played once more when the screen stays still after it +// (the game dropped the hold), and once when it moves. +UnitTestResult test_walk_plays_still_leg_again(CancellableScope& scope){ + StoryCheckpoint row; + row.id = "03.06"; + row.steps.push_back(StoryStep{.kind = Pokemon::StoryStepKind::GAME, .name = "center_to_zone_1", .why = "test", .action = "walk"}); + row.steps.back().args["legs"] = std::vector{{.turn = 0, .ms = 2000}}; + { + FakeBackend backend = fake_plza({look_at(0ms)}, scope); + if (run_plza(backend, row).verdict != Pokemon::CheckpointVerdict::PASSED || count_inputs(backend, "hold") != 1){ + return std::format("Moving: expected one hold, got [{}].", joined(backend.inputs())); + } + } + FakeBackend backend = fake_plza({look_at(0ms, {EngineEvent::SCREEN_STILL})}, scope); + if (run_plza(backend, row).verdict != Pokemon::CheckpointVerdict::PASSED || count_inputs(backend, "hold") != 2){ + return std::format("Still: expected two holds, got [{}].", joined(backend.inputs())); + } + return true; +} + +// A gate's "A Enter" alone in a checkpoint (mash_to_move_hints with +// press_a_first). +StoryCheckpoint enter_gate_row(){ + StoryCheckpoint row; + row.id = "03.06"; + row.steps.push_back(StoryStep{ + .kind = Pokemon::StoryStepKind::GAME, .name = "enter_zone_1", .why = "test", .action = "mash_to_move_hints", + .args = {{"press_a_first", true}}, + }); + return row; +} + +// Looks every 250 ms over each span: [from, to), with its events. +struct LookSpan{ + Milliseconds from; + Milliseconds to; + std::initializer_list events; +}; +std::vector> looks_over(std::initializer_list spans){ + std::vector> looks; + for (const LookSpan& span : spans){ + for (Milliseconds at = span.from; at < span.to; at += 250ms){ + looks.push_back(look_at(at, span.events)); + } + } + return looks; +} + +// press_a_first: the party bar under a gone prompt is not control before +// the gate's late fade (2 s after the A): the step waits the fade out. +UnitTestResult test_prompt_waits_for_late_fade(CancellableScope& scope){ + FakeBackend backend = fake_plza(looks_over({ + {0ms, 2000ms, {EngineEvent::PLAYER_CAN_MOVE}}, {2000ms, 3000ms, {EngineEvent::FADE_BLACK}}, + {3000ms, 6000ms, {EngineEvent::PLAYER_CAN_MOVE}}, + }), scope); + if (run_plza(backend, enter_gate_row()).verdict != Pokemon::CheckpointVerdict::PASSED || count_inputs(backend, "press A") != 1){ + return std::format("Expected a pass on one A, got [{}]: {}", joined(backend.inputs()), joined(backend.lines())); + } + if (line_index(backend.lines(), "mash_to_move_hints] fade_black") == backend.lines().size()){ + return std::format("Expected the step to wait the fade out: {}", joined(backend.lines())); + } + return true; +} + +// press_a_first: A again when the prompt stays with no fade (a dropped A). +UnitTestResult test_prompt_pressed_again_when_it_stays(CancellableScope& scope){ + FakeBackend backend = fake_plza(looks_over({ + {0ms, 3000ms, {EngineEvent::PLAYER_CAN_MOVE, EngineEvent::INTERACT_PROMPT}}, + {3000ms, 4000ms, {EngineEvent::FADE_BLACK}}, {4000ms, 7000ms, {EngineEvent::PLAYER_CAN_MOVE}}, + }), scope); + if (run_plza(backend, enter_gate_row()).verdict != Pokemon::CheckpointVerdict::PASSED || count_inputs(backend, "press A") != 2){ + return std::format("Expected a pass on two A, got [{}]: {}", joined(backend.inputs()), joined(backend.lines())); + } + return true; +} + +struct EngineTestCase{ + std::string name; + struct Input{ + std::function body; + }; + Input input; + // What each body checks is in its own code: these cases are functions. + struct Expectation{ + }; + Expectation expectation; +}; + +class Test_AutoStoryEngine : public UnitTest{ +public: + explicit Test_AutoStoryEngine(EngineTestCase test_case) + : UnitTest(std::format("PokemonLZA::AutoStoryEngine - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + try{ + return m_case.input.body(scope); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + } + } + +private: + EngineTestCase m_case; +}; + +} // namespace + + +const EngineTestCase ENGINE_TEST_CASES[] = { + {.name = "01.00 opening: no presses, done on two looks at the platform after the autosave", .input = {.body = test_opening_waits_for_platform}, .expectation = {}}, + {.name = "01.00 opening: one A at the arrival text with the advance arrow", .input = {.body = test_opening_presses_through_arrival_text}, .expectation = {}}, + {.name = "01.01 start check: fails without the platform", .input = {.body = test_start_check_needs_platform}, .expectation = {}}, + {.name = "01.01 text_to_choice: B through the text, done at the choice", .input = {.body = test_text_to_choice}, .expectation = {}}, + {.name = "01.01 arrival_scenes: A through text and choice, done on the controls hint", .input = {.body = test_arrival_ends_on_controls_hint}, .expectation = {}}, + {.name = "01.01 arrival_scenes: A through the ad's boxless subtitles", .input = {.body = test_arrival_presses_through_the_ad}, .expectation = {}}, + {.name = "01.01 arrival_scenes: done on the mission banner once it has gone, A if it stays", .input = {.body = test_arrival_ends_on_mission_banner}, .expectation = {}}, + {.name = "01.03 after_andi: A at the mission complete card, then the banner, A if it stays", .input = {.body = test_after_andi_presses_complete_card}, .expectation = {}}, + {.name = "01.01 arrival_scenes: a quiet minute without the hint fails", .input = {.body = test_arrival_quiet_fails}, .expectation = {}}, + {.name = "02.02 street_scene: A at boxes and cards, done once the party bar holds", .input = {.body = test_scene_step_presses_to_overworld}, .expectation = {}}, + {.name = "02.02 street_scene: no box in the start window fails", .input = {.body = test_scene_step_never_started}, .expectation = {}}, + {.name = "01.02 battle_area: done on the \"A: Talk\" prompt", .input = {.body = test_battle_area_ends_on_interact_prompt}, .expectation = {}}, + {.name = "02.01 battle_zone_to_brigitte: a held walk waits, then holds each leg's angle", .input = {.body = test_held_walk_inputs}, .expectation = {}}, + {.name = "face_heading: turns by the minimap's heading", .input = {.body = test_face_heading}, .expectation = {}}, + {.name = "01.01 platform_to_plaza: no walk without free control", .input = {.body = test_walk_needs_free_control}, .expectation = {}}, + {.name = "01.01 platform_to_plaza: ends on the white fade", .input = {.body = test_walk_ends_on_white_fade}, .expectation = {}}, + {.name = "01.01 platform_to_plaza: fails at its bound", .input = {.body = test_walk_fails_at_bound}, .expectation = {}}, + {.name = "refused: console actions off a console, tile walks, unknown actions", .input = {.body = test_refused_steps}, .expectation = {}}, + {.name = "every checkpoint runs in step order, testing never saves", .input = {.body = test_every_checkpoint_runs}, .expectation = {}}, + {.name = "reload_when_chained: reload between the rows, as its own event", .input = {.body = test_reload_when_chained}, .expectation = {}}, + {.name = "reload_when_chained: no reload from the row's save or for other rows", .input = {.body = test_no_reload_unless_chained}, .expectation = {}}, + {.name = "reload_when_chained: a reload onto the platform fails", .input = {.body = test_reload_lands_on_older_save}, .expectation = {}}, + {.name = "reload_when_chained: straight through, no reload at a boundary", .input = {.body = test_straight_through_has_no_reload}, .expectation = {}}, + {.name = "reload_when_chained: \"always\" reloads straight through too", .input = {.body = test_straight_through_reloads_always}, .expectation = {}}, + {.name = "walk_to_prompt: walks until the A prompt, none when it shows", .input = {.body = test_walk_to_prompt}, .expectation = {}}, + {.name = "breakpoints: a walk pauses before each leg", .input = {.body = test_walk_pauses_before_each_leg}, .expectation = {}}, + {.name = "walk: a leg the screen stays still after is played once more", .input = {.body = test_walk_plays_still_leg_again}, .expectation = {}}, + {.name = "press_a_first: waits out a late fade, not done on the party bar", .input = {.body = test_prompt_waits_for_late_fade}, .expectation = {}}, + {.name = "press_a_first: A again while the prompt stays with no fade", .input = {.body = test_prompt_pressed_again_when_it_stays}, .expectation = {}}, + {.name = "03.10 to_lab_elevator: one look once the legs are in", .input = {.body = test_walk_looks_after_its_legs}, .expectation = {}}, + {.name = "03.11 to_mable: the last leg held until Mable's dialog box", .input = {.body = test_walk_ends_in_mables_talk}, .expectation = {}}, + {.name = "03.11 to_mable: a black fade in the last leg ends the walk", .input = {.body = test_walk_ends_on_black_fade}, .expectation = {}}, + {.name = "03.11 mable_talk: free control before her talk fails at the start window", .input = {.body = test_talk_scene_needs_the_talk}, .expectation = {}}, + {.name = "03.11 mable_talk: B through her lines, A at her question, done on control", .input = {.body = test_talk_scene_ends_after_the_talk}, .expectation = {}}, +}; + + +namespace{ + +// plza_title(): which looks after the launch take the title's A. +struct LaunchTitleCase{ + std::string name; + struct Input{ + std::vector events; + }; + Input input; + struct Expectation{ + bool title; + }; + Expectation expectation; +}; + +const LaunchTitleCase LAUNCH_TITLE_CASES[] = { + // The title's centred "PRESS (A) BUTTON" reads + // as an A prompt; the launch waited on it. + {.name = "PRESS (A) BUTTON read as an A prompt", .input = {.events = {EngineEvent::INTERACT_PROMPT}}, .expectation = {.title = true}}, + {.name = "a plain screen", .input = {.events = {}}, .expectation = {.title = true}}, + {.name = "an A prompt on the overworld", .input = {.events = {EngineEvent::INTERACT_PROMPT, EngineEvent::PLAYER_CAN_MOVE}}, .expectation = {.title = false}}, + {.name = "the overworld", .input = {.events = {EngineEvent::PLAYER_CAN_MOVE}}, .expectation = {.title = false}}, + {.name = "a black fade", .input = {.events = {EngineEvent::FADE_BLACK}}, .expectation = {.title = false}}, + {.name = "a battle", .input = {.events = {EngineEvent::BATTLE_STARTED}}, .expectation = {.title = false}}, +}; + +class Test_LaunchTitle : public UnitTest{ +public: + explicit Test_LaunchTitle(const LaunchTitleCase& test_case) + : UnitTest(std::format("PokemonLZA::AutoStoryEngine - launch title: {}", test_case.name)) + , m_case(test_case) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + ScreenObservation look; + for (EngineEvent event : m_case.input.events){ + look.events.set(event, true); + } + look.frame = VideoSnapshot(ImageRGB32(16, 9), current_time()); + if (plza_title(look) != m_case.expectation.title){ + return std::format("Expected title = {}.", m_case.expectation.title); + } + return true; + } + +private: + const LaunchTitleCase& m_case; +}; + +} // namespace + +void add_tests_AutoStoryEngine(UnitTestDatabase& database){ + for (const EngineTestCase& item : ENGINE_TEST_CASES){ + database.add(item); + } + for (const LaunchTitleCase& item : LAUNCH_TITLE_CASES){ + database.add(item); + } +} + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.h new file mode 100644 index 0000000000..aeb7bc7e75 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.h @@ -0,0 +1,26 @@ +/* PokemonLZA AutoStory - Engine Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLZA_AutoStoryEngine_Tests_H +#define PokemonAutomation_PokemonLZA_AutoStoryEngine_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + + +// PLZA's checkpoints and the new game's scene steps on the shared story engine, +// with a scripted backend: no console. +void add_tests_AutoStoryEngine(UnitTestDatabase& database); + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp new file mode 100644 index 0000000000..8d413dd121 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp @@ -0,0 +1,984 @@ +/* PokemonLZA AutoStory - Story game + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.h" +#include "VideoGames/PokemonLZA/Resources/PokemonLZA_Locations.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryActions.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryCatches.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryConfirmChoices.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryDialogs.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryMarkerWalks.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryMoves.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryScenes.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryWalkScreenChecks.h" +#include "PokemonLZA_AutoStoryLaunch.h" +#include "PokemonLZA_AutoStorySceneMachine.h" +#include "PokemonLZA_AutoStoryStepValidator.h" +#include "PokemonLZA_AutoStoryGame.h" +#include "PokemonLZA_AutoStoryFailures.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + +using namespace std::chrono_literals; +using Pokemon::Outcome; +using Pokemon::StoryActionArgs; +using Pokemon::StoryActionCall; +using Pokemon::StoryActionSpec; +using Pokemon::StoryArgSpec; +using Pokemon::StoryArgType; +using Pokemon::StoryStepKind; +using Pokemon::ZonePose; +using Handler = Pokemon::StoryActionHandler; + + +const std::map>& story_actions_not_implemented(){ + static const std::map> todos{ + }; + return todos; +} + + +namespace{ + +using TimedLegs = std::vector; + +// What a console action does with the run's console and the step's args. +using ConsoleBody = std::function; + +// A GAME action that only presses through the game's own screens: one +// call on the console, with no args. +using ConsoleStep = void (*)(StoryEnv& env); + +// The game onto `save` by the shared launch (start_launch_request()): +// closed and launched again from HOME, or for StartSave::RUNNING kept as +// it runs; fails as Pokemon::STORY_LAUNCH_FAILED. +Outcome reload_save(StoryEnv& env, Pokemon::StoryBackend& backend, StartSave save){ + return Pokemon::launch_story_game(backend, plza_launch_policy(env.env.console), start_launch_request(save)); +} + +// The GAME actions that are one ConsoleStep each, by name: console_only. +const std::map>& console_game_actions(){ + static const std::map> actions{ + {"confirm_new_game", [](StoryEnv& env){ confirm_new_game_choices(env.env.console, env.context); }}, + {"choose_0", [](StoryEnv& env){ choose_dialog_option(env.env.console, env.context, 0); }}, + {"choose_1", [](StoryEnv& env){ choose_dialog_option(env.env.console, env.context, 1); }}, + {"story_battle", [](StoryEnv& env){ + fight_battle_in_progress(env.env, env.env.console, env.context, env.battle_ai, 120s); + }}, + {"talk_through_map_screen", [](StoryEnv& env){ talk_through_map_screen(env.env.console, env.context); }}, + {"climb_ladder", [](StoryEnv& env){ climb_ladder(env.env.console, env.context); }}, + {"catch_tutorial", [](StoryEnv& env){ catch_tutorial(env.env, env.env.console, env.context, env.battle_ai, 6); }}, + {"battle_then_catch", [](StoryEnv& env){ + battle_then_catch(env.env, env.env.console, env.context, env.battle_ai, 6); + }}, + // 03.08: 3 species after the tutorial, 2 more for the Research Lab gate's 5. + {"catch_in_zone", [](StoryEnv& env){ + catch_in_zone(env.env, env.env.console, env.context, env.battle_ai, ZoneCatchGoal{ + .new_species = 2, .dex_species = 5, .max_throws = 12, .checks = env.checks + }); + }}, + {"walk_to_marker", [](StoryEnv& env){ walk_to_marker(env.env.console, env.context); }}, + {"walk_back_to_zone_road", [](StoryEnv& env){ walk_back_to_zone_road(env.env.console, env.context); }}, + {"fly_to_center_or_stay", [](StoryEnv& env){ fly_to_or_stay(env.env.console, env.context, env.language, Location::VERT_POKEMON_CENTER); }}, + {"check_out_of_wild_zone", [](StoryEnv& env){ check_out_of_wild_zone(env.env.console, env.context); }}, + {"claim_mable_research_reward", [](StoryEnv& env){ claim_mable_research_reward(env.env.console, env.context); }}, + }; + return actions; +} + +// The built-in action of `kind` named `name`: a replacement keeps its args. +StoryActionSpec builtin_spec(StoryStepKind kind, std::string name){ + const StoryActionSpec* spec = Pokemon::find_story_action(Pokemon::builtin_story_actions(), kind, name); + if (spec != nullptr){ + return *spec; + } + return StoryActionSpec{.kind = kind, .name = std::move(name), .args = {}}; +} + +// `spec`, run only on a console. +StoryActionSpec console_only(StoryActionSpec spec){ + spec.console_only = true; + return spec; +} + +StoryActionSpec game_spec(std::string name, std::vector args = {}){ + return StoryActionSpec{.kind = StoryStepKind::GAME, .name = std::move(name), .args = std::move(args)}; +} + +StoryArgSpec optional_ms(std::string key, int64_t fallback, std::string why){ + return StoryArgSpec{.key = std::move(key), .type = StoryArgType::INTEGER, .required = false, .fallback = fallback, .why = std::move(why)}; +} + +StoryArgSpec legs_arg(std::string key, bool required, std::string why){ + return StoryArgSpec{.key = std::move(key), .type = StoryArgType::TIMED_LEGS, .required = required, .fallback = std::nullopt, .why = std::move(why)}; +} + +// "walk_to_zone_gate_entrance": the heading it faces first, its bound. +StoryActionSpec gate_walk_spec(){ + return game_spec("walk_to_zone_gate_entrance", { + StoryArgSpec{ + .key = "heading", .type = StoryArgType::INTEGER, .required = false, .fallback = std::nullopt, + .why = "the compass heading along the street to the gate, faced first, clockwise from north", + }, + optional_ms("timeout_ms", 15000, "walking this long with no A prompt fails the step"), + }); +} + +// "walk": its legs, the fade it ends on, the heading it faces first. +StoryActionSpec walk_spec(){ + return game_spec("walk", { + legs_arg("legs", true, "the legs: [turn in degrees, clockwise (negative: left), walk ms] each"), + StoryArgSpec{ + .key = "end", .type = StoryArgType::WORD, .required = false, .fallback = std::nullopt, + .why = "\"fade_white\", \"fade_black\" or \"dialog\": the last leg is held until it shows, its ms the bound", + }, + StoryArgSpec{ + .key = "heading", .type = StoryArgType::INTEGER, .required = false, .fallback = std::nullopt, + .why = "the compass heading to face first, clockwise from north", + }, + StoryArgSpec{ + .key = "held", .type = StoryArgType::BOOLEAN, .required = false, .fallback = false, + .why = "hold the stick at each leg's angle (L only before a later turning leg), not tap-and-forward", + }, + StoryArgSpec{ + .key = "wait_ms", .type = StoryArgType::INTEGER, .required = false, .fallback = std::nullopt, + .why = "wait this long before looking for free control: NPCs moving off, a ride's fade starting", + }, + }); +} + +// "approach_starter": the walk to each starter, by the starter's key. +StoryActionSpec approach_starter_spec(){ + std::vector args; + for (StarterChoice starter : STARTER_CHOICES){ + args.push_back(legs_arg(std::string(starter_key(starter)), false, "the walk to this starter, as a walk's legs")); + } + return game_spec("approach_starter", std::move(args)); +} + + + +// `move`, once the screen shows free control; held until the event of +// `call`'s "end" arg, if it names one, else finished with one look +// (finish_walk()). Each leg is a breakpoint. +Outcome walk_legs( + Pokemon::StoryBackend& backend, const StoryActionCall& call, const StoryMove& move, + const PlzaReader& heading +){ + const std::string_view name = call.step.name; + const StoryActionArgs& args = call.args; + if (move.wait_first > Milliseconds(0)){ + backend.wait(move.wait_first); + } + const Outcome free = check_can_walk(backend, name); + if (!free.succeeded()){ + return free; + } + const auto end = args.find("end"); + std::optional end_event; + if (end != args.end()){ + end_event = walk_end_event(std::get(end->second)); + } + if (end_event){ + return walk_until(backend, name, move, heading, *end_event, &call.pause); + } + const Outcome walked = run_story_move(backend, move, heading, &call.pause); + if (walked.succeeded()){ + finish_walk(backend, name); + } + return walked; +} + +// A walk's body, with the run's compass reader for the heading it faces. +using HeadingBody = Outcome (*)(Pokemon::StoryBackend& backend, const StoryActionCall& call, const PlzaReader& heading); + +// "walk": its args' legs, walked once the screen shows free control, +// until its end event if it has one. +Outcome walk_step(Pokemon::StoryBackend& backend, const StoryActionCall& call, const PlzaReader& heading){ + return walk_legs(backend, call, story_walk_move(call.args, "legs"), heading); +} + +// "walk_to_zone_gate_entrance": its args' heading faced first, if any, +// then the walk steered by the gate on screen to its A prompt. +Outcome gate_walk_step(Pokemon::StoryBackend& backend, const StoryActionCall& call, const PlzaReader& heading){ + GateWalk walk; + walk.timeout = Milliseconds(Pokemon::story_arg(call.args, "timeout_ms")); + const auto facing = call.args.find("heading"); + if (facing != call.args.end()){ + walk.heading = (double)std::get(facing->second); + } + return walk_to_zone_gate_entrance(backend, heading, zone_gate_reader(), walk); +} + +// After A at a gate's or door's prompt: how long a fade or text may take +// to show (the sweep's late fade starts 1.8 s after the A), how often it +// is looked for, and how many times A is pressed while the prompt stays +// with neither (a dropped A). +constexpr Milliseconds PROMPT_TAKEN_WAIT(3000); +constexpr Milliseconds PROMPT_POLL(250); +constexpr size_t PROMPT_PRESSES = 3; + +// Whether `look` shows that A at a prompt was taken: a fade, or text. +bool prompt_taken(const Pokemon::Observation& look){ + using PokemonAutomation::ScreenEvent; + return look.events.has(ScreenEvent::FADE_BLACK) || look.events.has(ScreenEvent::FADE_WHITE) || + look.events.has(ScreenEvent::DIALOG_BOX) || look.events.has(ScreenEvent::CHOICE_BOX); +} + +// A at the A prompt the player stands at, then looks for up to +// PROMPT_TAKEN_WAIT until a fade or text shows; while the prompt stays +// with neither, A again, PROMPT_PRESSES times at most. The party bar +// shows under the prompt, so the scene machine +// that follows would take it for control before a late fade. A prompt +// gone with no fade or text is left to the scene machine, as is one +// still up after the last A. +void press_through_prompt(Pokemon::StoryBackend& backend){ + for (size_t press = 1; press <= PROMPT_PRESSES; press++){ + backend.press(BUTTON_A, 160ms, 400ms); + bool prompt = true; + for (Milliseconds waited(0); waited < PROMPT_TAKEN_WAIT; waited += PROMPT_POLL){ + backend.scope().throw_if_cancelled(); + const Pokemon::Observation look = backend.observe(); + if (prompt_taken(look)){ + return; + } + prompt = look.events.has(PokemonAutomation::ScreenEvent::INTERACT_PROMPT); + backend.wait(PROMPT_POLL); + } + if (!prompt){ + backend.log(std::format("[PLZA] mash_to_move_hints: the prompt went with no fade in {} ms", PROMPT_TAKEN_WAIT.count())); + return; + } + backend.log(std::format("[PLZA] mash_to_move_hints: the prompt is still up {} ms after A {}", PROMPT_TAKEN_WAIT.count(), press)); + } +} + +// Builds the handlers. The console actions hold the console; without one +// (a test, a simulation) their specs are console_only and the engine +// refuses them before their handler. +class PlzaHandlers{ +public: + PlzaHandlers(StoryEnv* env, StarterChoice starter) + : m_env(env) + , m_starter(starter) + { + if (m_env != nullptr){ + m_heading = heading_reader(*m_env); + } + } + + // `body` on the console. A console step that fails becomes a failed + // Outcome, so the run can reload; an action that is not implemented + // ends the run. + Handler console(std::string name, ConsoleBody body) const{ + if (m_env == nullptr){ + return [name = std::move(name)](Pokemon::StoryBackend&, const StoryActionCall&, Pokemon::RunState&){ + return Pokemon::outcome_failed(std::string(Pokemon::CONSOLE_ONLY), std::format("{} runs only on a console", name)); + }; + } + StoryEnv& env = *m_env; + return [&env, name = std::move(name), body = std::move(body)]( + Pokemon::StoryBackend& backend, const StoryActionCall& call, Pokemon::RunState& + ){ + try{ + body(env, call.args); + }catch (Pokemon::StoryActionNotImplemented&){ + throw; + }catch (OperationFailedException& e){ + backend.log(std::format("[PLZA] {} failed: {}", name, e.message())); + return plza_failed(std::string(console_step_failure(name)), e.message()); + } + return Pokemon::outcome_ok(); + }; + } + + // `body` with the run's compass reader (heading_reader()). + Handler with_heading(HeadingBody body) const{ + return [heading = m_heading, body](Pokemon::StoryBackend& backend, const StoryActionCall& call, Pokemon::RunState&){ + return body(backend, call, heading); + }; + } + + // "approach_starter": the walk to the run's starter, from the arg of + // its name. A starter with no walk is not implemented. + Handler approach_starter() const{ + return [heading = m_heading, starter = m_starter]( + Pokemon::StoryBackend& backend, const StoryActionCall& call, Pokemon::RunState& state + ){ + const std::string_view key = starter_key(starter); + if (!call.args.contains(key)){ + return not_implemented("approach_starter", std::format( + "the walk to {}: only Chikorita's was recorded.", key + ))(backend, call, state); + } + return walk_legs(backend, call, story_walk_move(call.args, key), heading); + }; + } + + // "load_backup_save", for reruns: the title screen's Up + + // B + X loads the save before the last one, as a catch's autosave moves + // the save past a checkpoint's start (03.08). + Handler load_backup_save() const{ + if (m_env == nullptr){ + return console("load_backup_save", {}); + } + StoryEnv& env = *m_env; + return [&env](Pokemon::StoryBackend& backend, const StoryActionCall&, Pokemon::RunState&){ + return reload_save(env, backend, StartSave::BACKUP); + }; + } + + static Handler not_implemented(std::string name, std::string todo){ + return [name = std::move(name), todo = std::move(todo)]( + Pokemon::StoryBackend& backend, const StoryActionCall&, Pokemon::RunState& + ) -> Outcome{ + const std::string message = std::format("PLZA AutoStory: {} is not implemented yet. TODO: {}", name, todo); + backend.log(message); + throw Pokemon::StoryActionNotImplemented(message); + }; + } + + // "mash_to_move_hints": A through the scenes (a choice takes its top + // row, the advance chevron its text) until the player has control: the + // controls hint or the party bar held a second, or a main mission's + // banner on two looks (01.01's arrival ends on "MAIN MISSION 01"; the + // step returns once it has gone, 10 s at most). 01.01's arrival takes + // ~240 s on the console, hence 360 s. A text-free cutscene + // (01.01's city flyover, ~20 s) is not control: nothing busy for the + // quiet time fails the step. After 5 s with nothing busy and no sign + // of control, A every 2 s, for text the detectors miss (01.01's ad). + // A banner that stays past the 10 s gets A up to 3 times (01.03's + // "MAIN MISSION 02"), so the step ends with control. "press_a_first" + // presses A at a prompt (02.03's Hotel Z door, "A Enter"), which + // would otherwise end the step at once as control, and waits for its + // fade or text (press_through_prompt()). "quiet_is_control" + // ends it on the quiet time instead of failing, inside Hotel Z. + static Handler move_hints(){ + return [](Pokemon::StoryBackend& backend, const StoryActionCall& call, Pokemon::RunState&){ + if (Pokemon::story_arg(call.args, "press_a_first")){ + press_through_prompt(backend); + } + SceneMachineConfig config; + config.quiet = Milliseconds(Pokemon::story_arg(call.args, "quiet_ms")); + config.min_length = Milliseconds(Pokemon::story_arg(call.args, "min_length_ms")); + config.quiet_is_control = Pokemon::story_arg(call.args, "quiet_is_control"); + config.blind_press_after = 5s; + return run_scene_machine(backend, "mash_to_move_hints", config, 360s); + }; + } + + // B advances text by default. "advance_with_a" is for a talk that B + // cancels: Hotel Z's elevator closes on B before "Which floor?" + // (02.05). + static Handler text_to_choice(){ + return [](Pokemon::StoryBackend& backend, const StoryActionCall& call, Pokemon::RunState&){ + SceneMachineConfig config; + config.goal = SceneMashGoal::CHOICE; + config.text_button = Pokemon::story_arg(call.args, "advance_with_a") ? BUTTON_A : BUTTON_B; + return run_scene_machine(backend, "text_to_choice", config, 60s); + }; + } + +private: + StoryEnv* m_env; + StarterChoice m_starter; + // The compass for the walks; none without a console, where a look + // carries its own heading. + PlzaReader m_heading; +}; + +// What a platform wait needs before the platform counts. +enum class PlatformWait{ + PLATFORM_ONLY, // "wait_for_platform": a start check + AFTER_AUTOSAVE, // "opening_to_platform": the autosave badge first +}; + +// Looks every PLATFORM_POLL: the autosave badge shows for 1-3 s, +// so at least 2 looks a second. +constexpr Milliseconds PLATFORM_POLL(300); +constexpr size_t PLATFORM_LOOKS = 2; + +// One platform wait's progress over its looks. +struct PlatformProgress{ + bool autosave_seen = false; + bool skip_prompt = false; + size_t streak = 0; + // The text with the advance arrow was on the last look. + bool text_waiting = false; +}; + +// Takes `look` into `progress`; logs the skip prompt and the autosave +// when they show. True once the platform has held PLATFORM_LOOKS looks. +bool platform_look(Pokemon::StoryBackend& backend, const ScreenObservation& look, PlatformWait wait, PlatformProgress& progress){ + const bool skip_now = look.readings.contains(SKIP_PROMPT_READING); + if (skip_now && !progress.skip_prompt){ + backend.log("[PLZA] platform wait: the skip prompt is on screen"); + } + progress.skip_prompt = skip_now; + if (look.readings.contains(AUTOSAVE_READING)){ + if (!progress.autosave_seen){ + backend.log("[PLZA] platform wait: the autosave badge is on screen"); + } + progress.autosave_seen = true; + progress.streak = 0; + return false; + } + const bool counts = wait == PlatformWait::PLATFORM_ONLY || progress.autosave_seen; + progress.streak = counts && look.readings.contains(PLATFORM_READING) ? progress.streak + 1 : 0; + return progress.streak >= PLATFORM_LOOKS; +} + +// A text box with the advance arrow: the opening's last line ("Your train +// has arrived in Lumiose City!") waits for A. +bool text_waiting_for_a(const ScreenObservation& look){ + return look.events.has(PokemonAutomation::ScreenEvent::DIALOG_BOX) && look.readings.contains(ADVANCE_ARROW_READING); +} + +// The station platform after the opening cutscene: PLATFORM_READING on +// PLATFORM_LOOKS looks in a row; AFTER_AUTOSAVE counts them only once the +// autosave badge has shown and gone. No input through the cutscene (A does +// not advance it), but one A for each text box with the advance arrow, when +// it shows (not again while the same one is up). Fails after `timeout`. +Outcome wait_for_platform(Pokemon::StoryBackend& backend, Milliseconds timeout, PlatformWait wait){ + // The looks bound a script whose time stands still. + const size_t max_looks = (size_t)(timeout / PLATFORM_POLL) + 1; + std::optional start; + PlatformProgress progress; + for (size_t looks = 0; looks < max_looks; looks++){ + backend.scope().throw_if_cancelled(); + const Pokemon::Observation look = backend.observe(); + start = start.value_or(look.when); + if (platform_look(backend, look, wait, progress)){ + backend.log(std::format("[PLZA] platform wait: on the platform after {} looks", looks + 1)); + return Pokemon::outcome_ok(); + } + if (look.when - *start >= timeout){ + break; + } + const bool text_now = text_waiting_for_a(look); + if (text_now && !progress.text_waiting){ + backend.log("[PLZA] platform wait: text waiting for A; A"); + backend.press(BUTTON_A, 160ms, 400ms); + } + progress.text_waiting = text_now; + backend.wait(PLATFORM_POLL); + } + return plza_failed("platform_not_seen", std::format( + "No platform on {} looks in a row within {} ms (autosave {}).", + PLATFORM_LOOKS, timeout.count(), progress.autosave_seen ? "seen" : "not seen" + )); +} + +// One slice of walk_to_prompt()'s walk between looks. +constexpr Milliseconds PROMPT_WALK_SLICE(250); + +// "walk_to_prompt": straight on until an A prompt shows (INTERACT_PROMPT: +// "A Leave" at the Battle Zone's gate), a slice at a time, nothing if it +// shows already. Fails after `timeout` of walking without one. +Outcome walk_to_prompt(Pokemon::StoryBackend& backend, Milliseconds timeout){ + Milliseconds walked(0); + while (true){ + backend.scope().throw_if_cancelled(); + if (backend.observe().events.has(PokemonAutomation::ScreenEvent::INTERACT_PROMPT)){ + backend.log(std::format("[PLZA] walk_to_prompt: the A prompt shows after {} ms of walking", walked.count())); + return Pokemon::outcome_ok(); + } + if (walked >= timeout){ + return plza_failed("no_prompt", std::format("walk_to_prompt: no A prompt in {} ms of walking", timeout.count())); + } + backend.hold(Pokemon::Direction::NORTH, PROMPT_WALK_SLICE, Pokemon::StoryPace::WALK); + walked += PROMPT_WALK_SLICE; + } +} + +// The handler of "wait_for_platform" or "opening_to_platform". +Handler platform_handler(PlatformWait wait){ + return [wait](Pokemon::StoryBackend& backend, const StoryActionCall& call, Pokemon::RunState&){ + return wait_for_platform(backend, Milliseconds(Pokemon::story_arg(call.args, "timeout_ms")), wait); + }; +} + +// The GAME actions that are not ConsoleSteps, by name: each one's handler +// from the run's handlers. +using HandlerOf = Handler (*)(const PlzaHandlers& handlers); +const std::map>& story_game_actions(){ + static const std::map> actions{ + {"walk", [](const PlzaHandlers& handlers){ return handlers.with_heading(walk_step); }}, + {"approach_starter", [](const PlzaHandlers& handlers){ return handlers.approach_starter(); }}, + {"walk_to_zone_gate_entrance", [](const PlzaHandlers& handlers){ return handlers.with_heading(gate_walk_step); }}, + {"load_backup_save", [](const PlzaHandlers& handlers){ return handlers.load_backup_save(); }}, + {"mash_to_move_hints", [](const PlzaHandlers&){ return PlzaHandlers::move_hints(); }}, + {"text_to_choice", [](const PlzaHandlers&){ return PlzaHandlers::text_to_choice(); }}, + {"wait_for_platform", [](const PlzaHandlers&){ return platform_handler(PlatformWait::PLATFORM_ONLY); }}, + {"opening_to_platform", [](const PlzaHandlers&){ return platform_handler(PlatformWait::AFTER_AUTOSAVE); }}, + {"walk_to_prompt", [](const PlzaHandlers&){ + return Handler([](Pokemon::StoryBackend& backend, const StoryActionCall& call, Pokemon::RunState&){ + return walk_to_prompt(backend, Milliseconds(Pokemon::story_arg(call.args, "timeout_ms"))); + }); + }}, + {"story_battle_start", [](const PlzaHandlers&){ + return Handler([](Pokemon::StoryBackend& backend, const StoryActionCall&, Pokemon::RunState&){ + return mash_scene(backend, SceneMashGoal::BATTLE, BUTTON_A, 90s); + }); + }}, + // B through the talk closes the Pokedex entry (A only plays its + // motions). + {"talk_to_pokedex_screen", [](const PlzaHandlers&){ + return Handler([](Pokemon::StoryBackend& backend, const StoryActionCall&, Pokemon::RunState&){ + return mash_scene(backend, SceneMashGoal::OVERWORLD, BUTTON_B, 90s); + }); + }}, + }; + return actions; +} + +// The handler of the GAME action `name`: a todo, a ConsoleStep or one of +// story_game_actions(). +Handler game_handler(const PlzaHandlers& handlers, const std::string& name){ + const auto todo = story_actions_not_implemented().find(name); + if (todo != story_actions_not_implemented().end()){ + return PlzaHandlers::not_implemented(name, todo->second); + } + const auto step = console_game_actions().find(name); + if (step != console_game_actions().end()){ + return handlers.console(name, [step = step->second](StoryEnv& env, const StoryActionArgs&){ + step(env); + }); + } + return story_game_actions().at(name)(handlers); +} + +// Where a fly to `args`' "place" leaves the player: in that place. +Pokemon::Pose flown_to(const StoryActionArgs& args){ + Pokemon::ZoneDeclared place; + place.place = Pokemon::story_arg(args, "place"); + return Pokemon::pose_of(Pokemon::DeclaredPose(std::move(place))); +} + +// The handler of each of plza_story_action_specs(), by kind and name. +Handler plza_handler(const PlzaHandlers& handlers, const StoryActionSpec& spec){ + const std::string& name = spec.name; + switch (spec.kind){ + case StoryStepKind::ROUTE:{ + Handler fly = handlers.console(name, [](StoryEnv& env, const StoryActionArgs& args){ + const std::string& place = Pokemon::story_arg(args, "place"); + fly_to(env.env.console, env.context, env.language, get_location_item_from_slug(place).location); + }); + // Flown: the player is at the target. + return [fly = std::move(fly)](Pokemon::StoryBackend& backend, const StoryActionCall& call, Pokemon::RunState& state){ + Outcome outcome = fly(backend, call, state); + if (outcome.succeeded()){ + outcome.pose = flown_to(call.args); + } + return outcome; + }; + } + case StoryStepKind::TALK: + return handlers.console(name, [](StoryEnv& env, const StoryActionArgs&){ + talk_to_facing(env.env.console, env.context); + }); + case StoryStepKind::ANSWER: + return handlers.console(name, [](StoryEnv& env, const StoryActionArgs& args){ + choose_dialog_option(env.env.console, env.context, Pokemon::story_arg(args, "yes") ? 0 : 1); + }); + case StoryStepKind::MASH:{ + const Button button = name == "a" ? BUTTON_A : BUTTON_B; + const SceneOpening opening = name == "talk" ? SceneOpening::TALK_FIRST : SceneOpening::CONTROL_ENDS; + return [button, opening](Pokemon::StoryBackend& backend, const StoryActionCall&, Pokemon::RunState&){ + return mash_story_scene(backend, button, opening); + }; + } + default: + return game_handler(handlers, name); + } +} + +const Pokemon::StoryActionRegistry& spec_registry(){ + static const Pokemon::StoryGame game = []{ + Pokemon::StoryGame specs_only; + specs_only.id = "plza"; + for (StoryActionSpec& spec : plza_story_action_specs()){ + specs_only.actions.push_back({.spec = std::move(spec), .handler = {}}); + } + return specs_only; + }(); + static const Pokemon::StoryActionRegistry registry(game); + return registry; +} + +// PLZA's actions over `env` (none: no console), with no save or reload. +Pokemon::StoryGame plza_game_actions(StoryEnv* env, StarterChoice starter){ + const PlzaHandlers handlers(env, starter); + Pokemon::StoryGame game; + game.id = "plza"; + for (StoryActionSpec& spec : plza_story_action_specs()){ + Handler handler = plza_handler(handlers, spec); + game.actions.push_back({.spec = std::move(spec), .handler = std::move(handler)}); + } + return game; +} + +// The specs of the console-only GAME actions: each ConsoleStep, +// load_backup_save, and the scene mashes that read the console's tutorial +// cards (TUTORIAL_CARD_READING). +std::vector console_game_specs(){ + std::vector specs; + for (const auto& [name, step] : console_game_actions()){ + specs.push_back(console_only(game_spec(name))); + } + specs.push_back(console_only(game_spec("load_backup_save"))); + specs.push_back(console_only(game_spec("story_battle_start"))); + specs.push_back(console_only(game_spec("talk_to_pokedex_screen"))); + return specs; +} + +} // namespace + + +std::vector plza_story_action_specs(){ + std::vector specs{ + console_only(StoryActionSpec{.kind = StoryStepKind::ROUTE, .name = "fly", .args = { + StoryArgSpec{ + .key = "place", .type = StoryArgType::WORD, .required = true, + .fallback = std::nullopt, .why = "the fast travel place, by slug", + }, + }}), + console_only(builtin_spec(StoryStepKind::TALK, "talk")), + console_only(builtin_spec(StoryStepKind::ANSWER, "answer")), + console_only(builtin_spec(StoryStepKind::MASH, "mash")), + console_only(StoryActionSpec{.kind = StoryStepKind::MASH, .name = "a", .args = {}}), + console_only(StoryActionSpec{.kind = StoryStepKind::MASH, .name = "talk", .args = {}}), + game_spec("mash_to_move_hints", { + optional_ms("min_length_ms", 0, "the scene's rough length: no quiet failure before it"), + optional_ms("quiet_ms", 60000, "nothing busy and no control this long fails the step"), + StoryArgSpec{ + .key = "press_a_first", .type = StoryArgType::BOOLEAN, .required = false, .fallback = false, + .why = "press A once first, at the prompt that starts the scene (a door's \"A Enter\")", + }, + StoryArgSpec{ + .key = "quiet_is_control", .type = StoryArgType::BOOLEAN, .required = false, .fallback = false, + .why = "the quiet time ends the step with control, where no party bar or prompt shows (Hotel Z)", + }, + }), + game_spec("text_to_choice", { + StoryArgSpec{ + .key = "advance_with_a", .type = StoryArgType::BOOLEAN, .required = false, .fallback = false, + .why = "advance the text with A, for a talk that B cancels", + }, + }), + game_spec("wait_for_platform", { + optional_ms("timeout_ms", 180000, "no platform this long fails the step"), + }), + game_spec("walk_to_prompt", { + optional_ms("timeout_ms", 10000, "walking this long with no A prompt fails the step"), + }), + game_spec("opening_to_platform", { + optional_ms("timeout_ms", 240000, "no autosave and platform this long fails the step"), + }), + walk_spec(), gate_walk_spec(), approach_starter_spec(), + }; + for (StoryActionSpec& spec : console_game_specs()){ + specs.push_back(std::move(spec)); + } + for (const auto& [name, todo] : story_actions_not_implemented()){ + specs.push_back(game_spec(name)); + } + return specs; +} + +const std::vector& plza_story_specs(){ + return spec_registry().specs(); +} + +std::vector plza_story_lint(const Pokemon::StoryCheckpoint& checkpoint){ + std::vector errors = spec_registry().lint(checkpoint); + if (!errors.empty()){ + return errors; + } + for (const Pokemon::StoryStep& step : checkpoint.steps){ + for (std::string& error : plza_step_arg_errors(step)){ + errors.push_back(std::format("{}: {}", checkpoint.id, error)); + } + } + return errors; +} + +StoryMove story_walk_move(const StoryActionArgs& args, std::string_view legs){ + StoryMove move; + const auto heading = args.find("heading"); + if (heading != args.end()){ + move.heading = (double)std::get(heading->second); + } + const auto held = args.find("held"); + move.held = held != args.end() && std::get(held->second); + const auto wait = args.find("wait_ms"); + if (wait != args.end()){ + move.wait_first = Milliseconds(std::get(wait->second)); + } + for (const Pokemon::StoryTimedLeg& row : Pokemon::story_arg(args, legs)){ + move.legs.push_back({.turn = (double)row.turn, .walk = Milliseconds(row.ms)}); + } + return move; +} + + +Pokemon::StoryGame make_plza_story_game( + StoryEnv& env, StarterChoice starter, std::set> autosave_rows +){ + Pokemon::StoryGame game = plza_game_actions(&env, starter); + // Slow, and it throws without the minimap: never after a checkpoint. + game.readers.push_back({ + .name = std::string(Pokemon::STORY_HEADING), .supplies = {std::string(Pokemon::STORY_HEADING)}, + .use = Pokemon::StoryReaderUse::ON_REQUEST, .console_only = true, .read = heading_reader(env), + }); + game.save = [&env, autosave_rows = std::move(autosave_rows)](Pokemon::StoryBackend& backend, const Pokemon::StoryCheckpoint& checkpoint){ + if (autosave_rows.contains(checkpoint.id)){ + backend.log(std::format("[Save] {}: the game autosaved at its end", checkpoint.id)); + return Pokemon::outcome_ok(); + } + try{ + save_story_game(env.env.console, env.context); + }catch (OperationFailedException& e){ + return Pokemon::outcome_failed("save_failed", e.message()); + } + return Pokemon::outcome_ok(); + }; + game.reload = [&env](Pokemon::StoryBackend& backend){ + return reload_save(env, backend, StartSave::LATEST); + }; + return game; +} + +Pokemon::StoryGame make_plza_story_game(StarterChoice starter){ + return plza_game_actions(nullptr, starter); +} + +namespace{ + +// Looks at a checkpoint's start: it shows once its sign holds +// START_SIGN_LOOKS looks in a row, PLATFORM_POLL apart. +constexpr size_t START_LOOKS = 8; +constexpr size_t START_SIGN_LOOKS = 2; + +// Whether the game shows `sign` now: it holds START_SIGN_LOOKS looks in a +// row within START_LOOKS. +bool at_checkpoint_start(Pokemon::StoryBackend& backend, const StartSign& sign){ + size_t streak = 0; + for (size_t looks = 0; looks < START_LOOKS; looks++){ + backend.scope().throw_if_cancelled(); + streak = backend.observe().events.has(sign.event) ? streak + 1 : 0; + if (streak >= START_SIGN_LOOKS){ + return true; + } + backend.wait(PLATFORM_POLL); + } + return false; +} + +std::string_view start_save_name(StartSave save){ + switch (save){ + case StartSave::LATEST: + return "the latest save"; + case StartSave::BACKUP: + return "the backup save"; + case StartSave::RUNNING: + return "the running game"; + } + return "?"; +} + +StartSave start_load_save(StartLoadAction action){ + switch (action){ + case StartLoadAction::LOAD_BACKUP: + return StartSave::BACKUP; + case StartLoadAction::RESUME: + return StartSave::RUNNING; + default: + return StartSave::LATEST; + } +} + +// What a run tried before stopping short of `from`'s start. +std::string_view start_tried(StartFrom from){ + switch (from){ + case StartFrom::LATEST_SAVE: + return "the latest and the backup save"; + case StartFrom::BACKUP_SAVE: + return "the backup save"; + case StartFrom::RUNNING_GAME: + return "the running game (no reload)"; + } + return "?"; +} + +// `row`'s start check after loading `save`, logged in one line; nothing +// when `row` has no check. The backup save's card (its play time and +// Pokedex count) is not read: there is no reader for it yet. +std::optional check_start(Pokemon::StoryBackend& backend, std::string_view row, StartSave save){ + const std::optional sign = checkpoint_start_sign(row); + if (!sign){ + backend.log(std::format("[Checkpoint] {}: no start check, starting from {}", row, start_save_name(save))); + return std::nullopt; + } + const bool at_start = at_checkpoint_start(backend, *sign); + if (at_start){ + backend.log(std::format("[Checkpoint] {}: start check after {}: at {}", row, start_save_name(save), sign->place)); + }else if (save == StartSave::LATEST){ + backend.log(std::format("[Checkpoint] {}: start check after {}: not at {}, loading the backup save", row, start_save_name(save), sign->place)); + }else{ + backend.log(std::format("[Checkpoint] {}: start check after {}: not at {}", row, start_save_name(save), sign->place)); + } + return at_start; +} + +// Saves with the menu's Report (StartLoadAction::REPORT_THEN_START), so +// the latest save is `row`'s start again for the next run. +Outcome report_at_start(StoryEnv& env, Pokemon::StoryBackend& backend, std::string_view row){ + try{ + save_story_game(env.env.console, env.context); + }catch (OperationFailedException& e){ + return Pokemon::outcome_failed("save_failed", e.message()); + } + const std::optional sign = checkpoint_start_sign(row); + backend.log(std::format("[Save] {}: the backup save at {}: saved with Report", row, sign ? sign->place : "its start")); + return Pokemon::outcome_ok(); +} + +} // namespace + +Outcome load_checkpoint_start(StoryEnv& env, Pokemon::StoryBackend& backend, std::string_view row, StartFrom from){ + std::vector loads; + while (true){ + const StartLoadAction action = next_start_load_action(from, loads); + if (action == StartLoadAction::START){ + return Pokemon::outcome_ok(); + } + if (action == StartLoadAction::REPORT_THEN_START){ + return report_at_start(env, backend, row); + } + if (action == StartLoadAction::STOP){ + const std::string_view tried = start_tried(from); + backend.log(std::format("[Checkpoint] {}: not at its start after {}, stopping", row, tried)); + return plza_failed("not_at_start", std::format("not at {}'s start after {}", row, tried)); + } + const StartSave save = start_load_save(action); + backend.log(std::format("[Save] {}: {} {}", row, save == StartSave::RUNNING ? "keeping" : "loading", start_save_name(save))); + const Outcome loaded = reload_save(env, backend, save); + if (!loaded.succeeded()){ + return loaded; + } + loads.push_back({.save = save, .at_start = check_start(backend, row, save)}); + } +} + + +namespace{ + +// Looks a reload at a boundary takes, PLATFORM_POLL apart, to tell 01.01's +// start from a later one: right after a load the platform reads on the +// first two. +constexpr size_t BOUNDARY_LOOKS = 4; + +// The reload before `row`, which a run reached from the row before it: the +// game's reload, then BOUNDARY_LOOKS looks, which fail if the station +// platform holds PLATFORM_LOOKS of them in a row. A save on the platform is +// 01.01's start: the reload did not bring back the autosave `row` starts +// from, which a reload_when_chained row comes after, but an older one. +Outcome reload_at_boundary(const Pokemon::StoryGame& game, Pokemon::StoryBackend& backend, std::string_view row){ + if (!game.reload){ + return plza_failed("no_reload", "this game has no reload"); + } + const Outcome reloaded = game.reload(backend); + if (!reloaded.succeeded()){ + return reloaded; + } + size_t streak = 0; + for (size_t looks = 0; looks < BOUNDARY_LOOKS; looks++){ + backend.scope().throw_if_cancelled(); + streak = backend.observe().readings.contains(PLATFORM_READING) ? streak + 1 : 0; + if (streak >= PLATFORM_LOOKS){ + return plza_failed("older_save", std::format( + "the reload did not land at {}'s start: the station platform shows, so it loaded an older save", row + )); + } + backend.wait(PLATFORM_POLL); + } + return Pokemon::outcome_ok(); +} + +void add_segment(const Pokemon::SegmentReport& part, Pokemon::SegmentReport& total){ + total.checkpoints_run += part.checkpoints_run; + total.reloads += part.reloads; + total.runs.insert(total.runs.end(), part.runs.begin(), part.runs.end()); + total.failed_checkpoint = part.failed_checkpoint; + total.failed_event = part.failed_event; + total.failure = part.failure; +} + +} // namespace + +Pokemon::SegmentReport run_plza_segment( + const Pokemon::StoryGame& game, const StoryData& story, + std::span rows, const Pokemon::StoryRunPolicy& policy, + Pokemon::StoryEngine& engine, Pokemon::StoryBackend& backend, Pokemon::RunState& state +){ + Pokemon::SegmentReport total; + size_t begin = 0; + while (begin < rows.size()){ + size_t end = begin + 1; + while (end < rows.size() && !Pokemon::story_reloads_before(story, policy.boundary_reload, rows[end].id)){ + end++; + } + if (begin > 0){ + const std::string& id = rows[begin].id; + backend.log(std::format("[Event] {}/0 reload_at_boundary: start", id)); + const Outcome reloaded = reload_at_boundary(game, backend, id); + if (!reloaded.succeeded()){ + backend.log(std::format("[Event] {}/0 reload_at_boundary: failed: {}", id, to_string(reloaded))); + total.failed_checkpoint = id; + total.failed_event = "reload_at_boundary"; + total.failure = reloaded; + return total; + } + backend.log(std::format("[Event] {}/0 reload_at_boundary: done", id)); + state = Pokemon::RunState{}; + } + const Pokemon::SegmentReport part = engine.run_segment("plza", rows.subspan(begin, end - begin), policy.attempts_per_checkpoint, state); + add_segment(part, total); + if (!part.completed){ + return total; + } + begin = end; + } + total.completed = true; + return total; +} + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h new file mode 100644 index 0000000000..dc69f76dbc --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h @@ -0,0 +1,147 @@ +/* PokemonLZA AutoStory - Story game + * + * From: https://github.com/PokemonAutomation/ + * + * PLZA for the shared story engine (Pokemon/AutoStory/Engine/): its + * actions as a StoryGame, and their specs, which a checkpoint's + * JSON is read against. It replaces PLZA's own story executor. + * + * The actions that read or press through the game's own screens (menus, + * the naming keyboard, the battle AI, fast travel) are console_only: the + * engine refuses them elsewhere. The new game's scenes and the walks run on + * any backend. + * + */ + +#ifndef PokemonAutomation_PokemonLZA_AutoStoryGame_H +#define PokemonAutomation_PokemonLZA_AutoStoryGame_H + +#include +#include +#include +#include +#include +#include +#include +#include "Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryGame.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "PokemonLZA_AutoStoryBackend.h" +#include "PokemonLZA_AutoStoryStartLoad.h" +#include "PokemonLZA_AutoStoryTable.h" +#include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryMoves.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + + +// The GAME actions whose code does not exist yet, by action, each with the +// code it waits for. They throw StoryActionNotImplemented with that text, +// which ends the run, instead of pressing buttons blind. +const std::map>& story_actions_not_implemented(); + +// PLZA's own actions and its replacements of built-in ones (same kind and +// name), in the order the game registers them: +// +// ROUTE "fly" fly to "place", a fast travel place's slug +// ("vert-pokemon-center") +// TALK "talk" A at what the player faces +// ANSWER "answer" the first choice for yes, the second for no +// MASH "mash" B through the text until the overworld is back +// MASH "a" A through it +// MASH "talk" B through a talk that must show: free control +// before a box or choice does not end it +// (SceneOpening::TALK_FIRST) +// GAME "walk" (args "legs", [[turn, ms], ...] as story_walk_move() +// reads them; "end", "fade_white", "fade_black" or "dialog"; +// "heading"), walked once the screen shows free control +// (check_can_walk()), until its end event if it has one +// (walk_until()), else until its legs have run +// (finish_walk()); "approach_starter" (args "chikorita", +// "tepig", "totodile", each a walk's legs: the run's starter's +// is walked as "walk" would, a starter with none is not +// implemented); the platform waits "wait_for_platform" and +// "opening_to_platform"; the scene machines +// "mash_to_move_hints" (args min_length_ms, quiet_ms) and +// "text_to_choice" (run_scene_machine()); a console step, one +// call through the game's own screens with no args: +// "confirm_new_game" (01.00, on "Confirm Choices"); +// "choose_0" / "choose_1" (that row of the choices on screen); +// "story_battle_start" (A to the battle), "story_battle" +// (attack until a dialog shows); "talk_through_map_screen", +// "talk_to_pokedex_screen", "climb_ladder"; the catches +// "catch_tutorial", "battle_then_catch", "catch_in_zone"; or +// an action of story_actions_not_implemented() +// +// Every action that works through the game's own screens is console_only. +// BATTLE is the built-in "fight" (the backend's battle), SAVE the +// engine's, and the built-in "route" and "shop" fail by name. Lumiose has +// no tiles: a step naming "legs" or "face" fails the lint. +std::vector plza_story_action_specs(); + +// Every action a PLZA checkpoint may name: the built-ins with +// plza_story_action_specs() on top, as the engine registers them. Its JSON +// is read against these. +const std::vector& plza_story_specs(); + +// What is wrong with `checkpoint` for PLZA's engine +// (StoryActionRegistry::lint), then with its steps' args +// (plza_step_arg_errors(), PokemonLZA_AutoStoryStepValidator.h). +std::vector plza_story_lint(const Pokemon::StoryCheckpoint& checkpoint); + +// The walk of `args`: the legs of its arg `legs` ("legs" for a walk, the +// starter's key for approach_starter), each [turn in degrees clockwise +// (negative: left), walk ms], and its "heading", if any. The args must +// have passed plza_story_lint(). +StoryMove story_walk_move(const Pokemon::StoryActionArgs& args, std::string_view legs); + +// PLZA as a StoryGame on the console `env`, which must outlive it. +// `starter` is the one approach_starter walks to; the walks read the +// compass with heading_reader(). The save waits out the game's autosave at +// the end of the checkpoints of `autosave_rows` (the run's +// StoryData::autosaves) and saves through the menu after the others; the +// reload resets the game from HOME onto the latest save. +Pokemon::StoryGame make_plza_story_game( + StoryEnv& env, StarterChoice starter, std::set> autosave_rows +); + +// The same with no console, for tests and simulations: the console_only +// actions fail as "console_only", the walks read the heading the looks +// carry, and there is no save or reload. +Pokemon::StoryGame make_plza_story_game(StarterChoice starter); + +// Loads the save `row` starts from by next_start_load_action(), or keeps +// the running game for StartFrom::RUNNING_GAME, checking the start after +// each load (checkpoint_start_sign(): 03.06, the nurse's "A" prompt +// at the Pokemon Center counter), and logs each load and check as +// "[Save]" and "[Checkpoint]" lines. When the backup save reached the +// start after the latest did not, saves with the menu's Report +// (StartLoadAction::REPORT_THEN_START). Fails when the game is not at +// `row`'s start after what `from` allows: the run must not start from an +// unknown spot. +Pokemon::Outcome load_checkpoint_start(StoryEnv& env, Pokemon::StoryBackend& backend, std::string_view row, StartFrom from); + +// `rows` in order from the save the game is on, as +// StoryEngine::run_segment() runs them, `policy`'s attempts per checkpoint. +// With Pokemon::StoryRunPolicy::BoundaryReload::AT_PLAN_BOUNDARIES, a row of `story`'s +// reload_when_chained after the run's first starts as from its save: the +// run's segment stops before it, the event "reload_at_boundary" reloads +// the save (`game`'s reload, the autosave the row before ended on) and +// checks that the station platform does not show (an older save), and a +// new segment starts at it. A failed reload fails the run there. The row +// before such a row ends its segment, so it ends at SavePoint::RUN_END. +Pokemon::SegmentReport run_plza_segment( + const Pokemon::StoryGame& game, const StoryData& story, + std::span rows, const Pokemon::StoryRunPolicy& policy, + Pokemon::StoryEngine& engine, Pokemon::StoryBackend& backend, + Pokemon::RunState& state +); + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine.h index d879b074f0..60ab203f9d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine.h +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine.h @@ -29,6 +29,7 @@ #include #include #include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonTools/ScreenMachine/ScreenObservation.h" #include "NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h" #include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" @@ -156,6 +157,9 @@ Pokemon::Outcome run_scene_machine( PlzaBackend& backend, std::string_view label, const SceneMachineConfig& config, Milliseconds timeout ); +// Registers the scene machine's tests: its states on sequences of events, +// no frames needed. +void add_tests_AutoStorySceneMachine(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine_Tests.cpp new file mode 100644 index 0000000000..e3ef4c4ad6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine_Tests.cpp @@ -0,0 +1,584 @@ +/* PokemonLZA AutoStory - Scene machine Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The scene machine's states on sequences of events, as PLZA's backend + * observes them (Pokemon::screen_observation()): no frames needed. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h" +#include "PokemonLZA_AutoStoryGame.h" +#include "PokemonLZA_AutoStoryReadings.h" +#include "PokemonLZA_AutoStorySceneMachine.h" +#include "PokemonLZA_AutoStoryStepValidator.h" +#include "PokemonLZA_AutoStoryStoryFiles.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + +using namespace std::chrono_literals; + +namespace{ + +// One read of the screen and what the machine should make of it. +struct Read{ + Milliseconds at; + ScreenEvents events; + bool still; + SceneScreen expected; + // The controls hint (CONTROLS_HINT_READING) shows. + bool hint = false; + // The advance chevron (ADVANCE_ARROW_READING) shows. + bool arrow = false; + // The mission banner (MISSION_BANNER_READING) shows. + bool banner = false; + // The mission complete card (MISSION_COMPLETE_READING) shows. + bool complete = false; + // The autosave badge (AUTOSAVE_READING) shows. + bool autosave = false; +}; + +// Feeds `reads` to a timeline as the machine does (classify, then record +// the read it acted on) and checks each state, until a terminal one. +UnitTestResult check_reads(const SceneMachineConfig& config, const std::vector& reads){ + const WallClock start = current_time(); + SceneTimeline timeline(config, start); + for (const Read& read : reads){ + ScreenObservation look = Pokemon::screen_observation(read.events); + look.when = start + read.at; + if (read.still){ + look.events.set(PokemonAutomation::ScreenEvent::SCREEN_STILL, true); + } + if (read.hint){ + look.readings[std::string(CONTROLS_HINT_READING)] = 1; + } + if (read.arrow){ + look.readings[std::string(ADVANCE_ARROW_READING)] = 1; + } + if (read.banner){ + look.readings[std::string(MISSION_BANNER_READING)] = 1; + } + if (read.complete){ + look.readings[std::string(MISSION_COMPLETE_READING)] = 1; + } + if (read.autosave){ + look.readings[std::string(AUTOSAVE_READING)] = 1; + } + const SceneScreen got = timeline.classify(look); + if (got != read.expected){ + return std::format("at {} ms ({}): expected {}, got {}.", + read.at.count(), describe(read.events), + scene_screen_name(read.expected), scene_screen_name(got)); + } + timeline.record(look); + } + return true; +} + +SceneMachineConfig opening_config(Milliseconds min_length){ + SceneMachineConfig config; + config.quiet = 8000ms; + config.min_length = min_length; + return config; +} + +const ScreenEvents NOTHING{}; +const ScreenEvents DIALOG{ScreenEvent::DIALOG_BOX}; +const ScreenEvents CHOICE{ScreenEvent::DIALOG_BOX, ScreenEvent::CHOICE_BOX}; +const ScreenEvents PARTY_BAR{ScreenEvent::PLAYER_CAN_MOVE}; +const ScreenEvents WHITE{ScreenEvent::FADE_WHITE}; +const ScreenEvents BLACK{ScreenEvent::FADE_BLACK}; +const ScreenEvents BATTLE{ScreenEvent::BATTLE_STARTED}; +const ScreenEvents PROMPT{ScreenEvent::INTERACT_PROMPT}; + +// mash_to_move_hints' config: a minute quiet, blind A after 5 s. +SceneMachineConfig arrival_config(){ + SceneMachineConfig config; + config.quiet = 60000ms; + config.blind_press_after = 5000ms; + return config; +} + +// The opening: a still frame past the quiet time does not end it before +// the scene's minimum length; then it does. +UnitTestResult test_quiet_waits_for_min_length(Logger&){ + return check_reads(opening_config(60000ms), { + {0ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {5000ms, DIALOG, false, SceneScreen::DIALOG}, + {10000ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {30000ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {59900ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {60000ms, NOTHING, true, SceneScreen::QUIET_END}, + }); +} + +// A box restarts the quiet time; a fade counts as busy too. +UnitTestResult test_quiet_restarts_on_busy(Logger&){ + return check_reads(opening_config(0ms), { + {0ms, DIALOG, false, SceneScreen::DIALOG}, + {7900ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {7950ms, WHITE, false, SceneScreen::FADE_WHITE}, + {15000ms, WHITE, true, SceneScreen::FADE_WHITE}, + {20000ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {22900ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {23000ms, NOTHING, true, SceneScreen::QUIET_END}, + }); +} + +// The party bar ends the scene once it has held a second; a box between +// lines starts the second again. +UnitTestResult test_party_bar_held(Logger&){ + return check_reads(opening_config(60000ms), { + {0ms, PARTY_BAR, false, SceneScreen::PARTY_BAR}, + {500ms, PARTY_BAR, true, SceneScreen::PARTY_BAR}, + {600ms, DIALOG, false, SceneScreen::DIALOG}, + {800ms, PARTY_BAR, false, SceneScreen::PARTY_BAR}, + {1700ms, PARTY_BAR, true, SceneScreen::PARTY_BAR}, + {1800ms, PARTY_BAR, true, SceneScreen::CAN_MOVE}, + }); +} + +// The controls hint ends the scene once it has held a second, ahead of +// the quiet end; a box over it starts the second again. +UnitTestResult test_controls_hint_held(Logger&){ + return check_reads(opening_config(0ms), { + {0ms, NOTHING, false, SceneScreen::HINT_SHOWING, true}, + {600ms, DIALOG, false, SceneScreen::DIALOG, true}, + {900ms, NOTHING, false, SceneScreen::HINT_SHOWING, true}, + {1800ms, NOTHING, true, SceneScreen::HINT_SHOWING, true}, + {9000ms, NOTHING, true, SceneScreen::CONTROLS_HINT, true}, + }); +} + +// 01.01's ad: subtitles with no box. The advance chevron is text to press +// on; with nothing seen for 5 s, A every 2 s. An interact prompt is free +// control like the controls hint: one look stops the presses, held a +// second it ends the scene (01.02's battle area shows only the prompt). +UnitTestResult test_ad_subtitles(Logger&){ + return check_reads(arrival_config(), { + {0ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {1000ms, NOTHING, false, SceneScreen::DIALOG, false, true}, + {1500ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {3000ms, NOTHING, true, SceneScreen::DIALOG, false, true}, + {7900ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {8000ms, NOTHING, true, SceneScreen::BLIND_PRESS}, + {9000ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {10000ms, NOTHING, false, SceneScreen::BLIND_PRESS}, + {12000ms, PROMPT, false, SceneScreen::HINT_SHOWING}, + {12100ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {14200ms, NOTHING, false, SceneScreen::HINT_SHOWING, true}, + {15000ms, NOTHING, true, SceneScreen::HINT_SHOWING, true}, + {15300ms, NOTHING, true, SceneScreen::CONTROLS_HINT, true}, + }); +} + +// 01.01's arrival : the last box, then "MAIN +// MISSION 01" over the scene. The banner's first look waits, its second +// ends the scene; a box between the two starts the count again. No blind +// A while it shows. +UnitTestResult test_mission_banner_ends(Logger&){ + return check_reads(arrival_config(), { + {0ms, DIALOG, false, SceneScreen::DIALOG}, + {500ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {6000ms, NOTHING, false, SceneScreen::BANNER_SHOWING, false, false, true}, + {6250ms, DIALOG, false, SceneScreen::DIALOG, false, false, true}, + {6500ms, NOTHING, false, SceneScreen::BANNER_SHOWING, false, false, true}, + {12000ms, NOTHING, true, SceneScreen::MISSION_BANNER, false, false, true}, + }); +} + +// 01.03's end: the "MAIN MISSION 01 COMPLETE" +// card waits for A. Each look at it presses A, and it is busy: no blind +// press and no quiet end however long it shows, and a look with the +// banner's reading too is the card. Then "MAIN MISSION 02" ends the scene +// on its second look. +UnitTestResult test_mission_complete_presses_a(Logger&){ + SceneMachineConfig config = arrival_config(); + config.quiet = 8000ms; + return check_reads(config, { + {0ms, DIALOG, false, SceneScreen::DIALOG}, + {4000ms, NOTHING, false, SceneScreen::MISSION_COMPLETE, false, false, false, true}, + {9000ms, NOTHING, true, SceneScreen::MISSION_COMPLETE, false, false, false, true}, + {20000ms, NOTHING, true, SceneScreen::MISSION_COMPLETE, false, false, true, true}, + {20500ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {21000ms, NOTHING, false, SceneScreen::BANNER_SHOWING, false, false, true}, + {21250ms, NOTHING, true, SceneScreen::MISSION_BANNER, false, false, true}, + }); +} + +// The banner ends only a scene after the overworld: B to a choice +// presses on past it. +UnitTestResult test_mission_banner_only_overworld(Logger&){ + SceneMachineConfig config; + config.goal = SceneMashGoal::CHOICE; + config.text_button = BUTTON_B; + return check_reads(config, { + {0ms, NOTHING, false, SceneScreen::SCENE_MOVING, false, false, true}, + {500ms, NOTHING, false, SceneScreen::SCENE_MOVING, false, false, true}, + {1000ms, CHOICE, false, SceneScreen::GOAL_CHOICE}, + }); +} + +// Blind presses are not busy: a minute of them still ends quiet; and only +// an A mash after control presses blind. +UnitTestResult test_blind_press_keeps_quiet(Logger& logger){ + const UnitTestResult quiet = check_reads(arrival_config(), { + {0ms, NOTHING, false, SceneScreen::DIALOG, false, true}, + {5000ms, NOTHING, true, SceneScreen::BLIND_PRESS}, + {6000ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {59000ms, NOTHING, true, SceneScreen::BLIND_PRESS}, + {60000ms, NOTHING, true, SceneScreen::QUIET_END}, + }); + if (quiet.result != UnitTestResult::PASSED){ + return quiet; + } + SceneMachineConfig to_choice = arrival_config(); + to_choice.goal = SceneMashGoal::CHOICE; + to_choice.text_button = BUTTON_B; + return check_reads(to_choice, { + {0ms, NOTHING, false, SceneScreen::DIALOG, false, true}, + {30000ms, NOTHING, true, SceneScreen::SCENE_STILL}, + }); +} + +// 02.04's check_in: the party bar without its D-pad hint reads as +// nothing, so 5 s quiet past the 30 s minimum is control. The text-free +// opening gets blind A; after the scene the quiet end comes before any +// blind A, which could talk to Taunie or AZ. +UnitTestResult test_check_in_quiet_is_control(Logger&){ + SceneMachineConfig config = arrival_config(); + config.quiet = 5000ms; + config.min_length = 30000ms; + config.quiet_is_control = true; + return check_reads(config, { + {0ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {5000ms, NOTHING, false, SceneScreen::BLIND_PRESS}, + {5400ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {16700ms, DIALOG, false, SceneScreen::DIALOG}, + {18000ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {20000ms, DIALOG, false, SceneScreen::DIALOG}, + {22000ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {24000ms, DIALOG, false, SceneScreen::DIALOG}, + {75000ms, DIALOG, false, SceneScreen::DIALOG}, + {75400ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {79900ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {80000ms, NOTHING, true, SceneScreen::QUIET_END}, + }); +} + +// The autosave badge, then 5 s with no box, ends the scene as control +// before the minimum length and the minute's quiet time; a box after the +// badge starts the 5 s again, and the badge is a cue, so no blind A +// comes before (02.04's check-in autosaves after AZ's talk). +UnitTestResult test_autosave_then_quiet_is_control(Logger&){ + SceneMachineConfig config = arrival_config(); + config.min_length = 30000ms; + return check_reads(config, { + {0ms, DIALOG, false, SceneScreen::DIALOG}, + {2000ms, NOTHING, false, SceneScreen::SCENE_MOVING, false, false, false, false, true}, + {3000ms, NOTHING, false, SceneScreen::SCENE_MOVING, false, false, false, false, true}, + {4000ms, DIALOG, false, SceneScreen::DIALOG}, + {5000ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {8900ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {9000ms, NOTHING, true, SceneScreen::AUTOSAVE_QUIET}, + }); +} + +// With no badge, the same scene waits out the minute's quiet time. +UnitTestResult test_no_autosave_no_early_end(Logger&){ + SceneMachineConfig config = arrival_config(); + config.min_length = 30000ms; + config.blind_press_after = std::nullopt; + return check_reads(config, { + {0ms, DIALOG, false, SceneScreen::DIALOG}, + {9000ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {59900ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {60000ms, NOTHING, true, SceneScreen::QUIET_END}, + }); +} + +// The autosave log names each appearance of the badge once, with the +// event last started; a look without it shorter than the gap between +// autosaves is the same appearance. +UnitTestResult test_autosave_spots(Logger&){ + const WallClock start = current_time(); + AutosaveSpots spots; + spots.on_log("[Event] 02.04/2 walk_to_desk: start"); + spots.on_log("[Event] 02.04/2 walk_to_desk: done"); + spots.on_log("[Event] 02.04/3 check_in: start"); + spots.on_log("[Step] check_in GAME/mash_to_move_hints: ok"); + const std::pair looks[] = { + {0ms, false}, {250ms, true}, {500ms, true}, {750ms, false}, {1000ms, true}, {1250ms, false}, + }; + std::vector lines; + for (const auto& [at, badge] : looks){ + std::optional line = spots.on_look(badge, start + at); + if (line){ + lines.push_back(*line); + } + } + spots.on_log("[Event] 02.05/1 take_elevator_up: start"); + std::optional later = spots.on_look(true, start + 60000ms); + if (later){ + lines.push_back(*later); + } + const std::vector expected = { + "[Autosave] 02.04/3 check_in", "[Autosave] 02.05/1 take_elevator_up", + }; + if (lines != expected){ + std::string got; + for (const std::string& line : lines){ + got += std::format("\"{}\" ", line); + } + return std::format("Expected the two appearances with their events, got: {}", got); + } + return true; +} + +// Without a quiet time only the party bar ends an overworld scene: a +// still screen waits until the machine's timeout. +UnitTestResult test_no_quiet_never_ends_still(Logger&){ + SceneMachineConfig config; + return check_reads(config, { + {0ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {300000ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {300100ms, BLACK, true, SceneScreen::FADE_BLACK}, + }); +} + +// Pancham cornered: B through the text and the scene, done at the choice. +UnitTestResult test_text_to_choice(Logger&){ + SceneMachineConfig config; + config.goal = SceneMashGoal::CHOICE; + config.text_button = BUTTON_B; + return check_reads(config, { + {0ms, NOTHING, false, SceneScreen::SCENE_MOVING}, + {1000ms, DIALOG, false, SceneScreen::DIALOG}, + {2000ms, PARTY_BAR, false, SceneScreen::SCENE_MOVING}, + {3000ms, CHOICE, false, SceneScreen::GOAL_CHOICE}, + }); +} + +// What each state presses. +UnitTestResult test_state_actions(Logger&){ + SceneMachineConfig a_mash = opening_config(0ms); + SceneMachineConfig b_to_choice; + b_to_choice.goal = SceneMashGoal::CHOICE; + b_to_choice.text_button = BUTTON_B; + SceneMachineConfig to_battle; + to_battle.goal = SceneMashGoal::BATTLE; + struct Case{ + SceneScreen screen; + const SceneMachineConfig& config; + SceneMashAction expected; + }; + const Case cases[] = { + {SceneScreen::DIALOG, a_mash, SceneMashAction::PRESS_TEXT}, + {SceneScreen::CHOICE, a_mash, SceneMashAction::PRESS_A}, + {SceneScreen::FADE_WHITE, a_mash, SceneMashAction::WAIT}, + {SceneScreen::FADE_BLACK, b_to_choice, SceneMashAction::WAIT}, + {SceneScreen::PARTY_BAR, a_mash, SceneMashAction::WAIT}, + {SceneScreen::SCENE_STILL, a_mash, SceneMashAction::WAIT}, + {SceneScreen::SCENE_MOVING, b_to_choice, SceneMashAction::PRESS_B}, + {SceneScreen::SCENE_MOVING, to_battle, SceneMashAction::PRESS_A}, + {SceneScreen::CAN_MOVE, a_mash, SceneMashAction::DONE}, + {SceneScreen::HINT_SHOWING, a_mash, SceneMashAction::WAIT}, + {SceneScreen::CONTROLS_HINT, a_mash, SceneMashAction::DONE}, + {SceneScreen::QUIET_END, a_mash, SceneMashAction::DONE}, + {SceneScreen::BLIND_PRESS, a_mash, SceneMashAction::PRESS_A}, + {SceneScreen::MISSION_COMPLETE, a_mash, SceneMashAction::PRESS_A}, + {SceneScreen::MISSION_COMPLETE, b_to_choice, SceneMashAction::PRESS_A}, + {SceneScreen::GOAL_CHOICE, b_to_choice, SceneMashAction::DONE}, + {SceneScreen::GOAL_BATTLE, to_battle, SceneMashAction::DONE}, + }; + for (const Case& item : cases){ + const SceneMashAction got = scene_screen_action(item.screen, item.config); + if (got != item.expected){ + return std::format("{}: expected action {}, got {}.", + scene_screen_name(item.screen), (int)item.expected, (int)got); + } + } + return true; +} + +// A battle goal presses A through cards and stops at the HUD. +UnitTestResult test_to_battle(Logger&){ + SceneMachineConfig config; + config.goal = SceneMashGoal::BATTLE; + return check_reads(config, { + {0ms, DIALOG, false, SceneScreen::DIALOG}, + {1000ms, NOTHING, true, SceneScreen::SCENE_STILL}, + {2000ms, BATTLE, false, SceneScreen::GOAL_BATTLE}, + }); +} + +// platform_to_plaza (the white fade) and 03.10's to_mable (Mable's +// dialog box) are the walks that end on an event, and every walk that +// ends on one holds a last leg that walks. +UnitTestResult test_move_ends(Logger&){ + std::vector ending; + for (const Pokemon::StoryCheckpoint& row : story_checkpoints()){ + for (const Pokemon::StoryStep& step : row.steps){ + const auto end = step.args.find("end"); + if (step.action != "walk" || end == step.args.end()){ + continue; + } + ending.push_back(step.name); + const StoryMove move = story_walk_move(step.args, "legs"); + if (move.legs.empty() || move.legs.back().walk <= 0ms){ + return std::format("{}: its last leg has no walk to hold until the event.", step.name); + } + const std::string& event = std::get(end->second); + if (!walk_end_event(event)){ + return std::format("{}: ends on {}, not a fade or a dialog.", step.name, event); + } + } + } + if (ending != std::vector{"platform_to_plaza", "to_mable"}){ + return std::format("Expected only platform_to_plaza and to_mable to end on an event, {} do.", ending.size()); + } + return true; +} + + +struct SceneMachineCase{ + std::string name; + struct Input{ + std::function body; + }; + Input input; + struct Expectation{ + }; + Expectation expectation; +}; + +class Test_AutoStorySceneMachine : public UnitTest{ +public: + explicit Test_AutoStorySceneMachine(SceneMachineCase test_case) + : UnitTest(std::format("PokemonLZA::AutoStorySceneMachine - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + return m_case.input.body(logger); + } + +private: + SceneMachineCase m_case; +}; + +} // namespace + + +const SceneMachineCase SCENE_MACHINE_CASES[] = { + { + .name = "quiet end waits for the scene's minimum length", + .input = {.body = test_quiet_waits_for_min_length}, + .expectation = {}, + }, + { + .name = "a box or a fade restarts the quiet time", + .input = {.body = test_quiet_restarts_on_busy}, + .expectation = {}, + }, + { + .name = "the party bar held a second ends the scene", + .input = {.body = test_party_bar_held}, + .expectation = {}, + }, + { + .name = "the controls hint held a second ends the scene", + .input = {.body = test_controls_hint_held}, + .expectation = {}, + }, + { + .name = "the ad's subtitles: A at the chevron, blind A, none at the hint", + .input = {.body = test_ad_subtitles}, + .expectation = {}, + }, + { + .name = "the mission banner on two looks ends the scene", + .input = {.body = test_mission_banner_ends}, + .expectation = {}, + }, + { + .name = "the mission complete card: A, busy, wins over the banner", + .input = {.body = test_mission_complete_presses_a}, + .expectation = {}, + }, + { + .name = "the mission banner does not end a mash to a choice", + .input = {.body = test_mission_banner_only_overworld}, + .expectation = {}, + }, + { + .name = "blind presses keep the quiet end, and only in an A mash", + .input = {.body = test_blind_press_keeps_quiet}, + .expectation = {}, + }, + { + .name = "02.04 check_in: quiet after the scene is control, before blind A", + .input = {.body = test_check_in_quiet_is_control}, + .expectation = {}, + }, + { + .name = "the autosave badge, then 5 s with no box, is control", + .input = {.body = test_autosave_then_quiet_is_control}, + .expectation = {}, + }, + { + .name = "no autosave badge: no early quiet end", + .input = {.body = test_no_autosave_no_early_end}, + .expectation = {}, + }, + { + .name = "the autosave log names each badge once, with its event", + .input = {.body = test_autosave_spots}, + .expectation = {}, + }, + { + .name = "without a quiet time a still screen never ends it", + .input = {.body = test_no_quiet_never_ends_still}, + .expectation = {}, + }, + { + .name = "B through the text to the choice", + .input = {.body = test_text_to_choice}, + .expectation = {}, + }, + { + .name = "A through the cards to the battle HUD", + .input = {.body = test_to_battle}, + .expectation = {}, + }, + { + .name = "what each state presses", + .input = {.body = test_state_actions}, + .expectation = {}, + }, + { + .name = "walks that end on an event", + .input = {.body = test_move_ends}, + .expectation = {}, + }, +}; + +void add_tests_AutoStorySceneMachine(UnitTestDatabase& database){ + for (const SceneMachineCase& item : SCENE_MACHINE_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.cpp new file mode 100644 index 0000000000..97d4d2837a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.cpp @@ -0,0 +1,83 @@ +/* PokemonLZA AutoStory - Story files + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h" +#include "PokemonLZA_AutoStoryGame.h" +#include "PokemonLZA_AutoStoryStoryFiles.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + +using Pokemon::StoryCheckpoint; +using Pokemon::StoryFileRow; +using Pokemon::StoryRowExecution; + + +namespace{ + +// A checkpoint file's checkpoint and its shared execution fields. `source` +// names the file in parse errors. +StoryFileRow read_checkpoint_file(std::string_view text, std::string_view source){ + StoryRowExecution read; + const Pokemon::ExecutionReader read_execution = [&read](const JsonObject& execution, std::string_view where){ + // Every PLZA file says how its row saves. + execution.get_string_throw("save"); + read = Pokemon::read_story_row_execution(execution, where, {}); + if (read.dev_only){ + throw ParseException(std::format("{}: unknown execution field dev_only", where)); + } + }; + StoryCheckpoint checkpoint = Pokemon::read_authored_checkpoint( + parse_json(std::string(text)), "plza", source, read_execution, plza_story_specs() + ); + return {.checkpoint = std::move(checkpoint), .execution = read}; +} + +} // namespace + + +const Pokemon::StoryFileReader& plza_story_file_reader(){ + static const Pokemon::StoryFileReader reader{ + .read = read_checkpoint_file, + .lint = plza_story_lint, + .starts_without_save = story_row_starts_without_save, + }; + return reader; +} + +StoryData load_story_data(std::span dev_files){ + return Pokemon::load_story_data( + std::span(autostory_checkpoint_json()), dev_files, plza_story_file_reader() + ); +} + +const StoryData& builtin_story_data(){ + static const StoryData data = load_story_data({}); + return data; +} + +const std::vector& story_checkpoints(){ + return builtin_story_data().checkpoints; +} + +const std::set>& story_autosave_rows(){ + return builtin_story_data().autosaves; +} + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h new file mode 100644 index 0000000000..8f0d6ac45d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h @@ -0,0 +1,74 @@ +/* PokemonLZA AutoStory - Story files + * + * From: https://github.com/PokemonAutomation/ + * + * Where the story (PokemonLZA_AutoStoryTable.h) is read from: the + * checked-in checkpoint files, StoryData/plza-.plan.json, built into + * the program. The shared loader (Pokemon_StoryFiles.h) reads them; this + * is PLZA's reader for it. Its tests hand the loader their own files + * (Pokemon_StoryDevFiles.h) in place of the built-in ones. + * + */ + +#ifndef PokemonAutomation_PokemonLZA_AutoStoryStoryFiles_H +#define PokemonAutomation_PokemonLZA_AutoStoryStoryFiles_H + +#include +#include +#include +#include +#include +#include +#include "Pokemon/AutoStory/Data/Pokemon_StoryDevFiles.h" +#include "Pokemon/AutoStory/Data/Pokemon_StoryFiles.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "PokemonLZA_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + + +// The checked-in checkpoint files, StoryData/plza-.plan.json, built +// into the program (cmake/EmbedTextFiles.cmake): (name, text), by name. +const std::vector>& autostory_checkpoint_json(); + +// How the shared loader reads a PLZA checkpoint file: its execution has +// only the shared "save" (required) and "reload_when_chained"; "dev_only" +// is refused, since PLZA lists every row. A dev file must pass +// plza_story_lint(), and 01.00 (story_row_starts_without_save()) has no +// save to reload. +const Pokemon::StoryFileReader& plza_story_file_reader(); + +// The built-in checkpoints, each of `dev_files` in place of the one of the +// same file name (Pokemon::load_story_data() with plza_story_file_reader()). +// Throws ParseException naming the file when a dev file does not parse, +// fails plza_story_lint(), matches no built-in file or changes its +// checkpoint's id. +StoryData load_story_data(std::span dev_files); + +// The built-in story, load_story_data() with no dev files, read once. +const StoryData& builtin_story_data(); + +// The built-in story (load_story_data() with no dev files), read once: +// what the tests, the lint and the program's dropdowns use. 01.xx Main +// Mission 01 (new game, Pancham, the starter), 02.xx Main Mission 02 (out +// of the Battle Zone to Hotel Z, the first night), 03.xx Main Mission 03 +// (Taunie's battle, the Pokemon Center, Wild Zone 1, Mable's Rock Smash +// TM). Only the first, 01.00, starts without a save: it plays a new game +// to the station platform from the new game's "Confirm Choices", its +// choices made by hand. +const std::vector& story_checkpoints(); + +// The built-in rows that end on one of the game's autosaves. Each ends +// where the game autosaved in the recording, so the next row reloads +// there. The menu (X, then R) can save from the start of the story too: +// 01.03 saves through it after Andi. +const std::set>& story_autosave_rows(); + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.cpp new file mode 100644 index 0000000000..05ac5e6b61 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.cpp @@ -0,0 +1,58 @@ +/* PokemonLZA AutoStory - Story table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonLZA_AutoStoryGame.h" +#include "PokemonLZA_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + +using Pokemon::StoryCheckpoint; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; + + +bool story_row_saves(const StoryData& story, const StoryCheckpoint& row){ + return !story.autosaves.contains(row.id); +} + +size_t story_rows_ready(const std::vector& checkpoints){ + size_t ready = 0; + for (const StoryCheckpoint& checkpoint : checkpoints){ + for (const StoryStep& step : checkpoint.steps){ + if (step.kind == StoryStepKind::GAME && story_actions_not_implemented().contains(step.action)){ + return ready; + } + } + ready++; + } + return ready; +} + +namespace{ + +// Whether `row`'s first step is the GAME action `action`. +bool first_game_action_is(const StoryCheckpoint& row, std::string_view action){ + if (row.steps.empty()){ + return false; + } + const StoryStep& first = row.steps.front(); + return first.kind == StoryStepKind::GAME && first.action == action; +} + +} // namespace + +bool story_row_starts_without_save(const StoryCheckpoint& row){ + return first_game_action_is(row, "confirm_new_game"); +} + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.h new file mode 100644 index 0000000000..bbaefa5508 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.h @@ -0,0 +1,60 @@ +/* PokemonLZA AutoStory - Story table + * + * From: https://github.com/PokemonAutomation/ + * + * The story as rows of the shared story steps + * (Pokemon/AutoStory/Types/Pokemon_StoryStep.h), plain data as BDSP's and + * FRLG's tables are, so unit tests can check it without a console. + * + * Lumiose has no tile grid, so a row's poses name a place and nothing more, + * and a walk in the overworld is a GAME "walk" step whose args hold its + * legs: a relative turn and a walk time each (PokemonLZA_AutoStoryGame.h). + * + * Recorded on the console, played step by step from a new + * game to the quest "Return to Hotel Z to meet up with Taunie" in Main + * Mission 03. Every walk was measured walking, not dashing. Steps the game + * has no code for yet are GAME steps of story_actions_not_implemented(). + * + * This is the story as data, with no IO: the checkpoint files it is read + * from, built in or from the dev folder, are PokemonLZA_AutoStoryStoryFiles.h. + * + */ + +#ifndef PokemonAutomation_PokemonLZA_AutoStoryTable_H +#define PokemonAutomation_PokemonLZA_AutoStoryTable_H + +#include +#include "Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + + +// The story a run plays: its checkpoints in order, and the rows their +// execution marks (Pokemon_StoryRowExecution.h): the autosave rows, which +// do not save themselves ("save": "autosave"), and the rows a run reloads +// before ("reload_when_chained"). +using StoryData = Pokemon::StoryData; + +// Whether `row` of `story` saves through the menu at its end: every row +// but the autosave rows. The menu (X, then R) can save from the start of +// the story too: 01.03 saves through it after Andi. +bool story_row_saves(const StoryData& story, const Pokemon::StoryCheckpoint& row); + +// How many rows of `checkpoints` from the first need no action of +// story_actions_not_implemented(): the part of the story a run can play. +size_t story_rows_ready(const std::vector& checkpoints); + +// Whether `row` starts with no save to load: it starts on the new game's +// "Confirm Choices" screen, the language, look and name chosen by hand +// (its first step is the GAME action "confirm_new_game"): 01.00. +bool story_row_starts_without_save(const Pokemon::StoryCheckpoint& row); + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.cpp new file mode 100644 index 0000000000..5405b9ab60 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.cpp @@ -0,0 +1,696 @@ +/* PokemonLZA AutoStory - Story table Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonLZA_AutoStoryGame.h" +#include "PokemonLZA_AutoStoryScreenEvents.h" +#include "PokemonLZA_AutoStoryStoryFiles.h" +#include "PokemonLZA_AutoStoryTable.h" +#include "PokemonLZA_AutoStoryTable_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + + +namespace{ + +using Pokemon::StoryCheckpoint; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; + +// The table: ids unique and in order, each row but the new game's (01.00) +// starts somewhere, and each lints against PLZA's actions in the engine. +UnitTestResult test_story_table_lints(Logger&){ + std::string previous; + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id <= previous){ + return std::format("{}: repeated or out of order after {}.", row.id, previous); + } + previous = row.id; + if (!row.start && !story_row_starts_without_save(row)){ + return std::format("{}: no start; every row after the new game starts from a save.", row.id); + } + const std::vector problems = plza_story_lint(row); + if (!problems.empty()){ + return problems[0]; + } + } + if (story_checkpoints().empty() || story_checkpoints()[0].id != "01.00"){ + return "Expected the table to start at 01.00, the new game."; + } + return true; +} + +// The step `name` of checkpoint `id` in `checkpoints`; null if none. +const StoryStep* find_step(const std::vector& checkpoints, std::string_view id, std::string_view name){ + for (const StoryCheckpoint& row : checkpoints){ + for (const StoryStep& step : row.steps){ + if (row.id == id && step.name == name){ + return &step; + } + } + } + return nullptr; +} + +// `move`'s legs as [turn, ms] pairs, for messages and comparisons. +std::vector> leg_pairs(const StoryMove& move){ + std::vector> pairs; + for (const StoryWalkLeg& leg : move.legs){ + pairs.emplace_back((int)leg.turn, leg.walk.count()); + } + return pairs; +} + +// Every walk reads as a move with legs (its args passed the lint), and +// platform_to_plaza reads as recorded, ending on the white fade. +UnitTestResult test_story_walks_read(Logger&){ + size_t walks = 0; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& step : row.steps){ + if (step.kind != StoryStepKind::GAME || step.action != "walk"){ + continue; + } + walks++; + if (story_walk_move(step.args, "legs").legs.empty()){ + return std::format("{} {}: no legs.", row.id, step.name); + } + } + } + if (walks != 28){ + return std::format("Expected the 28 walks, found {}.", walks); + } + const StoryStep* plaza = find_step(story_checkpoints(), "01.01", "platform_to_plaza"); + if (plaza == nullptr){ + return "Expected 01.01 platform_to_plaza."; + } + const std::vector> expected{{0, 4500}, {90, 10000}}; + if (leg_pairs(story_walk_move(plaza->args, "legs")) != expected){ + return "Expected platform_to_plaza's legs [[0, 4500], [90, 10000]]."; + } + const auto end = plaza->args.find("end"); + if (end == plaza->args.end() || std::get(end->second) != "fade_white"){ + return "Expected platform_to_plaza to end on the white fade."; + } + return true; +} + +// Each action that is not implemented says what it waits for, is no move's +// name, and is in a step. +UnitTestResult test_not_implemented_actions(Logger&){ + std::set used; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& step : row.steps){ + if (step.kind == StoryStepKind::GAME){ + used.insert(step.action); + } + } + } + for (const auto& [name, todo] : story_actions_not_implemented()){ + if (todo.empty()){ + return std::format("{}: no TODO.", name); + } + if (name == "walk" || name == "approach_starter"){ + return std::format("{}: also a walk's action.", name); + } + if (!used.contains(name)){ + return std::format("{}: in no step.", name); + } + } + return true; +} + +// Every autosave row is in the table, and 01.03 saves through the menu +// (the menu can save from the start of the story). +UnitTestResult test_autosave_rows(Logger&){ + size_t seen = 0; + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id == "01.03" && !story_row_saves(builtin_story_data(), row)){ + return "Expected 01.03 to save through the menu."; + } + if (!story_row_saves(builtin_story_data(), row)){ + seen++; + } + } + if (seen != story_autosave_rows().size()){ + return std::format("Expected {} autosave rows in the table, found {}.", story_autosave_rows().size(), seen); + } + return true; +} + +// 03.05 heals at the Pokemon Center and ends there: talk to the nurse, +// her scene, then the checkpoint's save. Healing writes a save, so the +// title screen's backup save (Up + B + X) lands on 03.05's end for +// Main Mission 03's retries (user). +UnitTestResult test_mm3_heal_row(Logger&){ + const StoryCheckpoint* heal = nullptr; + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id == "03.05"){ + heal = &row; + } + } + if (heal == nullptr || heal->steps.size() < 2){ + return "Expected 03.05, the heal, with at least two steps."; + } + const StoryStep& talk = heal->steps[heal->steps.size() - 2]; + const StoryStep& scene = heal->steps.back(); + if (talk.name != "talk_to_nurse" || talk.kind != StoryStepKind::TALK){ + return "Expected 03.05 to talk to the nurse before its last step."; + } + if (scene.name != "heal_party" || scene.kind != StoryStepKind::MASH){ + return "Expected 03.05 to end on the nurse's heal_party scene."; + } + if (!story_row_saves(builtin_story_data(), *heal)){ + return "Expected 03.05 to save after the heal."; + } + const StoryStep* leave = find_step(story_checkpoints(), "03.06", "out_of_pokemon_center"); + if (leave == nullptr || leave->kind != StoryStepKind::GAME || leave->action != "walk"){ + return "Expected 03.06 to walk out of the Pokemon Center."; + } + return true; +} + +// The built-in file of checkpoint `id` with its execution's save line +// replaced by `execution` (the fields after "execution": {), as a dev file. +Pokemon::StoryDevFile dev_with_execution(std::string_view id, std::string_view execution){ + for (const auto& [name, text] : autostory_checkpoint_json()){ + if (name != std::format("plza-{}.plan", id)){ + continue; + } + std::string edited = text; + const size_t at = edited.find("\"save\": \"autosave\""); + if (at != std::string::npos){ + edited.replace(at, std::string_view("\"save\": \"autosave\"").size(), execution); + } + return Pokemon::StoryDevFile{.name = std::format("{}.json", name), .path = std::format("dev/{}.json", name), .text = edited}; + } + return Pokemon::StoryDevFile{}; +} + +// The ParseException message of load_story_data() on the one dev file +// `dev`; empty if it loads. +std::string load_problem(const Pokemon::StoryDevFile& dev){ + try{ + load_story_data(std::span(&dev, 1)); + }catch (ParseException& e){ + return e.message(); + } + return ""; +} + +// 01.00, the new game (story_row_starts_without_save()), has no save to +// reload: the shared loader refuses its "reload_when_chained". +UnitTestResult test_reload_when_chained_field(Logger&){ + for (std::string_view reload : {"true", "\"always\""}){ + const std::string execution = std::format("\"save\": \"autosave\", \"reload_when_chained\": {}", reload); + const std::string problem = load_problem(dev_with_execution("01.00", execution)); + if (problem.find("no save to reload") == std::string::npos){ + return std::format("01.00 with {}: expected \"no save to reload\", got \"{}\".", execution, problem); + } + } + return true; +} + +// 01.02 reloads when run after 01.01, whose autosave is 01.02's start; +// with 01.01 saving through the menu instead, 01.02's reload is refused. +UnitTestResult test_mm1_reload_when_chained(Logger&){ + if (!builtin_story_data().reload_when_chained.contains("01.02")){ + return "Expected 01.02 to reload when chained."; + } + const std::string problem = load_problem(dev_with_execution("01.01", R"("save": "menu")")); + if (problem.find("does not end on the game's autosave") == std::string::npos){ + return std::format("01.01 saving through the menu: expected 01.02's reload refused, got \"{}\".", problem); + } + return true; +} + +// 03.04 reloads even in a run straight through: its walk to the nurse +// starts from 03.03's autosave, not from where 03.03's scene leaves the +// player. +UnitTestResult test_0304_reloads_always(Logger&){ + const StoryData& data = builtin_story_data(); + if (!data.reload_always.contains("03.04") || !data.autosaves.contains("03.03")){ + return "Expected 03.04 to always reload, after 03.03's autosave."; + } + return true; +} + +// A run can play every row: none names an action that is not implemented. +UnitTestResult test_every_row_ready(Logger&){ + const size_t ready = story_rows_ready(story_checkpoints()); + if (ready != story_checkpoints().size()){ + return std::format("Expected all {} rows to be ready, {} are.", story_checkpoints().size(), ready); + } + return true; +} + +// A scene step's start window: a box, a choice or a battle within it +// starts the scene; fades and quiet frames alone (02.02's street missed +// after the Brigitte battle) fail at its end, not +// before. +UnitTestResult test_scene_start_window(Logger&){ + const WallClock start = current_time(); + const auto at = [start](int64_t seconds){ + return start + Milliseconds(seconds * 1000); + }; + SceneStart missed(start, SCENE_START_WINDOW); + if (missed.never_started({ScreenEvent::FADE_BLACK}, at(10)) || missed.never_started({}, at(44))){ + return "Expected no failure inside the window."; + } + if (!missed.never_started({ScreenEvent::PLAYER_CAN_MOVE}, at(45))){ + return "Expected a scene with only a fade and quiet frames to fail at the window's end."; + } + for (const ScreenEvent event : {ScreenEvent::DIALOG_BOX, ScreenEvent::CHOICE_BOX, ScreenEvent::BATTLE_STARTED}){ + SceneStart started(start, SCENE_START_WINDOW); + if (started.never_started({event}, at(10)) || started.never_started({}, at(100))){ + return "Expected a box, a choice or a battle to start the scene."; + } + } + return true; +} + +// SceneMash on each kind of frame, as a first look. +UnitTestResult test_scene_mash_rule(Logger&){ + struct Case{ + std::string_view name; + ScreenEvents events; + SceneMashGoal goal; + Button text_button; + SceneMashAction expected; + }; + const Case cases[] = { + {"box, A mash", {ScreenEvent::DIALOG_BOX}, SceneMashGoal::OVERWORLD, BUTTON_A, SceneMashAction::PRESS_TEXT}, + {"box, B mash", {ScreenEvent::DIALOG_BOX}, SceneMashGoal::OVERWORLD, BUTTON_B, SceneMashAction::PRESS_TEXT}, + {"choice takes the top", {ScreenEvent::DIALOG_BOX, ScreenEvent::CHOICE_BOX}, SceneMashGoal::OVERWORLD, BUTTON_B, SceneMashAction::PRESS_A}, + {"choice is the goal", {ScreenEvent::DIALOG_BOX, ScreenEvent::CHOICE_BOX}, SceneMashGoal::CHOICE, BUTTON_B, SceneMashAction::DONE}, + {"party bar, not held yet", {ScreenEvent::PLAYER_CAN_MOVE}, SceneMashGoal::OVERWORLD, BUTTON_A, SceneMashAction::WAIT}, + {"party bar, not held yet, B mash", {ScreenEvent::PLAYER_CAN_MOVE}, SceneMashGoal::OVERWORLD, BUTTON_B, SceneMashAction::WAIT}, + // The party bar with a box or a choice is mid-scene: the box gets the + // text button and the choice A (the old rule waited on the party bar). + {"party bar with a box", {ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::DIALOG_BOX}, SceneMashGoal::OVERWORLD, BUTTON_B, SceneMashAction::PRESS_TEXT}, + {"party bar with a choice", {ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::DIALOG_BOX, ScreenEvent::CHOICE_BOX}, SceneMashGoal::OVERWORLD, BUTTON_A, SceneMashAction::PRESS_A}, + {"party bar, not the goal", {ScreenEvent::PLAYER_CAN_MOVE}, SceneMashGoal::BATTLE, BUTTON_A, SceneMashAction::PRESS_A}, + {"black fade waits", {ScreenEvent::FADE_BLACK}, SceneMashGoal::BATTLE, BUTTON_A, SceneMashAction::WAIT}, + {"white fade waits", {ScreenEvent::FADE_WHITE}, SceneMashGoal::OVERWORLD, BUTTON_B, SceneMashAction::WAIT}, + {"battle HUD", {ScreenEvent::BATTLE_STARTED}, SceneMashGoal::BATTLE, BUTTON_A, SceneMashAction::DONE}, + {"card before a battle", {}, SceneMashGoal::BATTLE, BUTTON_A, SceneMashAction::PRESS_A}, + {"quiet, A mash", {}, SceneMashGoal::OVERWORLD, BUTTON_A, SceneMashAction::WAIT}, + {"quiet, B mash (map, Pokedex)", {}, SceneMashGoal::OVERWORLD, BUTTON_B, SceneMashAction::PRESS_B}, + {"prompt alone, A mash", {ScreenEvent::INTERACT_PROMPT}, SceneMashGoal::OVERWORLD, BUTTON_A, SceneMashAction::WAIT}, + }; + for (const Case& item : cases){ + SceneMash mash(item.goal, item.text_button); + const SceneMashAction got = mash.look(item.events, current_time()); + if (got != item.expected){ + return std::format("{}: expected action {}, got {}.", item.name, (int)item.expected, (int)got); + } + } + return true; +} + +// An OVERWORLD mash ends once the party bar has held OVERWORLD_HOLD +// (TalkOver's calm time): a box between lines starts the hold again. +UnitTestResult test_scene_mash_party_bar_held(Logger&){ + struct Look{ + Milliseconds at; + ScreenEvents events; + SceneMashAction expected; + }; + const ScreenEvents party_bar{ScreenEvent::PLAYER_CAN_MOVE}; + const Look looks[] = { + {Milliseconds(0), party_bar, SceneMashAction::WAIT}, + {Milliseconds(500), party_bar, SceneMashAction::WAIT}, + {Milliseconds(600), {ScreenEvent::DIALOG_BOX}, SceneMashAction::PRESS_TEXT}, + {Milliseconds(700), party_bar, SceneMashAction::WAIT}, + {Milliseconds(1600), party_bar, SceneMashAction::WAIT}, + {Milliseconds(1700), party_bar, SceneMashAction::DONE}, + }; + const WallClock start = current_time(); + SceneMash mash(SceneMashGoal::OVERWORLD, BUTTON_A); + for (const Look& look : looks){ + const SceneMashAction got = mash.look(look.events, start + look.at); + if (got != look.expected){ + return std::format("at {} ms: expected action {}, got {}.", look.at.count(), (int)look.expected, (int)got); + } + } + return true; +} + +// A battle's HUD with the party bar is not the overworld: TalkOver's +// BATTLE_STARTED restarts the hold, so an OVERWORLD mash waits through it +// and does not end after OVERWORLD_HOLD. +UnitTestResult test_scene_mash_battle_hud_not_overworld(Logger&){ + const ScreenEvents battle_hud{ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::BATTLE_STARTED}; + const WallClock start = current_time(); + SceneMash mash(SceneMashGoal::OVERWORLD, BUTTON_A); + for (Milliseconds at(0); at <= Milliseconds(3000); at += Milliseconds(500)){ + const SceneMashAction got = mash.look(battle_hud, start + at); + if (got != SceneMashAction::WAIT){ + return std::format("at {} ms: expected action {}, got {}.", at.count(), (int)SceneMashAction::WAIT, (int)got); + } + } + return true; +} + +// Chikorita's walk is recorded in 01.03's approach_starter, and only hers. +UnitTestResult test_starter_moves(Logger&){ + const StoryStep* approach = find_step(story_checkpoints(), "01.03", "approach_starter"); + if (approach == nullptr || approach->action != "approach_starter"){ + return "Expected 01.03 approach_starter."; + } + if (approach->args.contains("tepig") || approach->args.contains("totodile")){ + return "Expected only Chikorita's walk."; + } + if (!approach->args.contains("chikorita")){ + return "Expected the walk to Chikorita."; + } + const std::vector> expected{{-70, 750}}; + if (leg_pairs(story_walk_move(approach->args, "chikorita")) != expected){ + return "Expected Chikorita's walk [[-70, 750]]."; + } + return true; +} + +// The built-in text of checkpoint file `name` ("plza-01.02.plan"). +std::string builtin_text(std::string_view name){ + for (const auto& [file, text] : autostory_checkpoint_json()){ + if (file == name){ + return text; + } + } + return ""; +} + +// `text` with its first `from` replaced by `to`. +std::string replaced(std::string text, std::string_view from, std::string_view to){ + const size_t at = text.find(from); + if (at != std::string::npos){ + text.replace(at, from.size(), to); + } + return text; +} + +// The ParseException message of load_story_data() on the one dev file +// `text`; empty if it loads. +std::string dev_load_error(std::string_view name, std::string text){ + return load_problem({.name = std::string(name), .path = std::format("/dev/{}", name), .text = std::move(text)}); +} + +// A dev file replaces the built-in checkpoint of its name and no other; a +// walk PLZA's reader refuses (a leg of 3 numbers, a negative walk) fails +// naming its path. +UnitTestResult test_dev_override(Logger&){ + const std::string chase = builtin_text("plza-01.02.plan"); + const std::string_view legs = "[[-15, 4000], [-75, 3500]"; + if (chase.find(legs) == std::string::npos){ + return "Expected chase_pancham's legs in plza-01.02.plan.json."; + } + const Pokemon::StoryDevFile dev{ + .name = "plza-01.02.plan.json", .path = "/dev/plza-01.02.plan.json", + .text = replaced(chase, legs, "[[-15, 4200], [-75, 3500]"), + }; + const StoryData data = load_story_data(std::span(&dev, 1)); + const StoryStep* tuned = find_step(data.checkpoints, "01.02", "chase_pancham"); + if (tuned == nullptr || leg_pairs(story_walk_move(tuned->args, "legs")).front() != std::pair(-15, 4200)){ + return "Expected the dev file's first leg, [-15, 4200]."; + } + const StoryStep* plaza = find_step(data.checkpoints, "01.01", "platform_to_plaza"); + if (plaza == nullptr || leg_pairs(story_walk_move(plaza->args, "legs")).front() != std::pair(0, 4500)){ + return "Expected 01.01 to stay built-in."; + } + for (const std::string_view bad_legs : {"[[-15, 4000, 1], [-75, 3500]", "[[-15, -4000], [-75, 3500]"}){ + const std::string error = dev_load_error("plza-01.02.plan.json", replaced(chase, legs, bad_legs)); + if (error.find("/dev/plza-01.02.plan.json") == std::string::npos){ + return std::format("Expected legs {} to fail naming the file, got \"{}\".", bad_legs, error); + } + } + return true; +} + + +// The new game's start: 01.00 starts on "Confirm Choices" after the +// choices made by hand, without a save; every later row loads one. +UnitTestResult test_new_game_rows(Logger&){ + for (const StoryCheckpoint& row : story_checkpoints()){ + const bool no_save = story_row_starts_without_save(row); + if (no_save != (row.id == "01.00")){ + return std::format("{}: starts without a save: {}; only 01.00 should.", row.id, no_save); + } + } + return true; +} + +// 03.08 ends out on the street, just through Wild Zone 1's far gate +// ("the end of 03.08 should be exit wild zone 1"); the +// walk on into the Research Lab is 03.09, whose lobby autosave is 03.10's +// start. (A minimap check after it was dropped: just outside the gate the +// arrow still reads in the zone's green;.) +UnitTestResult test_zone_1_exit_row(Logger&){ + const std::vector& rows = story_checkpoints(); + size_t index = 0; + while (index < rows.size() && rows[index].id != "03.09"){ + index++; + } + if (index == 0 || index + 1 >= rows.size() + || rows[index - 1].id != "03.08" || rows[index + 1].id != "03.10" + ){ + return "Expected 03.09 in the story rows, between 03.08 and 03.10."; + } + const StoryCheckpoint& zone = rows[index - 1]; + const StoryCheckpoint& lab = rows[index]; + const size_t steps = zone.steps.size(); + if (steps == 0 || zone.steps.back().name != "leave_zone_1"){ + return "Expected 03.08 to end with leave_zone_1."; + } + if (lab.steps.empty() || lab.steps.front().name != "to_research_lab" || lab.steps.back().name != "lab_lobby"){ + return "Expected 03.09 to run from to_research_lab to lab_lobby."; + } + return true; +} + +// 03.10 ends on the game's autosave on 3F, after the elevator ride; 03.11 +// starts there, from Mable's walk on ("if this is the +// auto save, we should divide a checkpoint here"). to_mable's legs were +// measured from the reloaded save, whose facing the ride does not leave, so +// 03.11 reloads it when chained after 03.10. +UnitTestResult test_director_office_row(Logger&){ + const std::vector& rows = story_checkpoints(); + size_t index = 0; + while (index < rows.size() && rows[index].id != "03.11"){ + index++; + } + if (index == 0 || index >= rows.size() || rows[index - 1].id != "03.10"){ + return "Expected 03.11 in the story rows, right after 03.10."; + } + const StoryCheckpoint& ride = rows[index - 1]; + const StoryCheckpoint& mable = rows[index]; + if (ride.steps.empty() || ride.steps.front().name != "to_lab_elevator" || ride.steps.back().name != "arrive_3f"){ + return "Expected 03.10 to run from to_lab_elevator to arrive_3f."; + } + if (mable.steps.empty() || mable.steps.front().name != "to_mable" || mable.steps.back().name != "leave_mable"){ + return "Expected 03.11 to run from to_mable to leave_mable."; + } + const StoryData& data = builtin_story_data(); + if (!data.autosaves.contains("03.10") || data.autosaves.contains("03.11") || !data.reload_when_chained.contains("03.11")){ + return "Expected 03.10 to end on the autosave and 03.11 to reload it when chained."; + } + return true; +} + +// The production story the program's dropdowns list, by index (the start +// and end options store the index): ids, the rows ending on the game's +// autosave and the rows reloading before them. Console runs name rows by +// these indices (03.08 is 18, 03.09 is 19, 03.10 is 20, +// 03.11 is 21), so a change to how the files +// are read must leave them as they are. +UnitTestResult test_production_rows(Logger&){ + const std::vector ids{ + "01.00", "01.01", "01.02", "01.03", + "02.01", "02.02", "02.03", "02.04", "02.05", "02.06", "02.07", + "03.01", "03.02", "03.03", "03.04", "03.05", "03.06", "03.07", "03.08", "03.09", "03.10", + "03.11", + }; + const std::set> autosaves{ + "01.00", "01.01", "01.02", "02.01", "02.02", "02.03", "02.04", "02.05", "02.06", "02.07", "03.01", "03.03", + // 03.08 ends on the street outside Wild Zone 1, which does not + // autosave; 03.09 ends on the Research Lab lobby's (user). + "03.09", + // 03.10 ends on the Director's Office's, on 3F (user). + "03.10", + }; + const std::set> reload_when_chained{ + "01.02", "02.02", "02.03", "02.04", "02.05", "02.07", "03.01", "03.02", "03.04", "03.11", + }; + const std::set> reload_always{"03.04"}; + const StoryData& data = builtin_story_data(); + if (data.checkpoints.size() != ids.size()){ + return std::format("Expected {} rows, got {}.", ids.size(), data.checkpoints.size()); + } + for (size_t index = 0; index < ids.size(); index++){ + if (data.checkpoints[index].id != ids[index]){ + return std::format("Row {}: expected {}, got {}.", index, ids[index], data.checkpoints[index].id); + } + } + if (data.autosaves != autosaves || data.reload_when_chained != reload_when_chained + || data.reload_always != reload_always || !data.dev_files.empty() + ){ + return "Expected the built-in autosave and reload rows, and no dev files."; + } + return true; +} + +struct AutoStoryTableCase{ + std::string name; + struct Input{ + std::function body; + }; + Input input; + // What each body checks is in its own code: these cases are functions. + struct Expectation{ + }; + Expectation expectation; +}; + +class Test_AutoStoryTable : public UnitTest{ +public: + explicit Test_AutoStoryTable(AutoStoryTableCase test_case) + : UnitTest(std::format("PokemonLZA::AutoStory - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + } + } + +private: + AutoStoryTableCase m_case; +}; + +} // namespace + + +const AutoStoryTableCase AUTO_STORY_TABLE_CASES[] = { + { + .name = "Story table: rows lint against PLZA's engine actions", + .input = {.body = test_story_table_lints}, + .expectation = {}, + }, + { + .name = "Story table: every walk reads its legs", + .input = {.body = test_story_walks_read}, + .expectation = {}, + }, + { + .name = "Story table: actions not implemented say what they wait for", + .input = {.body = test_not_implemented_actions}, + .expectation = {}, + }, + { + .name = "Starters: the walk to Chikorita is recorded", + .input = {.body = test_starter_moves}, + .expectation = {}, + }, + { + .name = "Dev checkpoints: replace the built-in file of their name, fail naming the file", + .input = {.body = test_dev_override}, + .expectation = {}, + }, + { + .name = "Story table: the autosave rows, and 01.03 saves through the menu", + .input = {.body = test_autosave_rows}, + .expectation = {}, + }, + { + .name = "Story table: 03.05 heals at the Pokemon Center and saves there", + .input = {.body = test_mm3_heal_row}, + .expectation = {}, + }, + { + .name = "Story table: every row is ready", + .input = {.body = test_every_row_ready}, + .expectation = {}, + }, + { + .name = "reload_when_chained: never on the new game row", + .input = {.body = test_reload_when_chained_field}, + .expectation = {}, + }, + { + .name = "reload_when_chained: 01.02 after 01.01's autosave", + .input = {.body = test_mm1_reload_when_chained}, + .expectation = {}, + }, + { + .name = "reload_when_chained: \"always\" on 03.04, after 03.03's autosave", + .input = {.body = test_0304_reloads_always}, + .expectation = {}, + }, + { + .name = "Scene mash: a scene that never starts fails at its start window", + .input = {.body = test_scene_start_window}, + .expectation = {}, + }, + { + .name = "Scene mash: what each frame presses", + .input = {.body = test_scene_mash_rule}, + .expectation = {}, + }, + { + .name = "Scene mash: the party bar held a second ends an overworld mash", + .input = {.body = test_scene_mash_party_bar_held}, + .expectation = {}, + }, + { + .name = "Scene mash: a battle HUD with the party bar does not end an overworld mash", + .input = {.body = test_scene_mash_battle_hud_not_overworld}, + .expectation = {}, + }, + { + .name = "Start checks: 01.00 starts the new game without a save", + .input = {.body = test_new_game_rows}, + .expectation = {}, + }, + { + .name = "Zone 1 exit: 03.08 ends through the far gate, 03.09 walks into the lab", + .input = {.body = test_zone_1_exit_row}, + .expectation = {}, + }, + { + .name = "Director's Office: 03.10 ends on the 3F autosave, 03.11 reloads it for Mable", + .input = {.body = test_director_office_row}, + .expectation = {}, + }, + { + .name = "Story table: the production rows by dropdown index, with their autosaves and reloads", + .input = {.body = test_production_rows}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ + for (const AutoStoryTableCase& item : AUTO_STORY_TABLE_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.h new file mode 100644 index 0000000000..fe82988970 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.h @@ -0,0 +1,26 @@ +/* PokemonLZA AutoStory - Story table Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLZA_AutoStoryTable_Tests_H +#define PokemonAutomation_PokemonLZA_AutoStoryTable_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + + +// Tests that need no console: the story table lints against PLZA's engine +// actions, its moves are known, and its autosave rows come first. +void add_tests_AutoStory_StoryTable(UnitTestDatabase& database); + + + +} // namespace PokemonLZA +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a664991553..7edd775f2c 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2420,6 +2420,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryDialogs_Tests.h Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk.cpp Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk.h + Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.cpp + Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.h Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryMarkerWalks.cpp Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryMarkerWalks.h Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryMoves.cpp @@ -2478,14 +2480,19 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonLZA/Programs/AutoStory/Detectors/PokemonLZA_AutoStoryZoneGateReader_Tests.h Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryBackend.cpp Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryBackend.h + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.cpp + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.h Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryFailures.cpp Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryFailures.h Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryFailures_Tests.cpp + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryLaunch.cpp Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryLaunch.h Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryReadings.h Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine.cpp Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine.h + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStorySceneMachine_Tests.cpp Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryScreenEvents.cpp Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryScreenEvents.h Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryScreenEvents_Tests.cpp @@ -2495,6 +2502,12 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStartLoad_Tests.h Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStepValidator.cpp Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStepValidator.h + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.cpp + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.cpp + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.h + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.cpp + Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.h Source/VideoGames/PokemonLZA/Programs/Farming/PokemonLZA_DonutMaker.cpp Source/VideoGames/PokemonLZA/Programs/Farming/PokemonLZA_DonutMaker.h Source/VideoGames/PokemonLZA/Programs/Farming/PokemonLZA_FriendshipFarmer.cpp From 3d36502c1a3613b2be5ab4af9d8aed30ae66fe53 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 12:27:19 -0800 Subject: [PATCH 2/4] PokemonLZA AutoStory: reload with go_home() + reset_game_from_home(); menu save behind a switch MENU_SAVE_AT_CHECKPOINT_END stays off: the engine does not menu-save yet, as before (user decision). run_checkpoint() takes no save point. --- .../PokemonLZA_AutoStoryGateWalk_Tests.cpp | 2 +- .../PokemonLZA_AutoStoryEngine_Tests.cpp | 60 +------------------ .../AutoStory/PokemonLZA_AutoStoryGame.cpp | 33 ++++++++-- .../AutoStory/PokemonLZA_AutoStoryGame.h | 8 +-- 4 files changed, 35 insertions(+), 68 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.cpp index 20788bcea2..556a746e1f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryGateWalk_Tests.cpp @@ -220,7 +220,7 @@ UnitTestResult check_plan_step(const PlanStepCase& test, CancellableScope& scope const Pokemon::StoryGame game = make_plza_story_game(StarterChoice::CHIKORITA); Pokemon::StoryEngine engine(game, backend); Pokemon::RunState state; - const Pokemon::StoryEngineReport report = engine.run_checkpoint(*row, Pokemon::SavePoint::RUN_END, state); + const Pokemon::StoryEngineReport report = engine.run_checkpoint(*row, state); if (report.verdict != Pokemon::CheckpointVerdict::PASSED){ return std::format("{}: expected a pass, got {}.", id, to_string(report.run.failure)); } diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.cpp index b73a1d6011..60d911edbc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryEngine_Tests.cpp @@ -24,7 +24,6 @@ #include "Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h" #include "Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h" #include "PokemonLZA_AutoStoryGame.h" -#include "PokemonLZA_AutoStoryLaunch.h" #include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryMoves.h" #include "PokemonLZA_AutoStoryReadings.h" #include "PokemonLZA_AutoStoryStoryFiles.h" @@ -90,7 +89,7 @@ Pokemon::StoryEngineReport run_plza(FakeBackend& backend, const StoryCheckpoint& const Pokemon::StoryGame game = make_plza_story_game(StarterChoice::CHIKORITA); Pokemon::StoryEngine engine(game, backend); Pokemon::RunState state; - return engine.run_checkpoint(checkpoint, Pokemon::SavePoint::RUN_END, state); + return engine.run_checkpoint(checkpoint, state); } std::string joined(const std::vector& lines){ @@ -665,7 +664,7 @@ UnitTestResult test_every_checkpoint_runs(CancellableScope& scope){ expected.push_back(std::format("{}/{}", Pokemon::story_step_kind_name(step.kind), spec ? spec->name : "?")); } Pokemon::RunState state; - const Pokemon::StoryEngineReport report = engine.run_checkpoint(checkpoint, Pokemon::SavePoint::RUN_END, state); + const Pokemon::StoryEngineReport report = engine.run_checkpoint(checkpoint, state); if (report.verdict != Pokemon::CheckpointVerdict::PASSED || report.saved){ return std::format("{}: expected a pass with no save, got {} ({}).", checkpoint.id, report.verdict == Pokemon::CheckpointVerdict::PASSED ? "a save" : "a failure", to_string(report.run.failure)); @@ -878,7 +877,7 @@ UnitTestResult test_walk_pauses_before_each_leg(CancellableScope& scope){ FakeBackend backend = fake_plza({look_at(0ms)}, scope); Pokemon::StoryEngine engine(game, backend); Pokemon::RunState state; - if (engine.run_checkpoint(row, Pokemon::SavePoint::RUN_END, state).verdict != Pokemon::CheckpointVerdict::PASSED){ + if (engine.run_checkpoint(row, state).verdict != Pokemon::CheckpointVerdict::PASSED){ return std::format("Expected the walk to pass: {}", joined(backend.lines())); } const std::vector expected{ @@ -1043,63 +1042,10 @@ const EngineTestCase ENGINE_TEST_CASES[] = { }; -namespace{ - -// plza_title(): which looks after the launch take the title's A. -struct LaunchTitleCase{ - std::string name; - struct Input{ - std::vector events; - }; - Input input; - struct Expectation{ - bool title; - }; - Expectation expectation; -}; - -const LaunchTitleCase LAUNCH_TITLE_CASES[] = { - // The title's centred "PRESS (A) BUTTON" reads - // as an A prompt; the launch waited on it. - {.name = "PRESS (A) BUTTON read as an A prompt", .input = {.events = {EngineEvent::INTERACT_PROMPT}}, .expectation = {.title = true}}, - {.name = "a plain screen", .input = {.events = {}}, .expectation = {.title = true}}, - {.name = "an A prompt on the overworld", .input = {.events = {EngineEvent::INTERACT_PROMPT, EngineEvent::PLAYER_CAN_MOVE}}, .expectation = {.title = false}}, - {.name = "the overworld", .input = {.events = {EngineEvent::PLAYER_CAN_MOVE}}, .expectation = {.title = false}}, - {.name = "a black fade", .input = {.events = {EngineEvent::FADE_BLACK}}, .expectation = {.title = false}}, - {.name = "a battle", .input = {.events = {EngineEvent::BATTLE_STARTED}}, .expectation = {.title = false}}, -}; - -class Test_LaunchTitle : public UnitTest{ -public: - explicit Test_LaunchTitle(const LaunchTitleCase& test_case) - : UnitTest(std::format("PokemonLZA::AutoStoryEngine - launch title: {}", test_case.name)) - , m_case(test_case) - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - ScreenObservation look; - for (EngineEvent event : m_case.input.events){ - look.events.set(event, true); - } - look.frame = VideoSnapshot(ImageRGB32(16, 9), current_time()); - if (plza_title(look) != m_case.expectation.title){ - return std::format("Expected title = {}.", m_case.expectation.title); - } - return true; - } - -private: - const LaunchTitleCase& m_case; -}; - -} // namespace - void add_tests_AutoStoryEngine(UnitTestDatabase& database){ for (const EngineTestCase& item : ENGINE_TEST_CASES){ database.add(item); } - for (const LaunchTitleCase& item : LAUNCH_TITLE_CASES){ - database.add(item); - } } diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp index 8d413dd121..a5444cecab 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp @@ -21,7 +21,8 @@ #include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" #include "Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.h" #include "Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h" -#include "Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "VideoGames/PokemonLZA/Programs/PokemonLZA_GameEntry.h" #include "VideoGames/PokemonLZA/Resources/PokemonLZA_Locations.h" #include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryActions.h" #include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryCatches.h" @@ -32,7 +33,7 @@ #include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryMoves.h" #include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryScenes.h" #include "VideoGames/PokemonLZA/Programs/AutoStory/Actions/PokemonLZA_AutoStoryWalkScreenChecks.h" -#include "PokemonLZA_AutoStoryLaunch.h" + #include "PokemonLZA_AutoStorySceneMachine.h" #include "PokemonLZA_AutoStoryStepValidator.h" #include "PokemonLZA_AutoStoryGame.h" @@ -72,13 +73,30 @@ using ConsoleBody = std::function& backend, StartSave save){ - return Pokemon::launch_story_game(backend, plza_launch_policy(env.env.console), start_launch_request(save)); + if (save == StartSave::RUNNING){ + backend.log("[Launch] keeping the running game"); + return Pokemon::outcome_ok(); + } + go_home(env.env.console, env.context); + if (!reset_game_from_home(env.env, env.env.console, env.context, save == StartSave::BACKUP)){ + return Pokemon::outcome_failed("launch_failed", "the game did not reach the overworld after the reload"); + } + return Pokemon::outcome_ok(); } +// Whether a checkpoint that passed and whose row does not autosave saves +// through the menu at its end (StoryGame::save). Off keeps the behavior the +// runs so far had: no menu save from the engine, so the 03.06 -> 03.08 +// backup-save recovery still finds 03.06's save. Turning it on is the +// user's decision (01.03, 03.02, 03.04, 03.06, 03.08 and 03.11 would start +// saving). +constexpr bool MENU_SAVE_AT_CHECKPOINT_END = false; + // The GAME actions that are one ConsoleStep each, by name: console_only. const std::map>& console_game_actions(){ static const std::map> actions{ @@ -759,6 +777,9 @@ Pokemon::StoryGame make_plza_story_game( backend.log(std::format("[Save] {}: the game autosaved at its end", checkpoint.id)); return Pokemon::outcome_ok(); } + if (!MENU_SAVE_AT_CHECKPOINT_END){ + return Pokemon::outcome_failed("menu_save_off", "MENU_SAVE_AT_CHECKPOINT_END is off: no menu save"); + } try{ save_story_game(env.env.console, env.context); }catch (OperationFailedException& e){ diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h index dc69f76dbc..0abc7e0e0d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h @@ -101,8 +101,9 @@ StoryMove story_walk_move(const Pokemon::StoryActionArgs& args, std::string_view // `starter` is the one approach_starter walks to; the walks read the // compass with heading_reader(). The save waits out the game's autosave at // the end of the checkpoints of `autosave_rows` (the run's -// StoryData::autosaves) and saves through the menu after the others; the -// reload resets the game from HOME onto the latest save. +// StoryData::autosaves); after the others it saves through the menu only +// when MENU_SAVE_AT_CHECKPOINT_END is on (off for now: a user decision). +// The reload resets the game from HOME onto the latest save. Pokemon::StoryGame make_plza_story_game( StoryEnv& env, StarterChoice starter, std::set> autosave_rows ); @@ -130,8 +131,7 @@ Pokemon::Outcome load_checkpoint_start(StoryEnv& env, Pokemon::StoryBackend& game, const StoryData& story, std::span rows, const Pokemon::StoryRunPolicy& policy, From 8a387c4d9d1430230f23b81a5dc4be0de1800643 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 12:28:49 -0800 Subject: [PATCH 3/4] PokemonLZA AutoStory: shorter comments keep AutoStoryGame.cpp under 1000 lines --- .../AutoStory/PokemonLZA_AutoStoryGame.cpp | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp index a5444cecab..45ae026791 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp @@ -73,10 +73,8 @@ using ConsoleBody = std::function& backend, StartSave save){ if (save == StartSave::RUNNING){ backend.log("[Launch] keeping the running game"); @@ -89,12 +87,8 @@ Outcome reload_save(StoryEnv& env, Pokemon::StoryBackend& backend, Sta return Pokemon::outcome_ok(); } -// Whether a checkpoint that passed and whose row does not autosave saves -// through the menu at its end (StoryGame::save). Off keeps the behavior the -// runs so far had: no menu save from the engine, so the 03.06 -> 03.08 -// backup-save recovery still finds 03.06's save. Turning it on is the -// user's decision (01.03, 03.02, 03.04, 03.06, 03.08 and 03.11 would start -// saving). +// Off (the user's call, pending): a passed non-autosave row does not save +// through the menu, as before, so the 03.06 -> 03.08 backup recovery holds. constexpr bool MENU_SAVE_AT_CHECKPOINT_END = false; // The GAME actions that are one ConsoleStep each, by name: console_only. From 1ff9338e6ff7f89f38f2dee7cec4f2e508632304 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 12:46:58 -0800 Subject: [PATCH 4/4] PokemonLZA AutoStory: no menu save; "save" is optional "menu" is gone from the plans, so MENU_SAVE_AT_CHECKPOINT_END, the menu-save path of StoryGame::save and story_row_saves() go. A row that does not end on a seen autosave fails its save as "no_autosave" (as "menu_save_off" before). The table tests follow the plans: autosave rows as the run logs show them, unverified ones apart, reloads only on 02.07, 03.02 and 03.04. --- .../AutoStory/PokemonLZA_AutoStoryGame.cpp | 16 +--- .../AutoStory/PokemonLZA_AutoStoryGame.h | 5 +- .../PokemonLZA_AutoStoryStoryFiles.cpp | 2 - .../PokemonLZA_AutoStoryStoryFiles.h | 9 +-- .../AutoStory/PokemonLZA_AutoStoryTable.cpp | 4 - .../AutoStory/PokemonLZA_AutoStoryTable.h | 11 +-- .../PokemonLZA_AutoStoryTable_Tests.cpp | 80 ++++++++++--------- 7 files changed, 54 insertions(+), 73 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp index 45ae026791..aa5e077926 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.cpp @@ -87,10 +87,6 @@ Outcome reload_save(StoryEnv& env, Pokemon::StoryBackend& backend, Sta return Pokemon::outcome_ok(); } -// Off (the user's call, pending): a passed non-autosave row does not save -// through the menu, as before, so the 03.06 -> 03.08 backup recovery holds. -constexpr bool MENU_SAVE_AT_CHECKPOINT_END = false; - // The GAME actions that are one ConsoleStep each, by name: console_only. const std::map>& console_game_actions(){ static const std::map> actions{ @@ -766,20 +762,12 @@ Pokemon::StoryGame make_plza_story_game( .name = std::string(Pokemon::STORY_HEADING), .supplies = {std::string(Pokemon::STORY_HEADING)}, .use = Pokemon::StoryReaderUse::ON_REQUEST, .console_only = true, .read = heading_reader(env), }); - game.save = [&env, autosave_rows = std::move(autosave_rows)](Pokemon::StoryBackend& backend, const Pokemon::StoryCheckpoint& checkpoint){ + game.save = [autosave_rows = std::move(autosave_rows)](Pokemon::StoryBackend& backend, const Pokemon::StoryCheckpoint& checkpoint){ if (autosave_rows.contains(checkpoint.id)){ backend.log(std::format("[Save] {}: the game autosaved at its end", checkpoint.id)); return Pokemon::outcome_ok(); } - if (!MENU_SAVE_AT_CHECKPOINT_END){ - return Pokemon::outcome_failed("menu_save_off", "MENU_SAVE_AT_CHECKPOINT_END is off: no menu save"); - } - try{ - save_story_game(env.env.console, env.context); - }catch (OperationFailedException& e){ - return Pokemon::outcome_failed("save_failed", e.message()); - } - return Pokemon::outcome_ok(); + return Pokemon::outcome_failed("no_autosave", "the row does not end on an autosave a run log has shown"); }; game.reload = [&env](Pokemon::StoryBackend& backend){ return reload_save(env, backend, StartSave::LATEST); diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h index 0abc7e0e0d..0fe3983a8e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryGame.h @@ -101,9 +101,8 @@ StoryMove story_walk_move(const Pokemon::StoryActionArgs& args, std::string_view // `starter` is the one approach_starter walks to; the walks read the // compass with heading_reader(). The save waits out the game's autosave at // the end of the checkpoints of `autosave_rows` (the run's -// StoryData::autosaves); after the others it saves through the menu only -// when MENU_SAVE_AT_CHECKPOINT_END is on (off for now: a user decision). -// The reload resets the game from HOME onto the latest save. +// StoryData::autosaves); after the others nothing saves, and it fails as +// "no_autosave". The reload resets the game from HOME onto the latest save. Pokemon::StoryGame make_plza_story_game( StoryEnv& env, StarterChoice starter, std::set> autosave_rows ); diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.cpp index 97d4d2837a..f78704aefd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.cpp @@ -32,8 +32,6 @@ namespace{ StoryFileRow read_checkpoint_file(std::string_view text, std::string_view source){ StoryRowExecution read; const Pokemon::ExecutionReader read_execution = [&read](const JsonObject& execution, std::string_view where){ - // Every PLZA file says how its row saves. - execution.get_string_throw("save"); read = Pokemon::read_story_row_execution(execution, where, {}); if (read.dev_only){ throw ParseException(std::format("{}: unknown execution field dev_only", where)); diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h index 8f0d6ac45d..447e43bf8a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryStoryFiles.h @@ -34,7 +34,7 @@ namespace PokemonLZA{ const std::vector>& autostory_checkpoint_json(); // How the shared loader reads a PLZA checkpoint file: its execution has -// only the shared "save" (required) and "reload_when_chained"; "dev_only" +// only the shared "save" and "reload_when_chained"; "dev_only" // is refused, since PLZA lists every row. A dev file must pass // plza_story_lint(), and 01.00 (story_row_starts_without_save()) has no // save to reload. @@ -60,10 +60,9 @@ const StoryData& builtin_story_data(); // choices made by hand. const std::vector& story_checkpoints(); -// The built-in rows that end on one of the game's autosaves. Each ends -// where the game autosaved in the recording, so the next row reloads -// there. The menu (X, then R) can save from the start of the story too: -// 01.03 saves through it after Andi. +// The built-in rows that end on one of the game's autosaves, as a run's log +// showed it ("save": "autosave"). Each ends where the game autosaved, so +// the next row can reload there. const std::set>& story_autosave_rows(); diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.cpp index 05ac5e6b61..e0f7eb843e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.cpp @@ -17,10 +17,6 @@ using Pokemon::StoryStep; using Pokemon::StoryStepKind; -bool story_row_saves(const StoryData& story, const StoryCheckpoint& row){ - return !story.autosaves.contains(row.id); -} - size_t story_rows_ready(const std::vector& checkpoints){ size_t ready = 0; for (const StoryCheckpoint& checkpoint : checkpoints){ diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.h index bbaefa5508..bdb44afd26 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable.h @@ -33,16 +33,11 @@ namespace PokemonLZA{ // The story a run plays: its checkpoints in order, and the rows their -// execution marks (Pokemon_StoryRowExecution.h): the autosave rows, which -// do not save themselves ("save": "autosave"), and the rows a run reloads -// before ("reload_when_chained"). +// execution marks (Pokemon_StoryRowExecution.h): the rows ending on the +// game's autosave ("save": "autosave", or "unverified" until a run's log +// shows it), and the rows a run reloads before ("reload_when_chained"). using StoryData = Pokemon::StoryData; -// Whether `row` of `story` saves through the menu at its end: every row -// but the autosave rows. The menu (X, then R) can save from the start of -// the story too: 01.03 saves through it after Andi. -bool story_row_saves(const StoryData& story, const Pokemon::StoryCheckpoint& row); - // How many rows of `checkpoints` from the first need no action of // story_actions_not_implemented(): the part of the story a run can play. size_t story_rows_ready(const std::vector& checkpoints); diff --git a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.cpp index 5405b9ab60..5763a9a069 100644 --- a/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonLZA/Programs/AutoStory/PokemonLZA_AutoStoryTable_Tests.cpp @@ -133,20 +133,21 @@ UnitTestResult test_not_implemented_actions(Logger&){ return true; } -// Every autosave row is in the table, and 01.03 saves through the menu -// (the menu can save from the start of the story). +// Every autosave row, seen or unverified, is in the table, and 01.03 ends +// on no save. UnitTestResult test_autosave_rows(Logger&){ + const StoryData& data = builtin_story_data(); size_t seen = 0; for (const StoryCheckpoint& row : story_checkpoints()){ - if (row.id == "01.03" && !story_row_saves(builtin_story_data(), row)){ - return "Expected 01.03 to save through the menu."; + if (row.id == "01.03" && (data.autosaves.contains(row.id) || data.unverified_autosaves.contains(row.id))){ + return "Expected 01.03 to end on no save."; } - if (!story_row_saves(builtin_story_data(), row)){ + if (data.autosaves.contains(row.id) || data.unverified_autosaves.contains(row.id)){ seen++; } } - if (seen != story_autosave_rows().size()){ - return std::format("Expected {} autosave rows in the table, found {}.", story_autosave_rows().size(), seen); + if (seen != data.autosaves.size() + data.unverified_autosaves.size()){ + return std::format("Expected {} autosave rows in the table, found {}.", data.autosaves.size() + data.unverified_autosaves.size(), seen); } return true; } @@ -173,8 +174,8 @@ UnitTestResult test_mm3_heal_row(Logger&){ if (scene.name != "heal_party" || scene.kind != StoryStepKind::MASH){ return "Expected 03.05 to end on the nurse's heal_party scene."; } - if (!story_row_saves(builtin_story_data(), *heal)){ - return "Expected 03.05 to save after the heal."; + if (!story_autosave_rows().contains("03.05")){ + return "Expected 03.05 to end on the game's autosave after the heal."; } const StoryStep* leave = find_step(story_checkpoints(), "03.06", "out_of_pokemon_center"); if (leave == nullptr || leave->kind != StoryStepKind::GAME || leave->action != "walk"){ @@ -183,17 +184,23 @@ UnitTestResult test_mm3_heal_row(Logger&){ return true; } -// The built-in file of checkpoint `id` with its execution's save line -// replaced by `execution` (the fields after "execution": {), as a dev file. +// The built-in file of checkpoint `id` with its execution's fields +// replaced by `execution` (the fields between "execution": { and }), as a +// dev file. Pokemon::StoryDevFile dev_with_execution(std::string_view id, std::string_view execution){ + constexpr std::string_view EXECUTION = "\"execution\": {"; for (const auto& [name, text] : autostory_checkpoint_json()){ if (name != std::format("plza-{}.plan", id)){ continue; } std::string edited = text; - const size_t at = edited.find("\"save\": \"autosave\""); - if (at != std::string::npos){ - edited.replace(at, std::string_view("\"save\": \"autosave\"").size(), execution); + const size_t start = edited.find(EXECUTION); + if (start != std::string::npos){ + const size_t fields = start + EXECUTION.size(); + const size_t end = edited.find('}', fields); + if (end != std::string::npos){ + edited.replace(fields, end - fields, execution); + } } return Pokemon::StoryDevFile{.name = std::format("{}.json", name), .path = std::format("dev/{}.json", name), .text = edited}; } @@ -224,15 +231,15 @@ UnitTestResult test_reload_when_chained_field(Logger&){ return true; } -// 01.02 reloads when run after 01.01, whose autosave is 01.02's start; -// with 01.01 saving through the menu instead, 01.02's reload is refused. +// 01.01's autosave is unverified (no run log shows it yet), so 01.02 does +// not reload when chained, and a dev file that makes it reload is refused. UnitTestResult test_mm1_reload_when_chained(Logger&){ - if (!builtin_story_data().reload_when_chained.contains("01.02")){ - return "Expected 01.02 to reload when chained."; + if (builtin_story_data().reload_when_chained.contains("01.02")){ + return "Expected 01.02 not to reload when chained."; } - const std::string problem = load_problem(dev_with_execution("01.01", R"("save": "menu")")); + const std::string problem = load_problem(dev_with_execution("01.02", R"("save": "unverified", "reload_when_chained": true)")); if (problem.find("does not end on the game's autosave") == std::string::npos){ - return std::format("01.01 saving through the menu: expected 01.02's reload refused, got \"{}\".", problem); + return std::format("01.02 reloading after 01.01's unverified autosave: expected it refused, got \"{}\".", problem); } return true; } @@ -484,8 +491,8 @@ UnitTestResult test_zone_1_exit_row(Logger&){ // 03.10 ends on the game's autosave on 3F, after the elevator ride; 03.11 // starts there, from Mable's walk on ("if this is the // auto save, we should divide a checkpoint here"). to_mable's legs were -// measured from the reloaded save, whose facing the ride does not leave, so -// 03.11 reloads it when chained after 03.10. +// measured from the reloaded save, whose facing the ride does not leave; +// 03.11 does not reload it while no run's log has shown that autosave. UnitTestResult test_director_office_row(Logger&){ const std::vector& rows = story_checkpoints(); size_t index = 0; @@ -504,8 +511,8 @@ UnitTestResult test_director_office_row(Logger&){ return "Expected 03.11 to run from to_mable to leave_mable."; } const StoryData& data = builtin_story_data(); - if (!data.autosaves.contains("03.10") || data.autosaves.contains("03.11") || !data.reload_when_chained.contains("03.11")){ - return "Expected 03.10 to end on the autosave and 03.11 to reload it when chained."; + if (!data.unverified_autosaves.contains("03.10") || data.autosaves.contains("03.11") || data.reload_when_chained.contains("03.11")){ + return "Expected 03.10 to end on an unverified autosave and 03.11 not to reload it when chained."; } return true; } @@ -523,17 +530,15 @@ UnitTestResult test_production_rows(Logger&){ "03.01", "03.02", "03.03", "03.04", "03.05", "03.06", "03.07", "03.08", "03.09", "03.10", "03.11", }; + // The rows a run's log showed [Autosave] at the end of. const std::set> autosaves{ - "01.00", "01.01", "01.02", "02.01", "02.02", "02.03", "02.04", "02.05", "02.06", "02.07", "03.01", "03.03", - // 03.08 ends on the street outside Wild Zone 1, which does not - // autosave; 03.09 ends on the Research Lab lobby's (user). - "03.09", - // 03.10 ends on the Director's Office's, on 3F (user). - "03.10", + "02.06", "03.01", "03.03", "03.05", "03.07", "03.08", "03.09", }; - const std::set> reload_when_chained{ - "01.02", "02.02", "02.03", "02.04", "02.05", "02.07", "03.01", "03.02", "03.04", "03.11", + // Believed to end on the game's autosave, not yet seen in a run's log. + const std::set> unverified_autosaves{ + "01.00", "01.01", "01.02", "02.01", "02.02", "02.03", "02.04", "02.05", "02.07", "03.10", }; + const std::set> reload_when_chained{"02.07", "03.02", "03.04"}; const std::set> reload_always{"03.04"}; const StoryData& data = builtin_story_data(); if (data.checkpoints.size() != ids.size()){ @@ -544,7 +549,8 @@ UnitTestResult test_production_rows(Logger&){ return std::format("Row {}: expected {}, got {}.", index, ids[index], data.checkpoints[index].id); } } - if (data.autosaves != autosaves || data.reload_when_chained != reload_when_chained + if (data.autosaves != autosaves || data.unverified_autosaves != unverified_autosaves + || data.reload_when_chained != reload_when_chained || data.reload_always != reload_always || !data.dev_files.empty() ){ return "Expected the built-in autosave and reload rows, and no dev files."; @@ -612,12 +618,12 @@ const AutoStoryTableCase AUTO_STORY_TABLE_CASES[] = { .expectation = {}, }, { - .name = "Story table: the autosave rows, and 01.03 saves through the menu", + .name = "Story table: the autosave rows, and 01.03 ends on no save", .input = {.body = test_autosave_rows}, .expectation = {}, }, { - .name = "Story table: 03.05 heals at the Pokemon Center and saves there", + .name = "Story table: 03.05 heals at the Pokemon Center and autosaves there", .input = {.body = test_mm3_heal_row}, .expectation = {}, }, @@ -632,7 +638,7 @@ const AutoStoryTableCase AUTO_STORY_TABLE_CASES[] = { .expectation = {}, }, { - .name = "reload_when_chained: 01.02 after 01.01's autosave", + .name = "reload_when_chained: refused on 01.02, after 01.01's unverified autosave", .input = {.body = test_mm1_reload_when_chained}, .expectation = {}, }, @@ -672,7 +678,7 @@ const AutoStoryTableCase AUTO_STORY_TABLE_CASES[] = { .expectation = {}, }, { - .name = "Director's Office: 03.10 ends on the 3F autosave, 03.11 reloads it for Mable", + .name = "Director's Office: 03.10 ends on the 3F autosave, unverified; 03.11 does not reload it", .input = {.body = test_director_office_row}, .expectation = {}, },