diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index b03c3bb1c5..ce0ec36aed 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -240,6 +240,8 @@ pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonFRLG/Programs/Aut VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h PokemonAutomation::NintendoSwitch::PokemonFRLG autostory_checkpoint_json) pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay.h PokemonAutomation::NintendoSwitch::PokemonFRLG story_replay_fixture_json) +pa_embed_text_files(SerialProgramsLib Source/Pokemon/Navigation/GateTestMaps + Pokemon/Navigation/Pokemon_NavigationGateTestMaps.h PokemonAutomation::Pokemon navigation_gate_test_map_json) # Create binary target diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index f9c4f6f51b..ed3655776b 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -39,6 +39,7 @@ #include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" #include "Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h" +#include "Pokemon/Navigation/Pokemon_Gates_Tests.h" #include "Pokemon/Navigation/Pokemon_LegPlanner_Tests.h" #include "Pokemon/Navigation/Pokemon_LegWalker_Tests.h" #include "Pokemon/Navigation/Pokemon_MapData_Tests.h" @@ -93,6 +94,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_WallRecovery(ret); Pokemon::add_tests_MapData(ret); Pokemon::add_tests_ConnectedMaps(ret); + Pokemon::add_tests_Gates(ret); Pokemon::add_tests_MoveMechanics(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp index 3d39269e07..c54b7f4141 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -323,8 +323,53 @@ DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source) return result; } +GateChange read_gate_change(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"opened", "switches"}, source); + GateChange result; + if (const JsonValue* field = root.get_value("opened")){ + for (std::string& key : read_strings(*field, source)){ + result.opened.insert(std::move(key)); + } + } + if (const JsonValue* field = root.get_value("switches")){ + for (const auto& [id, on] : field->to_object_throw(std::string(source))){ + result.switches[id] = on.to_boolean_throw(std::string(source)); + } + } + return result; +} + +JsonValue write_gate_change(const GateChange& change){ + JsonObject object; + if (!change.opened.empty()){ + JsonArray opened; + for (const std::string& key : change.opened){ + opened.push_back(key); + } + object["opened"] = std::move(opened); + } + if (!change.switches.empty()){ + JsonObject switches; + for (const auto& [id, on] : change.switches){ + switches[id] = on; + } + object["switches"] = std::move(switches); + } + return object; +} + +GateState read_gate_state(const JsonValue& value, std::string_view source){ + GateState result; + apply_gate_change(result, read_gate_change(value, source)); + return result; +} + +JsonValue write_gate_state(const GateState& state){ + return write_gate_change(gate_change_between(GateState(), state)); +} + StoryStep read_story_step(const JsonValue& value, std::string_view source, std::span actions){ - const JsonObject& root = fields(value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after"}, source); + const JsonObject& root = fields(value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after", "gates_after", "flags_after"}, source); StoryStep result; result.name = root.get_string_throw("id"); if (result.name.empty()){ @@ -344,11 +389,17 @@ StoryStep read_story_step(const JsonValue& value, std::string_view source, std:: if (const JsonValue* field = root.get_value("declared_after")){ result.pose_after = read_declared_pose(*field, source); } + if (const JsonValue* field = root.get_value("gates_after")){ + result.gates_after = read_gate_change(*field, source); + } + if (const JsonValue* field = root.get_value("flags_after")){ + result.flags_after = read_strings(*field, source); + } return result; } StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source, std::span actions){ - const JsonObject& root = fields(value, {"id", "title", "start", "events", "metadata"}, source); + const JsonObject& root = fields(value, {"id", "title", "start", "start_gates", "start_flags", "events", "metadata"}, source); StoryCheckpoint result; result.id = root.get_string_throw("id"); if (result.id.empty()){ @@ -358,6 +409,12 @@ StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view s if (const JsonValue* start = root.get_value("start")){ result.start = read_declared_pose(*start, source); } + if (const JsonValue* gates = root.get_value("start_gates")){ + result.start_gates = read_gate_state(*gates, source); + } + if (const JsonValue* flags = root.get_value("start_flags")){ + result.start_flags = read_strings(*flags, source); + } std::set names; result.steps_json = root.get_value_throw("events").dump(-1); for (const JsonValue& event : root.get_array_throw("events")){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h index a67f5df31c..5bc64ab097 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -36,6 +36,20 @@ GridPose read_grid_pose(const JsonValue& value, std::string_view source); DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source); +// Read a gate change, {"opened": ["SilphCo_5F/door_1"], "switches": {"mansion": true}} +// (the gates a step opens, the switches it sets; both optional, unknown +// fields fail) and write it back. +GateChange read_gate_change(const JsonValue& value, std::string_view source); +// The change as JSON, as read_gate_change() reads it. +JsonValue write_gate_change(const GateChange& change); + +// The same as a state: what a checkpoint's "start_gates" says is open and +// on. "switches" that are off need not be listed, and are not written. +GateState read_gate_state(const JsonValue& value, std::string_view source); +// The state as JSON, as read_gate_state() reads it. +JsonValue write_gate_state(const GateState& state); + + // Read a step, its args parsed against its action among `actions` (by // default the built-in ones; a game passes them with its own) and their // fallbacks filled in. Unknown fields, kinds, actions and args, mistyped diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 69f213ad13..7fcedf7887 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -134,6 +134,47 @@ const WireCase CASES[] = { const DeclaredPose start = ZoneDeclared{.place = "HotelZ", .spot = std::nullopt, .heading = std::nullopt}; return expect(checkpoint.start == start && checkpoint.steps.size() == 1 && checkpoint.steps[0].kind == StoryStepKind::MASH, "a zone start and one scene"); }}}, + {.input = {.name = "step opens gates", .json = R"({"id":"unlock","kind":"talk","gates_after":{"opened":["SilphCo_5F/door_1"],"switches":{"mansion":true}}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryStep& step = step_of(record); + GateChange expected; + expected.opened.insert("SilphCo_5F/door_1"); + expected.switches["mansion"] = true; + return expect(step.gates_after && *step.gates_after == expected, "door_1 opened and the mansion switch on"); + }}}, + {.input = {.name = "step with no gates", .json = R"({"id":"plain","kind":"talk"})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(!step_of(record).gates_after, "no gate change"); + }}}, + {.input = {.name = "flags: given after a step, held at the start", .record = Record::CHECKPOINT, .json = R"({"id":"16.02","title":"Silph","start_flags":["has_pass"],"events":[{"id":"a","kind":"talk","flags_after":["card_key_held"]},{"id":"b","kind":"talk"}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect( + checkpoint.start_flags == std::vector{"has_pass"} + && checkpoint.steps[0].flags_after == std::vector{"card_key_held"} + && checkpoint.steps[1].flags_after.empty(), + "start_flags and flags_after" + ); + }}}, + {.input = {.name = "gate change with an unknown field", .json = R"({"id":"x","kind":"talk","gates_after":{"closed":["a/b"]}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "checkpoint gate state", .record = Record::CHECKPOINT, .json = R"({"id":"16.02","title":"Silph","start_gates":{"opened":["SilphCo_5F/door_1"]},"events":[{"id":"a","kind":"talk","gates_after":{"opened":["SilphCo_5F/door_2"]}},{"id":"b","kind":"talk","gates_after":{"switches":{"mansion":true}}},{"id":"c","kind":"talk"}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + if (!checkpoint.start_gates || checkpoint.start_gates->opened.size() != 1){ + return std::string("Expected start_gates with door_1 open."); + } + const GateState none = checkpoint_gates(checkpoint, 0); + const GateState first = checkpoint_gates(checkpoint, 1); + const GateState all = checkpoint_gates(checkpoint, 3); + if (!(none == *checkpoint.start_gates) || first.opened.size() != 2 || first.switch_on("mansion")){ + return std::string("Expected the start, then door_2 as well after one step."); + } + if (!all.switch_on("mansion") || !(checkpoint_gates(checkpoint, 99) == all)){ + return std::string("Expected the switch on after the steps, and past the end the same."); + } + const JsonValue written = write_gate_state(all); + return expect(read_gate_state(written, "round trip") == all, "the gate state to read back as written"); + }}}, + {.input = {.name = "checkpoint without gates", .record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect(!checkpoint.start_gates && checkpoint_gates(checkpoint, 1) == GateState(), "no start gates and nothing open"); + }}}, {.input = {.name = "ordered checkpoint", .record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[ {"id":"first","kind":"talk"}, {"id":"second","kind":"scene"} ]})"}, .expectation = {.check = [](const ReadRecord& record){ const StoryCheckpoint& checkpoint = std::get(record); return expect(checkpoint.id == "00.05" && checkpoint.title == "Parcel" && !checkpoint.start && checkpoint.steps.size() == 2 diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h index b9c0eb53db..d3081a8a8c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h @@ -17,6 +17,8 @@ #include #include #include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon/Navigation/Pokemon_GatedTypes.h" +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon_StoryLog.h" namespace PokemonAutomation{ @@ -70,8 +72,17 @@ std::string to_string(const Pose& pose); struct RunState{ Pose pose; std::set flags; + // The gates open and the switches on (Pokemon_GateState.h): from the + // checkpoint's start_gates, then each step's gates_after as it is done. + GateState gates; }; +// The rules a plan over `state`'s gates follows: the flag "card_key_held" +// (set after the Card Key is picked up) lets it open card-key gates. +inline GateRules gate_rules_of(const RunState& state){ + return GateRules{.card_key_held = state.flags.contains("card_key_held")}; +} + } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp index 4693e73eec..dcb18049cb 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp @@ -52,7 +52,15 @@ Event story_event(const StoryStep& step, StoryStepExecutor& executor){ })); } event.act = [&executor, &step](RunState& state){ - return executor.run(step, state); + Outcome outcome = executor.run(step, state); + // What a step that failed did to the game is not known to the run. + if (outcome.succeeded()){ + if (step.gates_after){ + apply_gate_change(state.gates, *step.gates_after); + } + state.flags.insert(step.flags_after.begin(), step.flags_after.end()); + } + return outcome; }; if (step.pose_after){ event.pose_learned = pose_of(*step.pose_after); @@ -63,13 +71,24 @@ Event story_event(const StoryStep& step, StoryStepExecutor& executor){ namespace{ // The first event of a checkpoint that starts from a save: where the save -// leaves the player, for a run that reloaded it. -Event from_save_event(const Pose& start){ +// leaves the player, and the gates and flags it has, for a run that +// reloaded it. +Event from_save_event(const StoryCheckpoint& data){ Event event; event.name = "from_save"; event.why = "where the checkpoint's save leaves the player"; - event.act = [](RunState&){ return outcome_ok(); }; - event.pose_learned = start; + // A checkpoint that does not say what its save has leaves the run's + // gates as the steps before it made them. + event.act = [gates = data.start_gates, flags = data.start_flags](RunState& state){ + if (gates){ + state.gates = *gates; + } + state.flags.insert(flags.begin(), flags.end()); + return outcome_ok(); + }; + if (data.start){ + event.pose_learned = pose_of(*data.start); + } return event; } @@ -99,8 +118,8 @@ Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor executor.begin_attempt(data); Checkpoint checkpoint; checkpoint.id = data.id; - if (data.start){ - checkpoint.events.push_back(from_save_event(pose_of(*data.start))); + if (data.start || data.start_gates || !data.start_flags.empty()){ + checkpoint.events.push_back(from_save_event(data)); } for (const StoryStep& step : data.steps){ checkpoint.events.push_back(story_event(step, executor)); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp index e22aa36eea..a14b5b766d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -50,6 +50,9 @@ class FakeExecutor : public StoryStepExecutor{ std::map failures_left; // The pose each step started from, by name. std::vector> poses_seen; + // The gates and the run flags each step started with, by name. + std::vector> gates_seen; + std::vector>> flags_seen; // The checkpoints begun, one per attempt. std::vector attempts; // Game steps by name that change nothing in the game. @@ -61,6 +64,8 @@ class FakeExecutor : public StoryStepExecutor{ virtual Outcome run(const StoryStep& step, RunState& state) override{ poses_seen.emplace_back(step.name, to_string(state.pose)); + gates_seen.emplace_back(step.name, state.gates); + flags_seen.emplace_back(step.name, state.flags); trace.push_back(std::format("{} {}", story_step_kind_name(step.kind), step.name)); if (failing.contains(step.name)){ return outcome_failed("blocked", std::format("{} was blocked", step.name)); @@ -294,6 +299,51 @@ UnitTestResult test_pose_propagation(){ return true; } +// A checkpoint whose save has Silph's first door open: a step opens the +// second and gives the Card Key, a failing step changes nothing. +StoryCheckpoint silph_checkpoint(){ + StoryStep key = make(StoryStepKind::TALK, "card_key"); + key.gates_after = GateChange{.opened = {"SilphCo_5F/door_2"}}; + key.flags_after = {"card_key_held"}; + StoryStep blocked = make(StoryStepKind::TALK, "blocked"); + blocked.gates_after = GateChange{.opened = {"SilphCo_5F/door_3"}}; + blocked.flags_after = {"never"}; + GateState start; + start.opened.insert("SilphCo_5F/door_1"); + return StoryCheckpoint{ + .id = "16.02", + .title = "Silph", + .steps = {make(StoryStepKind::TALK, "before"), key, make(StoryStepKind::TALK, "after"), blocked}, + .start_gates = start, + .start_flags = {"has_pass"}, + }; +} + +UnitTestResult test_gate_state_carried(){ + const StoryCheckpoint data = silph_checkpoint(); + FakeExecutor executor; + executor.failing = {"blocked"}; + const Run result = run(data, executor); + if (executor.gates_seen.size() != 4){ + return std::format("Expected four steps run, got {}:{}", executor.gates_seen.size(), joined(executor.trace)); + } + const GateState& before = executor.gates_seen[0].second; + const GateState& after = executor.gates_seen[2].second; + if (before.opened != std::set{"SilphCo_5F/door_1"} || !executor.flags_seen[0].second.contains("has_pass")){ + return "Expected the save's own gates and flags at the first step."; + } + if (executor.flags_seen[1].second.contains("card_key_held")){ + return "The Card Key was held before its step was done."; + } + if (after.opened != std::set{"SilphCo_5F/door_1", "SilphCo_5F/door_2"} || !executor.flags_seen[2].second.contains("card_key_held")){ + return "Expected door_2 open and the Card Key held after the step that gave it."; + } + if (result.state.gates.opened.contains("SilphCo_5F/door_3") || result.state.flags.contains("never")){ + return "A step that failed changed the gates or the flags."; + } + return true; +} + UnitTestResult test_failure_names_the_step(){ const StoryCheckpoint data = lab_checkpoint(); FakeExecutor executor; @@ -772,6 +822,10 @@ const StoryStepTestCase STORY_STEP_CASES[] = { .input = {.name = "a failure names its step", .test = test_failure_names_the_step}, .expectation = {.description = "records failing step identifier on error"}, }, + { + .input = {.name = "gate state and run flags carried from the save through the steps", .test = test_gate_state_carried}, + .expectation = {.description = "applies start_gates, start_flags, gates_after and flags_after in order"}, + }, { .input = {.name = "unsupported kinds and lost battles", .test = test_unsupported_and_lost_battles}, .expectation = {.description = "flags unsupported step types and handles battle defeat"}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h index 6a0c04702d..cc3bf66ce3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -14,6 +14,7 @@ #include #include #include +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon_DeclaredPose.h" #include "Pokemon_StoryCheckpointMetadata.h" #include "Pokemon_StoryPostconditions.h" @@ -39,8 +40,23 @@ struct StoryCheckpoint{ // Its phase and verification (JSON "metadata"), which decide when a // run of it may save. StoryCheckpointMetadata metadata = {}; + // Which gates are open and which switches are on at the start, where the + // save has any of the story's gates (Silph Co., Pokemon Mansion); none + // where the checkpoint does not say, which the run infers from the + // story so far, or else observes. JSON: "start_gates". + std::optional start_gates = {}; + // The run flags that hold at the start, as flags_after would have set + // them in the story so far, which a reload loses ("card_key_held" in a + // save made after the Card Key). JSON: "start_flags". + std::vector start_flags = {}; }; +// The gate state of `checkpoint` once its first `steps_done` steps are done: +// its start_gates (nothing open, no switch on if it has none) with the +// steps' gates_after applied in order. `steps_done` past the last step is +// the end. +GateState checkpoint_gates(const StoryCheckpoint& checkpoint, size_t steps_done); + } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp new file mode 100644 index 0000000000..2a3561835c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp @@ -0,0 +1,28 @@ +/* Story Checkpoint Gates + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +GateState checkpoint_gates(const StoryCheckpoint& checkpoint, size_t steps_done){ + GateState gates = checkpoint.start_gates.value_or(GateState()); + const size_t done = std::min(steps_done, checkpoint.steps.size()); + for (size_t c = 0; c < done; c++){ + if (checkpoint.steps[c].gates_after){ + apply_gate_change(gates, *checkpoint.steps[c].gates_after); + } + } + return gates; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h index 4500111b71..d561b0add0 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -15,6 +15,7 @@ #include #include #include +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon_DeclaredPose.h" #include "Pokemon_StoryActionArg.h" #include "Pokemon_StoryStepKind.h" @@ -51,6 +52,14 @@ struct StoryStep{ // Where the step leaves the player, when its action does not say: the // end of a scene that moves the player. std::optional pose_after; + // The gates the step opens and the switches it sets + // (Pokemon/Navigation/Pokemon_GateState.h), applied to the run's gate + // state when the step is done. + std::optional gates_after = {}; + // The run flags the step sets when it is done (JSON "flags_after"): what + // the story's later steps and the planner read, as "card_key_held" after + // the Card Key is picked up, which lets plans open card-key gates. + std::vector flags_after = {}; }; diff --git a/SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/PokemonMansion_1F.json b/SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/PokemonMansion_1F.json new file mode 100644 index 0000000000..a7d5797eb4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/PokemonMansion_1F.json @@ -0,0 +1,63 @@ +{ + "format": "pokesim-runtime-map/2", + "name": "PokemonMansion_1F", + "source": {"decomp_file": "data/maps/PokemonMansion_1F/map.json", "revision": "ce6406d8c2eaf46d543c8a2606de0c3cb1951982", "date": "2026-10-31"}, + "tiles": [ + "######################################", + "######################################", + "######################################", + "#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#", + "#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#", + "#~~#~#~###~~~#~~~~~#~#~#~#~~#####~~~~#", + "#~~#~~~###~~~#~~~~~#~#~#~#~~#####~~~##", + "#~~~~~~~~~~~~#~~~~~~~~~~~~~~#####~~~##", + "#~~~~~~~~~~~~#~~~~~~~~~~~~~~#~~~~~~~~#", + "#~~~~~~~~~~~~##~~~####~~~####~~~~~~~~#", + "################~~####GGG####~~~###~~#", + "################~~####GGG####~~~###~~#", + "##############~~~~#~~~~~~~####~~~~~~~#", + "#~~~~~~~~~.###~~~~#~~~~~~~~###~~~~~~~#", + "#~~~~~~~~~~###~~~~#~~~~~~~~~##~~~~~~~#", + "#~~~~~~~~~~~~~~~~~#~~~~~~~~~##~~~~~~~#", + "#~~~~~~~~~~~~~~~~~#~~~~~~~~~##~~~~~~~#", + "#~~~~~~~~~~~~~~~###############~~~####", + "#~~~~~~~~~~~~~~~###############GGG####", + "##~~~~~~~~~~~~~~###############GGG####", + "###~~#~~~~~#~~~##~~#####~~~~~~~~~~~~~#", + "###~~#~~~~~#~~~##~~~~~~#~~~~~~~~~~~~~#", + "###~~#~~~~~#~~~##~~~~~~#~~~~~~~~~~~~~#", + "###~~~~~~~~~~~~~#~~~~~~#~~~~~~~~~~~~~#", + "#~~~~~~~~~~~~~~~#~~~~~~####~~~##~~~###", + "#~~~~#~~~~~#~~~~#~~~~~~####GGG##GGG###", + "#~~~~#~~~~~#~~~~#~~########GGG##GGG###", + "#~~~~#~~~~~#~~~~#~~~~~~##.~~~~~#~~~~~#", + "#~~~~~~~~~~~~~~~#~~~~~~##~~~~~~#~~~~~#", + "#~~~~~~~~~~~~~~~#~~~~~~~~~~~~~~#~~~~~#", + "#~~~~#~~~~~#~~~~#~~~~~~~~~~~~~~#~~~~~#", + "#~~~~#~~~~~#~~~~#~~~~~~~~~~~~~~#~~~~~#", + "#~~~~#~~~~~#~~~~#~~######~~~~~~#~~~~~#", + "#~~~~~~~.~~~~~~~#~~~~~~~~~~~~~~#~~.~~#", + "######################################" + ], + "points": {"warp_1": [8, 33], "warp_3": [10, 13], "warp_4": [25, 27], "warp_7": [19, 22], "warp_8": [20, 22]}, + "warps": [ + {"enter": "walk_into", "to_map": "CinnabarIsland", "to_point": "warp_0", "coord": [7, 33]}, + {"enter": "walk_south", "to_map": "CinnabarIsland", "to_point": "warp_0", "coord": [8, 33]}, + {"enter": "walk_into", "to_map": "CinnabarIsland", "to_point": "warp_0", "coord": [9, 33]}, + {"enter": "walk_east", "to_map": "PokemonMansion_2F", "to_point": "warp_2", "coord": [10, 13]}, + {"enter": "walk_west", "to_map": "PokemonMansion_B1F", "to_point": "warp_0", "coord": [25, 27]}, + {"enter": "walk_south", "to_map": "CinnabarIsland", "to_point": "warp_0", "coord": [34, 33]}, + {"enter": "walk_into", "to_map": "CinnabarIsland", "to_point": "warp_0", "coord": [35, 34]}, + {"enter": "walk_into", "to_map": "PokemonMansion_3F", "to_point": "warp_3", "coord": [19, 22]}, + {"enter": "walk_into", "to_map": "PokemonMansion_3F", "to_point": "warp_4", "coord": [20, 22]}, + {"enter": "walk_into", "to_map": "PokemonMansion_2F", "to_point": "warp_2", "coord": [11, 13]} + ], + "connections": [], + "gates": { + "barrier_1": {"tiles": [[22, 10], [22, 11], [23, 10], [23, 11], [24, 10], [24, 11]], "open_glyph": "~", "new_game": "closed", "switch": "mansion", "open_when": "on"}, + "barrier_2": {"tiles": [[31, 18], [31, 19], [32, 18], [32, 19], [33, 18], [33, 19]], "open_glyph": "~", "new_game": "open", "switch": "mansion", "open_when": "off"}, + "barrier_3": {"tiles": [[27, 25], [27, 26], [28, 25], [28, 26], [29, 25], [29, 26]], "open_glyph": "~", "new_game": "closed", "switch": "mansion", "open_when": "on"}, + "barrier_4": {"tiles": [[32, 25], [32, 26], [33, 25], [33, 26], [34, 25], [34, 26]], "open_glyph": "~", "new_game": "closed", "switch": "mansion", "open_when": "on"} + }, + "switches": {"mansion": {"flag": "FLAG_POKEMON_MANSION_SWITCH_STATE", "toggle": true, "floors": ["PokemonMansion_1F", "PokemonMansion_2F", "PokemonMansion_3F", "PokemonMansion_B1F"], "statues": [{"coord": [5, 5], "face_from": [5, 6], "facing": "north"}]}} +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/PokemonMansion_3F.json b/SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/PokemonMansion_3F.json new file mode 100644 index 0000000000..8dc8b4874e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/PokemonMansion_3F.json @@ -0,0 +1,59 @@ +{ + "format": "pokesim-runtime-map/2", + "name": "PokemonMansion_3F", + "source": {"decomp_file": "data/maps/PokemonMansion_3F/map.json", "revision": "ce6406d8c2eaf46d543c8a2606de0c3cb1951982", "date": "2026-10-31"}, + "tiles": [ + "######################################", + "######################################", + "######################################", + "#~~~~~##.~~~~~~~###~~#~~~~~~~#~~~#~~~#", + "#~~~~~##~~~~~~~~~##~~#~~~~~~~#~~~~#~~#", + "##~~~~~~~~~~#~~~~##~~#~~###~~#~~~~##~#", + "###~~~~~~~~~~~~~~~~~~G~~###~~~~~~~~###", + "###~~~~~~~~~~~~~~~~~~G~~~~~~~~~~~~~~~#", + "########~######~~~~~~G~~~~~~~~~~~~~~~#", + "###############~~~~~~#~~~~~~~~~~~~~~~#", + "########~########~~~######~###~#######", + "#~###~~~~##.~~###GGG##################", + "#~~##~~~~##~~~###GGG######~~~~~#######", + "#~~#~~~~~~~~~~##~~~~~~~~~~~~~~~~~~~~~#", + "#~~~~~~~~~~~~~#~~~~~~~~~~~~~~~~~~~~~~#", + "#~~~~~~~~~~~~~####~~~##~~##~~#########", + "#~~~~~###~~~~~####~~~##~~##~~#########", + "####~~###~~~~#####~~~##~~##~~#########", + "####~~~~~~~~######~~~##~~##~~~~~##.~~#", + "#~~~~~~~~~~################~~~~~##~~~#", + "#~~~~~~~~~~~~~#############~~~~~~~~~~#", + "#~~~~~~~~~~~~~#############~~~~~~~~~~#", + "######################################", + "######################################", + "######################################", + "######################################", + "######################################", + "######################################", + "######################################", + "######################################", + "######################################", + "######################################", + "######################################", + "######################################", + "######################################" + ], + "points": {"warp_0": [8, 3], "warp_1": [34, 18], "warp_2": [11, 11], "warp_3": [18, 18], "warp_4": [19, 18], "warp_5": [23, 18]}, + "warps": [ + {"enter": "walk_west", "to_map": "PokemonMansion_2F", "to_point": "warp_0", "coord": [8, 3]}, + {"enter": "walk_west", "to_map": "PokemonMansion_2F", "to_point": "warp_1", "coord": [34, 18]}, + {"enter": "walk_west", "to_map": "PokemonMansion_2F", "to_point": "warp_3", "coord": [11, 11]}, + {"enter": "step_on", "to_map": "PokemonMansion_1F", "to_point": "warp_7", "one_way": true, "coord": [18, 18]}, + {"enter": "step_on", "to_map": "PokemonMansion_1F", "to_point": "warp_8", "one_way": true, "coord": [19, 18]}, + {"enter": "step_on", "to_map": "PokemonMansion_2F", "to_point": "warp_4", "one_way": true, "coord": [23, 18]}, + {"enter": "step_on", "to_map": "PokemonMansion_1F", "to_point": "warp_8", "one_way": true, "coord": [20, 18]}, + {"enter": "step_on", "to_map": "PokemonMansion_2F", "to_point": "warp_4", "one_way": true, "coord": [24, 18]} + ], + "connections": [], + "gates": { + "barrier_1": {"tiles": [[21, 6], [21, 7], [21, 8]], "open_glyph": "~", "new_game": "open", "switch": "mansion", "open_when": "off"}, + "barrier_2": {"tiles": [[17, 11], [17, 12], [18, 11], [18, 12], [19, 11], [19, 12]], "open_glyph": "~", "new_game": "closed", "switch": "mansion", "open_when": "on"} + }, + "switches": {"mansion": {"flag": "FLAG_POKEMON_MANSION_SWITCH_STATE", "toggle": true, "floors": ["PokemonMansion_1F", "PokemonMansion_2F", "PokemonMansion_3F", "PokemonMansion_B1F"], "statues": [{"coord": [12, 5], "face_from": [12, 6], "facing": "north"}]}} +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/SilphCo_5F.json b/SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/SilphCo_5F.json new file mode 100644 index 0000000000..53ecd291ad --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/SilphCo_5F.json @@ -0,0 +1,45 @@ +{ + "format": "pokesim-runtime-map/2", + "name": "SilphCo_5F", + "source": {"decomp_file": "data/maps/SilphCo_5F/map.json", "revision": "ce6406d8c2eaf46d543c8a2606de0c3cb1951982", "date": "2026-10-31"}, + "tiles": [ + "####################################", + "####################################", + "############################...#####", + "######################D#####...#####", + ".......##........###................", + ".......##...........................", + ".#.#.#.##...........................", + ".......##.........##########..#####.", + ".......##.........##########..#####.", + ".......GG..#########............###.", + ".......GG..#########.............##.", + ".#.#.#.##..##.....##.....######..##.", + ".......##..##.....##........###..##.", + "#########..###....GG........###..##.", + "#########..##.....GG........###..##.", + ".......##..##.....##.....######..##.", + "...##..##..###....##.............##.", + ".#####.##..##.....##.............##.", + "..####.GG..########################.", + "...###.GG..########################.", + "...###.##....#..#..#..#..#..#..#....", + ".......##..........................." + ], + "points": {"warp_0": [28, 2], "warp_1": [15, 7], "warp_2": [30, 2], "warp_3": [10, 20], "warp_4": [2, 20], "warp_5": [33, 5]}, + "warps": [ + {"enter": "walk_west", "to_map": "SilphCo_4F", "to_point": "warp_0", "coord": [28, 2]}, + {"enter": "step_on", "to_map": "SilphCo_3F", "to_point": "warp_1", "coord": [15, 7]}, + {"enter": "walk_east", "to_map": "SilphCo_6F", "to_point": "warp_2", "coord": [30, 2]}, + {"enter": "step_on", "to_map": "SilphCo_9F", "to_point": "warp_1", "coord": [10, 20]}, + {"enter": "step_on", "to_map": "SilphCo_3F", "to_point": "warp_5", "coord": [2, 20]}, + {"enter": "step_on", "to_map": "SilphCo_7F", "to_point": "warp_2", "coord": [33, 5]}, + {"enter": "walk_into", "to_map": "SilphCo_Elevator", "to_point": "warp_0", "coord": [22, 3]} + ], + "connections": [], + "gates": { + "door_1": {"tiles": [[7, 9], [7, 10], [8, 9], [8, 10]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "FLAG_SILPH_5F_DOOR_1"}, + "door_2": {"tiles": [[7, 18], [7, 19], [8, 18], [8, 19]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "FLAG_SILPH_5F_DOOR_2"}, + "door_3": {"tiles": [[18, 13], [18, 14], [19, 13], [19, 14]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "FLAG_SILPH_5F_DOOR_3"} + } +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp new file mode 100644 index 0000000000..8488e7783d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp @@ -0,0 +1,67 @@ +/* Gate State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_GateState.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +bool GateState::switch_on(const std::string& id) const{ + return switches_on.contains(id); +} + +std::string gate_key(const std::string& map, const std::string& gate_id){ + return map + "/" + gate_id; +} + +void apply_gate_change(GateState& state, const GateChange& change){ + state.opened.insert(change.opened.begin(), change.opened.end()); + for (const auto& [id, on] : change.switches){ + if (on){ + state.switches_on.insert(id); + }else{ + state.switches_on.erase(id); + } + } +} + +GateChange gate_change_between(const GateState& before, const GateState& after){ + GateChange change; + for (const std::string& key : after.opened){ + if (!before.opened.contains(key)){ + change.opened.insert(key); + } + } + for (const std::string& id : after.switches_on){ + if (!before.switch_on(id)){ + change.switches[id] = true; + } + } + for (const std::string& id : before.switches_on){ + if (!after.switch_on(id)){ + change.switches[id] = false; + } + } + return change; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +size_t std::hash::operator()(const PokemonAutomation::Pokemon::GateState& state) const{ + size_t hash = 0; + for (const std::string& key : state.opened){ + hash = hash * 31 + std::hash()(key); + } + for (const std::string& id : state.switches_on){ + hash = hash * 37 + std::hash()(id); + } + return hash; +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h new file mode 100644 index 0000000000..b8d007d668 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h @@ -0,0 +1,76 @@ +/* Gate State + * + * From: https://github.com/PokemonAutomation/ + * + * Which of the maps' gates (MapData::gates) are open: the card-key doors + * the player has opened, and the state of each switch. A switch is shared + * by every map that lists it as a floor (Pokemon Mansion's statue + * switch), and every gate that follows it is open or closed with it. + * + * The state is plain data, with no map in it; the story keeps it + * (Pokemon_StoryCheckpoint.h). What it makes of a map's tiles is + * Pokemon_GateTiles.h, and the gated planner (Pokemon_GatedPlanner.h) + * searches over it. + * + */ + +#ifndef PokemonAutomation_Pokemon_GateState_H +#define PokemonAutomation_Pokemon_GateState_H + +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Which gates are open and which switches are on. +struct GateState{ + // The card-key gates opened, each as gate_key(map, gate id). + std::set opened; + // The switches (by id) that are on. One not here is off, as at a new game. + std::set switches_on; + + bool operator==(const GateState& other) const = default; + + bool switch_on(const std::string& id) const; +}; + +// What a story step does to the state: gates it opens and switches it sets. +// What a step does to a GateState: gates it opens, switches it sets. +struct GateChange{ + std::set opened; + // The switch's new state, on or off. + std::map switches; + + bool operator==(const GateChange& other) const = default; +}; + +// Names a gate across maps: "SilphCo_5F/door_1". +std::string gate_key(const std::string& map, const std::string& gate_id); + +// Puts `change` on `state`: its gates are opened and its switches set. +void apply_gate_change(GateState& state, const GateChange& change); + +// The change that takes `before` to `after`: the gates `after` has opened +// that `before` has not, and the switches whose state differs. A card-key +// gate does not close again, so one `before` has opened and `after` has not +// is ignored. +GateChange gate_change_between(const GateState& before, const GateState& after); + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +// A hash of GateState, for planners that keep it in the search state. +template <> +struct std::hash{ + size_t operator()(const PokemonAutomation::Pokemon::GateState& state) const; +}; + +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp new file mode 100644 index 0000000000..bca7bbbdd8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp @@ -0,0 +1,93 @@ +/* Gate Tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_GateTiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string switch_key(const MapSwitch& pressed){ + return pressed.floors.size() == 1 ? gate_key(pressed.floors.front(), pressed.id) : pressed.id; +} + +const MapSwitch* switch_with_button(const MapData& map, const TilePos& pos){ + for (const auto& [id, result] : map.switches){ + for (const TilePos& button : result.buttons){ + if (button == pos){ + return &result; + } + } + } + return nullptr; +} + +const MapGate* gate_at(const MapData& map, const TilePos& pos){ + for (const auto& [id, gate] : map.gates){ + for (const TilePos& tile : gate.tiles){ + if (tile == pos){ + return &gate; + } + } + } + return nullptr; +} + +bool gate_is_open(const MapData& map, const MapGate& gate, const GateState& state){ + if (gate.kind == GateKind::SWITCH){ + const auto found = map.switches.find(gate.switch_id); + const std::string key = found == map.switches.end() ? gate.switch_id : switch_key(found->second); + return state.switch_on(key) == gate.open_when_on; + } + return gate.open_at_new_game || state.opened.contains(gate_key(map.name, gate.id)); +} + +TileKind resolved_tile(const MapData& map, const TilePos& pos, const GateState& state){ + const TileKind tile = map.tiles.at(pos); + if (tile != TileKind::GATE){ + return tile; + } + const MapGate* gate = gate_at(map, pos); + return gate != nullptr && gate_is_open(map, *gate, state) ? gate->open_tile : TileKind::WALL; +} + +Grid resolve_tiles(const MapData& map, const GateState& state){ + Grid grid = map.tiles; + for (int y = 0; y < grid.height; y++){ + for (int x = 0; x < grid.width; x++){ + cell_at(TilePos{x, y}, grid) = resolved_tile(map, TilePos{x, y}, state); + } + } + return grid; +} + +const MapGate* closed_card_key_gate_faced(const MapData& map, const TilePos& from, Direction direction, const GateState& state){ + const TilePos ahead = from.next(direction); + if (!map.tiles.contains(ahead) || map.tiles.at(ahead) != TileKind::GATE){ + return nullptr; + } + const MapGate* gate = gate_at(map, ahead); + if (gate == nullptr || gate->kind != GateKind::CARD_KEY || gate_is_open(map, *gate, state)){ + return nullptr; + } + return gate; +} + +const MapSwitch* switch_pressed(const MapData& map, const TilePos& from, Direction direction){ + for (const auto& [id, result] : map.switches){ + for (const MapStatue& statue : result.statues){ + if (statue.face_from == from && statue.facing == direction){ + return &result; + } + } + } + return nullptr; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h new file mode 100644 index 0000000000..6a413df2a3 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h @@ -0,0 +1,60 @@ +/* Gate Tiles + * + * From: https://github.com/PokemonAutomation/ + * + * What a gate state (Pokemon_GateState.h) makes of a map's tiles: a closed + * gate is a wall; an open one is the tile its `open_glyph` names. + * + */ + +#ifndef PokemonAutomation_Pokemon_GateTiles_H +#define PokemonAutomation_Pokemon_GateTiles_H + +#include +#include "Pokemon_GateState.h" +#include "Pokemon_Grid.h" +#include "Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The name GateState::switches_on knows `pressed` by: its id when several +// maps share it (Pokemon Mansion's floors), and gate_key(its map, its id) +// when it is one map's own (each Victory Road floor has a +// "floor_switch_1" of its own, with its own flag). +std::string switch_key(const MapSwitch& pressed); + +// The switch whose boulder button is `pos`, or nullptr if no switch's is. +const MapSwitch* switch_with_button(const MapData& map, const TilePos& pos); + +// The gate that has `pos`, or nullptr if no gate does. +const MapGate* gate_at(const MapData& map, const TilePos& pos); + +// Whether `gate` of `map` is open: a card-key gate is open at a new game, +// if the map says so, or once opened; a switch's gate is open while the +// switch is in its `open_when` state. +bool gate_is_open(const MapData& map, const MapGate& gate, const GateState& state); + +// The tile at `pos` for walking: a gate tile is a wall while its gate is +// closed and its `open_glyph` tile once open; any other tile is as it is. +// `pos` must be inside the map. +TileKind resolved_tile(const MapData& map, const TilePos& pos, const GateState& state); + +// All the map's tiles, resolved. +Grid resolve_tiles(const MapData& map, const GateState& state); + +// The closed card-key gate that a player standing on `from` and facing +// `direction` faces, or nullptr if there is none (a wall, an open gate, a +// switch's gate). +const MapGate* closed_card_key_gate_faced(const MapData& map, const TilePos& from, Direction direction, const GateState& state); + +// The switch with a statue that a player standing on `from` and facing +// `direction` presses with A, or nullptr if there is none. +const MapSwitch* switch_pressed(const MapData& map, const TilePos& from, Direction direction); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h new file mode 100644 index 0000000000..1528831b52 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h @@ -0,0 +1,233 @@ +/* Gated Planner + * + * From: https://github.com/PokemonAutomation/ + * + * Plans legs (Pokemon_LegPlanner.h) over maps with gates (Pokemon_GateState.h). + * The game's step model walks the maps with a gate state; this wraps it, so + * the search state is the game's state and the gate state: + * + * - a closed gate is a wall, so a route goes round it; + * - a closed card-key gate the player faces can be opened (an + * ACTION_OPEN_GATE leg: face it, press A), if the Card Key is held; the + * state after the leg has it open, and the route may go through; + * - a statue faced from its tile can be pressed (an ACTION_PRESS_SWITCH + * leg), which flips the switch, so every gate that follows it changes + * with it, on every floor. A route may flip it, and flip it back. + * + * The game's step model, as for plan_legs() but taking the gate state, and + * telling where its state is: + * + * using State = ...; + * using StateHash = ...; + * std::optional> press(const State&, Direction, const GateState&) const; + * bool held_at(const State&, Direction, const GateState&) const; + * MapPlace place_of(const State&) const; + * + * and may have open_stop_risk(const State&, Direction, const GateState&) + * const and tap_stop_risk() with the same parameters, as plan_legs()'s + * model may have them without the gates. + * + * press() reads each tile with resolved_tile(), which makes a closed gate a + * wall. One-way warps (MapWarp::one_way) are the game's to take as any warp: + * the model leads the player to the warp's arrival, and the maps give no way + * back from it, so a route takes it forward only. + * + */ + +#ifndef PokemonAutomation_Pokemon_GatedPlanner_H +#define PokemonAutomation_Pokemon_GatedPlanner_H + +#include +#include +#include +#include +#include +#include "Pokemon_ConnectedMaps.h" +#include "Pokemon_GateTiles.h" +#include "Pokemon_GatedTypes.h" +#include "Pokemon_LegPlanner.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A step model that weighs an open stop (see the top of this file). +template +concept HasOpenStopRisk = requires (const Inner& inner, const typename Inner::State& state, const GateState& gates){ + { inner.open_stop_risk(state, Direction::NORTH, gates) } -> std::convertible_to; +}; + +// A step model that weighs an open stop after one step (see the top of +// this file). +template +concept HasTapStopRisk = requires (const Inner& inner, const typename Inner::State& state, const GateState& gates){ + { inner.tap_stop_risk(state, Direction::NORTH, gates) } -> std::convertible_to>; +}; + +// The game's step model, wrapped: see the top of this file. +template +class GatedModel{ +public: + using InnerState = typename Inner::State; + using State = GatedState; + + struct StateHash{ + size_t operator()(const State& state) const{ + return typename Inner::StateHash()(state.inner) * 31 + std::hash()(state.gates); + } + }; + + // `inner` and `world` must outlive the model. + GatedModel(const Inner& inner, const ConnectedMaps& world, const GateRules& rules) + : m_inner(inner) + , m_world(world) + , m_rules(rules) + {} + + std::optional> press(const State& state, Direction direction) const{ + if (std::optional> walked = m_inner.press(state.inner, direction, state.gates)){ + return carry(*walked, state.gates); + } + const MapPlace place = m_inner.place_of(state.inner); + const MapData& map = m_world.map(place.map); + if (m_rules.card_key_held){ + if (const MapGate* gate = closed_card_key_gate_faced(map, place.tile, direction, state.gates)){ + return open_gate(state, map, *gate, direction); + } + } + if (const MapSwitch* pressed = switch_pressed(map, place.tile, direction)){ + return press_switch(state, *pressed, direction); + } + return std::nullopt; + } + + bool held_at(const State& state, Direction direction) const{ + return m_inner.held_at(state.inner, direction, state.gates); + } + + // The inner model's risk of an open stop (see Pokemon_LegPlanner.h), if + // it has one, read through the gates the stop is made in. + int open_stop_risk(const State& state, Direction direction) const requires HasOpenStopRisk{ + return m_inner.open_stop_risk(state.inner, direction, state.gates); + } + std::optional tap_stop_risk(const State& state, Direction direction) const requires HasTapStopRisk{ + return m_inner.tap_stop_risk(state.inner, direction, state.gates); + } + +private: + static Step carry(const Step& walked, const GateState& gates){ + Step step; + step.next = State{walked.next, gates}; + step.action = walked.action; + step.starts_leg = walked.starts_leg; + step.ends_leg = walked.ends_leg; + step.warped = walked.warped; + step.facing = walked.facing; + step.extra_cost = walked.extra_cost; + step.wild = walked.wild; + return step; + } + + // The player stays where they are, facing the gate, which is open afterwards. + Step open_gate(const State& state, const MapData& map, const MapGate& gate, Direction direction) const{ + Step step; + step.next = state; + step.next.gates.opened.insert(gate_key(map.name, gate.id)); + step.action = ACTION_OPEN_GATE; + step.ends_leg = true; + step.facing = direction; + step.extra_cost = m_rules.open_gate_cost; + return step; + } + + Step press_switch(const State& state, const MapSwitch& pressed, Direction direction) const{ + Step step; + step.next = state; + const std::string key = switch_key(pressed); + const bool now_on = pressed.toggle ? !state.gates.switch_on(key) : true; + if (now_on){ + step.next.gates.switches_on.insert(key); + }else{ + step.next.gates.switches_on.erase(key); + } + step.action = ACTION_PRESS_SWITCH; + step.ends_leg = true; + step.facing = direction; + step.extra_cost = m_rules.press_switch_cost; + return step; + } + + const Inner& m_inner; + const ConnectedMaps& m_world; + GateRules m_rules; +}; + + +// Where a plan starts: the game's state, the gates, and the way the player faces if known. +template +struct GatedStart{ + InnerState state; + GateState gates; + std::optional facing = std::nullopt; +}; + +// Where a plan ends: a state of the game where `at_goal` holds, facing `facing` if given. +template +struct GatedGoal{ + std::function at_goal; + std::optional facing = std::nullopt; +}; + +// The cheapest legs from `start` to `goal` (as plan_legs()), or nothing. +// Each leg's start and end carry the gate state; gate_change_of() says what +// an ACTION leg did to it. +template +std::optional>>> plan_gated_legs( + const Inner& inner, const ConnectedMaps& world, const GateRules& rules, + const GatedStart& start, + const GatedGoal& goal, + const LegCosts& costs = LegCosts() +); + +// What a leg did to the gates: the gate it opened, the switch it flipped. +template +GateChange gate_change_of(const Leg>& leg); + +// The gate state after the last of `legs`, or `before` if there are none. +template +GateState gates_after(const GateState& before, const std::vector>>& legs); + + +template +std::optional>>> plan_gated_legs( + const Inner& inner, const ConnectedMaps& world, const GateRules& rules, + const GatedStart& start, + const GatedGoal& goal, + const LegCosts& costs +){ + using State = GatedState; + const GatedModel model(inner, world, rules); + return plan_legs( + model, State{start.state, start.gates}, start.facing, + std::function([&](const State& state){ + return goal.at_goal(state.inner); + }), + goal.facing, costs + ); +} + +template +GateChange gate_change_of(const Leg>& leg){ + return gate_change_between(leg.start.gates, leg.end.gates); +} + +template +GateState gates_after(const GateState& before, const std::vector>>& legs){ + return legs.empty() ? before : legs.back().end.gates; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedTypes.h new file mode 100644 index 0000000000..70d1b3a4e1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedTypes.h @@ -0,0 +1,49 @@ +/* Gated Types + * + * From: https://github.com/PokemonAutomation/ + * + * What the gated planner (Pokemon_GatedPlanner.h) shares with the games + * that plan with it: its actions, rules, and search state. + * + */ + +#ifndef PokemonAutomation_Pokemon_GatedTypes_H +#define PokemonAutomation_Pokemon_GatedTypes_H + +#include "Pokemon_GateState.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The Step::action of the legs the wrapper adds. A game's own actions must +// differ from these. +constexpr int ACTION_OPEN_GATE = 1000; +// See ACTION_OPEN_GATE: the leg that presses a statue. +constexpr int ACTION_PRESS_SWITCH = 1001; + +// What the story lets a plan do, and what it costs. +struct GateRules{ + // The story state says the player holds the Card Key: a plan may open card-key gates. + bool card_key_held = false; + // Cost of opening a gate or pressing a statue, on top of LegCosts::per_tile: + // the dialog, and for a statue its yes/no. + int open_gate_cost = 10; + int press_switch_cost = 20; +}; + + +// The game's state and the gate state. +template +struct GatedState{ + InnerState inner; + GateState gates; + + bool operator==(const GatedState& other) const = default; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.cpp new file mode 100644 index 0000000000..46f062f7f6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.cpp @@ -0,0 +1,494 @@ +/* Gates Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Fixtures: GateTestMaps/, trimmed from PokemonSimulation's runtime maps + * (SilphCo_5F: card-key doors; PokemonMansion_1F and _3F: statue switch, + * barriers, holes). + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_GatedPlanner.h" +#include "Pokemon_Gates_Tests.h" +#include "Pokemon_NavigationGateTestMaps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + + +MapData load(const std::string& name){ + for (const auto& [file, text] : navigation_gate_test_map_json()){ + if (file == name){ + return parse_map(parse_json(text), name + ".json"); + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No gate test map " + name); +} + +// Silph 5F, Mansion 1F and 3F, in that order. +const std::vector& maps(){ + static const std::vector loaded{ + load("SilphCo_5F"), + load("PokemonMansion_1F"), + load("PokemonMansion_3F"), + }; + return loaded; +} +constexpr size_t SILPH = 0; +constexpr size_t MANSION_1F = 1; +constexpr size_t MANSION_3F = 2; + +const ConnectedMaps& world(){ + static const ConnectedMaps connected(maps()); + return connected; +} + + +// Walks the maps with the gates as the state says; a step onto a step-on +// warp takes it. Walk-into warps are not modeled: they are not the topic. +class GateGame{ +public: + using State = MapPlace; + using StateHash = std::hash; + + std::optional> press(const State& state, Direction direction, const GateState& gates) const{ + const MapData& map = world().map(state.map); + const TilePos next = state.tile.next(direction); + if (!map.tiles.contains(next) || !walkable(resolved_tile(map, next, gates))){ + return std::nullopt; + } + Step step; + step.next = {state.map, next}; + step.facing = direction; + for (const MapWarp& warp : map.warps){ + if (warp.enter != WarpEntry::STEP_ON || warp.x != next.x || warp.y != next.y){ + continue; + } + const std::optional arrival = warp.to ? world().warp_arrival(warp) : std::nullopt; + if (!arrival){ + return std::nullopt; + } + step.next = *arrival; + step.warped = true; + step.ends_leg = true; + } + return step; + } + bool held_at(const State& state, Direction direction, const GateState& gates) const{ + const MapData& map = world().map(state.map); + const TilePos next = state.tile.next(direction); + return !map.tiles.contains(next) || !walkable(resolved_tile(map, next, gates)); + } + MapPlace place_of(const State& state) const{ + return state; + } + +private: + static bool walkable(TileKind tile){ + return tile == TileKind::OPEN || tile == TileKind::TALL_GRASS; + } +}; + +using GatedLegs = std::vector>>; + +std::optional plan( + const MapPlace& from, const MapPlace& to, const GateState& gates, bool card_key_held +){ + GateRules rules; + rules.card_key_held = card_key_held; + return plan_gated_legs( + GateGame(), world(), rules, GatedStart{from, gates}, + GatedGoal{std::function([to](const MapPlace& place){ return place == to; })} + ); +} + +int count_actions(const GatedLegs& legs, int action){ + int count = 0; + for (const auto& leg : legs){ + if (leg.kind == LegKind::ACTION && leg.action == action){ + count++; + } + } + return count; +} + + +// Reader + +UnitTestResult test_reads_card_key_doors(){ + const MapData& silph = maps()[SILPH]; + if (silph.gates.size() != 3 || !silph.switches.empty()){ + return std::format("Expected 3 gates and no switches, got {} and {}.", silph.gates.size(), silph.switches.size()); + } + const auto found = silph.gates.find("door_1"); + if (found == silph.gates.end()){ + return "No door_1."; + } + const MapGate& door = found->second; + if (door.kind != GateKind::CARD_KEY || door.flag != "FLAG_SILPH_5F_DOOR_1" || door.open_at_new_game || + door.open_tile != TileKind::OPEN || door.tiles.size() != 4 + ){ + return "door_1 is not a closed card-key door of 4 tiles opening to floor with its flag."; + } + if (silph.tiles.at(TilePos{7, 9}) != TileKind::GATE){ + return "Tile (7, 9) is not a gate."; + } + return true; +} + +UnitTestResult test_reads_switches(){ + const MapData& first = maps()[MANSION_1F]; + if (first.gates.size() != 4 || first.switches.size() != 1){ + return std::format("Expected 4 gates and 1 switch, got {} and {}.", first.gates.size(), first.switches.size()); + } + const MapGate& open_first = first.gates.at("barrier_2"); + if (open_first.kind != GateKind::SWITCH || open_first.switch_id != "mansion" || open_first.open_when_on || !open_first.open_at_new_game){ + return "1F barrier_2 should open when the switch is off."; + } + if (!first.gates.at("barrier_1").open_when_on){ + return "1F barrier_1 should open when the switch is on."; + } + const MapSwitch& pressing = first.switches.at("mansion"); + if (!pressing.toggle || pressing.floors.size() != 4 || pressing.flag != "FLAG_POKEMON_MANSION_SWITCH_STATE"){ + return "The switch is a toggle on 4 floors with its flag."; + } + if (pressing.statues.size() != 1 || pressing.statues[0].tile != TilePos{5, 5} || + pressing.statues[0].face_from != TilePos{5, 6} || pressing.statues[0].facing != Direction::NORTH + ){ + return "1F statue should be (5, 5), pressed from (5, 6) facing north."; + } + return true; +} + +UnitTestResult test_reads_one_way_warps(){ + int drops = 0; + for (const MapWarp& warp : maps()[MANSION_3F].warps){ + drops += warp.one_way ? 1 : 0; + } + if (drops != 5){ + return std::format("Expected 5 one-way warps on 3F, got {}.", drops); + } + for (const MapWarp& warp : maps()[MANSION_1F].warps){ + if (warp.one_way){ + return "A 1F warp is one-way."; + } + } + return true; +} + +// A 3x3 map with `gates` and `switches` (JSON object text) on tiles "G..". +std::string parse_error(const std::string& rows, const std::string& gates, const std::string& switches){ + const std::string text = std::format(R"({{ + "format": "pokesim-runtime-map/2", "name": "T", + "source": {{"decomp_file": "x", "revision": "y", "date": "z"}}, + "tiles": [{}], "points": {{}}, "warps": [], "connections": [], + "gates": {}, "switches": {} + }})", rows, gates, switches); + try{ + parse_map(parse_json(text), "T.json"); + }catch (ParseException& e){ + return e.message(); + } + return ""; +} + +UnitTestResult test_gate_errors(){ + const std::string rows = R"("G..", "...", "...")"; + const std::string door = R"({"d": {"tiles": [[0, 0]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "F"}})"; + if (!parse_error(rows, door, "{}").empty()){ + return "A valid gate failed to parse."; + } + if (parse_error(rows, "{}", "{}").empty()){ + return "A G tile in no gate was accepted."; + } + if (parse_error(R"("...", "...", "...")", door, "{}").empty()){ + return "A gate on a tile that is not G was accepted."; + } + const std::string unknown_switch = R"({"d": {"tiles": [[0, 0]], "open_glyph": ".", "new_game": "closed", "switch": "nope", "open_when": "on"}})"; + if (parse_error(rows, unknown_switch, "{}").empty()){ + return "A gate on an unlisted switch was accepted."; + } + const std::string far_statue = R"({"s": {"flag": "F", "toggle": true, "floors": ["T"], "statues": [{"coord": [9, 9], "face_from": [1, 1], "facing": "north"}]}})"; + if (parse_error(rows, door, far_statue).empty()){ + return "A statue outside the map was accepted."; + } + return true; +} + + +// State and tiles + +UnitTestResult test_tiles_follow_state(){ + const MapData& silph = maps()[SILPH]; + GateState state; + if (resolved_tile(silph, TilePos{7, 9}, state) != TileKind::WALL){ + return "A closed door is not a wall."; + } + state.opened.insert(gate_key("SilphCo_5F", "door_1")); + if (resolved_tile(silph, TilePos{7, 9}, state) != TileKind::OPEN || resolved_tile(silph, TilePos{7, 18}, state) != TileKind::WALL){ + return "Only door_1 should be open."; + } + if (resolve_tiles(silph, state).at(TilePos{8, 10}) != TileKind::OPEN){ + return "resolve_tiles disagrees."; + } + + // The Mansion's gates follow the one switch on every floor. + const MapData& first = maps()[MANSION_1F]; + const MapData& third = maps()[MANSION_3F]; + GateState off; + GateState on; + on.switches_on.insert("mansion"); + if (resolved_tile(first, TilePos{22, 10}, off) != TileKind::WALL || resolved_tile(first, TilePos{22, 10}, on) != TileKind::TALL_GRASS){ + return "1F barrier_1 should open with the switch on."; + } + if (resolved_tile(third, TilePos{21, 6}, off) != TileKind::TALL_GRASS || resolved_tile(third, TilePos{21, 6}, on) != TileKind::WALL){ + return "3F barrier_1 should close with the switch on."; + } + return true; +} + +UnitTestResult test_gate_change(){ + GateState state; + GateChange change; + change.opened.insert("SilphCo_5F/door_1"); + change.switches["mansion"] = true; + apply_gate_change(state, change); + if (!state.opened.contains("SilphCo_5F/door_1") || !state.switch_on("mansion")){ + return "The change was not applied."; + } + GateChange off; + off.switches["mansion"] = false; + GateState after = state; + apply_gate_change(after, off); + if (after.switch_on("mansion") || !after.opened.contains("SilphCo_5F/door_1")){ + return "Turning the switch off changed more, or nothing."; + } + GateState rebuilt; + apply_gate_change(rebuilt, gate_change_between(GateState(), state)); + if (!(rebuilt == state)){ + return "gate_change_between from nothing does not rebuild the state."; + } + apply_gate_change(rebuilt, gate_change_between(state, after)); + if (!(rebuilt == after)){ + return "gate_change_between does not carry state to state."; + } + const GateState copy = after; + if (std::hash()(copy) != std::hash()(rebuilt)){ + return "Equal states hash differently."; + } + return true; +} + + +// Planner + +UnitTestResult test_silph_door_needs_key(){ + const MapPlace from{SILPH, {10, 9}}; + const MapPlace to{SILPH, {5, 9}}; + if (plan(from, to, GateState(), false)){ + return "Planned into the room without the Card Key."; + } + const auto legs = plan(from, to, GateState(), true); + if (!legs){ + return "No route with the Card Key."; + } + if (count_actions(*legs, ACTION_OPEN_GATE) != 1){ + return std::format("Expected one open-gate leg, got {}.", count_actions(*legs, ACTION_OPEN_GATE)); + } + GateChange expected; + expected.opened.insert("SilphCo_5F/door_1"); + for (const auto& leg : *legs){ + if (leg.kind == LegKind::ACTION){ + if (!(gate_change_of(leg) == expected)){ + return "The open-gate leg did not open door_1 alone."; + } + if (leg.direction != Direction::WEST || !(leg.start.inner == MapPlace{SILPH, {9, 9}})){ + return "Expected to open it facing west from (9, 9)."; + } + } + } + if (!gates_after(GateState(), *legs).opened.contains("SilphCo_5F/door_1")){ + return "The state after the plan does not have door_1 open."; + } + return true; +} + +UnitTestResult test_silph_open_door_needs_no_key(){ + GateState opened; + opened.opened.insert(gate_key("SilphCo_5F", "door_1")); + const auto legs = plan({SILPH, {10, 9}}, {SILPH, {5, 9}}, opened, false); + if (!legs){ + return "No route through an open door."; + } + if (count_actions(*legs, ACTION_OPEN_GATE) != 0){ + return "Opened a door that was open."; + } + return true; +} + +UnitTestResult test_mansion_press_opens_barrier(){ + // (19, 13) lies behind barrier_1 and barrier_2 of 1F, which open with the switch on. + const MapPlace from{MANSION_1F, {5, 8}}; + const MapPlace to{MANSION_1F, {19, 13}}; + const auto legs = plan(from, to, GateState(), false); + if (!legs){ + return "No route."; + } + if (count_actions(*legs, ACTION_PRESS_SWITCH) != 1){ + return std::format("Expected one statue press, got {}.", count_actions(*legs, ACTION_PRESS_SWITCH)); + } + if (!gates_after(GateState(), *legs).switch_on("mansion")){ + return "The switch is not on after the plan."; + } + for (const auto& leg : *legs){ + if (leg.kind == LegKind::ACTION && (leg.direction != Direction::NORTH || !(leg.start.inner == MapPlace{MANSION_1F, {5, 6}}))){ + return "Expected to press the statue from (5, 6) facing north."; + } + } + return true; +} + +UnitTestResult test_mansion_press_again(){ + // Switch already on; (25, 21) is reachable only with it off. + GateState on; + on.switches_on.insert("mansion"); + const auto legs = plan({MANSION_1F, {5, 6}}, {MANSION_1F, {25, 21}}, on, false); + if (!legs){ + return "No route."; + } + if (count_actions(*legs, ACTION_PRESS_SWITCH) != 1 || gates_after(on, *legs).switch_on("mansion")){ + return "Expected one press, ending with the switch off."; + } + return true; +} + +UnitTestResult test_mansion_no_press_needed(){ + // Reachable with the switch as it is: no press. + const auto legs = plan({MANSION_1F, {5, 6}}, {MANSION_1F, {5, 8}}, GateState(), false); + if (!legs || count_actions(*legs, ACTION_PRESS_SWITCH) != 0){ + return "Pressed a statue that was not needed."; + } + return true; +} + +UnitTestResult test_hole_one_way(){ + // The 3F hole at (18, 18) drops to 1F's (19, 22); nothing leads back up. + const auto down = plan({MANSION_3F, {18, 17}}, {MANSION_1F, {19, 22}}, GateState(), false); + if (!down){ + return "No route down the hole."; + } + bool warped = false; + for (const auto& leg : *down){ + warped = warped || leg.warps; + } + if (!warped){ + return "The route does not take the warp."; + } + if (plan({MANSION_1F, {19, 22}}, {MANSION_3F, {18, 17}}, GateState(), false)){ + return "Planned back up a hole."; + } + return true; +} + + +struct GatesTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_Gates : public UnitTest{ +public: + explicit Test_Gates(GatesTestCase scenario) + : UnitTest(std::format("Pokemon::Gates - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + GatesTestCase m_scenario; +}; + +const GatesTestCase GATES_CASES[] = { + { + .input = {.name = "reads card-key doors", .test = test_reads_card_key_doors}, + .expectation = {.description = "Silph 5F doors parse with tiles, flag, open glyph"}, + }, + { + .input = {.name = "reads switches and statues", .test = test_reads_switches}, + .expectation = {.description = "Mansion gates follow the switch; statue tile and press spot"}, + }, + { + .input = {.name = "reads one-way warps", .test = test_reads_one_way_warps}, + .expectation = {.description = "3F holes are one-way"}, + }, + { + .input = {.name = "gate errors", .test = test_gate_errors}, + .expectation = {.description = "bad gates fail to parse"}, + }, + { + .input = {.name = "tiles follow the state", .test = test_tiles_follow_state}, + .expectation = {.description = "closed gate is a wall, open is its glyph, Mansion follows the switch"}, + }, + { + .input = {.name = "gate change", .test = test_gate_change}, + .expectation = {.description = "apply and between agree"}, + }, + { + .input = {.name = "a card-key door needs the key", .test = test_silph_door_needs_key}, + .expectation = {.description = "open-gate leg only with the Card Key held"}, + }, + { + .input = {.name = "an open door needs no key", .test = test_silph_open_door_needs_no_key}, + .expectation = {.description = "no open-gate leg when the state has it open"}, + }, + { + .input = {.name = "a statue press opens a barrier", .test = test_mansion_press_opens_barrier}, + .expectation = {.description = "one press-switch leg; switch on afterwards"}, + }, + { + .input = {.name = "a press again closes it", .test = test_mansion_press_again}, + .expectation = {.description = "switch is part of the search state"}, + }, + { + .input = {.name = "no press when not needed", .test = test_mansion_no_press_needed}, + .expectation = {.description = "does not toggle without reason"}, + }, + { + .input = {.name = "a hole is one-way", .test = test_hole_one_way}, + .expectation = {.description = "down yes, back up no"}, + }, +}; + +} // namespace + + +void add_tests_Gates(UnitTestDatabase& database){ + for (const auto& scenario : GATES_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.h new file mode 100644 index 0000000000..e82848786c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.h @@ -0,0 +1,24 @@ +/* Gates Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_Gates_Tests_H +#define PokemonAutomation_Pokemon_Gates_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the gate tests: the map reader's gates, switches and one-way +// warps, the gate state, and the gated planner. +void add_tests_Gates(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp index 0f44118a9e..59e052b9de 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp @@ -43,6 +43,7 @@ constexpr std::pair GLYPHS[] = { {'o', TileKind::STOP_SPIN}, {'H', TileKind::FALL_HOLE}, {'B', TileKind::STRENGTH_BUTTON}, + {'G', TileKind::GATE}, }; constexpr std::pair WARP_ENTRIES[] = { @@ -368,6 +369,7 @@ MapWarp read_warp(const JsonObject& object, const std::string& where){ warp.x = pos.x; warp.y = pos.y; warp.enter = read_warp_entry(object, where); + warp.one_way = optional_bool(object, "one_way", false, where); const bool has_map = object.get_value("to_map") != nullptr; const bool has_point = object.get_value("to_point") != nullptr; if (has_map != has_point){ @@ -487,6 +489,131 @@ MapPatch read_patch(const JsonObject& object, const std::string& where){ return patch; } +// The tiles of a gate or a coordinate pair, `[x, y]` each. +std::vector read_pair_list(const JsonObject& object, const std::string& key, const std::string& where){ + const JsonArray* array = optional_array(object, key, where); + if (array == nullptr || array->empty()){ + throw ParseException(std::format("{}{} is not a non-empty list of [x, y].", where, key)); + } + std::vector pairs; + for (size_t c = 0; c < array->size(); c++){ + pairs.push_back(read_pair((*array)[c], std::format("{}{}[{}]", where, key, c))); + } + return pairs; +} + +TilePos read_pair_field(const JsonObject& object, const std::string& key, const std::string& where){ + return read_pair(read_field(object, key, where), std::format("{}{}", where, key)); +} + +bool read_on_off(const JsonObject& object, const std::string& key, const std::string& where){ + const std::string text = read_string(object, key, where); + if (text != "on" && text != "off"){ + throw ParseException(std::format("{}{} \"{}\" is not on or off.", where, key, text)); + } + return text == "on"; +} + +// A gate is a card-key door (opens_by and flag) or follows a switch (switch +// and open_when); never both. +MapGate read_gate(const std::string& id, const JsonObject& object, const std::string& where){ + MapGate gate; + gate.id = id; + gate.tiles = read_pair_list(object, "tiles", where); + const std::string glyph = read_string(object, "open_glyph", where); + const std::optional open = glyph.size() == 1 ? tile_from_glyph(glyph[0]) : std::nullopt; + if (!open || *open == TileKind::GATE){ + throw ParseException(std::format("{}open_glyph \"{}\" is not a tile glyph other than G.", where, glyph)); + } + gate.open_tile = *open; + const std::string new_game = read_string(object, "new_game", where); + if (new_game != "open" && new_game != "closed"){ + throw ParseException(std::format("{}new_game \"{}\" is not open or closed.", where, new_game)); + } + gate.open_at_new_game = new_game == "open"; + const bool by_key = object.get_value("opens_by") != nullptr || object.get_value("flag") != nullptr; + const bool by_switch = object.get_value("switch") != nullptr || object.get_value("open_when") != nullptr; + if (by_key == by_switch){ + throw ParseException(std::format("{}needs opens_by and flag, or switch and open_when, and not both.", where)); + } + if (by_key){ + const std::string opens_by = read_string(object, "opens_by", where); + if (opens_by != "card_key_face_a"){ + throw ParseException(std::format("{}opens_by \"{}\" is not card_key_face_a.", where, opens_by)); + } + gate.kind = GateKind::CARD_KEY; + gate.flag = read_string(object, "flag", where); + }else{ + gate.kind = GateKind::SWITCH; + gate.switch_id = read_string(object, "switch", where); + gate.open_when_on = read_on_off(object, "open_when", where); + } + return gate; +} + +std::map read_gates(const JsonObject& root, const std::string& where){ + std::map gates; + const JsonObject* object = optional_object(root, "gates", where); + if (object == nullptr){ + return gates; + } + for (const auto& [id, value] : *object){ + const std::string gate_where = std::format("{}gates.{}", where, id); + gates[id] = read_gate(id, as_object(value, gate_where), gate_where + "."); + } + return gates; +} + +MapStatue read_statue(const JsonObject& object, const std::string& where){ + MapStatue statue; + statue.tile = read_pair_field(object, "coord", where); + statue.face_from = read_pair_field(object, "face_from", where); + statue.facing = read_direction(object, "facing", where); + return statue; +} + +TilePos read_button(const JsonObject& object, const std::string& where){ + return read_pair_field(object, "coord", where); +} + +MapSwitch read_switch(const std::string& id, const JsonObject& object, const std::string& where){ + MapSwitch result; + result.id = id; + result.flag = read_string(object, "flag", where); + const JsonValue* toggle = object.get_value("toggle"); + if (toggle != nullptr && !toggle->is_boolean()){ + throw ParseException(std::format("{}toggle is not true or false.", where)); + } + result.toggle = toggle == nullptr || toggle->to_boolean_default(true); + const JsonArray* floors = optional_array(object, "floors", where); + if (floors == nullptr || floors->empty()){ + throw ParseException(std::format("{}floors is not a non-empty list of map names.", where)); + } + for (size_t c = 0; c < floors->size(); c++){ + const std::string* floor = (*floors)[c].to_string(); + if (floor == nullptr){ + throw ParseException(std::format("{}floors[{}] is not a string.", where, c)); + } + result.floors.push_back(*floor); + } + result.statues = read_list(object, "statues", where, read_statue); + result.buttons = read_list(object, "buttons", where, read_button); + return result; +} + +std::map read_switches(const JsonObject& root, const std::string& where){ + std::map switches; + const JsonObject* object = optional_object(root, "switches", where); + if (object == nullptr){ + return switches; + } + for (const auto& [id, value] : *object){ + const std::string switch_where = std::format("{}switches.{}", where, id); + switches[id] = read_switch(id, as_object(value, switch_where), switch_where + "."); + } + return switches; +} + void check_inside(const Grid& tiles, const TilePos& pos, const std::string& where){ if (!tiles.contains(pos)){ @@ -527,6 +654,45 @@ void check_places(const MapData& map, const std::string& where){ } } +// Every gate tile is a G tile, in one gate only; every G tile is in a +// gate; a gate follows a switch the map lists; a statue stands on a wall +// and is faced from a tile inside the map. +void check_gates(const MapData& map, const std::string& where){ + std::set in_gate; + for (const auto& [id, gate] : map.gates){ + for (size_t c = 0; c < gate.tiles.size(); c++){ + const std::string tile_where = std::format("{}gates.{}.tiles[{}]", where, id, c); + check_inside(map.tiles, gate.tiles[c], tile_where); + if (map.tiles.at(gate.tiles[c]) != TileKind::GATE){ + throw ParseException(std::format("{} {} is not a G tile.", tile_where, to_string(gate.tiles[c]))); + } + if (!in_gate.insert(gate.tiles[c]).second){ + throw ParseException(std::format("{} {} is in another gate too.", tile_where, to_string(gate.tiles[c]))); + } + } + if (gate.kind == GateKind::SWITCH && !map.switches.contains(gate.switch_id)){ + throw ParseException(std::format("{}gates.{}.switch \"{}\" is not in switches.", where, id, gate.switch_id)); + } + } + for (int y = 0; y < map.tiles.height; y++){ + for (int x = 0; x < map.tiles.width; x++){ + if (map.tiles.at({x, y}) == TileKind::GATE && !in_gate.contains(TilePos{x, y})){ + throw ParseException(std::format("{}tiles has a G at {} that no gate lists.", where, to_string(TilePos{x, y}))); + } + } + } + for (const auto& [id, result] : map.switches){ + for (size_t c = 0; c < result.statues.size(); c++){ + const std::string statue_where = std::format("{}switches.{}.statues[{}]", where, id, c); + check_inside(map.tiles, result.statues[c].tile, statue_where); + check_inside(map.tiles, result.statues[c].face_from, statue_where); + } + for (size_t c = 0; c < result.buttons.size(); c++){ + check_inside(map.tiles, result.buttons[c], std::format("{}switches.{}.buttons[{}]", where, id, c)); + } + } +} + } // namespace @@ -549,10 +715,13 @@ MapData parse_map(const JsonValue& json, const std::string& source_name){ map.flag_sets = read_flag_sets(root, where); map.connections = read_list(root, "connections", where, read_connection); map.patches = read_list(root, "patches", where, read_patch); + map.gates = read_gates(root, where); + map.switches = read_switches(root, where); check_places(map, where); for (const MapPatch& patch : map.patches){ cell_at(TilePos{patch.x, patch.y}, map.tiles) = patch.glyph; } + check_gates(map, where); return map; } diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h index 6b4d923fbf..35d485e577 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h @@ -26,9 +26,19 @@ * "triggers": [{"name": "mom_warning", "box": {"x0": 1, "y0": 2, "x1": 1, "y1": 2}, "when": "00.01"}, ...], * "flag_sets": {"after_00.01": ["FLAG_HIDE_MOM", ...], ...}, * "connections": [{"side": "east", "to_map": "Route 1", "offset": 0}, ...], - * "patches": [{"x": 2, "y": 1, "glyph": "#", "measured_by": "run 3, 2026-10-30"}, ...] + * "patches": [{"x": 2, "y": 1, "glyph": "#", "measured_by": "run 3, 2026-10-30"}, ...], + * "gates": {"door_1": {"tiles": [[7, 9], [7, 10]], "open_glyph": ".", "new_game": "closed", + * "opens_by": "card_key_face_a", "flag": "FLAG_SILPH_5F_DOOR_1"}, + * "barrier_1": {"tiles": [[22, 10]], "open_glyph": "~", "new_game": "closed", + * "switch": "mansion", "open_when": "on"}, ...}, + * "switches": {"mansion": {"flag": "FLAG_POKEMON_MANSION_SWITCH_STATE", "toggle": true, + * "floors": ["PokemonMansion_1F", ...], + * "statues": [{"coord": [5, 5], "face_from": [5, 6], "facing": "north"}]}} * } * + * A warp may carry "one_way": true (a drop). A map's tiles show each gate + * tile as 'G', and every 'G' tile is in a gate. + * * `name`, `source` and `tiles` are required; everything else may be left * out. Which game's planner reads these maps, and how, is the game's * business. @@ -47,6 +57,7 @@ #include "Common/Cpp/Json/JsonValue.h" #include "Pokemon_Grid.h" #include "Pokemon_MapFeatures.h" +#include "Pokemon_MapGates.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -76,6 +87,12 @@ struct MapData{ std::map> flag_sets; std::vector connections; std::vector patches; + // The barriers the story opens, by id. Every GATE tile of `tiles` is in + // exactly one gate. + std::map gates; + // The switches (by id) that gates of this map follow or that have a + // statue on it. + std::map switches; }; // Reads legacy/unmarked v1 or compact pokesim-runtime-map/2 JSON. diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h index b39d50bbf7..fd44902707 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h @@ -31,6 +31,9 @@ struct MapWarp{ int y = 0; WarpEntry enter = WarpEntry::WALK_INTO; std::optional to; + // A drop (a hole the player falls through): the landing has no way back + // up, so a route takes it forward only. + bool one_way = false; }; // Type classification for interactive map objects. diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h new file mode 100644 index 0000000000..11f902b09f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h @@ -0,0 +1,73 @@ +/* Map Gates + * + * From: https://github.com/PokemonAutomation/ + * + * The barriers a map's story opens (card-key doors, switch-driven walls) and + * the statues that press the switches. Pokemon_MapData.h holds them in a + * map's `gates` and `switches`; Pokemon_GateState.h says which are open. + * + */ + +#ifndef PokemonAutomation_Pokemon_MapGates_H +#define PokemonAutomation_Pokemon_MapGates_H + +#include +#include +#include "Pokemon_Grid.h" +#include "Pokemon_MapTiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What opens a gate. +enum class GateKind{ + CARD_KEY, // "card_key_face_a": faced from a side tile and opened with A, once the player holds the Card Key + SWITCH, // a switch's state (MapSwitch): open while the switch is `open_when_on` +}; + +// A barrier the story opens or closes: some tiles of the map that are `G` +// in `tiles`. Open, they read as `open_tile`; closed, as a wall. +struct MapGate{ + std::string id; + std::vector tiles; + TileKind open_tile = TileKind::OPEN; + // Whether a new game has it open. + bool open_at_new_game = false; + GateKind kind = GateKind::CARD_KEY; + // CARD_KEY: the event flag the game sets once it is opened. + std::string flag = {}; + // SWITCH: the switch (a key of MapData::switches, shared by the + // maps in its `floors`), and the state in which this gate is open. + std::string switch_id = {}; + bool open_when_on = false; +}; + +// A statue that presses a switch: the player stands on `face_from`, faces +// `facing` and presses A. The statue is the wall tile `tile`. +struct MapStatue{ + TilePos tile; + TilePos face_from; + Direction facing = Direction::NORTH; +}; + +// A switch the map's gates follow. One state is shared by every map in +// `floors` (Pokemon Mansion's statue switch, an event flag): pressing a +// statue flips it, and each floor redraws its gates when it loads. +// `statues` are the statues on this map only. `buttons` are the tiles a +// Strength boulder turns it on from (Victory Road's floor switches, which +// stay on). +struct MapSwitch{ + std::string id; + std::string flag; + bool toggle = true; + std::vector floors; + std::vector statues; + std::vector buttons = {}; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h index 65d581b14c..16500f1060 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h @@ -47,6 +47,10 @@ enum class TileKind : uint8_t{ STOP_SPIN, // 'o' open; where a spin's slide stops FALL_HOLE, // 'H' open; a hole that drops the player a floor STRENGTH_BUTTON,// 'B' open; Victory Road's switch for a boulder + GATE, // 'G' a wall until the story opens it: the map's `gates` + // table names the gate, and Pokemon_GateState.h says + // whether it is open (a reader that ignores gates + // treats it as a wall) }; // The tile a glyph stands for, or nothing if it isn't one. std::optional tile_from_glyph(char glyph); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_NavigationGateTestMaps.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_NavigationGateTestMaps.h new file mode 100644 index 0000000000..2b3503fee4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_NavigationGateTestMaps.h @@ -0,0 +1,30 @@ +/* Navigation Gate Test Maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_NavigationGateTestMaps_H +#define PokemonAutomation_Pokemon_NavigationGateTestMaps_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// (name, JSON text) of each map in Pokemon/Navigation/GateTestMaps/, built +// into the program by pa_embed_text_files() (cmake/EmbedTextFiles.cmake): +// SilphCo_5F (card-key doors), PokemonMansion_1F (statue-switch barriers) +// and PokemonMansion_3F (barriers, a statue, and holes: one-way warps), +// trimmed from PokemonSimulation's runtime maps. 3F's hole tiles are +// tall grass here, which the reader knows. +const std::vector>& navigation_gate_test_map_json(); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp index 19ac59cf41..39889a01c1 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp @@ -33,6 +33,10 @@ std::string to_string(const RouteLogLeg& leg){ return std::format("surf {}", direction); case RouteLegAction::FACE: return std::format("face {}", direction); + case RouteLegAction::OPEN_GATE: + return std::format("open gate {}", direction); + case RouteLegAction::PRESS_SWITCH: + return std::format("press switch {}", direction); case RouteLegAction::WALK: break; } diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h index cbdd909b62..34258fc7e0 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h @@ -38,6 +38,10 @@ enum class RouteLegAction{ WALK, SURF, FACE, + // Face a gate and press A: a card-key gate opens. + OPEN_GATE, + // Face a statue and press A, then Yes: a switch flips. + PRESS_SWITCH, }; // How a leg ends: at a wall, on a warp, or where it is timed to. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h new file mode 100644 index 0000000000..a4401abd1e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h @@ -0,0 +1,56 @@ +/* Overworld Gated Route + * + * From: https://github.com/PokemonAutomation/ + * + * Plans a route over FRLG maps that have gates (Pokemon_GateState.h): Silph + * Co.'s card-key doors and Pokemon Mansion's statue switch. The game's + * step rules (plan_overworld_route()) are wrapped by the shared gated + * planner (Pokemon_GatedPlanner.h), so a closed gate is a wall, and a route + * may open a card-key gate (RouteAction::OPEN_GATE) when the story says the + * player holds the Card Key, or press a statue (RouteAction::PRESS_SWITCH). + * The gates after the route are gates_after_route(). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldGatedRoute_H +#define PokemonAutomation_PokemonFRLG_OverworldGatedRoute_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_GatedTypes.h" +#include "PokemonFRLG_OverworldRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// plan_overworld_route() with the gates as `gates` says and `rules` allows. +// Without gates in `maps` the route is the same. +std::optional> plan_overworld_route_gated( + const std::vector& maps, + const MapPosition& start, + const RouteGoal& goal, + const Pokemon::GateState& gates, + const Pokemon::GateRules& rules, + const RouteCosts& costs = default_route_costs(), + std::optional start_facing = std::nullopt +); + +// `before` with the gates `route` opens and the switches it flips. +Pokemon::GateState gates_after_route(const Pokemon::GateState& before, const std::vector& route); + +// Whether any of `maps` has a gate (MapData::gates). +bool has_gates(const std::vector& maps); + +// `maps` with the gate tiles of each as `gates` makes them: a closed gate +// is a wall (a GATE tile), an open one its open tile. What a walk reads +// its tiles from, as the maps stay as loaded. +std::vector resolve_maps(const std::vector& maps, const Pokemon::GateState& gates); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp new file mode 100644 index 0000000000..2d0770d661 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp @@ -0,0 +1,271 @@ +/* Overworld Gates Tests + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's step rules under the gated planner, and the sim walking the routes + * that open a card-key gate and press a statue. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_OverworldGatedRoute.h" +#include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::GateRules; +using Pokemon::GateState; + +namespace{ + +struct GatesInput{ + std::string name; + std::function body; +}; +struct GatesExpectation{ +}; +struct GatesCase{ + GatesInput input; + GatesExpectation expectation; +}; + +class Test_OverworldGates : public UnitTest{ +public: + explicit Test_OverworldGates(GatesCase test_case) + : UnitTest("PokemonFRLG::OverworldGates - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_case.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + GatesCase m_case; +}; + +// A corridor with a Silph Co. card-key door at (4, 1). +const std::vector& door_maps(){ + static const std::vector MAPS{parse_map(R"({ + "format": "pokesim-runtime-map/2", "name": "GateHall", "points": {}, "warps": [], "connections": [], "source": {"decomp_file": "", "revision": "test", "date": "2026-11-12"}, + "tiles": ["#########", "#...G...#", "#########"], + "gates": {"door_1": {"tiles": [[4, 1]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "FLAG_TEST"}} + })", "GateHall")}; + return MAPS; +} + +// The same corridor with a Mansion statue at (1, 0), above the start, and a +// barrier at (4, 1) that is open while the switch is on. +const std::vector& statue_maps(){ + static const std::vector MAPS{parse_map(R"({ + "format": "pokesim-runtime-map/2", "name": "GateStatue", "points": {}, "warps": [], "connections": [], "source": {"decomp_file": "", "revision": "test", "date": "2026-11-12"}, + "tiles": ["#########", "#...G...#", "#########"], + "gates": {"barrier_1": {"tiles": [[4, 1]], "open_glyph": ".", "new_game": "closed", "switch": "mansion", "open_when": "on"}}, + "switches": {"mansion": {"flag": "FLAG_TEST_SWITCH", "toggle": true, "floors": ["GateStatue"], + "statues": [{"coord": [1, 0], "face_from": [1, 1], "facing": "north"}]}} + })", "GateStatue")}; + return MAPS; +} + +const MapPosition HALL_START{"GateHall", {1, 1}}; +const MapPosition HALL_GOAL{"GateHall", {6, 1}}; +const MapPosition STATUE_START{"GateStatue", {1, 1}}; +const MapPosition STATUE_GOAL{"GateStatue", {6, 1}}; + +GateRules with_card_key(bool held){ + GateRules rules; + rules.card_key_held = held; + return rules; +} + +int count_steps(const std::vector& route, RouteAction action){ + return (int)std::count_if(route.begin(), route.end(), [&](const RouteStep& step){ return step.action == action; }); +} + +std::string describe(const std::vector& route){ + std::string text; + for (const RouteStep& step : route){ + text += "\n " + to_string(step); + } + return text; +} + + +// The game's step rules read a gate tile a map has not resolved as a wall. +UnitTestResult test_plain_route_stops_at_gate(){ + if (plan_overworld_route(door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt})){ + return "The plain planner walked through a closed gate."; + } + return true; +} + +UnitTestResult test_route_opens_gate(){ + const auto route = plan_overworld_route_gated( + door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, GateState(), with_card_key(true) + ); + if (!route){ + return "No route to the far side of the door with the Card Key."; + } + if (count_steps(*route, RouteAction::OPEN_GATE) != 1 || !(route->back().end == HALL_GOAL)){ + return "Expected one open-gate step and the goal reached:" + describe(*route); + } + const auto opens = std::find_if(route->begin(), route->end(), [](const RouteStep& step){ return step.action == RouteAction::OPEN_GATE; }); + if (opens->direction != Direction::EAST || !opens->gate_change.opened.contains("GateHall/door_1")){ + return "The open-gate step does not face east and open GateHall/door_1:" + describe(*route); + } + if (!gates_after_route(GateState(), *route).opened.contains("GateHall/door_1")){ + return "gates_after_route() does not have the door open."; + } + return true; +} + +UnitTestResult test_route_needs_card_key(){ + if (plan_overworld_route_gated(door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, GateState(), with_card_key(false))){ + return "A route opened a card-key door without the Card Key."; + } + return true; +} + +UnitTestResult test_route_through_open_gate(){ + GateState open; + open.opened.insert(Pokemon::gate_key("GateHall", "door_1")); + const auto route = plan_overworld_route_gated( + door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, open, with_card_key(false) + ); + if (!route || count_steps(*route, RouteAction::OPEN_GATE) != 0){ + return "Expected a plain walk through the open door."; + } + return true; +} + +UnitTestResult test_route_presses_statue(){ + const auto route = plan_overworld_route_gated( + statue_maps(), STATUE_START, RouteGoal{STATUE_GOAL, std::nullopt}, GateState(), with_card_key(false) + ); + if (!route){ + return "No route past the barrier by pressing the statue."; + } + if (count_steps(*route, RouteAction::PRESS_SWITCH) != 1 || !(route->back().end == STATUE_GOAL)){ + return "Expected one press-switch step and the goal reached:" + describe(*route); + } + if (!gates_after_route(GateState(), *route).switch_on("mansion")){ + return "gates_after_route() does not have the switch on."; + } + return true; +} + + +// Walks `route` in the sim from `start`, with the Card Key as `card_key`. +struct SimRun{ + std::string failure; + GateState gates; + MapPosition position; + std::vector log; +}; +SimRun walk_in_sim(const std::vector& maps, const MapPosition& start, const std::vector& route, bool card_key){ + SimScript script; + script.card_key_held = card_key; + OverworldSim sim(maps, start, Direction::EAST, script); + OverworldSimWalker walker(sim, SimWalkerRules{}); + const RoutePlanning planning{.maps = &maps, .costs = default_route_costs(), .start = start, .label = "Sim"}; + SimRun run; + run.failure = walker.run(route, planning); + run.gates = sim.state().gates; + run.position = sim.state().position; + run.log = sim.state().log; + run.log.insert(run.log.end(), walker.log().begin(), walker.log().end()); + return run; +} + +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += "\n " + line; + } + return text; +} + +// The leg to the sim's command: face the door, A; the door is open and the +// rest of the route walks through it. +UnitTestResult test_sim_opens_gate(){ + const auto route = plan_overworld_route_gated( + door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, GateState(), with_card_key(true) + ); + if (!route){ + return "No route."; + } + const SimRun run = walk_in_sim(door_maps(), HALL_START, *route, true); + if (!run.failure.empty() || !(run.position == HALL_GOAL) || !run.gates.opened.contains("GateHall/door_1")){ + return std::format("Expected the door opened and the goal reached, ended at {}: \"{}\"", to_string(run.position), run.failure) + + describe(*route) + joined(run.log); + } + return true; +} + +UnitTestResult test_sim_presses_statue(){ + const auto route = plan_overworld_route_gated( + statue_maps(), STATUE_START, RouteGoal{STATUE_GOAL, std::nullopt}, GateState(), with_card_key(false) + ); + if (!route){ + return "No route."; + } + const SimRun run = walk_in_sim(statue_maps(), STATUE_START, *route, false); + if (!run.failure.empty() || !(run.position == STATUE_GOAL) || !run.gates.switch_on("mansion")){ + return std::format("Expected the switch on and the goal reached, ended at {}: \"{}\"", to_string(run.position), run.failure) + + describe(*route) + joined(run.log); + } + return true; +} + +// The sim, like the game, does not open a card-key door for a player +// without the Card Key. +UnitTestResult test_sim_door_stays_shut_without_card_key(){ + const auto route = plan_overworld_route_gated( + door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, GateState(), with_card_key(true) + ); + if (!route){ + return "No route."; + } + const SimRun run = walk_in_sim(door_maps(), HALL_START, *route, false); + if (run.failure.empty() || run.gates.opened.contains("GateHall/door_1")){ + return "The door opened for a player without the Card Key." + joined(run.log); + } + return true; +} + +const std::vector GATES_CASES{ + {.input = {.name = "the plain planner: a closed gate is a wall", .body = test_plain_route_stops_at_gate}, .expectation = {}}, + {.input = {.name = "the route opens a card-key gate with the Card Key", .body = test_route_opens_gate}, .expectation = {}}, + {.input = {.name = "no route through a card-key gate without the Card Key", .body = test_route_needs_card_key}, .expectation = {}}, + {.input = {.name = "an open gate is walked through", .body = test_route_through_open_gate}, .expectation = {}}, + {.input = {.name = "the route presses a statue for a switch's barrier", .body = test_route_presses_statue}, .expectation = {}}, + {.input = {.name = "sim: face the door, A, walk through", .body = test_sim_opens_gate}, .expectation = {}}, + {.input = {.name = "sim: face the statue, A, YES, walk through", .body = test_sim_presses_statue}, .expectation = {}}, + {.input = {.name = "sim: the door stays shut without the Card Key", .body = test_sim_door_stays_shut_without_card_key}, .expectation = {}}, +}; + +} // namespace + + +void add_tests_OverworldGates(UnitTestDatabase& database){ + for (const GatesCase& item : GATES_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp index 3ba0bda2d4..9d14c9daa4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp @@ -30,7 +30,7 @@ uint8_t elevation_at(const MapData& map, const TilePos& point){ bool is_wall(const MapData& map, const TilePos& point){ const TileKind tile = tile_at(map, point); - return tile == TileKind::WALL || tile == TileKind::DOOR || tile == TileKind::SIGN || is_ledge(map, point); + return tile == TileKind::WALL || tile == TileKind::GATE || tile == TileKind::DOOR || tile == TileKind::SIGN || is_ledge(map, point); } bool is_ledge(const MapData& map, const TilePos& point){ switch (tile_at(map, point)){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp index 060a6a82bb..6707652723 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp @@ -176,6 +176,15 @@ constexpr std::string_view MAP_NAMES[] = { "CeruleanCave_1F", "CeruleanCave_2F", "CeruleanCave_B1F", + // Route 22's east end to Indigo Plateau: its north gate, Route 23 with + // its badge guards, Victory Road's three floors and the Plateau's Center. + "Route22_NorthEntrance", + "Route23", + "VictoryRoad_1F", + "VictoryRoad_2F", + "VictoryRoad_3F", + "IndigoPlateau_Exterior", + "IndigoPlateau_PokemonCenter_1F", }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp index 7a71b90d1c..bb0f438d3f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp @@ -35,6 +35,10 @@ Pokemon::RouteLogLeg route_log_leg(const RouteStep& step){ leg.action = Pokemon::RouteLegAction::SURF; }else if (step.action == RouteAction::FACE){ leg.action = Pokemon::RouteLegAction::FACE; + }else if (step.action == RouteAction::OPEN_GATE){ + leg.action = Pokemon::RouteLegAction::OPEN_GATE; + }else if (step.action == RouteAction::PRESS_SWITCH){ + leg.action = Pokemon::RouteLegAction::PRESS_SWITCH; }else if (step.warps){ leg.end = Pokemon::RouteLegEnd::WARP; }else if (step.to_wall){ @@ -220,7 +224,12 @@ class RouteRun{ , m_plan(with_warp_slack(route)) , m_at(planning != nullptr ? planning->start : std::nullopt) , m_facing(facing) - {} + { + if (planning != nullptr && planning->maps != nullptr){ + m_gates = planning->gates; + read_gates(); + } + } void run(){ m_lines.plan(m_at, m_plan); @@ -230,6 +239,20 @@ class RouteRun{ // Where a hold that finds the player starts isn't known. const std::optional crossing = m_next >= m_holds ? crossing_here(step) : std::nullopt; const StepOutcome outcome = m_steps.walk(step, m_facing, crossing); + if (is_gate_step(step)){ + // The player stays on their tile: nothing to find again if + // the gate didn't open, so the route fails. + if (outcome.end != StepEnd::DONE){ + m_calls.fail("walk_overworld_route(): " + to_string(step) + " did not finish."); + return; + } + m_walked.reset(); + Pokemon::apply_gate_change(m_gates, step.gate_change); + read_gates(); + m_facing = step.facing_after; + m_lines.done(step, ++m_next, m_holds); + continue; + } if (outcome.end == StepEnd::DONE){ const std::optional start = m_next >= m_unchecked ? m_at : std::nullopt; remember_walked(step); @@ -259,8 +282,21 @@ class RouteRun{ } private: + static bool is_gate_step(const RouteStep& step){ + return step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH; + } + + // The maps through the gates as they are now. The planning's own maps + // while none of them has a gate. const std::vector* maps() const{ - return m_planning != nullptr ? m_planning->maps : nullptr; + if (m_planning == nullptr || m_planning->maps == nullptr){ + return nullptr; + } + return m_resolved ? &*m_resolved : m_planning->maps; + } + + void read_gates(){ + m_resolved = has_gates(*m_planning->maps) ? std::optional(resolve_maps(*m_planning->maps, m_gates)) : std::nullopt; } std::optional crossing_here(const RouteStep& step) const{ @@ -569,6 +605,8 @@ class RouteRun{ std::vector m_plan; std::optional m_at; std::optional m_facing; + Pokemon::GateState m_gates; + std::optional> m_resolved; size_t m_next = 0; size_t m_stops = 0; size_t m_holds = 0; // of the plan, holds to walls that find the player diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h index 3b0f02b2b9..b215e3f524 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h @@ -43,6 +43,7 @@ #include #include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldGatedRoute.h" #include "PokemonFRLG_OverworldReanchor.h" #include "PokemonFRLG_OverworldRoute.h" #include "PokemonFRLG_OverworldTrainerCrossing.h" @@ -57,7 +58,11 @@ namespace PokemonFRLG{ // (with the event flags the caller set) and the costs; and, for the route // log (Pokemon_RouteLog.h), where it starts and what the caller calls it. struct RoutePlanning{ + // The maps as loaded: a gate tile is a wall until `gates` has it open. + // The run reads them through the gates, which each OPEN_GATE or + // PRESS_SWITCH step it walks changes. const std::vector* maps = nullptr; + Pokemon::GateState gates; RouteCosts costs = default_route_costs(); std::optional start; std::string label = "Route"; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index 736be580db..4ffaab310b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -22,6 +22,7 @@ #include "PokemonFRLG_OverworldBikeTaps.h" #include "PokemonFRLG_OverworldLateBattle.h" #include "PokemonFRLG_OverworldRecoveryWalk.h" +#include "PokemonFRLG_OverworldWalkGates.h" #include "PokemonFRLG_BikeSpinPresses.h" #include "PokemonFRLG_OverworldBike.h" #include "PokemonFRLG_OverworldMaps.h" @@ -197,54 +198,71 @@ bool on_dark_cave(ConsoleHandle& console){ return screen && dark_cave_screen(*screen.frame); } -// One step of a route, for a player facing `facing`. -StepWalk walk_step( +// One WALK step: turned first when it should, then its hold, and the warp it ends on. +StepWalk walk_hold_step( ConsoleHandle& console, ProControllerContext& context, const RouteStep& step, std::optional facing, const OverworldInterruptSet& interrupts, MoveSpeed speed, PlayerGender player ){ StepWalk out{std::nullopt, current_time(), false, false}; - switch (step.action){ - case RouteAction::WALK:{ - // Turning first, with a tap, starts the hold from a standstill facing - // the right way: exact over 15 tiles, where a turn lost one. - if (turns_first(step, speed, facing)){ - turn_to(console, context, step.direction, player); - } - if (const std::string note = speed_note(step, speed); !note.empty()){ - console.log(note); - } - context.wait_for_all_requests(); - out.dark = on_dark_cave(console); - const VideoSnapshot before = console.video().snapshot(); - out.hold_start = current_time(); - BlackScreenOverWatcher arrival(COLOR_RED); - Pokemon::WatchAlong fade(arrival); - const Pokemon::LegResult result = Pokemon::walk_leg( - console, context, leg_mover(step, speed), step.wild ? interrupts.wild : interrupts.other, - leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG, warp_hold_watchers(step, fade) - ); - if (result.stopped){ - out.stopped = logged_stop_tiles(console, step, out.dark, walked_near(step, result.tiles, tile_time(step, speed))); + // Turning first, with a tap, starts the hold from a standstill facing + // the right way: exact over 15 tiles, where a turn lost one. + if (turns_first(step, speed, facing)){ + turn_to(console, context, step.direction, player); + } + if (const std::string note = speed_note(step, speed); !note.empty()){ + console.log(note); + } + context.wait_for_all_requests(); + out.dark = on_dark_cave(console); + const VideoSnapshot before = console.video().snapshot(); + out.hold_start = current_time(); + BlackScreenOverWatcher arrival(COLOR_RED); + Pokemon::WatchAlong fade(arrival); + const Pokemon::LegResult result = Pokemon::walk_leg( + console, context, leg_mover(step, speed), step.wild ? interrupts.wild : interrupts.other, + leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG, warp_hold_watchers(step, fade) + ); + if (result.stopped){ + out.stopped = logged_stop_tiles(console, step, out.dark, walked_near(step, result.tiles, tile_time(step, speed))); + return out; + } + if (step.warps){ + wait_out_warp(console, context, step, fade, before); + static_assert(AFTER_WARP_BATTLE_WATCH >= AFTER_WARP); + if (run_from_battle_after_warp(console, context)){ + console.log("Route: a wild battle, not the warp to " + step.end.map + "; the player is on " + to_string(step) + " before the warp.", COLOR_ORANGE); + out.stopped = walked_before_warp(step); return out; } - if (step.warps){ - wait_out_warp(console, context, step, fade, before); - static_assert(AFTER_WARP_BATTLE_WATCH >= AFTER_WARP); - if (run_from_battle_after_warp(console, context)){ - console.log("Route: a wild battle, not the warp to " + step.end.map + "; the player is on " + to_string(step) + " before the warp.", COLOR_ORANGE); - out.stopped = walked_before_warp(step); - return out; - } - } - break; } + return out; +} + +// One step of a route, for a player facing `facing`. +StepWalk walk_step( + ConsoleHandle& console, ProControllerContext& context, + const RouteStep& step, std::optional facing, + const OverworldInterruptSet& interrupts, MoveSpeed speed, PlayerGender player +){ + StepWalk out{std::nullopt, current_time(), false, false}; + switch (step.action){ + case RouteAction::WALK: + return walk_hold_step(console, context, step, facing, interrupts, speed, player); case RouteAction::SURF: start_surf(console, context, step.direction, facing == step.direction); break; case RouteAction::FACE: turn_to(console, context, step.direction, player); break; + case RouteAction::OPEN_GATE: + turn_to(console, context, step.direction, player); + open_gate(console, context, step.direction, true); + break; + case RouteAction::PRESS_SWITCH: + turn_to(console, context, step.direction, player); + press_switch(console, context, step.direction, true); + break; } return out; } @@ -324,7 +342,7 @@ StepOutcome walk_and_watch( if (walked.stopped){ return StepOutcome{.end = StepEnd::STOPPED, .walked = walked.stopped, .blocked = walked.blocked}; } - if (step.action == RouteAction::FACE){ + if (step.action == RouteAction::FACE || step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH){ return StepOutcome{}; } const Milliseconds watch = step.wild ? AFTER_WILD_LEG_WATCH : AFTER_LEG_WATCH; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp index 4f809df56d..06e4227675 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp @@ -9,9 +9,13 @@ #include #include #include +#include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Navigation/Pokemon_GatedPlanner.h" +#include "Pokemon/Navigation/Pokemon_GateTiles.h" #include "Pokemon/Navigation/Pokemon_LegPlanner.h" +#include "PokemonFRLG_OverworldGatedRoute.h" #include "PokemonFRLG_OverworldMaps.h" #include "PokemonFRLG_OverworldObjects.h" #include "PokemonFRLG_OverworldRoute.h" @@ -347,6 +351,60 @@ class StepModel{ const RouteCosts& m_costs; }; +// The maps through each gate state a search reaches, resolved once. +class GateMaps{ +public: + explicit GateMaps(const std::vector& maps) + : m_maps(maps) + , m_gated(has_gates(maps)) + {} + + const std::vector& at(const Pokemon::GateState& gates) const{ + if (!m_gated){ + return m_maps; + } + auto iter = m_resolved.find(gates); + if (iter == m_resolved.end()){ + iter = m_resolved.emplace(gates, resolve_maps(m_maps, gates)).first; + } + return iter->second; + } + +private: + const std::vector& m_maps; + bool m_gated; + // Nodes keep their addresses, so a reference stays good while the + // search adds states. + mutable std::unordered_map> m_resolved; +}; + +// StepModel for the gated planner (Pokemon_GatedPlanner.h): the same step +// rules over the maps as the gates make them. +class GatedStepModel{ +public: + using State = Located; + using StateHash = LocatedHash; + + GatedStepModel(const GateMaps& maps, const RouteCosts& costs) + : m_maps(maps) + , m_costs(costs) + {} + + std::optional> press(const State& state, Direction direction, const Pokemon::GateState& gates) const{ + return StepModel(m_maps.at(gates), m_costs).press(state, direction); + } + bool held_at(const State& state, Direction direction, const Pokemon::GateState& gates) const{ + return StepModel(m_maps.at(gates), m_costs).held_at(state, direction); + } + Pokemon::MapPlace place_of(const State& state) const{ + return Pokemon::MapPlace{(size_t)state.map, state.state.position}; + } + +private: + const GateMaps& m_maps; + const RouteCosts& m_costs; +}; + Pokemon::LegCosts to_leg_costs(const RouteCosts& costs){ Pokemon::LegCosts leg_costs; leg_costs.per_tile = route_cost(costs, RouteCost::TILE); @@ -415,14 +473,24 @@ RouteStep to_route_step(const std::vector& maps, const Pokemon::Leg& maps, const Pokemon::Leg> plan_overworld_route( } +bool has_gates(const std::vector& maps){ + return std::ranges::any_of(maps, [](const MapData& map){ + return !map.gates.empty(); + }); +} + +std::vector resolve_maps(const std::vector& maps, const Pokemon::GateState& gates){ + std::vector resolved = maps; + for (MapData& map : resolved){ + if (!map.gates.empty()){ + map.tiles = Pokemon::resolve_tiles(map, gates); + } + } + return resolved; +} + +namespace{ + +// `legs` as route steps, each read on the maps its gates make. +std::vector gated_route_steps(const GateMaps& gate_maps, const std::vector>>& legs){ + std::vector route; + for (const Pokemon::Leg>& gated : legs){ + Pokemon::Leg leg{ + .kind = gated.kind, .action = gated.action, .direction = gated.direction, .tiles = gated.tiles, + .warps = gated.warps, .to_wall = gated.to_wall, .wild = gated.wild, .facing_after = gated.facing_after, + .start = gated.start.inner, .end = gated.end.inner, + }; + RouteStep step = to_route_step(gate_maps.at(gated.start.gates), leg); + step.gate_change = Pokemon::gate_change_of(gated); + route.push_back(std::move(step)); + } + return route; +} + +} // namespace + +std::optional> plan_overworld_route_gated( + const std::vector& maps, + const MapPosition& start, + const RouteGoal& goal, + const Pokemon::GateState& gates, + const Pokemon::GateRules& rules, + const RouteCosts& costs, + std::optional start_facing +){ + if (!has_gates(maps)){ + return plan_overworld_route(maps, start, goal, costs, start_facing); + } + const int start_map = find_map(maps, start.map); + const int goal_map = find_map(maps, goal.position.map); + if (start_map < 0 || goal_map < 0){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Route between maps that aren't loaded."); + } + const GateMaps gate_maps(maps); + const std::vector& first_maps = gate_maps.at(gates); + Pokemon::GatedStart first; + first.state.map = start_map; + first.state.state.position = start.point; + first.state.state.elevation = elevation_at(first_maps[start_map], start.point); + first.state.state.surfing = is_water(first_maps[start_map], start.point); + first.gates = gates; + first.facing = start_facing; + + const Pokemon::ConnectedMaps world(maps); + const GatedStepModel model(gate_maps, costs); + const auto legs = Pokemon::plan_gated_legs( + model, world, rules, first, + Pokemon::GatedGoal{ + .at_goal = [&](const Located& player){ + return player.map == goal_map && player.state.position == goal.position.point; + }, + .facing = goal.facing, + }, + to_leg_costs(costs) + ); + if (!legs){ + return std::nullopt; + } + + std::vector route = gated_route_steps(gate_maps, *legs); + tap_from_known_tile(route); + return route; +} + +Pokemon::GateState gates_after_route(const Pokemon::GateState& before, const std::vector& route){ + Pokemon::GateState gates = before; + for (const RouteStep& step : route){ + Pokemon::apply_gate_change(gates, step.gate_change); + } + return gates; +} + + namespace{ // Further than any straight line on a map. @@ -592,11 +753,44 @@ std::vector leg_tiles( return tiles; } +namespace{ + +// `step`'s tiles from `player`, on `maps` as the gates now make them. +void follow_step(const std::vector& maps, Located& player, const RouteStep& step){ + for (int c = 0; c < step.tiles; c++){ + const std::optional transition = press(maps, player, step.direction); + if (!transition || transition->action != step.action){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Step refused at " + to_string(MapPosition{maps[player.map].name, player.state.position}) + ": " + to_string(step) + ); + } + player = transition->next; + } + const MapPosition position{maps[player.map].name, player.state.position}; + if (!(position == step.end)){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Ended at " + to_string(position) + " instead of " + to_string(step.end) + ); + } +} + +} // namespace + MapPosition follow_overworld_route( const std::vector& maps, const MapPosition& start, - const std::vector& route + const std::vector& route, + const Pokemon::GateState& start_gates ){ + Pokemon::GateState gates = start_gates; + // Only maps with gates are copied to read through them. + const bool gated = has_gates(maps); + std::vector resolved; + if (gated){ + resolved = resolve_maps(maps, gates); + } Located player; player.map = find_map(maps, start.map); if (player.map < 0){ @@ -610,23 +804,14 @@ MapPosition follow_overworld_route( if (step.action == RouteAction::FACE){ continue; } - for (int c = 0; c < step.tiles; c++){ - const std::optional transition = press(maps, player, step.direction); - if (!transition || transition->action != step.action){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Step refused at " + to_string(MapPosition{maps[player.map].name, player.state.position}) + ": " + to_string(step) - ); + if (step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH){ + Pokemon::apply_gate_change(gates, step.gate_change); + if (gated){ + resolved = resolve_maps(maps, gates); } - player = transition->next; - } - const MapPosition position{maps[player.map].name, player.state.position}; - if (!(position == step.end)){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Ended at " + to_string(position) + " instead of " + to_string(step.end) - ); + continue; } + follow_step(gated ? resolved : maps, player, step); } return MapPosition{maps[player.map].name, player.state.position}; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h index fd06a21aec..605e61f49d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h @@ -66,10 +66,13 @@ std::vector leg_tiles( // Replays `route` from `start` with the game's step rules and returns where // it ends. Throws InternalProgramError if a step can't be taken as planned. +// A route with gates (plan_overworld_route_gated()) starts with `gates`; its +// OPEN_GATE and PRESS_SWITCH steps change them. MapPosition follow_overworld_route( const std::vector& maps, const MapPosition& start, - const std::vector& route + const std::vector& route, + const Pokemon::GateState& gates = {} ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h index 3f4d90bea7..60fc968525 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h @@ -15,6 +15,7 @@ #include #include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "PokemonFRLG_OverworldMap.h" namespace PokemonAutomation{ @@ -38,6 +39,12 @@ enum class RouteAction{ WALK, // hold `direction` for `tiles` tiles SURF, // face `direction`, use Surf, and land on the water there FACE, // turn to `direction` without moving + // Face the closed card-key gate in `direction` and open it with A: the + // Silph Co. door's message follows. The player stays on the tile. + OPEN_GATE, + // Face the statue in `direction` and press it with A, YES to the + // switch's question (Pokemon Mansion). The player stays on the tile. + PRESS_SWITCH, }; // A single step along an overworld path. @@ -93,6 +100,9 @@ struct RouteStep{ Direction facing_after = Direction::NORTH; // Where the player is after the step. MapPosition end; + // OPEN_GATE, PRESS_SWITCH: what the step does to the gates, for the + // story to keep (gates_after_route()). + Pokemon::GateChange gate_change = {}; }; // Formats a RouteStep as a string. std::string to_string(const RouteStep& step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteStrings.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteStrings.cpp index 8b7175b066..b26cd60248 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteStrings.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteStrings.cpp @@ -31,6 +31,12 @@ std::string to_string(const RouteStep& step){ case RouteAction::FACE: text = "face " + std::string(direction_name(step.direction)); break; + case RouteAction::OPEN_GATE: + text = "open gate " + std::string(direction_name(step.direction)); + break; + case RouteAction::PRESS_SWITCH: + text = "press switch " + std::string(direction_name(step.direction)); + break; } return text + " -> " + to_string(step.end); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index cfd9e60267..0b872f1210 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -147,6 +147,8 @@ OverworldSim::OverworldSim(std::vector maps, MapPosition start, Directi throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Sim: start on a map that isn't loaded: " + start.map); } add_coded_field(); + m_state.gates = m_script.gates; + read_gates(); m_player = PlayerState{start.point, elevation_at(map(), start.point), false}; m_state.facing = facing; m_state.on_bike = m_script.on_bike; @@ -837,21 +839,15 @@ std::optional OverworldSimWalker::walk_step(const RouteStep& step, if (step.action == RouteAction::SURF){ return surf(step); } + if (step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH){ + return use_gate(step); + } if (turns_first(step, m_speed, facing)){ sim_turn_to(m_sim, step.direction, m_rules.confirm_turn); } const int warps_before = m_sim.state().warps; const std::vector& ints = interrupts(step); - Pokemon::LegSpec leg; - leg.direction = step.direction; - leg.tiles = step.tiles + step.warp_slack; - leg.to_wall = step.to_wall; - leg.tile_time = tile_time(step, m_speed); - leg.stop_on_interrupt = !step.to_wall; - leg.stop_if_blocked = step.to_wall && m_rules.stop_if_blocked; - if (m_rules.hold_over_connections){ - leg.stalled_steps = step.connection_steps; - } + const Pokemon::LegSpec leg = leg_spec(step); Pokemon::LegCalls calls; calls.hold_watching = [&](Milliseconds hold) -> std::optional{ const std::optional seen = hold_watching(step, hold, ints); @@ -901,7 +897,7 @@ StepOutcome OverworldSimWalker::walk_ridden(const RouteStep& step, std::optional }else if (const std::optional walked = walk_step(step, facing)){ return StepOutcome{.end = StepEnd::STOPPED, .walked = walked}; } - if (step.action == RouteAction::FACE){ + if (step.action == RouteAction::FACE || step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH){ return StepOutcome{}; } size_t late = clear_late(interrupts(step), step.wild ? m_rules.after_wild_leg_watch : AFTER_LEG_WATCH, MAX_INTERRUPTIONS_PER_LEG); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 3edb52e8df..67c2b03df7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -111,6 +111,11 @@ class OverworldSim{ // A on what the player faces, as `field` says (`floor`: the lift's). // Returns whether it was there. (PokemonFRLG_OverworldSimField.cpp) bool use_field(SimField field, size_t floor = 0); + // What stands on the current map now: a pushed boulder is where it was + // pushed to, a cut tree is gone. + const std::vector& objects() const{ + return m_maps[m_map].objects; + } private: // A screen that shows at `at`; `unfreeze`: the player can move again. @@ -169,7 +174,15 @@ class OverworldSim{ bool cut_tree(); bool choose_lift_floor(size_t floor); bool push_poster_switch(); + // SimField::PUSH_BOULDER. (PokemonFRLG_OverworldSimField.cpp) + bool push_boulder(); bool start_surf(); + // A on the gate or the statue the player faces; false, as a violation, + // if there is none or the Card Key is missing. + bool open_gate(); + bool press_switch(); + // Reads each map's gate tiles through the gates of m_state. + void read_gates(); bool fly_to_town(size_t town); // The trees cut come back, as after a warp. void regrow_cut_trees(); @@ -196,6 +209,8 @@ class OverworldSim{ const MapData& map() const{ return m_maps[m_map]; } std::vector m_maps; + // The maps as loaded, with the gates closed or open as the map says. + std::vector m_source_maps; SimScript m_script; int m_map = 0; PlayerState m_player; @@ -432,6 +447,11 @@ class OverworldSimWalker{ // Nothing: a Surf is never stopped part-way. // (PokemonFRLG_OverworldSimField.cpp) std::optional surf(const RouteStep& step); + // OPEN_GATE, PRESS_SWITCH: turned to the gate or statue, A (and YES), + // as use_field(). (PokemonFRLG_OverworldSimField.cpp) + std::optional use_gate(const RouteStep& step); + // The hold of a WALK step. (PokemonFRLG_OverworldSimField.cpp) + Pokemon::LegSpec leg_spec(const RouteStep& step) const; bool after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); bool fade_over_since(Milliseconds from) const; // after_warp() on a fade seen with no warp: fails, or with @@ -475,6 +495,8 @@ void add_tests_OverworldSim(UnitTestDatabase& database); void add_tests_OverworldWarpFade(UnitTestDatabase& database); // Register the tests of the way a warp leaves the player facing. void add_tests_OverworldStairs(UnitTestDatabase& database); +// Register the tests of gated routes, and of the sim opening gates. +void add_tests_OverworldGates(UnitTestDatabase& database); } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp index 84384e54da..cc3b4a836d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp @@ -10,10 +10,13 @@ #include #include +#include "Pokemon/Navigation/Pokemon_GateTiles.h" #include "PokemonFRLG_CodedRooms.h" #include "PokemonFRLG_FlyMap.h" +#include "PokemonFRLG_OverworldGatedRoute.h" #include "PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_OverworldSimField.h" +#include "PokemonFRLG_OverworldWalk.h" #include "PokemonFRLG_BikeSpinMechanics.h" #include "PokemonFRLG_OverworldSpin.h" @@ -26,6 +29,8 @@ namespace{ // The questions, " used CUT!" and the tree falling. constexpr Milliseconds CUT_TIME(4000); +// The boulder's slide, one tile. Not measured on the console. +constexpr Milliseconds PUSH_TIME(500); } // namespace @@ -36,6 +41,8 @@ bool OverworldSim::use_field(SimField field, size_t floor){ return cut_tree(); case SimField::POSTER_SWITCH: return push_poster_switch(); + case SimField::PUSH_BOULDER: + return push_boulder(); case SimField::LIFT_FLOOR: return choose_lift_floor(floor); case SimField::BIKE_SELECT: @@ -44,6 +51,10 @@ bool OverworldSim::use_field(SimField field, size_t floor){ return start_surf(); case SimField::FLY: return fly_to_town(floor); + case SimField::OPEN_GATE: + return open_gate(); + case SimField::PRESS_SWITCH: + return press_switch(); } return false; } @@ -108,6 +119,30 @@ bool OverworldSim::cut_tree(){ return false; } +bool OverworldSim::push_boulder(){ + std::vector& objects = m_maps[m_map].objects; + const TilePos ahead = m_player.position.next(m_state.facing); + const auto boulder = std::find_if(objects.begin(), objects.end(), [&](const MapObject& object){ + return object.name == "pushable_boulder" && object.x == ahead.x && object.y == ahead.y; + }); + if (boulder == objects.end() || m_state.screen != SimScreen::OVERWORLD || m_frozen){ + violation("no boulder " + std::string(direction_name(m_state.facing)) + " of " + to_string(m_state.position) + "."); + return false; + } + // The boulder moves where a player on its tile could step. + const PlayerState on_boulder{ahead, elevation_at(map(), ahead), false}; + if (classify_step(map(), on_boulder, m_state.facing) != StepKind::WALK){ + violation("the boulder on " + to_string(MapPosition{map().name, ahead}) + " does not move " + std::string(direction_name(m_state.facing)) + "."); + return false; + } + const TilePos beyond = ahead.next(m_state.facing); + boulder->x = beyond.x; + boulder->y = beyond.y; + advance_to(m_now + PUSH_TIME); + note("pushed the boulder to " + to_string(MapPosition{map().name, beyond}) + "."); + return true; +} + bool OverworldSim::choose_lift_floor(size_t floor){ const auto lift = m_script.lift_floors.find(map().name); if (lift == m_script.lift_floors.end() || floor >= lift->second.size() || m_frozen){ @@ -137,6 +172,62 @@ bool OverworldSim::start_surf(){ return true; } +void OverworldSim::read_gates(){ + // Only the tiles: the objects the sim has changed stay as they are. + // Maps without a gate were not copied. + if (m_source_maps.empty() && has_gates(m_maps)){ + m_source_maps = m_maps; + } + for (size_t c = 0; c < m_source_maps.size(); c++){ + if (!m_source_maps[c].gates.empty()){ + m_maps[c].tiles = Pokemon::resolve_tiles(m_source_maps[c], m_state.gates); + } + } +} + +bool OverworldSim::open_gate(){ + if (m_source_maps.empty()){ + violation("no gates on the maps."); + return false; + } + const MapData& source = m_source_maps[m_map]; + const Pokemon::MapGate* gate = Pokemon::closed_card_key_gate_faced(source, m_player.position, m_state.facing, m_state.gates); + if (gate == nullptr || !m_script.card_key_held || m_state.screen != SimScreen::OVERWORLD || m_frozen){ + violation(std::format( + "no card-key gate to open {} of {}{}.", + direction_name(m_state.facing), to_string(m_state.position), m_script.card_key_held ? "" : " (no Card Key)" + )); + return false; + } + // "Opened the door with the CARD KEY!", then the door. + advance_to(m_now + m_script.timing.message); + m_state.gates.opened.insert(Pokemon::gate_key(source.name, gate->id)); + read_gates(); + note("opened " + Pokemon::gate_key(source.name, gate->id) + "."); + return true; +} + +bool OverworldSim::press_switch(){ + const Pokemon::MapSwitch* pressed = m_source_maps.empty() + ? nullptr + : Pokemon::switch_pressed(m_source_maps[m_map], m_player.position, m_state.facing); + if (pressed == nullptr || m_state.screen != SimScreen::OVERWORLD || m_frozen){ + violation(std::format("no statue to press {} of {}.", direction_name(m_state.facing), to_string(m_state.position))); + return false; + } + // The prompt, YES, and the text after it. + advance_to(m_now + m_script.timing.message); + const bool now_on = pressed->toggle ? !m_state.gates.switch_on(pressed->id) : true; + if (now_on){ + m_state.gates.switches_on.insert(pressed->id); + }else{ + m_state.gates.switches_on.erase(pressed->id); + } + read_gates(); + note(std::format("switch {} is {}.", pressed->id, now_on ? "on" : "off")); + return true; +} + bool OverworldSim::fly_to_town(size_t town){ const std::vector& towns = kanto_fly_towns(); const MapPosition* landing = town < towns.size() ? &towns[town].landing : nullptr; @@ -162,6 +253,31 @@ bool OverworldSim::fly_to_town(size_t town){ return true; } +Pokemon::LegSpec OverworldSimWalker::leg_spec(const RouteStep& step) const{ + Pokemon::LegSpec leg; + leg.direction = step.direction; + leg.tiles = step.tiles + step.warp_slack; + leg.to_wall = step.to_wall; + leg.tile_time = OverworldWalkSteps::tile_time(step, m_speed); + leg.stop_on_interrupt = !step.to_wall; + leg.stop_if_blocked = step.to_wall && m_rules.stop_if_blocked; + if (m_rules.hold_over_connections){ + leg.stalled_steps = step.connection_steps; + } + return leg; +} + +std::optional OverworldSimWalker::use_gate(const RouteStep& step){ + if (m_sim.state().facing != step.direction){ + sim_turn_to(m_sim, step.direction, m_rules.confirm_turn); + } + const bool opens = step.action == RouteAction::OPEN_GATE; + if (!m_sim.use_field(opens ? SimField::OPEN_GATE : SimField::PRESS_SWITCH)){ + fail("walk_overworld_route(): " + to_string(step) + " did not open anything."); + } + return std::nullopt; +} + std::optional OverworldSimWalker::surf(const RouteStep& step){ if (m_sim.state().facing != step.direction){ sim_turn_to(m_sim, step.direction, m_rules.confirm_turn); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h index b4993fa1e8..ffaa1bd629 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h @@ -41,10 +41,21 @@ enum class SimField{ // Each step on the water then takes SimTiming::surf_tile, and a step // onto land gets the player off. SURF, + // The boulder the player faces (an object named "pushable_boulder") + // pushed one tile on, if the tile beyond is free ground: it moves there + // and the player's next step takes the tile it left. Strength is the + // console's: the sim does not ask for it. + PUSH_BOULDER, // Not A: Fly from the party menu to the town numbered `floor` in // kanto_fly_towns(), outdoors: the fade, then the player on its landing // tile facing south, still for SimTiming::fly. FLY, + // The card-key gate the player faces (a `G` tile of a map's `gates`), + // with SimScript::card_key_held: its message, and the gate is open. + OPEN_GATE, + // The statue the player faces (a map's `switches`): the prompt, YES, and + // the switch flips, with every gate that follows it on every map. + PRESS_SWITCH, }; // Register the tests of the Bicycle's taps and SELECT on a made-up map. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h index 8c593077a4..765d00794c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h @@ -29,6 +29,12 @@ namespace PokemonFRLG{ // What a test sets up beyond the maps. struct SimScript{ std::vector encounters; + // The player holds the Card Key: A on a card-key gate opens it + // (SimField::OPEN_GATE). Without it the door does not open, as in the game. + bool card_key_held = false; + // The gates open at the start. The sim reads each map's gate tiles + // through them (Pokemon_GateTiles.h). + Pokemon::GateState gates; // The START menu is open at the start: the D-pad moves its cursor. bool start_menu_open = false; // The hold numbered by the key (from 1) stops this many tiles short, @@ -130,6 +136,9 @@ struct SimScript{ // The player and the screen, and what went wrong that the game would show. struct SimState{ MapPosition position; + // The gates open and the switches on (SimScript::gates, then what the + // player opened and pressed). + Pokemon::GateState gates; Direction facing = Direction::SOUTH; SimScreen screen = SimScreen::OVERWORLD; // Whether black shows below the map: the player stands near the bottom diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index b47e21f6d1..3dcbaaa052 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -1038,12 +1038,12 @@ void add_tests_OverworldSim(UnitTestDatabase& database){ add_tests_OverworldLateBattle(database); add_tests_OverworldWarpFade(database); add_tests_OverworldStairs(database); + add_tests_OverworldGates(database); add_tests_OverworldSpin(database); add_tests_OverworldBike(database); } - } // namespace PokemonFRLG } // namespace NintendoSwitch } // namespace PokemonAutomation \ No newline at end of file diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp index 1c37503a94..ebf46afd7d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -25,6 +25,7 @@ #include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" #include "PokemonFRLG_PlayerFacingReader.h" #include "PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_OverworldWalkGates.h" #include "PokemonFRLG_OverworldBike.h" #include "PokemonFRLG_BikeSpinMechanics.h" #include "PokemonFRLG_BikeSpinPresses.h" @@ -44,6 +45,14 @@ namespace{ constexpr Milliseconds WARP_TIMEOUT = 8000ms; constexpr Milliseconds SURF_PROMPT_TIMEOUT = 5000ms; constexpr Milliseconds SURF_ANIMATION = 3000ms; +// A card-key door's message, and the door opening after it. +constexpr Milliseconds GATE_MESSAGE_WAIT = 1500ms; +constexpr Milliseconds GATE_SETTLE = 1500ms; +// The Yes/No prompt of a statue, and how long B's through the text before +// and after the switch last. +constexpr Milliseconds SWITCH_PROMPT_TIMEOUT = 5000ms; +constexpr Milliseconds SWITCH_SETTLE = 2000ms; +constexpr int MAX_TEXT_BOXES = 5; // After a message closes: a trainer who saw the player speaks first, then // the battle starts, with " would like to battle!" seconds later. constexpr Milliseconds TRAINER_BATTLE_WATCH = 6000ms; @@ -761,6 +770,56 @@ void start_surf(ConsoleHandle& console, ProControllerContext& context, Direction pbf_wait(context, SURF_ANIMATION); } +namespace{ + +// B through the text boxes that are open, at most MAX_TEXT_BOXES of them. +void clear_text(ConsoleHandle& console, ProControllerContext& context){ + for (int c = 0; c < MAX_TEXT_BOXES; c++){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (!screen || !WhiteDialogDetector(COLOR_RED).detect(screen)){ + return; + } + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + } +} + +void face_for_a(ProControllerContext& context, Direction direction, bool facing){ + // An A pressed while the player is still turning is lost. + if (!facing){ + pbf_press_dpad(context, dpad(direction), FACE_HOLD, FACE_SETTLE); + } +} + +} // namespace + +void open_gate(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_gate){ + face_for_a(context, direction, facing_gate); + pbf_press_button(context, BUTTON_A, 160ms, GATE_MESSAGE_WAIT); + clear_text(console, context); + pbf_wait(context, GATE_SETTLE); + context.wait_for_all_requests(); +} + +void press_switch(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_statue){ + face_for_a(context, direction, facing_statue); + pbf_press_button(context, BUTTON_A, 160ms, 0ms); + SelectionDialogWatcher prompt(COLOR_RED); + context.wait_for_all_requests(); + if (wait_until(console, context, SWITCH_PROMPT_TIMEOUT, {prompt}) < 0){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "walk_overworld_route(): no prompt facing the statue.", + console + ); + } + // Yes is selected. + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + clear_text(console, context); + pbf_wait(context, SWITCH_SETTLE); + context.wait_for_all_requests(); +} + } // namespace OverworldWalkSteps @@ -858,6 +917,25 @@ void walk_step_leg( check_warp_was_no_battle(console, context, step); } +// A WALK step: turned first, then its leg. +void walk_hold( + ConsoleHandle& console, ProControllerContext& context, + const RouteStep& step, std::optional facing, + const OverworldInterruptSet& interrupts, MoveSpeed speed, PlayerGender player +){ + // Turning first, with a tap, makes the hold start from a standstill + // facing the right way: holding through a turn lost a tile on the + // console, while holds from a standstill were exact over 15 tiles. + // Not on the Bicycle, where the tap is a step. + if (turns_first(step, speed, facing)){ + turn_to(console, context, step.direction, player); + } + if (const std::string note = speed_note(step, speed); !note.empty()){ + console.log(note); + } + walk_step_leg(console, context, step, interrupts, speed); +} + } // namespace @@ -878,17 +956,7 @@ void walk_overworld_route( check_overworld(console, context, step); switch (step.action){ case RouteAction::WALK: - // Turning first, with a tap, makes the hold start from a standstill - // facing the right way: holding through a turn lost a tile on the - // console, while holds from a standstill were exact over 15 tiles. - // Not on the Bicycle, where the tap is a step. - if (turns_first(step, speed, facing)){ - turn_to(console, context, step.direction, player); - } - if (const std::string note = speed_note(step, speed); !note.empty()){ - console.log(note); - } - walk_step_leg(console, context, step, interrupts, speed); + walk_hold(console, context, step, facing, interrupts, speed, player); break; case RouteAction::SURF: start_surf(console, context, step.direction, facing == step.direction); @@ -899,8 +967,17 @@ void walk_overworld_route( // (console B, 2026-11-11, 09.02 moon_stone). turn_to(console, context, step.direction, player); break; + case RouteAction::OPEN_GATE: + case RouteAction::PRESS_SWITCH: + turn_to(console, context, step.direction, player); + if (step.action == RouteAction::OPEN_GATE){ + open_gate(console, context, step.direction, true); + }else{ + press_switch(console, context, step.direction, true); + } + break; } - if (step.action != RouteAction::FACE){ + if (step.action != RouteAction::FACE && step.action != RouteAction::OPEN_GATE && step.action != RouteAction::PRESS_SWITCH){ const OverworldInterrupts& watched = step.wild ? interrupts.wild : interrupts.other; if (Pokemon::clear_late_interrupts(console, context, watched, step.wild ? AFTER_WILD_LEG_WATCH : AFTER_LEG_WATCH, MAX_INTERRUPTIONS_PER_LEG) == 0){ clear_unseen_battle(console, context, interrupts.wild, step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkGates.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkGates.h new file mode 100644 index 0000000000..cdbbfd6907 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkGates.h @@ -0,0 +1,38 @@ +/* Overworld Walk Gates + * + * From: https://github.com/PokemonAutomation/ + * + * The console steps of a route through gates (RouteAction::OPEN_GATE and + * PRESS_SWITCH), next to the other steps of OverworldWalkSteps. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldWalkGates_H +#define PokemonAutomation_PokemonFRLG_OverworldWalkGates_H + +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_OverworldRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ +namespace OverworldWalkSteps{ + + +// Facing a card-key gate `direction` (turning first unless `facing_gate`), +// presses A: with the Card Key the game says so and the door opens. B +// clears the message, then the walk waits for the door to settle. +void open_gate(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_gate); + +// Facing a statue `direction` (turning first unless `facing_statue`), +// presses A, takes Yes at the prompt, and clears the text with B. +void press_switch(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_statue); + + + +} // namespace OverworldWalkSteps +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index c515e04367..21fd494009 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -9,6 +9,7 @@ #include "Common/Cpp/Filesystem/Filesystem.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/StaticGlobals.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h" #include "Inference/Box/PokemonFRLG_BoxCellOccupiedDetector.h" #include "Inference/Box/PokemonFRLG_BoxCellReader.h" #include "Inference/Box/PokemonFRLG_BoxGenderReader.h" @@ -37,7 +38,6 @@ #include "Inference/PokemonFRLG_StatsReader.h" #include "Inference/PokemonFRLG_TrainerIdReader.h" #include "Inference/PokemonFRLG_WildEncounterReader.h" -#include "Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h" #include "Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.h" #include "Overworld/PokemonFRLG_OverworldMaps.h" #include "Overworld/PokemonFRLG_OverworldReanchor.h" @@ -61,6 +61,7 @@ #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows13_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows16_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows17_Tests.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.h" #include "Programs/AutoStory/Data/Json_Tests.h" @@ -120,6 +121,8 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& database){ add_tests_AutoStorySilph(database); add_tests_AutoStoryMansion(database); add_tests_AutoStoryViridian(database); + add_tests_AutoStoryVictoryRoad(database); + add_tests_AutoStoryBoulders(database); } void add_tests(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBoulders_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBoulders_Tests.cpp new file mode 100644 index 0000000000..f19ebd507f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBoulders_Tests.cpp @@ -0,0 +1,301 @@ +/* AutoStory Boulders Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Victory Road's boulder puzzles: a search over where the boulders stand + * (Pokemon_BoulderSolver below), and the sim's PUSH_BOULDER, which the + * search's answer is replayed on. + * + * TODO(map edit, needs the user's OK): the Victory Road maps have the + * boulders (objects named "pushable_boulder") but not the switches' + * barriers or which tiles the switches press, so the planner walks + * through the barriers. The data below is from the decompilation + * (pokefirered data/maps/VictoryRoad_*), kept here until the maps carry + * it as `gates` and `switches`; then this search reads them from the map. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTiles.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryPoses.h" +#include "PokemonFRLG_AutoStoryRowSim.h" +#include "PokemonFRLG_AutoStoryRows19_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::MapData; +using Pokemon::MapObject; +using Pokemon::TilePos; +using Pokemon::Direction; + +namespace{ + +struct AutoStoryBouldersInput{ + std::string name; + std::function body; +}; + +struct AutoStoryBouldersExpectation{ + std::string_view description; +}; + +struct AutoStoryBouldersCase{ + AutoStoryBouldersInput input; + AutoStoryBouldersExpectation expectation; +}; + +class Test_AutoStoryBoulders : public UnitTest{ +public: + explicit Test_AutoStoryBoulders(AutoStoryBouldersCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStory - Boulders: {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_case.input.body(); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + } + } + +private: + AutoStoryBouldersCase m_case; +}; + + +// One floor's puzzle: where the player enters, the tiles that stay shut +// until a switch is pressed, and the tiles a boulder presses. +struct BoulderPuzzle{ + std::string map; + TilePos player; + std::vector barriers; + std::vector switches; +}; + +// Victory Road 1F: the barriers at (12, 14) and (12, 15), opened by the +// switch at (20, 16) (the map's B tile). +BoulderPuzzle victory_road_1f(){ + return {"VictoryRoad_1F", {11, 19}, {{12, 14}, {12, 15}}, {{20, 16}}}; +} + +const Direction DIRECTIONS[] = {Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST}; + +// The player's moves (a step each; one onto a boulder pushes it) that put +// a boulder on a switch, or nothing if no moves do. Breadth first over +// the player's tile and the boulders': the fewest moves. +std::optional> solve_boulders(const MapData& map, const BoulderPuzzle& puzzle){ + std::vector boulders; + for (const MapObject& object : map.objects){ + if (object.name == "pushable_boulder"){ + boulders.push_back({object.x, object.y}); + } + } + const std::set barriers(puzzle.barriers.begin(), puzzle.barriers.end()); + const std::set switches(puzzle.switches.begin(), puzzle.switches.end()); + // Other people stand where they stand. + std::set people; + for (const MapObject& object : map.objects){ + if (object.name != "pushable_boulder"){ + people.insert({object.x, object.y}); + } + } + const auto floor = [&](const TilePos& tile){ + return switches.count(tile) != 0 || (!is_wall(map, tile) && barriers.count(tile) == 0 && people.count(tile) == 0); + }; + using State = std::pair>; + std::set seen; + std::deque>> queue; + State start{puzzle.player, boulders}; + seen.insert(start); + queue.push_back({start, {}}); + while (!queue.empty() && seen.size() < 2000000){ + auto [state, moves] = std::move(queue.front()); + queue.pop_front(); + for (Direction direction : DIRECTIONS){ + State next = state; + const TilePos ahead = state.first.next(direction); + next.first = ahead; + const auto boulder = std::find(next.second.begin(), next.second.end(), ahead); + if (boulder != next.second.end()){ + const TilePos beyond = ahead.next(direction); + if (!floor(beyond) || std::find(next.second.begin(), next.second.end(), beyond) != next.second.end()){ + continue; + } + *boulder = beyond; + }else if (!floor(ahead)){ + continue; + } + if (!seen.insert(next).second){ + continue; + } + std::vector more = moves; + more.push_back(direction); + const bool pressed = std::any_of(next.second.begin(), next.second.end(), [&](const TilePos& tile){ + return switches.count(tile) != 0; + }); + if (pressed){ + return more; + } + queue.push_back({std::move(next), std::move(more)}); + } + } + return std::nullopt; +} + +const MapData& map_named(const std::string& name){ + for (const MapData& map : story_maps()){ + if (map.name == name){ + return map; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No map {}.", name)); +} + +// A boulder one tile north of the player moves one tile north, and the +// step after takes the player onto its old tile. +UnitTestResult test_sim_pushes_a_boulder(){ + OverworldSim sim(story_maps(), MapPosition{"VictoryRoad_1F", {7, 19}}, Direction::NORTH); + if (!sim.use_field(SimField::PUSH_BOULDER)){ + return "no boulder pushed from (7, 19) north."; + } + sim_step_once(sim, Direction::NORTH); + if (!(sim.state().position == MapPosition{"VictoryRoad_1F", {7, 18}})){ + return "after the push, the player is on " + to_string(sim.state().position) + ", not (7, 18)."; + } + // The boulder is in the way again one tile further on. + if (!sim.use_field(SimField::PUSH_BOULDER)){ + return "the pushed boulder is not at (7, 17)."; + } + return true; +} + +// A boulder with a wall beyond it stays, and so does the player. +UnitTestResult test_sim_boulder_stops_at_a_wall(){ + OverworldSim sim(story_maps(), MapPosition{"VictoryRoad_1F", {6, 18}}, Direction::EAST); + if (sim.use_field(SimField::PUSH_BOULDER)){ + return "the boulder moved onto the wall at (8, 18)."; + } + if (sim.state().violations.empty()){ + return "no rule broken by pushing a boulder into a wall."; + } + return true; +} + +// Nothing to push on an empty tile. +UnitTestResult test_sim_no_boulder(){ + OverworldSim sim(story_maps(), MapPosition{"VictoryRoad_1F", {11, 19}}, Direction::NORTH); + if (sim.use_field(SimField::PUSH_BOULDER)){ + return "pushed a boulder that is not there."; + } + return true; +} + +// 1F's switch is pressed in some number of moves, and the moves played on +// the sim leave a boulder on the switch tile. +UnitTestResult test_1f_solution_replays_on_sim(){ + const BoulderPuzzle puzzle = victory_road_1f(); + const std::optional> moves = solve_boulders(map_named(puzzle.map), puzzle); + if (!moves){ + return "no way to put a boulder on Victory Road 1F's switch (20, 16)."; + } + OverworldSim sim(story_maps(), MapPosition{puzzle.map, puzzle.player}, Direction::NORTH); + for (Direction direction : *moves){ + if (sim.state().facing != direction){ + sim_turn_to(sim, direction); + } + const TilePos ahead = sim.state().position.point.next(direction); + const bool boulder_ahead = std::any_of(sim.objects().begin(), sim.objects().end(), [&](const MapObject& object){ + return object.name == "pushable_boulder" && object.x == ahead.x && object.y == ahead.y; + }); + if (boulder_ahead && !sim.use_field(SimField::PUSH_BOULDER)){ + return std::format("the sim would not push at {} ({} moves).", to_string(sim.state().position), moves->size()); + } + sim_step_once(sim, direction); + } + const TilePos press = puzzle.switches.front(); + const bool pressed = std::any_of(sim.objects().begin(), sim.objects().end(), [&](const MapObject& object){ + return object.name == "pushable_boulder" && object.x == press.x && object.y == press.y; + }); + if (!pressed){ + return std::format("after {} moves, no boulder on the switch {}.", moves->size(), to_string(press)); + } + return true; +} + +// The step as a row plays it: two tiles north from (7, 19), the boulder +// from (7, 18) to (7, 16) and the player on (7, 17). +UnitTestResult test_push_boulder_step_on_sim(){ + OverworldSim sim(story_maps(), MapPosition{"VictoryRoad_1F", {7, 19}}, Direction::NORTH); + StoryPose at{"VictoryRoad_1F", {7, 19}, Direction::NORTH}; + StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = "push"; + step.action = PUSH_BOULDER_VARIANT; + step.args = {{"direction", Direction::NORTH}, {"tiles", int64_t(2)}, {"activate", false}}; + if (const std::string failure = row_step_on_sim(sim, at, step, "19.04"); !failure.empty()){ + return failure; + } + if (!(sim.state().position == MapPosition{"VictoryRoad_1F", {7, 17}})){ + return "after the step, on " + to_string(sim.state().position) + ", not (7, 17)."; + } + const bool moved = std::any_of(sim.objects().begin(), sim.objects().end(), [](const MapObject& object){ + return object.name == "pushable_boulder" && object.x == 7 && object.y == 16; + }); + if (!moved){ + return "no boulder on (7, 16)."; + } + return true; +} + +const AutoStoryBouldersCase AUTO_STORY_BOULDERS_CASES[] = { + { + .input = {.name = "a push_boulder step on the sim", .body = test_push_boulder_step_on_sim}, + .expectation = {.description = "two tiles pushed, the player behind the boulder"}, + }, + { + .input = {.name = "the sim pushes a boulder one tile", .body = test_sim_pushes_a_boulder}, + .expectation = {.description = "the boulder moves north, the player takes its tile"}, + }, + { + .input = {.name = "the sim's boulder stops at a wall", .body = test_sim_boulder_stops_at_a_wall}, + .expectation = {.description = "no push, a rule broken"}, + }, + { + .input = {.name = "the sim has no boulder to push on a bare tile", .body = test_sim_no_boulder}, + .expectation = {.description = "no push"}, + }, + { + .input = {.name = "Victory Road 1F's solution replays on the sim", .body = test_1f_solution_replays_on_sim}, + .expectation = {.description = "a boulder on the switch (20, 16)"}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryBoulders(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_BOULDERS_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 4c7ef857c4..0e9dfabf3c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -14,6 +14,7 @@ #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/Navigation/Pokemon_RouteLog.h" #include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.h" @@ -158,7 +159,7 @@ Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step, const return Pokemon::outcome_failed("bad_target", Pokemon::to_string(target_pose)); } const RouteGoal goal{{target->map, target->tile}, target->facing}; - const std::optional> route = plan_story_route(maps, state.pose, facing, goal); + const std::optional> route = plan_story_route(maps, state.pose, facing, goal, state.gates, Pokemon::gate_rules_of(state)); if (!route){ return Pokemon::outcome_failed("no_route", Pokemon::to_string(state.pose) + " to " + to_string(goal.position)); } @@ -167,10 +168,10 @@ Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step, const } const OverworldInterruptSet interrupts = walk_interrupts(env, step); // Planning lets the walker recover a stopped open leg: it plans back to - // the leg's end, then walks the rest as given. From a set of tiles - // the start isn't known: the walker reads the facing. - const RoutePlanning planning{.maps = &maps, .costs = story_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; + // the leg's end, then walks the rest. From a set of tiles: reads the facing. + const RoutePlanning planning{.maps = &maps, .gates = state.gates, .costs = story_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; walk_overworld_route_with_recovery(env.console, env.context, *route, planning, env.player_gender, facing, interrupts, move_speed(step)); + state.gates = gates_after_route(state.gates, *route); log_arrival(env, step.name, target->map, target->tile); const std::optional end_facing = route->empty() ? facing : std::optional(route->back().facing_after); return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, end_facing})); @@ -362,6 +363,8 @@ std::string save_card_place(const std::string& map){ {"CeruleanCity", "cerulean-city"}, {"Route24", "route-24"}, {"Route25", "route-25"}, + {"Route22", "route-22"}, + {"Route23", "route-23"}, {"VermilionCity", "vermilion-city"}, {"Route10", "route-10"}, {"LavenderTown", "lavender-town"}, @@ -435,7 +438,8 @@ Pokemon::Pose paced_pose(const Pokemon::Pose& patch, const StoryStep& step){ std::optional> plan_story_route( const std::vector& maps, const Pokemon::Pose& pose, - std::optional facing, const RouteGoal& goal + std::optional facing, const RouteGoal& goal, + const Pokemon::GateState& gates, const Pokemon::GateRules& rules ){ std::vector tiles; for (const TilePos& tile : Pokemon::tiles_of(pose)){ @@ -449,7 +453,7 @@ std::optional> plan_story_route( if (!holds->empty()){ facing = holds->back().facing_after; } - std::optional> route = plan_overworld_route(maps, from, goal, story_route_costs(), facing); + std::optional> route = plan_overworld_route_gated(maps, from, goal, gates, rules, story_route_costs(), facing); if (route){ route->insert(route->begin(), holds->begin(), holds->end()); } @@ -609,6 +613,33 @@ Outcome cut_tree(StoryEnv& env, RunState& state, const StoryStep& step){ return Pokemon::outcome_ok(to_pose(StoryPose{here->map, here->tile.next(direction), direction})); } +// PUSH_BOULDER_VARIANT: the boulder in the step's direction, Strength +// used if the step says so, and `tiles` steps pushing it on. Not yet +// checked on the console. +Outcome push_boulder(StoryEnv& env, RunState& state, const StoryStep& step){ + const std::optional here = story_pose(state.pose); + if (!here){ + return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); + } + const Direction direction = arg(step, "direction"); + const int64_t tiles = arg(step, "tiles"); + if (here->facing != direction){ + // The boulder is in the way: a tap only turns the player to it. + face_wall(env.console, env.context, direction, env.player_gender); + } + if (arg(step, "activate")){ + pbf_press_button(env.context, BUTTON_A, 160ms, 800ms); + answer_yes_no(env.console, env.context, true, BUTTON_B, YES_NO_TIMEOUT); + mash_until_overworld(env.console, env.context, SCENE_TIMEOUT); + } + StoryPose at = *here; + for (int64_t c = 0; c < tiles; c++){ + step_once(env.console, env.context, direction, direction, env.player_gender); + at = StoryPose{at.map, at.tile.next(direction), direction}; + } + return Pokemon::outcome_ok(to_pose(at)); +} + // Vermilion Gym's trash cans on the console: a walk to each can's stand // (a ROUTE planned on trash_can_maps()), A, and its pages counted. class ConsoleTrashCans{ @@ -713,6 +744,8 @@ ConsoleAction game_console_action(StoryActionId id){ }; case StoryActionId::CUT_TREE: return cut_tree; + case StoryActionId::PUSH_BOULDER: + return push_boulder; case StoryActionId::TRASH_CANS: return open_gym_door; case StoryActionId::GAME: diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h index 46590fe54b..6fac86baf3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h @@ -12,6 +12,7 @@ #include #include +#include "Pokemon/Navigation/Pokemon_GatedTypes.h" #include "Pokemon/Navigation/Pokemon_Grid.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" @@ -45,7 +46,8 @@ const RouteCosts& story_route_costs(); // Nothing if either can't be planned. std::optional> plan_story_route( const std::vector& maps, const Pokemon::Pose& pose, - std::optional facing, const RouteGoal& goal + std::optional facing, const RouteGoal& goal, + const Pokemon::GateState& gates = Pokemon::GateState(), const Pokemon::GateRules& rules = Pokemon::GateRules() ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h new file mode 100644 index 0000000000..872c365fae --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h @@ -0,0 +1,122 @@ +/* FRLG AutoStory Plan Golden, Segment 19 + * + * From: https://github.com/PokemonAutomation/ + * + * The golden's lines for 19.01a and after (Route 22's rival, Route 23, + * Victory Road and Indigo Plateau), in the story's order, after + * PokemonFRLG_AutoStoryPlanGolden17.h's 17.02 to 17.04. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryPlanGolden19_H +#define PokemonAutomation_PokemonFRLG_AutoStoryPlanGolden19_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +// The stored plan lines of 19.01a and after. +inline constexpr std::string_view FRLG_PLAN_GOLDEN_19[] = { + "19.01a viridian_mart_clerk from ViridianCity_PokemonCenter_1F (7, 4) facing north to ViridianCity_Mart (4, 3) facing west", + "19.01a walk south 5 (warp) -> ViridianCity (26, 27) [walk only]", + "19.01a walk south 2 -> ViridianCity (26, 29)", + "19.01a walk east 10 -> ViridianCity (36, 29)", + "19.01a walk north 10 (warp) -> ViridianCity_Mart (4, 7)", + "19.01a walk north 4 -> ViridianCity_Mart (4, 3) [walk only]", + "19.01a face west -> ViridianCity_Mart (4, 3) [walk only]", + "19.01 route22_east_of_trigger from ViridianCity_Mart (4, 3) facing west to Route22 (34, 5) facing west", + "19.01 walk south 5 (warp) -> ViridianCity (36, 20) [walk only]", + "19.01 walk west 13 -> ViridianCity (23, 20)", + "19.01 walk north 1 (to wall) -> ViridianCity (23, 19)", + "19.01 walk west 29 (to wall) -> Route22 (42, 9) [connection 24]", + "19.01 walk south 5 -> Route22 (42, 14)", + "19.01 walk west 6 -> Route22 (36, 14)", + "19.01 walk north 9 -> Route22 (36, 5) [wild]", + "19.01 walk west 2 -> Route22 (34, 5)", + "19.02 above_route22_ledge from Route22 (33, 5) facing west to Route22 (18, 7) facing south", + "19.02 walk west 15 -> Route22 (18, 5)", + "19.02 walk south 2 -> Route22 (18, 7)", + "19.02 below_gate_guard_trigger from Route22 (18, 9) facing south to Route22_NorthEntrance (7, 3) facing north", + "19.02 walk east 3 (to wall) -> Route22 (21, 9) [wild]", + "19.02 surf east -> Route22 (22, 9) [wild]", + "19.02 walk south 2 -> Route22 (22, 11) [surfing] [wild]", + "19.02 walk south 1 -> Route22 (22, 12) [surfing] [wild]", + "19.02 walk south 2 -> Route22 (22, 14)", + "19.02 walk west 18 (to wall) -> Route22 (4, 14)", + "19.02 walk north 4 -> Route22 (4, 10)", + "19.02 walk east 6 -> Route22 (10, 10)", + "19.02 walk north 4 (to wall) -> Route22 (10, 6)", + "19.02 walk west 2 -> Route22 (8, 6)", + "19.02 walk north 1 (warp) -> Route22_NorthEntrance (7, 10)", + "19.02 walk north 7 -> Route22_NorthEntrance (7, 3) [walk only]", + "19.03 cascade_guard_approach from Route23 (8, 153) facing north to Route23 (13, 150) facing north", + "19.03 walk north 3 -> Route23 (8, 150)", + "19.03 walk east 5 -> Route23 (13, 150)", + "19.03 face north -> Route23 (13, 150)", + "19.03 thunder_guard_approach from Route23 (13, 149) facing north to Route23 (7, 141) facing north", + "19.03 walk north 8 -> Route23 (13, 141)", + "19.03 walk west 6 -> Route23 (7, 141)", + "19.03 face north -> Route23 (7, 141)", + "19.03 rainbow_guard_approach from Route23 (7, 140) facing north to Route23 (12, 124) facing north", + "19.03 walk north 9 (to wall) -> Route23 (7, 131)", + "19.03 walk west 5 (to wall) -> Route23 (2, 131)", + "19.03 walk north 7 -> Route23 (2, 124)", + "19.03 walk east 10 -> Route23 (12, 124)", + "19.03 face north -> Route23 (12, 124)", + "19.03 soul_shore from Route23 (12, 123) facing north to Route23 (13, 118) facing north", + "19.03 walk north 5 (to wall) -> Route23 (12, 118)", + "19.03 walk east 1 -> Route23 (13, 118)", + "19.03 face north -> Route23 (13, 118)", + "19.03 soul_guard_approach from Route23 (13, 117) facing north to Route23 (13, 113) facing north", + "19.03 walk north 4 -> Route23 (13, 113) [surfing] [wild]", + "19.03 marsh_guard_approach from Route23 (13, 112) facing north to Route23 (9, 95) facing north", + "19.03 walk north 8 -> Route23 (13, 104) [surfing] [wild]", + "19.03 walk north 1 -> Route23 (13, 103) [surfing] [wild]", + "19.03 walk north 4 (to wall) -> Route23 (13, 99)", + "19.03 walk west 4 -> Route23 (9, 99)", + "19.03 surf north -> Route23 (9, 98) [wild]", + "19.03 walk north 3 -> Route23 (9, 95) [surfing] [wild]", + "19.03 land_below_volcano from Route23 (9, 94) facing north to Route23 (17, 77) facing north", + "19.03 walk north 15 -> Route23 (9, 79) [surfing] [wild]", + "19.03 walk north 1 -> Route23 (9, 78) [surfing] [wild]", + "19.03 walk north 1 (to wall) -> Route23 (9, 77)", + "19.03 walk east 8 -> Route23 (17, 77)", + "19.03 face north -> Route23 (17, 77)", + "19.03 volcano_guard_approach from Route23 (17, 77) facing north to Route23 (12, 62) facing north", + "19.03 walk north 16 (to wall) -> Route23 (17, 61) [wild]", + "19.03 walk south 1 -> Route23 (17, 62)", + "19.03 walk west 5 -> Route23 (12, 62)", + "19.03 face north -> Route23 (12, 62)", + "19.03 earth_guard_approach from Route23 (12, 61) facing north to Route23 (5, 36) facing north", + "19.03 walk north 14 (to wall) -> Route23 (12, 47)", + "19.03 walk west 3 (to wall) -> Route23 (9, 47)", + "19.03 walk north 5 (to wall) -> Route23 (9, 42)", + "19.03 walk west 4 -> Route23 (5, 42)", + "19.03 walk north 6 -> Route23 (5, 36)", + "19.03 victory_road_mouth from Route23 (5, 35) facing north to Route23 (5, 29) facing north", + "19.03 walk north 6 -> Route23 (5, 29)", + "19.05 indigo_door from Route23 (18, 28) facing south to IndigoPlateau_Exterior (11, 7) facing north", + "19.05 walk south 4 (to wall) -> Route23 (18, 32)", + "19.05 walk east 3 (to wall) -> Route23 (21, 32)", + "19.05 walk north 14 -> Route23 (21, 18)", + "19.05 walk west 7 -> Route23 (14, 18)", + "19.05 walk north 13 (to wall) -> Route23 (14, 5)", + "19.05 walk east 1 (to wall) -> Route23 (15, 5)", + "19.05 walk north 4 (to wall) -> Route23 (15, 1)", + "19.05 walk west 1 (to wall) -> Route23 (14, 1)", + "19.05 walk south 1 (to wall) -> Route23 (14, 2)", + "19.05 walk west 3 -> Route23 (11, 2)", + "19.05 walk north 15 -> IndigoPlateau_Exterior (11, 7) [connection 3]", + "19.05 indigo_nurse from IndigoPlateau_Exterior (11, 7) facing north to IndigoPlateau_PokemonCenter_1F (13, 12) facing north", + "19.05 walk north 1 (warp) -> IndigoPlateau_PokemonCenter_1F (11, 16)", + "19.05 walk north 4 (to wall) -> IndigoPlateau_PokemonCenter_1F (11, 12) [walk only]", + "19.05 walk east 2 -> IndigoPlateau_PokemonCenter_1F (13, 12) [walk only]", + "19.05 face north -> IndigoPlateau_PokemonCenter_1F (13, 12) [walk only]", +}; + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h index 03700ed58e..d002cf03d8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h @@ -70,6 +70,14 @@ inline const std::string LEAVE_GIFT_SUMMARY = "leave_gift_summary"; // FLAG_TEMP), so the walk back cuts it again. inline const std::string CUT_TREE_VARIANT = "cut_tree"; +// The GAME step that pushes the boulder the player faces, `direction`, +// `tiles` tiles on (pokefirered EventScript_StrengthBoulder): with +// `activate`, A and YES to "Would you like to use STRENGTH?" first (the +// game keeps Strength on until the player leaves the map); then `tiles` +// steps, each of which moves the boulder a tile and the player into the +// tile it left. The boulder stops at a wall or another object. +inline const std::string PUSH_BOULDER_VARIANT = "push_boulder"; + // How `step`, a ROUTE or LEGS, moves the player: RUN_VARIANT runs, // BIKE_VARIANT rides. MoveSpeed move_speed(const StoryStep& step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp index eef3bd93cd..e48263ba7a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -226,6 +226,7 @@ Pokemon::StoryAction StoryMapsSim::action(StoryActionId id){ case StoryActionId::CLOSE_TRAINER_CARD: case StoryActionId::LEAVE_GIFT_SUMMARY: case StoryActionId::CUT_TREE: + case StoryActionId::PUSH_BOULDER: case StoryActionId::TRASH_CANS: case StoryActionId::GAME: return m_stubs.stub([](const StoryStep& step, RunState& state){ @@ -381,6 +382,9 @@ Pokemon::StoryAction OverworldStepSim::action(StoryActionId id){ case StoryActionId::CUT_TREE: body = &OverworldStepSim::cut; break; + case StoryActionId::PUSH_BOULDER: + body = &OverworldStepSim::push_boulder; + break; case StoryActionId::BATTLE: body = &OverworldStepSim::battle; break; @@ -564,6 +568,27 @@ std::string OverworldStepSim::cut(const StoryStep& step){ return ""; } +// A PUSH_BOULDER_VARIANT step: turned to the boulder, and `tiles` pushes, +// each followed by the step onto the tile the boulder left. +std::string OverworldStepSim::push_boulder(const StoryStep& step){ + const Direction direction = Pokemon::story_arg(step.args, "direction"); + const int64_t tiles = Pokemon::story_arg(step.args, "tiles"); + if (m_sim.state().facing != direction){ + sim_turn_to(m_sim, direction); + } + for (int64_t c = 0; c < tiles; c++){ + if (!m_sim.use_field(SimField::PUSH_BOULDER)){ + return "no boulder to push."; + } + sim_step_once(m_sim, direction); + m_at = StoryPose{m_at.map, m_at.tile.next(direction), direction}; + if (!(m_sim.state().position == MapPosition{m_at.map, m_at.tile})){ + return "expected to step onto the boulder's tile " + to_string(MapPosition{m_at.map, m_at.tile}) + "."; + } + } + return ""; +} + namespace{ // walk_room_legs() on the sim: a step tap a tile, each warp's fade and diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h index b4f7327504..4c06878b63 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h @@ -145,6 +145,7 @@ class OverworldStepSim : public Pokemon::TableExecutor{ std::string step_onto(const StoryStep& step); std::string step_onto_warp(const RouteStep& warp); std::string cut(const StoryStep& step); + std::string push_boulder(const StoryStep& step); std::string battle(const StoryStep& step); Pokemon::StoryAction hideout_or_stub(); std::string hideout(const StoryStep& step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h new file mode 100644 index 0000000000..f0680bbc25 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h @@ -0,0 +1,29 @@ +/* AutoStory Row Tests, Segment 19 + * + * From: https://github.com/PokemonAutomation/ + * + * Registration of the tests that run segment 19's rows (Route 22's rival, + * Route 23, Victory Road) on the overworld sim. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRows19_Tests_H +#define PokemonAutomation_PokemonFRLG_AutoStoryRows19_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Rows 19.01a and after on the overworld sim (PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp). +void add_tests_AutoStoryVictoryRoad(UnitTestDatabase& database); +// The boulder solver and the sim's boulders (PokemonFRLG_AutoStoryBoulders_Tests.cpp). +void add_tests_AutoStoryBoulders(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp index 695738d0e9..1bdf311e59 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp @@ -145,7 +145,7 @@ class Test_RunPlan : public UnitTest{ const RunPlanScenario m_scenario; }; -const std::string TODAY = "01.01 01.03 01.04 01.05 02.01 02.02 02.03 03.01 03.02 03.03 04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 17.02 17.03 17.04 17.04b"; +const std::string TODAY = "01.01 01.03 01.04 01.05 02.01 02.02 02.03 03.01 03.02 03.03 04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.05"; const RunPlanScenario RUN_PLAN_CASES[] = { { @@ -236,11 +236,11 @@ const RunPlanScenario RUN_PLAN_CASES[] = { }, { .input = {.name = "Gift RNG off: 04.03 is passed over", .first = "04.01"}, - .expectation = {.expected_ids = "04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 17.02 17.03 17.04 17.04b"}, + .expectation = {.expected_ids = "04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.05"}, }, { .input = {.name = "Gift RNG off: 04.03 runs when started at", .first = "04.03"}, - .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 17.02 17.03 17.04 17.04b"}, + .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.05"}, }, { .input = { .name = "Gift RNG: started at 04.03, from the save beside the salesman", @@ -279,7 +279,7 @@ const RunPlanScenario RUN_PLAN_CASES[] = { }, { .input = {.name = "Starter RNG alone: 04.03 runs when started at", .first = "04.03", .handoffs = {.starter_rng = true}}, - .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 17.02 17.03 17.04 17.04b"}, + .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.02b 12.03 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 14.03 14.04 14.04b 15.01 16.01 17.02 17.03 17.04 17.04b 19.01a 19.01 19.02 19.03 19.04 19.05"}, }, { .input = { .name = "Starter RNG first, with both on", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index 97b298f70e..621647dffe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -48,6 +48,7 @@ std::string_view story_action_name(StoryActionId id){ case StoryActionId::CLOSE_TRAINER_CARD: return "close_trainer_card"; case StoryActionId::LEAVE_GIFT_SUMMARY: return "leave_gift_summary"; case StoryActionId::CUT_TREE: return "cut_tree"; + case StoryActionId::PUSH_BOULDER: return "push_boulder"; case StoryActionId::TRASH_CANS: return "trash_cans"; case StoryActionId::GAME: return "game"; } @@ -71,6 +72,7 @@ const std::vector& story_action_rows(){ {StoryStepKind::GAME, CLOSE_TRAINER_CARD, StoryActionId::CLOSE_TRAINER_CARD}, {StoryStepKind::GAME, LEAVE_GIFT_SUMMARY, StoryActionId::LEAVE_GIFT_SUMMARY}, {StoryStepKind::GAME, CUT_TREE_VARIANT, StoryActionId::CUT_TREE}, + {StoryStepKind::GAME, PUSH_BOULDER_VARIANT, StoryActionId::PUSH_BOULDER}, {StoryStepKind::GAME, TRASH_CANS_VARIANT, StoryActionId::TRASH_CANS}, {StoryStepKind::GAME, "", StoryActionId::GAME}, }; @@ -258,6 +260,11 @@ std::span story_action_specs(){ specs.push_back({.kind = StoryStepKind::GAME, .name = CUT_TREE_VARIANT, .args = { required_arg("direction", StoryArgType::DIRECTION, "the way to the tree, which the step then walks onto"), }}); + specs.push_back({.kind = StoryStepKind::GAME, .name = PUSH_BOULDER_VARIANT, .args = { + required_arg("direction", StoryArgType::DIRECTION, "the way to the boulder, which the step then pushes"), + optional_arg("tiles", StoryArgType::INTEGER, int64_t(1), "how many tiles to push it"), + optional_arg("activate", StoryArgType::BOOLEAN, false, "use Strength first: A and YES at the boulder"), + }}); specs.push_back({.kind = StoryStepKind::GAME, .name = TRASH_CANS_VARIANT, .args = {}}); for (Pokemon::StoryActionSpec spec : { pc_action_spec(), capture_action_spec(), fossil_action_spec(), level_action_spec(), diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h index c7d89a441a..8dcd4fe0c5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h @@ -47,6 +47,8 @@ enum class StoryActionId{ LEAVE_GIFT_SUMMARY, // CUT_TREE_VARIANT: the tree ahead cut, and a step onto its tile. CUT_TREE, + // PUSH_BOULDER_VARIANT: Strength, and the boulder ahead pushed on. + PUSH_BOULDER, // TRASH_CANS_VARIANT: the search for Vermilion Gym's switches. TRASH_CANS, // Any other GAME step: a capture or a PC deposit or withdrawal diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp index 926b48d2c4..d14007cca2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp @@ -53,6 +53,9 @@ StoryActionId old_game_dispatch(const StoryStep& step){ if (step.action == CUT_TREE_VARIANT){ return StoryActionId::CUT_TREE; } + if (step.action == PUSH_BOULDER_VARIANT){ + return StoryActionId::PUSH_BOULDER; + } if (step.action == TRASH_CANS_VARIANT){ return StoryActionId::TRASH_CANS; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index 24679243de..31559b05e1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -237,7 +237,7 @@ constexpr std::string_view STORY_ORDER[] = { "12.01", "12.02", "12.02b", "12.03", "13.01", "13.02", "13.03", "13.04", "14.01", "14.02", "14.02b", "14.03", "14.04", "14.04b", "15.01", "16.01", - "17.02", "17.03", "17.04", "17.04b", + "17.02", "17.03", "17.04", "17.04b", "19.01a", "19.01", "19.02", "19.03", "19.04", "19.05", }; // `checkpoints` in STORY_ORDER's order. Throws ParseException for a diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryUnauthoredStarts_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryUnauthoredStarts_Tests.h index 3ba3dbe560..5e4f1ef1fa 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryUnauthoredStarts_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryUnauthoredStarts_Tests.h @@ -21,11 +21,12 @@ namespace PokemonFRLG{ // the story's order (STORY_ORDER in PokemonFRLG_AutoStoryTable.cpp) ends. // 17.02 starts at Saffron's Center nurse, where no row before it in the // order ends (Silph Co.'s 16.01 ends on a pad on 5F; the rest of Silph Co. -// and Sabrina are not authored). 14.01 starts outside the Pokemon Mansion, +// and Sabrina are not authored). 19.05 starts at Victory Road's second-floor exit, after the +// cave's floors, whose boulder puzzles are not authored (19.04). 14.01 starts outside the Pokemon Mansion, // after its Escape Rope (13.04), which is not authored. An id leaves this // list once the rows before it are in. inline bool starts_after_unauthored_rows(std::string_view id){ - return id == "17.02" || id == "14.01"; + return id == "17.02" || id == "14.01" || id == "19.05"; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp new file mode 100644 index 0000000000..ac2fa55d56 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp @@ -0,0 +1,328 @@ +/* AutoStory Victory Road Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Rows 19.01a and after (StoryData/frlg-19.0N.plan.json) on the overworld + * sim: Viridian's Center to Route 22's rival, Route 23, Victory Road and + * Indigo Plateau's Center. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryFieldMoves.h" +#include "PokemonFRLG_AutoStoryRooms.h" +#include "PokemonFRLG_AutoStoryRowSim.h" +#include "PokemonFRLG_AutoStoryRows_Tests.h" +#include "PokemonFRLG_AutoStoryRows19_Tests.h" +#include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryTeachPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct AutoStoryVictoryRoadInput{ + std::string name; + std::function body; +}; + +struct AutoStoryVictoryRoadExpectation{ + std::string_view description; +}; + +struct AutoStoryVictoryRoadCase{ + AutoStoryVictoryRoadInput input; + AutoStoryVictoryRoadExpectation expectation; +}; + +class Test_AutoStoryVictoryRoad : public UnitTest{ +public: + explicit Test_AutoStoryVictoryRoad(AutoStoryVictoryRoadCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStory - Simulation: {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_case.input.body(); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + } + } + +private: + AutoStoryVictoryRoadCase m_case; +}; + +const StoryCheckpoint& checkpoint(std::string_view id){ + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id == id){ + return row; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No checkpoint {}.", id)); +} + +// Runs the walking steps of `row` on the sim from its start, up to (not +// including) the step named `until`, or all of them if `until` is empty; +// the steps that are not walks (the Mart, the level check, a scene, the +// battle) are the console's. `marked` is where the sim stood after the +// step named `mark`. +std::string walk_row( + OverworldSim& sim, StoryPose& at, const StoryCheckpoint& row, + std::string_view until, std::string_view mark = {}, MapPosition* marked = nullptr +){ + for (const StoryStep& step : row.steps){ + if (step.name == until){ + return ""; + } + if (step.kind != StoryStepKind::ROUTE && step.kind != StoryStepKind::LEGS && step.kind != StoryStepKind::STEP){ + continue; + } + if (const std::string failure = row_step_on_sim(sim, at, step, row.id); !failure.empty()){ + return failure; + } + if (marked != nullptr && step.name == mark){ + *marked = sim.state().position; + } + } + return until.empty() ? "" : std::format("{}: no step {}.", row.id, until); +} + +// 19.01a: the street to the Mart's counter, where 19.01 starts. 19.01: out +// of the Mart, along the street to Route 22 and along it to the rival's +// trigger column, then the step onto it. The rival is the battle step's, so +// the walk ends on the trigger tile (33, 5), facing west, with no trainer met. +UnitTestResult test_route22_rival_trigger(){ + const StoryCheckpoint& shop = checkpoint("19.01a"); + StoryPose at = *story_pose(Pokemon::pose_of(*shop.start)); + OverworldSim sim(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + if (const std::string failure = walk_row(sim, at, shop, ""); !failure.empty()){ + return failure; + } + const MapPosition counter{"ViridianCity_Mart", {4, 3}}; + if (!(sim.state().position == counter)){ + return std::format("19.01a: ended on {}, not the Mart's counter {}.", to_string(sim.state().position), to_string(counter)); + } + const StoryCheckpoint& row = checkpoint("19.01"); + const StoryPose next = *story_pose(Pokemon::pose_of(*row.start)); + if (next.map != counter.map || !(next.tile == counter.point)){ + return "19.01 doesn't start where 19.01a ends."; + } + if (const std::string failure = walk_row(sim, at, row, "rival_route22"); !failure.empty()){ + return failure; + } + const MapPosition trigger{"Route22", {33, 5}}; + if (!(sim.state().position == trigger)){ + return std::format("19.01: ended on {}, not the rival's trigger {}.", to_string(sim.state().position), to_string(trigger)); + } + if (!sim.state().trainers_beaten.empty() || !sim.state().violations.empty()){ + return "19.01: met a trainer or broke a rule on the way."; + } + return true; +} + +// 19.02: Route 22's ledge and the way round to the north gate; the step +// onto the guard's trigger tile (7, 2) must land on it (the scene after it +// is the console's), and the door beyond leads to Route 23's south end. +UnitTestResult test_gate_guard_trigger_and_route23(){ + const StoryCheckpoint& row = checkpoint("19.02"); + StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + OverworldSim sim(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + MapPosition at_trigger; + if (const std::string failure = walk_row(sim, at, row, "", "gate_guard_trigger", &at_trigger); !failure.empty()){ + return failure; + } + const MapPosition trigger{"Route22_NorthEntrance", {7, 2}}; + if (!(at_trigger == trigger)){ + return std::format("19.02: the guard's step ended on {}, not the trigger {}.", to_string(at_trigger), to_string(trigger)); + } + const MapPosition route23{"Route23", {8, 153}}; + if (!(sim.state().position == route23)){ + return std::format("19.02: ended on {}, not Route 23's south end {}.", to_string(sim.state().position), to_string(route23)); + } + if (!sim.state().trainers_beaten.empty() || !sim.state().violations.empty()){ + return "19.02: met a trainer or broke a rule on the way."; + } + return true; +} + +// The step of row `id` named `name`. +const StoryStep& step_of(std::string_view id, std::string_view name){ + for (const StoryStep& step : checkpoint(id).steps){ + if (step.name == name){ + return step; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No step {} in {}.", name, id)); +} + +// 19.01's rival rows are PokemonSimulation's planning_risk() for each foe +// leading against the entry state of its route22-rival case +// (src/pokesim/games/frlg/battle/player_strategy/planning.py): speed, the +// 80th percentile loss, the mean, the worst case, and the worst normal hit. +UnitTestResult test_rival_foe_threats_are_the_generators(){ + const StoryStep& rival = step_of("19.01", "rival_route22"); + const auto found = rival.args.find("foe_threats"); + const auto* rows = found == rival.args.end() ? nullptr : std::get_if>>(&found->second); + const std::vector> expected = { + {99, 29, 27, 60, 30, 0, 0}, // Pidgeot + {35, 46, 30, 126, 59, 0, 0}, // Rhyhorn + {86, 15, 4, 36, 18, 0, 0}, // Gyarados + {67, 0, 1, 50, 25, 0, 0}, // Growlithe + {126, 55, 20, 120, 60, 0, 0}, // Alakazam + {105, 69, 20, 156, 78, 0, 0}, // Venusaur + }; + if (rows == nullptr || *rows != expected){ + return "19.01 rival_route22: foe_threats are not the generator's rows for the route22-rival case."; + } + return true; +} + +// Where the sim stood after each walking step of `row`, by step name. +std::string walk_row_landings( + OverworldSim& sim, StoryPose& at, const StoryCheckpoint& row, + std::map& landings +){ + for (const StoryStep& step : row.steps){ + if (step.kind != StoryStepKind::ROUTE && step.kind != StoryStepKind::LEGS && step.kind != StoryStepKind::STEP && !is_field_move_step(step)){ + continue; + } + if (const std::string failure = row_step_on_sim(sim, at, step, row.id); !failure.empty()){ + return failure; + } + landings[step.name] = sim.state().position; + } + return ""; +} + +// 19.03: each badge guard's trigger step lands on the tile of its coord +// event (Route23 map.json), and the row ends below Victory Road's mouth. +UnitTestResult test_route23_guard_triggers(){ + const StoryCheckpoint& row = checkpoint("19.03"); + StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + OverworldSim sim(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + std::map landings; + if (const std::string failure = walk_row_landings(sim, at, row, landings); !failure.empty()){ + return failure; + } + const std::pair guards[] = { + {"cascade_guard_trigger", {"Route23", {13, 149}}}, + {"thunder_guard_trigger", {"Route23", {7, 140}}}, + {"rainbow_guard_trigger", {"Route23", {12, 123}}}, + {"soul_guard_trigger", {"Route23", {13, 112}}}, + {"marsh_guard_trigger", {"Route23", {9, 94}}}, + {"volcano_guard_trigger", {"Route23", {12, 61}}}, + {"earth_guard_trigger", {"Route23", {5, 35}}}, + }; + for (const auto& guard : guards){ + const MapPosition& landed = landings[guard.first]; + if (!(landed == guard.second)){ + return std::format("19.03 {}: landed on {}, not {}.", guard.first, to_string(landed), to_string(guard.second)); + } + } + const MapPosition mouth{"Route23", {5, 29}}; + if (!(sim.state().position == mouth)){ + return std::format("19.03: ended on {}, not {}.", to_string(sim.state().position), to_string(mouth)); + } + if (!sim.state().trainers_beaten.empty() || !sim.state().violations.empty()){ + return "19.03: met a trainer or broke a rule on the way."; + } + return true; +} + +// 19.04: Strength replaces Water Pulse, as pokeguy keeps Strength, Surf, +// Bite and Blizzard; the row ends on Victory Road 1F's south end. +UnitTestResult test_strength_teach_and_cave_mouth(){ + const StoryStep& teach = step_of("19.04", "teach_strength"); + const std::optional plan = teach_plan_of(teach.args); + if (!plan.has_value() || plan->item != "hm04" || plan->move != "strength"){ + return "19.04 teach_strength: not HM04 Strength."; + } + const std::vector keep = {"surf", "bite", "blizzard"}; + if (plan->keep != keep){ + return "19.04 teach_strength: keep is not surf, bite, blizzard."; + } + const StoryCheckpoint& row = checkpoint("19.04"); + StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + OverworldSim sim(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + if (const std::string failure = walk_row(sim, at, row, ""); !failure.empty()){ + return failure; + } + const MapPosition end{"VictoryRoad_1F", {11, 20}}; + if (!(sim.state().position == end)){ + return std::format("19.04: ended on {}, not {}.", to_string(sim.state().position), to_string(end)); + } + return true; +} + +// 19.05: from Victory Road's exit on Route 23 to the nurse's counter. +UnitTestResult test_indigo_center_walk(){ + const StoryCheckpoint& row = checkpoint("19.05"); + StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + OverworldSim sim(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + if (const std::string failure = walk_row(sim, at, row, ""); !failure.empty()){ + return failure; + } + const MapPosition end{"IndigoPlateau_PokemonCenter_1F", {13, 12}}; + if (!(sim.state().position == end)){ + return std::format("19.05: ended on {}, not {}.", to_string(sim.state().position), to_string(end)); + } + return true; +} + +const AutoStoryVictoryRoadCase AUTO_STORY_VICTORY_ROAD_CASES[] = { + { + .input = {.name = "19.01a Viridian's Mart and 19.01 to the Route 22 rival's trigger", .body = test_route22_rival_trigger}, + .expectation = {.description = "Route 22 (33, 5), no trainer met"}, + }, + { + .input = {.name = "19.02 Route 22's gate guard trigger, onto Route 23", .body = test_gate_guard_trigger_and_route23}, + .expectation = {.description = "the trigger (7, 2) stepped onto, Route 23 (8, 153), no trainer met"}, + }, + { + .input = {.name = "19.01 the rival's foe rows are the generator's", .body = test_rival_foe_threats_are_the_generators}, + .expectation = {.description = "PokemonSimulation planning_risk() rows"}, + }, + { + .input = {.name = "19.03 Route 23's guard triggers, to Victory Road's mouth", .body = test_route23_guard_triggers}, + .expectation = {.description = "each trigger tile landed on, Route 23 (5, 29)"}, + }, + { + .input = {.name = "19.04 Strength over Water Pulse, into the cave", .body = test_strength_teach_and_cave_mouth}, + .expectation = {.description = "keep surf, bite, blizzard; Victory Road 1F (11, 20)"}, + }, + { + .input = {.name = "19.05 Indigo Plateau's Center", .body = test_indigo_center_walk}, + .expectation = {.description = "Indigo Plateau Center (13, 12)"}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryVictoryRoad(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_VICTORY_ROAD_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index d88532ea20..b503efea43 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -43,6 +43,7 @@ #include "PokemonFRLG_AutoStoryPlanGolden16.h" #include "PokemonFRLG_AutoStoryPlanGolden17.h" #include "PokemonFRLG_AutoStoryPlanGolden13.h" +#include "PokemonFRLG_AutoStoryPlanGolden19.h" #include "PokemonFRLG_AutoStoryRows_Tests.h" #include "PokemonFRLG_AutoStoryMoveData.h" #include "PokemonFRLG_AutoStoryStepTable.h" @@ -292,8 +293,8 @@ UnitTestResult check_checkpoint(const StoryCheckpoint& checkpoint, StoryPose& po // start: starts_after_unauthored_rows()), and adds the plans to `golden`. UnitTestResult chain_story_routes(std::vector& golden){ const std::vector& checkpoints = story_checkpoints(); - if (checkpoints.size() != 70 || checkpoints[0].start){ - return "Expected 70 checkpoints, the first from a new game."; + if (checkpoints.size() != 76 || checkpoints[0].start){ + return "Expected 76 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ @@ -343,6 +344,7 @@ UnitTestResult test_golden_plans(){ golden.insert(golden.end(), std::begin(FRLG_PLAN_GOLDEN_15), std::end(FRLG_PLAN_GOLDEN_15)); golden.insert(golden.end(), std::begin(FRLG_PLAN_GOLDEN_16), std::end(FRLG_PLAN_GOLDEN_16)); golden.insert(golden.end(), std::begin(FRLG_PLAN_GOLDEN_17_GYM), std::end(FRLG_PLAN_GOLDEN_17_GYM)); + golden.insert(golden.end(), std::begin(FRLG_PLAN_GOLDEN_19), std::end(FRLG_PLAN_GOLDEN_19)); const size_t stored = golden.size(); size_t first_diff = 0; while (first_diff < actual.size() && first_diff < stored && actual[first_diff] == golden[first_diff]){ @@ -1077,7 +1079,7 @@ UnitTestResult test_save_places(){ if (save_card_place("Route24") != "route-24" || save_card_place("Route25_SeaCottage") != "route-25"){ return "Wrong save card places on Route 24 and 25."; } - if (!save_card_place("Route22").empty() || !save_card_place("Route2").empty()){ + if (!save_card_place("Route9").empty() || !save_card_place("Route2").empty()){ return "A place for a map the table doesn't use."; } return true; @@ -1099,7 +1101,7 @@ UnitTestResult test_save_place_error(){ {.start_map = "PalletTown_PlayersHouse_2F", .place = "", .error = false}, {.start_map = "ViridianForest", .place = "viridian-city", .error = true}, // A map with no known place isn't checked. - {.start_map = "Route22", .place = "pewter-city", .error = false}, + {.start_map = "Route9", .place = "pewter-city", .error = false}, }; for (const Case& c : CASES){ const std::string error = save_place_error(c.start_map, c.place); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.01.plan.json new file mode 100644 index 0000000000..68715f1332 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.01.plan.json @@ -0,0 +1,82 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "19.01", + "title": "The rival on Route 22, at the road's east end", + "start": {"map": "ViridianCity_Mart", "tiles": [[4, 3]], "facing": "west"}, + "events": [ + { + "id": "lead_lv49_for_rival_route22", + "kind": "game_action", + "action": "level", + "args": { + "slot": 1, + "min": 49 + }, + "why": "the precondition for the Route 22 rival: the lead at least Lv49, pokeguy's Blastoise here (docs/battles/pokeguy-conditions.md route22-rival); 17.04's Giovanni needs Lv50" + }, + { + "id": "route22_east_of_trigger", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "Route22", "tiles": [[34, 5]], "facing": "west"} + }, + "why": "out of the Mart and west out of Viridian City onto Route 22, along row 5 to (34, 5), a tile short of the rival's trigger column (33, 4..6)" + }, + { + "id": "rival_trigger", + "kind": "step", + "args": {"direction": "west"}, + "declared_after": {"map": "Route22", "tiles": [[33, 5]], "facing": "west"}, + "why": "onto (33, 5): Route22_EventScript_LateRivalTriggerMid (VAR_MAP_SCENE_ROUTE22 is 3 once Giovanni is beaten, 17.04) puts the rival at (25, 5) and walks him seven tiles east to face the player" + }, + { + "id": "rival_route22", + "kind": "battle", + "args": { + "trainer": "TRAINER_RIVAL_ROUTE22_LATE_BULBASAUR", + "foes": [ + "pidgeot", + "rhyhorn", + "gyarados", + "growlithe", + "alakazam", + "venusaur" + ], + "policy": "goal-based-setup", + "setup_spa": 2, + "setup_accuracy": 2, + "setup_outspeed": true, + "setup_guard_accuracy": true, + "foe_threats": [ + [99, 29, 27, 60, 30, 0, 0], + [35, 46, 30, 126, 59, 0, 0], + [86, 15, 4, 36, 18, 0, 0], + [67, 0, 1, 50, 25, 0, 0], + [126, 55, 20, 120, 60, 0, 0], + [105, 69, 20, 156, 78, 0, 0] + ] + }, + "declared_after": {"map": "Route22", "tiles": [[33, 5]], "facing": "west"}, + "why": "the rival (TRAINER_RIVAL_ROUTE22_LATE_BULBASAUR for a player who took Squirtle): Pidgeot Lv47, Rhyhorn Lv45, Gyarados Lv45, Growlithe Lv45, Alakazam Lv47, Venusaur Lv53; fought by pokeguy's policy C2 (goal-based-setup: Sp. Atk +2 and Accuracy +2 by X Specials and X Accuracies, X Speed until faster, the doc's route22-rival row); foe_threats are the rows PokemonSimulation's player-strategy planning_risk() gives for each foe leading against the entry state (153/153, the doc's route22-rival case: the 80th percentile of the foe's move choice, its mean, its worst case, and its worst normal hit), one row per foe: Venusaur's worst case (crit Razor Leaf) is 156 of 153 HP, Rhyhorn's 126. Then he walks off and the player stays facing west" + } + ] + }, + "execution": { + "menu": "full", + "notes": { + "checkpoint": [ + "Starts in the Viridian Mart where 19.01a ends, with the potions bought. The rival's trigger needs VAR_MAP_SCENE_ROUTE22 at 3, which Giovanni's defeat sets (ViridianCity_Gym scripts), so the row can not be reached by hand before the Earth Badge. PokeGuy has this fight at 1:46 (docs/battles/pokeguy-conditions.md, route22-rival) at 153/153 HP; the Center heal in 17.04b is that entry.", + "Ends on Route 22 at (33, 5) facing west, saved there (the battle saves after it): 19.02 walks on to the north gate (8, 5) and Route 23." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": {"map": "Route22", "tiles": [[33, 5]], "facing": "west"} + } + } +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.01a.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.01a.plan.json new file mode 100644 index 0000000000..cbcd2ebb10 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.01a.plan.json @@ -0,0 +1,50 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "19.01a", + "title": "Viridian's Mart: potions before the rival on Route 22", + "start": { + "map": "ViridianCity_PokemonCenter_1F", + "tiles": [[7, 4]], + "facing": "north" + }, + "events": [ + { + "id": "viridian_mart_clerk", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "ViridianCity_Mart", "tiles": [[4, 3]], "facing": "west"} + }, + "why": "out of the Center and along the street to the Mart's door, in and up to the counter, facing the clerk (as 02.03)" + }, + { + "id": "buy_potions", + "kind": "game_action", + "action": "mart", + "args": { + "map": "ViridianCity_Mart", + "items": [{"item": "potion", "quantity": 4}], + "fill_to": 4 + }, + "why": "Potions up to 4 in the bag, as in PokeGuy's bag at the Route 22 rival (potion x4, superpotion x4, xaccuracy x4, xspecial x17, xspeed x5, guardspec x2; PokemonSimulation docs/battles/pokeguy-conditions.md); the Super Potions are 12.01's. Early in the row, so a failed purchase stops it before the walk. Buys 4 less what the bag holds, skipped at 4" + } + ] + }, + "execution": { + "menu": "full", + "notes": { + "checkpoint": [ + "Starts at Viridian's nurse, where 17.04b ends. The Mart's clerk is first in the checkpoint: the potions are bought before the rival, and 19.01 starts in the Mart with the bag as it should be.", + "Ends in the Viridian Mart at (4, 3) facing the clerk, where 19.01 starts." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": {"map": "ViridianCity_Mart", "tiles": [[4, 3]], "facing": "west"} + } + } +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.02.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.02.plan.json new file mode 100644 index 0000000000..d42b395036 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.02.plan.json @@ -0,0 +1,75 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "19.02", + "title": "Route 22's north gate: the Boulder Badge guard, onto Route 23", + "start": { + "map": "Route22", + "tiles": [[33, 5]], + "facing": "west" + }, + "events": [ + { + "id": "above_route22_ledge", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "Route22", "tiles": [[18, 7]], "facing": "south"} + }, + "why": "west along the road's north side (row 5, the rival's tiles) to above the ledge row (15..21, 8): the north-west part, with the gate's door, is reached over this ledge and by no other way on foot (the gap at (36, 8) and (37, 8) leads only to the east grass)" + }, + { + "id": "route22_ledge_hop", + "kind": "step", + "args": {"direction": "south"}, + "declared_after": {"map": "Route22", "tiles": [[18, 9]], "facing": "south"}, + "why": "the ledge (18, 8): a hop over it onto the grass (18, 9) below" + }, + { + "id": "below_gate_guard_trigger", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "Route22_NorthEntrance", "tiles": [[7, 3]], "facing": "north"} + }, + "why": "through the grass and west along the road's west part to the north gate's door (8, 5) and in, up the hall to (7, 3), short of the guard's trigger at (7, 2) (Route22_NorthEntrance map.json coord_event)" + }, + { + "id": "gate_guard_trigger", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "Route22_NorthEntrance", "tiles": [[7, 2]], "facing": "north"}, + "why": "onto (7, 2): Route22_NorthEntrance_EventScript_BoulderBadgeGuardTrigger (VAR_MAP_SCENE_ROUTE23 is 0) turns the guard at (8, 2) to the player" + }, + { + "id": "gate_guard_scene", + "kind": "scene", + "declared_after": {"map": "Route22_NorthEntrance", "tiles": [[7, 2]], "facing": "north"}, + "why": "the guard recognizes the BOULDERBADGE (the text, a fanfare, A) and sets VAR_MAP_SCENE_ROUTE23 to 1 (route23.inc Route23_EventScript_RecognizeBoulderBadgeTrigger); a player without it is walked back down instead, which the row does not expect: 17.04 has all eight" + }, + { + "id": "gate_north_door", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "Route23", "tiles": [[8, 153]], "facing": "north"}, + "why": "through the gate's north door (7, 1) onto Route 23's south end (8, 153)" + } + ] + }, + "execution": { + "menu": "full", + "notes": { + "checkpoint": [ + "Starts where 19.01 ends: Route 22 (33, 5), the rival gone (VAR_MAP_SCENE_ROUTE22 is 4). The gate's guard is a trigger, not a talk: with all eight badges there is one message and no movement.", + "Ends on Route 23's south end (8, 153), where the first of the seven badge guards (Cascade, at (15, 149)) is ahead: Route 23's guards, its water (Surf, HM03 taught in 12.01), Strength's teach over Water Pulse (pokeguy, D3) and Victory Road are not authored here." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": {"map": "Route23", "tiles": [[8, 153]], "facing": "north"} + } + } +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.03.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.03.plan.json new file mode 100644 index 0000000000..7c4d9edbb9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.03.plan.json @@ -0,0 +1,196 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "19.03", + "title": "Route 23: the seven badge guards and the Surf stretch, to Victory Road's mouth", + "start": {"map": "Route23", "tiles": [[8, 153]], "facing": "north"}, + "events": [ + { + "id": "cascade_guard_approach", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[13, 150]], "facing": "north"}}, + "why": "to just south of the Cascade guard's trigger tile (13, 149) (Route23 map.json coord_events; the guard stands at (15, 149)), by the way the planner finds" + }, + { + "id": "cascade_guard_trigger", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "Route23", "tiles": [[13, 149]], "facing": "north"}, + "why": "onto (13, 149): Route23_EventScript_CascadeBadgeGuardTrigger (VAR_MAP_SCENE_ROUTE23 is 1) turns the guard to the player; every other trigger of this guard is out of the way, and the guards ahead trigger on a later value" + }, + { + "id": "cascade_guard_scene", + "kind": "scene", + "declared_after": {"map": "Route23", "tiles": [[13, 149]], "facing": "north"}, + "why": "the guard recognizes the CASCADEBADGE (the text, A) and sets VAR_MAP_SCENE_ROUTE23 to 2 (route23.inc Route23_EventScript_RecognizeBadgeTrigger); a player without it is walked back down instead, which the row does not expect: 17.04 has all eight" + }, + { + "id": "thunder_guard_approach", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[7, 141]], "facing": "north"}}, + "why": "to just south of the Thunder guard's trigger tile (7, 140) (Route23 map.json coord_events; the guard stands at (8, 140)), by the way the planner finds" + }, + { + "id": "thunder_guard_trigger", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "Route23", "tiles": [[7, 140]], "facing": "north"}, + "why": "onto (7, 140): Route23_EventScript_ThunderBadgeGuardTrigger (VAR_MAP_SCENE_ROUTE23 is 2) turns the guard to the player; every other trigger of this guard is out of the way, and the guards ahead trigger on a later value" + }, + { + "id": "thunder_guard_scene", + "kind": "scene", + "declared_after": {"map": "Route23", "tiles": [[7, 140]], "facing": "north"}, + "why": "the guard recognizes the THUNDERBADGE (the text, A) and sets VAR_MAP_SCENE_ROUTE23 to 3 (route23.inc Route23_EventScript_RecognizeBadgeTrigger); a player without it is walked back down instead, which the row does not expect: 17.04 has all eight" + }, + { + "id": "rainbow_guard_approach", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[12, 124]], "facing": "north"}}, + "why": "to just south of the Rainbow guard's trigger tile (12, 123) (Route23 map.json coord_events; the guard stands at (14, 123)), by the way the planner finds" + }, + { + "id": "rainbow_guard_trigger", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "Route23", "tiles": [[12, 123]], "facing": "north"}, + "why": "onto (12, 123): Route23_EventScript_RainbowBadgeGuardTrigger (VAR_MAP_SCENE_ROUTE23 is 3) turns the guard to the player; every other trigger of this guard is out of the way, and the guards ahead trigger on a later value" + }, + { + "id": "rainbow_guard_scene", + "kind": "scene", + "declared_after": {"map": "Route23", "tiles": [[12, 123]], "facing": "north"}, + "why": "the guard recognizes the RAINBOWBADGE (the text, A) and sets VAR_MAP_SCENE_ROUTE23 to 4 (route23.inc Route23_EventScript_RecognizeBadgeTrigger); a player without it is walked back down instead, which the row does not expect: 17.04 has all eight" + }, + { + "id": "soul_shore", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[13, 118]], "facing": "north"}}, + "why": "from the Rainbow guard on to the lake's south shore (12..14, 118), facing the water: Route 23's water runs north from here (112 to 78) to the shore below the Volcano guard" + }, + { + "id": "surf_off_shore", + "kind": "game_action", + "action": "surf", + "args": {"direction": "north"}, + "declared_after": {"map": "Route23", "tiles": [[13, 117]], "facing": "north"}, + "why": "the lead's Surf (taught in 12.01): A at the water, YES, onto (13, 117); the Soul and Marsh guards' trigger tiles are on the water" + }, + { + "id": "soul_guard_approach", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[13, 113]], "facing": "north"}}, + "why": "to just south of the Soul guard's trigger tile (13, 112) (Route23 map.json coord_events; the guard stands at (16, 112)), by the way the planner finds over the water: Surf from the shore (taught in 12.01), the guard stands on the water's edge and the trigger tiles are in the water" + }, + { + "id": "soul_guard_trigger", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "Route23", "tiles": [[13, 112]], "facing": "north"}, + "why": "onto (13, 112): Route23_EventScript_SoulBadgeGuardTrigger (VAR_MAP_SCENE_ROUTE23 is 4) turns the guard to the player; every other trigger of this guard is out of the way, and the guards ahead trigger on a later value" + }, + { + "id": "soul_guard_scene", + "kind": "scene", + "declared_after": {"map": "Route23", "tiles": [[13, 112]], "facing": "north"}, + "why": "the guard recognizes the SOULBADGE (the text, A) and sets VAR_MAP_SCENE_ROUTE23 to 5 (route23.inc Route23_EventScript_RecognizeBadgeTrigger); a player without it is walked back down instead, which the row does not expect: 17.04 has all eight" + }, + { + "id": "marsh_guard_approach", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[9, 95]], "facing": "north"}}, + "why": "to just south of the Marsh guard's trigger tile (9, 94) (Route23 map.json coord_events; the guard stands at (10, 94)), by the way the planner finds; still on the water, which ends on the island's north shore and goes on to the lake" + }, + { + "id": "marsh_guard_trigger", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "Route23", "tiles": [[9, 94]], "facing": "north"}, + "why": "onto (9, 94): Route23_EventScript_MarshBadgeGuardTrigger (VAR_MAP_SCENE_ROUTE23 is 5) turns the guard to the player; every other trigger of this guard is out of the way, and the guards ahead trigger on a later value" + }, + { + "id": "marsh_guard_scene", + "kind": "scene", + "declared_after": {"map": "Route23", "tiles": [[9, 94]], "facing": "north"}, + "why": "the guard recognizes the MARSHBADGE (the text, A) and sets VAR_MAP_SCENE_ROUTE23 to 6 (route23.inc Route23_EventScript_RecognizeBadgeTrigger); a player without it is walked back down instead, which the row does not expect: 17.04 has all eight" + }, + { + "id": "land_below_volcano", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[17, 77]], "facing": "north"}}, + "why": "off the water onto the shore (16..21, 77..78) below the Volcano guard" + }, + { + "id": "volcano_guard_approach", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[12, 62]], "facing": "north"}}, + "why": "to just south of the Volcano guard's trigger tile (12, 61) (Route23 map.json coord_events; the guard stands at (14, 61)), by the way the planner finds" + }, + { + "id": "volcano_guard_trigger", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "Route23", "tiles": [[12, 61]], "facing": "north"}, + "why": "onto (12, 61): Route23_EventScript_VolcanoBadgeGuardTrigger (VAR_MAP_SCENE_ROUTE23 is 6) turns the guard to the player; every other trigger of this guard is out of the way, and the guards ahead trigger on a later value" + }, + { + "id": "volcano_guard_scene", + "kind": "scene", + "declared_after": {"map": "Route23", "tiles": [[12, 61]], "facing": "north"}, + "why": "the guard recognizes the VOLCANOBADGE (the text, A) and sets VAR_MAP_SCENE_ROUTE23 to 7 (route23.inc Route23_EventScript_RecognizeBadgeTrigger); a player without it is walked back down instead, which the row does not expect: 17.04 has all eight" + }, + { + "id": "earth_guard_approach", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[5, 36]], "facing": "north"}}, + "why": "to just south of the Earth guard's trigger tile (5, 35) (Route23 map.json coord_events; the guard stands at (6, 35)), by the way the planner finds" + }, + { + "id": "earth_guard_trigger", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "Route23", "tiles": [[5, 35]], "facing": "north"}, + "why": "onto (5, 35): Route23_EventScript_EarthBadgeGuardTrigger (VAR_MAP_SCENE_ROUTE23 is 7) turns the guard to the player; every other trigger of this guard is out of the way, and the guards ahead trigger on a later value" + }, + { + "id": "earth_guard_scene", + "kind": "scene", + "declared_after": {"map": "Route23", "tiles": [[5, 35]], "facing": "north"}, + "why": "the guard recognizes the EARTHBADGE (the text, A) and sets VAR_MAP_SCENE_ROUTE23 to 8 (route23.inc Route23_EventScript_RecognizeBadgeTrigger); a player without it is walked back down instead, which the row does not expect: 17.04 has all eight" + }, + { + "id": "victory_road_mouth", + "kind": "route", + "action": "run", + "args": {"target": {"map": "Route23", "tiles": [[5, 29]], "facing": "north"}}, + "why": "north past the last guard to below the cave mouth (5, 28), the warp into Victory Road 1F" + } + ] + }, + "execution": { + "menu": "full", + "notes": { + "checkpoint": [ + "Starts where 19.02 ends: Route 23's south end (8, 153), VAR_MAP_SCENE_ROUTE23 at 1 (the Boulder Badge guard recognized). Each of the seven guards (Cascade to Earth) is a coord-event trigger, not a talk: stepping onto one of the live trigger tiles starts the scene, and with all eight badges it is one message and A; the next guard's triggers go live at the new value, the finished guards' stay quiet.", + "The stretch from (13, 118) to (x, 78) is water: the planner Surfs from the shore (HM03 Surf, taught in 12.01) and gets off on the north shore (rows 77 and up). The Soul and Marsh guards stand on its edge, with their triggers in the water, and are triggered while surfing.", + "Ends below Victory Road's mouth, Route 23 (5, 29), facing north; 19.04 teaches Strength and walks in." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": {"map": "Route23", "tiles": [[5, 29]], "facing": "north"} + } + } +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.04.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.04.plan.json new file mode 100644 index 0000000000..330d22ae1d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.04.plan.json @@ -0,0 +1,45 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "19.04", + "title": "Victory Road: HM04 Strength over Water Pulse, into the cave", + "start": {"map": "Route23", "tiles": [[5, 29]], "facing": "north"}, + "events": [ + { + "id": "teach_strength", + "kind": "game_action", + "action": "teach", + "args": { + "item": "hm04", + "move": "strength", + "slot": 1, + "keep": ["surf", "bite", "blizzard"] + }, + "why": "HM04 Strength in place of Water Pulse, as pokeguy at Victory Road (PokemonSimulation docs/progression/pokeguy-moves.md: Strength, Surf, Bite, Blizzard; docs/battles/pokeguy-conditions.md, the move-learning table: STRENGTH replaces WATER_PULSE); an HM, so not a one-shot TM; keep list: Surf, Bite and Blizzard stay and the one other move (Water Pulse) goes; fails if none or several are outside the list. The Rainbow Badge it needs is 14.04's" + }, + { + "id": "cave_mouth", + "kind": "step", + "args": {"direction": "north"}, + "declared_after": {"map": "VictoryRoad_1F", "tiles": [[11, 20]], "facing": "north"}, + "why": "north onto the cave mouth (5, 28), the warp into Victory Road 1F's south end (11, 20)" + } + ] + }, + "execution": { + "menu": "full", + "notes": { + "checkpoint": [ + "Starts below Victory Road's mouth, where 19.03 ends. Strength is taught here, at the cave's start, because every floor's boulders need it (pokeguy teaches it over Water Pulse at Victory Road, 1:43:24 on his video: the 12.02 note that pointed at 19.02, D3 meant this row).", + "Ends on Victory Road 1F's south end (11, 20). The boulder puzzles of the three floors are not authored: the maps have the boulders as objects but not the switches' barriers (1F (12, 14) and (12, 15); 2F (13, 10) and (13, 11), (33, 16) and (33, 17); 3F (12, 12) and (12, 13)) nor which tiles the switches press (1F (20, 16); 2F (2, 19), (14, 19); 3F (7, 7)), so the planner would walk through them. Pokemon_BoulderSolver in PokemonFRLG_AutoStoryBoulders_Tests.cpp holds the data and the search; the barriers need the user's map edit (TODO)." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": {"map": "VictoryRoad_1F", "tiles": [[11, 20]], "facing": "north"} + } + } +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.05.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.05.plan.json new file mode 100644 index 0000000000..5e46ffceec --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.05.plan.json @@ -0,0 +1,49 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "19.05", + "title": "Victory Road's exit to Indigo Plateau: heal at its Center", + "start": {"map": "Route23", "tiles": [[18, 28]], "facing": "south"}, + "events": [ + { + "id": "indigo_door", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "IndigoPlateau_Exterior", "tiles": [[11, 7]], "facing": "north"} + }, + "why": "from Victory Road's second-floor exit (Route 23 (18, 28)) north along Route 23 to Indigo Plateau (its north connection) and up to below the Center's door (11, 6)" + }, + { + "id": "indigo_nurse", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "IndigoPlateau_PokemonCenter_1F", "tiles": [[13, 12]], "facing": "north"} + }, + "why": "in through the door and across the lobby to below the counter (13, 11), the nurse at (13, 10); this Center is not the standard one, so center_enter's legs do not apply" + }, + { + "id": "heal_indigo", + "kind": "heal", + "why": "full HP and PP before the League; the nurse's text and the jingle" + } + ] + }, + "execution": { + "menu": "full", + "notes": { + "checkpoint": [ + "Starts on Route 23 (18, 28), where Victory Road 2F's exit (48, 12) leaves the player, facing south. Victory Road's floors are not authored (19.04's note), so this row's start is its own (starts_after_unauthored_rows()).", + "Ends at Indigo Plateau's nurse below the counter (13, 12): the save point of the League's door, where the first League row (Lorelei) starts." + ] + } + }, + "metadata": { + "phase": "testing", + "postconditions": { + "position": {"map": "IndigoPlateau_PokemonCenter_1F", "tiles": [[13, 12]], "facing": "north"} + } + } +} diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index dabb7d7783..2de75ee5a7 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1489,12 +1489,21 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h + Source/Pokemon/Navigation/Pokemon_GatedPlanner.h + Source/Pokemon/Navigation/Pokemon_GatedTypes.h + Source/Pokemon/Navigation/Pokemon_GateState.cpp + Source/Pokemon/Navigation/Pokemon_GateState.h + Source/Pokemon/Navigation/Pokemon_GateTiles.cpp + Source/Pokemon/Navigation/Pokemon_GateTiles.h + Source/Pokemon/Navigation/Pokemon_Gates_Tests.cpp + Source/Pokemon/Navigation/Pokemon_Gates_Tests.h Source/Pokemon/Navigation/Pokemon_Direction.cpp Source/Pokemon/Navigation/Pokemon_Direction.h Source/Pokemon/Navigation/Pokemon_Grid.cpp Source/Pokemon/Navigation/Pokemon_Grid.h Source/Pokemon/Navigation/Pokemon_LegTypes.h Source/Pokemon/Navigation/Pokemon_MapFeatures.h + Source/Pokemon/Navigation/Pokemon_MapGates.h Source/Pokemon/Navigation/Pokemon_MapTiles.h Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h @@ -1520,6 +1529,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h Source/Pokemon/Navigation/Pokemon_NavigationTestMaps.h + Source/Pokemon/Navigation/Pokemon_NavigationGateTestMaps.h Source/Pokemon/Navigation/Pokemon_RouteLog.cpp Source/Pokemon/Navigation/Pokemon_RouteLog.h Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp @@ -1679,6 +1689,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h @@ -2017,6 +2028,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldBikeTaps.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldBikeTaps.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldBike_Tests.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldLateBattle.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldLateBattle.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldLateBattle_Tests.cpp @@ -2064,6 +2077,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWarpFade_Tests.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkGates.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkMoves.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkOptions.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkTimes.h @@ -2113,8 +2127,11 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySilph_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows16_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows17_Tests.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMansion_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryViridian_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBoulders_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows13_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryUnauthoredStarts_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryChoice.cpp @@ -2207,6 +2224,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden15.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden16.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden17.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden13.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.h diff --git a/devtools/story-data-tests/CMakeLists.txt b/devtools/story-data-tests/CMakeLists.txt index c8fe360274..9a46137153 100644 --- a/devtools/story-data-tests/CMakeLists.txt +++ b/devtools/story-data-tests/CMakeLists.txt @@ -14,6 +14,8 @@ add_executable(StoryDataTests "${STORY}/Types/Pokemon_StoryActionArg.cpp" "${STORY}/Types/Pokemon_StoryActionSpec.cpp" "${STORY}/Types/Pokemon_StoryCheckpointMetadata.cpp" + "${STORY}/Types/Pokemon_StoryCheckpointGates.cpp" + "${ROOT}/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp" "${ROOT}/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp" "${ROOT}/Common/Cpp/Exceptions.cpp" "${ROOT}/Common/Cpp/Json/JsonValue.cpp"