From cb5d05423adc5f628ac2c669034d49c9f6d5e497 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:51:39 -0800 Subject: [PATCH 01/15] Navigation: gates, switches and one-way warps; gated planner; gate state in story data Runtime maps carry gates (G tiles), switches (statue presses) and one_way warps. A gate state (opened gates, switches on) resolves tiles; plan_gated_legs wraps a game step model and adds open-gate / press-switch action legs. Steps carry gates_after, checkpoints start_gates. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- SerialPrograms/CMakeLists.txt | 2 + .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../AutoStory/Data/Pokemon_StoryStepJson.cpp | 55 +- .../AutoStory/Data/Pokemon_StoryStepJson.h | 12 + .../Data/Pokemon_StoryStepJson_Tests.cpp | 32 ++ .../AutoStory/Types/Pokemon_StoryCheckpoint.h | 12 + .../Types/Pokemon_StoryCheckpointGates.cpp | 28 + .../AutoStory/Types/Pokemon_StoryStep.h | 5 + .../GateTestMaps/PokemonMansion_1F.json | 63 +++ .../GateTestMaps/PokemonMansion_3F.json | 59 +++ .../Navigation/GateTestMaps/SilphCo_5F.json | 45 ++ .../Pokemon/Navigation/Pokemon_GateState.cpp | 67 +++ .../Pokemon/Navigation/Pokemon_GateState.h | 74 +++ .../Pokemon/Navigation/Pokemon_GateTiles.cpp | 76 +++ .../Pokemon/Navigation/Pokemon_GateTiles.h | 50 ++ .../Pokemon/Navigation/Pokemon_GatedPlanner.h | 198 +++++++ .../Navigation/Pokemon_Gates_Tests.cpp | 499 ++++++++++++++++++ .../Pokemon/Navigation/Pokemon_Gates_Tests.h | 24 + .../Pokemon/Navigation/Pokemon_MapData.cpp | 161 ++++++ .../Pokemon/Navigation/Pokemon_MapData.h | 18 +- .../Pokemon/Navigation/Pokemon_MapFeatures.h | 46 ++ .../Pokemon/Navigation/Pokemon_MapTiles.h | 4 + .../Pokemon_NavigationGateTestMaps.h | 30 ++ SerialPrograms/cmake/SourceFiles.cmake | 9 + devtools/story-data-tests/CMakeLists.txt | 2 + 25 files changed, 1570 insertions(+), 3 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/PokemonMansion_1F.json create mode 100644 SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/PokemonMansion_3F.json create mode 100644 SerialPrograms/Source/Pokemon/Navigation/GateTestMaps/SilphCo_5F.json create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_NavigationGateTestMaps.h diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index 62d006eb4c..b9258b6165 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -230,6 +230,8 @@ add_library(SerialProgramsLib STATIC ${CORE_LIBRARY_SOURCES} ${LIBRARY_SOURCES}) include(cmake/EmbedTextFiles.cmake) pa_embed_text_files(SerialProgramsLib Source/Pokemon/Navigation/TestMaps Pokemon/Navigation/Pokemon_NavigationTestMaps.h PokemonAutomation::Pokemon navigation_test_map_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 e56c4a593b..9a5cf86d3d 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -36,6 +36,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" @@ -88,6 +89,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..9b9f64665d 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"}, source); StoryStep result; result.name = root.get_string_throw("id"); if (result.name.empty()){ @@ -344,11 +389,14 @@ 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); + } 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", "events", "metadata"}, source); StoryCheckpoint result; result.id = root.get_string_throw("id"); if (result.id.empty()){ @@ -358,6 +406,9 @@ 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); + } 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..83680b7701 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -36,6 +36,18 @@ 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); +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); +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..9eb48cba9b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -134,6 +134,38 @@ 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 = "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/Types/Pokemon_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h index 6a0c04702d..1f76989b29 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,19 @@ 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 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..8b004bbf8c 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,10 @@ 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 = {}; }; 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..8b4ec23a42 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h @@ -0,0 +1,74 @@ +/* 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{ + + +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. +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..2c3053b27d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp @@ -0,0 +1,76 @@ +/* Gate Tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_GateTiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +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){ + return state.switch_on(gate.switch_id) == 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..89a0c4fcd7 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h @@ -0,0 +1,50 @@ +/* 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 "Pokemon_GateState.h" +#include "Pokemon_Grid.h" +#include "Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// 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..d04be50145 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h @@ -0,0 +1,198 @@ +/* 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; + * + * 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 "Pokemon_ConnectedMaps.h" +#include "Pokemon_GateTiles.h" +#include "Pokemon_LegPlanner.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; +constexpr int ACTION_PRESS_SWITCH = 1001; + +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; +}; + + +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); + } + +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 bool now_on = pressed.toggle ? !state.gates.switch_on(pressed.id) : true; + if (now_on){ + step.next.gates.switches_on.insert(pressed.id); + }else{ + step.next.gates.switches_on.erase(pressed.id); + } + 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; +}; + + +// The cheapest legs from `start` with the gates as `gates` to a state of the +// game where `at_goal` holds (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 typename Inner::State& start, const GateState& gates, std::optional start_facing, + const std::function& at_goal, + std::optional goal_facing, + const LegCosts& costs = LegCosts() +){ + using State = GatedState; + const GatedModel model(inner, world, rules); + return plan_legs( + model, State{start, gates}, start_facing, + std::function([&](const State& state){ + return at_goal(state.inner); + }), + goal_facing, costs + ); +} + +// What a leg did to the gates: the gate it opened, the switch it flipped. +template +GateChange gate_change_of(const Leg>& leg){ + return gate_change_between(leg.start.gates, leg.end.gates); +} + +// 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){ + return legs.empty() ? before : legs.back().end.gates; +} + + + +} // 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..91ecdae4f4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.cpp @@ -0,0 +1,499 @@ +/* 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, from, gates, std::nullopt, + std::function([to](const MapPlace& place){ return place == to; }), + std::nullopt + ); +} + +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 stray = R"({"d": {"tiles": [[0, 0]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "F", "bogus": 1}})"; + if (parse_error(rows, stray, "{}").empty()){ + return "An unknown gate field 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 6fde755d24..c47971e71f 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp @@ -36,6 +36,7 @@ constexpr std::pair GLYPHS[] = { {'2', TileKind::CLOSED_SOUTH}, {'4', TileKind::CLOSED_WEST}, {'6', TileKind::CLOSED_EAST}, + {'G', TileKind::GATE}, }; constexpr std::pair WARP_ENTRIES[] = { @@ -361,6 +362,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){ @@ -480,6 +482,126 @@ 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; +} + +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); + 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)){ @@ -520,6 +642,42 @@ 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); + } + } +} + } // namespace @@ -542,10 +700,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..47a4eab708 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. @@ -76,6 +86,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..9c7ac2ed15 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. @@ -85,6 +88,49 @@ struct MapConnection{ int offset = 0; }; +// 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. +struct MapSwitch{ + std::string id; + std::string flag; + bool toggle = true; + std::vector floors; + std::vector statues; +}; + // A tile measured on the console that differs from the decompilation's. struct MapPatch{ int x = 0; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h index 63ebf79735..d795966527 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h @@ -40,6 +40,10 @@ enum class TileKind : uint8_t{ CLOSED_SOUTH, // '2' not entered from it, nor left through it (the CLOSED_WEST, // '4' number pad's arrows) CLOSED_EAST, // '6' + 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/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 1dee3d03ee..550247cb76 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1472,6 +1472,13 @@ 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_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 @@ -1503,6 +1510,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 @@ -1656,6 +1664,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 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" From ac601a8af0ed03f2f52c87b14f62827144b0cfe1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:54:25 -0800 Subject: [PATCH 02/15] Gates: split MapGates and GatedTypes headers, document, bundle planner start/goal Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/Pokemon_StoryStepJson.h | 2 + .../Pokemon/Navigation/Pokemon_GateState.h | 2 + .../Pokemon/Navigation/Pokemon_GatedPlanner.h | 78 ++++++++++--------- .../Pokemon/Navigation/Pokemon_GatedTypes.h | 49 ++++++++++++ .../Navigation/Pokemon_Gates_Tests.cpp | 9 +-- .../Pokemon/Navigation/Pokemon_MapData.h | 1 + .../Pokemon/Navigation/Pokemon_MapFeatures.h | 43 ---------- .../Pokemon/Navigation/Pokemon_MapGates.h | 70 +++++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 9 files changed, 170 insertions(+), 86 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedTypes.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h index 83680b7701..5bc64ab097 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -40,11 +40,13 @@ DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source) // (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); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h index 8b4ec23a42..b8d007d668 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h @@ -27,6 +27,7 @@ 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; @@ -39,6 +40,7 @@ struct GateState{ }; // 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. diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h index d04be50145..fde399180f 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h @@ -38,37 +38,14 @@ #include #include "Pokemon_ConnectedMaps.h" #include "Pokemon_GateTiles.h" +#include "Pokemon_GatedTypes.h" #include "Pokemon_LegPlanner.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; -constexpr int ACTION_PRESS_SWITCH = 1001; - -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; -}; - - +// The game's step model, wrapped: see the top of this file. template class GatedModel{ public: @@ -157,35 +134,64 @@ class GatedModel{ }; -// The cheapest legs from `start` with the gates as `gates` to a state of the -// game where `at_goal` holds (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. +// 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 typename Inner::State& start, const GateState& gates, std::optional start_facing, - const std::function& at_goal, - std::optional goal_facing, + 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, gates}, start_facing, + model, State{start.state, start.gates}, start.facing, std::function([&](const State& state){ - return at_goal(state.inner); + return goal.at_goal(state.inner); }), - goal_facing, costs + goal.facing, costs ); } -// What a leg did to the gates: the gate it opened, the switch it flipped. template GateChange gate_change_of(const Leg>& leg){ return gate_change_between(leg.start.gates, leg.end.gates); } -// 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){ return legs.empty() ? before : legs.back().end.gates; 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 index 91ecdae4f4..46f062f7f6 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Gates_Tests.cpp @@ -106,9 +106,8 @@ std::optional plan( GateRules rules; rules.card_key_held = card_key_held; return plan_gated_legs( - GateGame(), world(), rules, from, gates, std::nullopt, - std::function([to](const MapPlace& place){ return place == to; }), - std::nullopt + GateGame(), world(), rules, GatedStart{from, gates}, + GatedGoal{std::function([to](const MapPlace& place){ return place == to; })} ); } @@ -218,10 +217,6 @@ UnitTestResult test_gate_errors(){ if (parse_error(rows, unknown_switch, "{}").empty()){ return "A gate on an unlisted switch was accepted."; } - const std::string stray = R"({"d": {"tiles": [[0, 0]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "F", "bogus": 1}})"; - if (parse_error(rows, stray, "{}").empty()){ - return "An unknown gate field 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."; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h index 47a4eab708..35d485e577 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h @@ -57,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{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h index 9c7ac2ed15..fd44902707 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h @@ -88,49 +88,6 @@ struct MapConnection{ int offset = 0; }; -// 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. -struct MapSwitch{ - std::string id; - std::string flag; - bool toggle = true; - std::vector floors; - std::vector statues; -}; - // A tile measured on the console that differs from the decompilation's. struct MapPatch{ int x = 0; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h new file mode 100644 index 0000000000..8c2ef63083 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h @@ -0,0 +1,70 @@ +/* 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. +struct MapSwitch{ + std::string id; + std::string flag; + bool toggle = true; + std::vector floors; + std::vector statues; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 550247cb76..2401804a64 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1473,6 +1473,7 @@ file(GLOB LIBRARY_SOURCES 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 @@ -1485,6 +1486,7 @@ file(GLOB LIBRARY_SOURCES 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 From d11b3606c68d9a66fe3100b3e7d2503a386a6e82 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:59:36 -0800 Subject: [PATCH 03/15] Merge nav/gates: keep the FRLG stack's PokemonFRLG_Navigation and EggRng --- .../PokemonFRLG/PokemonFRLG_Navigation.cpp | 224 ++++++++++++------ .../PokemonFRLG/PokemonFRLG_Navigation.h | 52 ++++ .../RngManipulation/PokemonFRLG_EggRng.cpp | 2 +- 3 files changed, 204 insertions(+), 74 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp index a7ddecc44a..970080ca26 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp @@ -573,7 +573,10 @@ void flee_battle(ConsoleHandle& console, ProControllerContext& context){ } } -bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, bool stop_on_move_learn, bool prevent_evolution){ +WildBattleExitResult exit_wild_battle( + Logger& logger, WildBattleExitActions& actions, + bool stop_on_move_learn, bool prevent_evolution +){ // For move learning, there are two dialog selection boxes in a row // we need to decline the first one and accept the second one, so mashing B won't work // The first one will occur after an Advance Battle Dialog @@ -585,113 +588,70 @@ bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, boo bool evolved = false; while (true){ if (errors > 5 || loops > 5){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, - "exit_wild_battle(): Failed to exit battle.", - console - ); + return WildBattleExitResult::Failed; } - BlackScreenWatcher battle_exited(COLOR_RED); - AdvanceBattleDialogWatcher advance_dialog(COLOR_RED); - BattleLearnDialogWatcher move_learn_select(COLOR_RED); + WildBattleExitEvent event = first_attempt + ? actions.mash_b_until_battle_exited() + : actions.press_until_dialog(rejected_first_box ? BUTTON_A : BUTTON_B); - context.wait_for_all_requests(); - WallClock deadline = current_time() + 30s; - int ret; - if (first_attempt){ - ret = run_until( - console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 20000ms); - }, - { battle_exited } - ); - }else{ - ret = run_until( - console, context, - [deadline, rejected_first_box](ProControllerContext& context){ - pbf_wait(context, 1000ms); // give the watchers a chance to detect something - while (current_time() < deadline){ - pbf_press_button(context, rejected_first_box ? BUTTON_A : BUTTON_B, 200ms, 1800ms); - // Presses are queued, so without this the loop queues a minute of them - // before the deadline and keeps pressing long after it. - context.wait_for_all_requests(); - } - }, - { battle_exited, advance_dialog, move_learn_select } - ); - } - - BattleDialogWatcher evolution_started(COLOR_RED); - int ret2; - - switch (ret){ - case 0: + switch (event){ + case WildBattleExitEvent::BattleExited: // check for the evolution screen - context.wait_for_all_requests(); - ret2 = run_until( - console, context, - [](ProControllerContext& context){ - pbf_wait(context, 2000ms); - }, - { evolution_started } - ); - - if (ret2 == 0){ - console.log("Evolution detected."); + if (actions.evolution_started()){ + logger.log("Evolution detected."); evolved = true; if (!prevent_evolution){ // make sure B isn't pressed too soon, which would cancel the evolution - pbf_wait(context, 20000ms); + actions.wait_for_evolution(); } rejected_first_box = false; continue; // press B as in other cases, and handle any move learning loops that might come up } - console.log("Battle exited."); - return move_learned; - case 1: - console.log("Battle Advance arrow detected."); - pbf_press_button(context, BUTTON_B, 200ms, 800ms); + logger.log("Battle exited."); + return move_learned ? WildBattleExitResult::ExitedAfterMoveLearn : WildBattleExitResult::Exited; + case WildBattleExitEvent::AdvanceDialog: + logger.log("Battle Advance arrow detected."); + actions.advance_dialog(); rejected_first_box = false; continue; - case 2: + case WildBattleExitEvent::MoveLearnPrompt: if (stop_on_move_learn){ - console.log("Move learn detected."); - return true; + logger.log("Move learn detected."); + return WildBattleExitResult::StoppedOnMoveLearn; }else if (rejected_first_box){ loops++; - console.log("Declined to learn new move."); - pbf_press_button(context, BUTTON_A, 200ms, 0ms); + logger.log("Declined to learn new move."); + actions.answer_move_prompt(BUTTON_A); }else{ - pbf_press_button(context, BUTTON_B, 200ms, 0ms); + actions.answer_move_prompt(BUTTON_B); rejected_first_box = true; move_learned = true; } continue; - default: + case WildBattleExitEvent::None: // An evolution ends on the overworld without another black screen, so nothing above // can see that it is over. Check for the overworld now, instead of pressing B for // another 30 seconds first. if (evolved){ evolved = false; first_attempt = false; - if (in_overworld(console, context)){ - console.log("Battle exited."); - return move_learned; + if (actions.return_to_overworld()){ + logger.log("Battle exited."); + return move_learned ? WildBattleExitResult::ExitedAfterMoveLearn : WildBattleExitResult::Exited; } continue; } if (first_attempt){ - console.log("Loop detected."); + logger.log("Loop detected."); first_attempt = false; continue; } - console.log("Failed to detect expected battle dialogs."); + logger.log("Failed to detect expected battle dialogs."); errors++; - if (in_overworld(console, context)){ - console.log("Battle exited."); - return move_learned; + if (actions.return_to_overworld()){ + logger.log("Battle exited."); + return move_learned ? WildBattleExitResult::ExitedAfterMoveLearn : WildBattleExitResult::Exited; } rejected_first_box = false; continue; @@ -699,6 +659,124 @@ bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, boo } } +namespace{ + +class ConsoleWildBattleExitActions : public WildBattleExitActions{ +public: + ConsoleWildBattleExitActions(ConsoleHandle& console, ProControllerContext& context) + : m_console(console), m_context(context) + {} + + virtual WildBattleExitEvent mash_b_until_battle_exited() override{ + BlackScreenWatcher battle_exited(COLOR_RED); + m_context.wait_for_all_requests(); + int ret = run_until( + m_console, m_context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 20000ms); + }, + { battle_exited } + ); + return ret == 0 ? WildBattleExitEvent::BattleExited : WildBattleExitEvent::None; + } + virtual WildBattleExitEvent press_until_dialog(Button button) override{ + BlackScreenWatcher battle_exited(COLOR_RED); + AdvanceBattleDialogWatcher advance_dialog(COLOR_RED); + BattleLearnDialogWatcher move_learn_select(COLOR_RED); + m_context.wait_for_all_requests(); + WallClock deadline = current_time() + 30s; + int ret = run_until( + m_console, m_context, + [deadline, button](ProControllerContext& context){ + pbf_wait(context, 1000ms); // give the watchers a chance to detect something + while (current_time() < deadline){ + pbf_press_button(context, button, 200ms, 1800ms); + // Presses are queued, so without this the loop queues a minute of them + // before the deadline and keeps pressing long after it. + context.wait_for_all_requests(); + } + }, + { battle_exited, advance_dialog, move_learn_select } + ); + switch (ret){ + case 0: + return WildBattleExitEvent::BattleExited; + case 1: + return WildBattleExitEvent::AdvanceDialog; + case 2: + return WildBattleExitEvent::MoveLearnPrompt; + default: + return WildBattleExitEvent::None; + } + } + virtual bool evolution_started() override{ + BattleDialogWatcher evolution_started(COLOR_RED); + m_context.wait_for_all_requests(); + int ret = run_until( + m_console, m_context, + [](ProControllerContext& context){ + pbf_wait(context, 2000ms); + }, + { evolution_started } + ); + return ret == 0; + } + virtual void wait_for_evolution() override{ + pbf_wait(m_context, 20000ms); + } + virtual void advance_dialog() override{ + pbf_press_button(m_context, BUTTON_B, 200ms, 800ms); + } + virtual void answer_move_prompt(Button button) override{ + pbf_press_button(m_context, button, 200ms, 0ms); + } + virtual bool return_to_overworld() override{ + StartMenuWatcher start_menu_open(COLOR_RED); + // attempt to exit any screen that might be open (party, bag, etc) + pbf_mash_button(m_context, BUTTON_B, 500ms); + // overworld detection: look for the start menu + m_context.wait_for_all_requests(); + int ret = run_until( + m_console, m_context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_PLUS, 200ms, 800ms); + pbf_press_button(context, BUTTON_PLUS, 200ms, 800ms); + pbf_press_button(context, BUTTON_PLUS, 200ms, 800ms); + }, + { start_menu_open } + ); + if (ret == 0){ + pbf_mash_button(m_context, BUTTON_B, 500ms); + } + m_context.wait_for_all_requests(); + return ret == 0; + } + +private: + ConsoleHandle& m_console; + ProControllerContext& m_context; +}; + +} + +bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, bool stop_on_move_learn, bool prevent_evolution){ + ConsoleWildBattleExitActions actions(console, context); + switch (exit_wild_battle(console.logger(), actions, stop_on_move_learn, prevent_evolution)){ + case WildBattleExitResult::Exited: + return false; + case WildBattleExitResult::ExitedAfterMoveLearn: + case WildBattleExitResult::StoppedOnMoveLearn: + return true; + case WildBattleExitResult::Failed: + break; + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "exit_wild_battle(): Failed to exit battle.", + console + ); +} + void open_party_menu_from_overworld(ConsoleHandle& console, ProControllerContext& context, StartMenuContext menu_context){ uint16_t errors = 0; bool start_menu_is_open = false; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h index b896431aa1..e802a4be6d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h @@ -9,6 +9,7 @@ #ifndef PokemonAutomation_PokemonFRLG_Navigation_H #define PokemonAutomation_PokemonFRLG_Navigation_H +#include "Common/Cpp/Logging/AbstractLogger.h" #include "CommonFramework/Language.h" #include "CommonFramework/Tools/VideoStream.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" @@ -74,6 +75,57 @@ void flee_battle(ConsoleHandle& console, ProControllerContext& context); // Returns true if a move was learned (even if it was rejected) and false otherwise. bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, bool stop_on_move_learn, bool prevent_evolution); +// What a step of exit_wild_battle() saw. +enum class WildBattleExitEvent{ + BattleExited, // The screen went black as the battle ended. + AdvanceDialog, // A battle dialog is waiting for a button. + MoveLearnPrompt, // A Pokemon is trying to learn a move. + None, // Nothing was seen before the step timed out. +}; + +// The game steps that exit_wild_battle() takes. They are injected so that its decisions (what to +// press after each dialog, when to give up) run in tests without a Switch. +class WildBattleExitActions{ +public: + virtual ~WildBattleExitActions() = default; + + // Mash B for up to 20 seconds, until the battle ends. + virtual WildBattleExitEvent mash_b_until_battle_exited() = 0; + + // Press `button` every 2 seconds for up to 30 seconds, until the battle ends, a battle dialog + // waits for a button, or a move-learn prompt opens. + virtual WildBattleExitEvent press_until_dialog(Button button) = 0; + + // Right after the battle ends, check for a dialog, which means a Pokemon is evolving. + virtual bool evolution_started() = 0; + + // Wait for an evolution to finish without pressing B, which would cancel it. + virtual void wait_for_evolution() = 0; + + // Close a battle dialog that is waiting for a button. + virtual void advance_dialog() = 0; + + // Answer a move-learn prompt with `button`. + virtual void answer_move_prompt(Button button) = 0; + + // Close any open screen, then check for the overworld by opening the start menu. Returns true + // if it opened; it is closed again. + virtual bool return_to_overworld() = 0; +}; + +enum class WildBattleExitResult{ + Exited, + ExitedAfterMoveLearn, // A move-learn prompt came up and the move was declined. + StoppedOnMoveLearn, // Stopped at a move-learn prompt, as stop_on_move_learn asks. + Failed, +}; + +// The decisions of exit_wild_battle(), taking its game steps from `actions`. +WildBattleExitResult exit_wild_battle( + Logger& logger, WildBattleExitActions& actions, + bool stop_on_move_learn, bool prevent_evolution +); + // Starting from the start menu, a sub-screen of the start menu, or the overworld, navigate to the party screen enum class StartMenuContext { STANDARD, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp index a05d693683..483b5fd0d9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp @@ -188,7 +188,7 @@ EggRng::EggRng() , HELD_ADVANCES( "Held Advances:
The total number of RNG advances for your held target.", LockMode::LOCK_WHILE_RUNNING, - 10000, 500, 1000000000 // default, min + 10000, 700, 1000000000 // default, min ) , m_pickup_settings("Pickup Frame Settings") , PICKUP_SEED( From 5f81d2a229a9d028a412b1be58a76fb390038b54 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 16:12:11 -0800 Subject: [PATCH 04/15] FRLG: gate-aware step model, OPEN_GATE/PRESS_SWITCH route steps in the executor and sim plan_overworld_route_gated() wraps FRLG's step rules in the shared gated planner (a closed gate is a wall; a plan may open a card-key gate with the Card Key or press a statue). Route steps OPEN_GATE and PRESS_SWITCH carry their gate change; the console walker faces the gate/statue, A (Yes), B through the text, and the run reads its maps through the gates each one changes. The sim holds the gate state (SimField::OPEN_GATE / PRESS_SWITCH), so the leg-to-command sequence is tested with the fake console. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/Navigation/Pokemon_RouteLog.cpp | 4 + .../Navigation/Pokemon_RouteLogTypes.h | 4 + .../PokemonFRLG_OverworldGatedRoute.h | 56 ++++ .../PokemonFRLG_OverworldGates_Tests.cpp | 271 ++++++++++++++++++ .../Overworld/PokemonFRLG_OverworldMap.cpp | 2 +- .../PokemonFRLG_OverworldRecovery.cpp | 42 ++- .../Overworld/PokemonFRLG_OverworldRecovery.h | 5 + .../PokemonFRLG_OverworldRecoveryWalk.cpp | 10 +- .../Overworld/PokemonFRLG_OverworldRoute.cpp | 173 ++++++++++- .../Overworld/PokemonFRLG_OverworldRoute.h | 5 +- .../PokemonFRLG_OverworldRouteSteps.h | 10 + .../PokemonFRLG_OverworldRouteStrings.cpp | 6 + .../Overworld/PokemonFRLG_OverworldSim.cpp | 11 +- .../Overworld/PokemonFRLG_OverworldSim.h | 18 ++ .../PokemonFRLG_OverworldSimField.cpp | 69 +++++ .../Overworld/PokemonFRLG_OverworldSimField.h | 6 + .../Overworld/PokemonFRLG_OverworldSimState.h | 6 + .../PokemonFRLG_OverworldSim_Tests.cpp | 1 + .../Overworld/PokemonFRLG_OverworldWalk.cpp | 68 ++++- .../Overworld/PokemonFRLG_OverworldWalk.h | 9 + SerialPrograms/cmake/SourceFiles.cmake | 2 + 21 files changed, 766 insertions(+), 12 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp 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..5c60571ebe --- /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.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 8a623e2745..13783ea074 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_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 47639d1887..e9dc390e8d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -245,6 +245,14 @@ StepWalk walk_step( 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 +332,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..26a172bbc3 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; +} + +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 +){ + 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; + 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)); + } + 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. @@ -595,8 +743,16 @@ std::vector leg_tiles( 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,8 +766,15 @@ MapPosition follow_overworld_route( if (step.action == RouteAction::FACE){ continue; } + 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); + } + continue; + } for (int c = 0; c < step.tiles; c++){ - const std::optional transition = press(maps, player, step.direction); + const std::optional transition = press(gated ? resolved : maps, player, step.direction); if (!transition || transition->action != step.action){ throw InternalProgramError( nullptr, PA_CURRENT_FUNCTION, 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 96d07b3d6f..38cfa12a06 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -15,6 +15,7 @@ #include "PokemonFRLG_OverworldWalk.h" #include "PokemonFRLG_OverworldBike.h" #include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldGatedRoute.h" #include "PokemonFRLG_OverworldSim.h" namespace PokemonAutomation{ @@ -147,6 +148,11 @@ 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(); + if (has_gates(m_maps)){ + m_source_maps = m_maps; + } + m_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,6 +843,9 @@ 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); } @@ -901,7 +910,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 2a4c86864d..241bb03f2d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -67,6 +67,10 @@ class OverworldSim{ const SimState& state() const{ return m_state; } + // The gates open and the switches on now (SimScript::gates, then what + // the player opened and pressed). + const Pokemon::GateState& gates() const{ return m_gates; } + // Whether the walker's screen check reads its last step tap as a // step: one that moved the player from `before`, but for // SimScript::unseen_step_taps, or a turn tap since `turn_taps_before` @@ -170,6 +174,12 @@ class OverworldSim{ bool choose_lift_floor(size_t floor); bool push_poster_switch(); 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 m_gates. + 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 +206,9 @@ 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; + Pokemon::GateState m_gates; SimScript m_script; int m_map = 0; PlayerState m_player; @@ -432,6 +445,9 @@ 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); 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 +491,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..e5625e48de 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp @@ -10,6 +10,7 @@ #include #include +#include "Pokemon/Navigation/Pokemon_GateTiles.h" #include "PokemonFRLG_CodedRooms.h" #include "PokemonFRLG_FlyMap.h" #include "PokemonFRLG_OverworldSim.h" @@ -44,6 +45,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; } @@ -137,6 +142,59 @@ 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. + 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_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_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_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_gates.switch_on(pressed->id) : true; + if (now_on){ + m_gates.switches_on.insert(pressed->id); + }else{ + m_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 +220,17 @@ bool OverworldSim::fly_to_town(size_t town){ return true; } +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..f2d8a29fe6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h @@ -45,6 +45,12 @@ enum class SimField{ // 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 e985f46736..691bea014d 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, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index b47e21f6d1..56e053d61f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -1038,6 +1038,7 @@ 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); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp index 1c37503a94..6c84d427bb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -44,6 +44,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 +769,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 @@ -899,8 +957,16 @@ 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: + 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; } - 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_OverworldWalk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h index 93b700d365..9dfefa8fee 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h @@ -110,6 +110,15 @@ void clear_open_message( // Facing `direction` (turning first unless `facing_water`), starts Surf. void start_surf(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_water); +// 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 diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 4d3b9b948f..a2d88cf33a 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2003,6 +2003,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 From d52801689c5330ab9420e4996873aca1cfbb5318 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 16:19:36 -0800 Subject: [PATCH 05/15] FRLG story: gate state and run flags carried through steps; walks plan with gates RunState carries GateState; steps apply gates_after and flags_after on success; checkpoints give start_gates and start_flags; walk_route plans with the gated planner when the maps have gates, and the Card Key flag allows card-key gates. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/Pokemon_StoryStepJson.cpp | 10 +++- .../Data/Pokemon_StoryStepJson_Tests.cpp | 9 ++++ .../Pokemon/AutoStory/Pokemon_StoryPose.h | 4 ++ .../AutoStory/Pokemon_StoryStepExecutor.cpp | 33 +++++++++--- .../Pokemon_StoryStepExecutor_Tests.cpp | 54 +++++++++++++++++++ .../AutoStory/Types/Pokemon_StoryCheckpoint.h | 4 ++ .../AutoStory/Types/Pokemon_StoryStep.h | 4 ++ .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 19 +++++-- .../PokemonFRLG_AutoStoryPacedRoute.h | 4 +- 9 files changed, 127 insertions(+), 14 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp index 9b9f64665d..c54b7f4141 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -369,7 +369,7 @@ JsonValue write_gate_state(const 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", "gates_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()){ @@ -392,11 +392,14 @@ StoryStep read_story_step(const JsonValue& value, std::string_view source, std:: 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", "start_gates", "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()){ @@ -409,6 +412,9 @@ StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view s 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_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 9eb48cba9b..7fcedf7887 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -144,6 +144,15 @@ const WireCase CASES[] = { {.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); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h index b9c0eb53db..dda997c988 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h @@ -17,6 +17,7 @@ #include #include #include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon_StoryLog.h" namespace PokemonAutomation{ @@ -70,6 +71,9 @@ 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; }; 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 1f76989b29..cc3bf66ce3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -45,6 +45,10 @@ struct StoryCheckpoint{ // 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: diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h index 8b004bbf8c..d561b0add0 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -56,6 +56,10 @@ struct StoryStep{ // (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/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 0256eae030..ae1561e3e1 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" @@ -136,6 +137,10 @@ OverworldInterruptSet walk_interrupts(StoryEnv& env, const StoryStep& step){ // `maps`: where the route is planned; the story's but where a step knows // better (the trash cans' walks, past trainers who have walked up). +Pokemon::GateRules gate_rules(const RunState& state){ + return Pokemon::GateRules{.card_key_held = state.flags.contains("card_key_held")}; +} + Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step, const std::vector& maps = story_maps()){ const std::vector tiles = Pokemon::tiles_of(state.pose); const bool known = state.pose.certainty == Pokemon::PoseCertainty::TILE @@ -157,7 +162,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, gate_rules(state)); if (!route){ return Pokemon::outcome_failed("no_route", Pokemon::to_string(state.pose) + " to " + to_string(goal.position)); } @@ -168,8 +173,10 @@ Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step, const // 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)}; + RoutePlanning planning{.maps = &maps, .costs = story_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; + planning.gates = state.gates; 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})); @@ -436,7 +443,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)){ @@ -450,7 +458,10 @@ 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); + // Maps without gates plan as ever (with the open legs' stop risk). + std::optional> route = has_gates(maps) + ? plan_overworld_route_gated(maps, from, goal, gates, rules, story_route_costs(), facing) + : plan_overworld_route(maps, from, goal, story_route_costs(), facing); if (route){ route->insert(route->begin(), holds->begin(), holds->end()); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h index 46590fe54b..4fe75de077 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 = {}, const Pokemon::GateRules& rules = {} ); From 521cfcf8815c7d473fb0ed429d5ee0d439439e76 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 16:28:01 -0800 Subject: [PATCH 06/15] FRLG gates: code-health splits (walk hold helpers, gates in SimState, WalkGates header) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_StoryPose.h | 7 ++ .../PokemonFRLG_OverworldGates_Tests.cpp | 2 +- .../PokemonFRLG_OverworldRecoveryWalk.cpp | 78 +++++++++++-------- .../Overworld/PokemonFRLG_OverworldRoute.cpp | 78 ++++++++++++------- .../Overworld/PokemonFRLG_OverworldSim.cpp | 17 +--- .../Overworld/PokemonFRLG_OverworldSim.h | 9 +-- .../PokemonFRLG_OverworldSimField.cpp | 31 ++++++-- .../Overworld/PokemonFRLG_OverworldSimState.h | 3 + .../PokemonFRLG_OverworldSim_Tests.cpp | 1 - .../Overworld/PokemonFRLG_OverworldWalk.cpp | 41 ++++++---- .../Overworld/PokemonFRLG_OverworldWalk.h | 9 --- .../PokemonFRLG_OverworldWalkGates.h | 38 +++++++++ .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 17 +--- .../PokemonFRLG_AutoStoryPacedRoute.h | 2 +- SerialPrograms/cmake/SourceFiles.cmake | 1 + 15 files changed, 205 insertions(+), 129 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkGates.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h index dda997c988..d3081a8a8c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h @@ -17,6 +17,7 @@ #include #include #include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon/Navigation/Pokemon_GatedTypes.h" #include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon_StoryLog.h" @@ -76,6 +77,12 @@ struct RunState{ 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/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp index 5c60571ebe..2d0770d661 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp @@ -181,7 +181,7 @@ SimRun walk_in_sim(const std::vector& maps, const MapPosition& start, c const RoutePlanning planning{.maps = &maps, .costs = default_route_costs(), .start = start, .label = "Sim"}; SimRun run; run.failure = walker.run(route, planning); - run.gates = sim.gates(); + 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()); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index e9dc390e8d..d2c4e322db 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,48 +198,57 @@ 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; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp index 26a172bbc3..06e4227675 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp @@ -598,6 +598,26 @@ std::vector resolve_maps(const std::vector& maps, const Pokemo 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, @@ -607,6 +627,9 @@ std::optional> plan_overworld_route_gated( 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){ @@ -638,17 +661,7 @@ std::optional> plan_overworld_route_gated( return std::nullopt; } - 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)); - } + std::vector route = gated_route_steps(gate_maps, *legs); tap_from_known_tile(route); return route; } @@ -740,6 +753,31 @@ 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, @@ -773,23 +811,7 @@ MapPosition follow_overworld_route( } continue; } - for (int c = 0; c < step.tiles; c++){ - const std::optional transition = press(gated ? resolved : 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) - ); - } + 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_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 38cfa12a06..2881dff960 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -15,7 +15,6 @@ #include "PokemonFRLG_OverworldWalk.h" #include "PokemonFRLG_OverworldBike.h" #include "PokemonFRLG_OverworldMaps.h" -#include "PokemonFRLG_OverworldGatedRoute.h" #include "PokemonFRLG_OverworldSim.h" namespace PokemonAutomation{ @@ -148,10 +147,7 @@ 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(); - if (has_gates(m_maps)){ - m_source_maps = m_maps; - } - m_gates = m_script.gates; + m_state.gates = m_script.gates; read_gates(); m_player = PlayerState{start.point, elevation_at(map(), start.point), false}; m_state.facing = facing; @@ -851,16 +847,7 @@ std::optional OverworldSimWalker::walk_step(const RouteStep& step, } 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); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 241bb03f2d..5e419e1ed3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -67,10 +67,6 @@ class OverworldSim{ const SimState& state() const{ return m_state; } - // The gates open and the switches on now (SimScript::gates, then what - // the player opened and pressed). - const Pokemon::GateState& gates() const{ return m_gates; } - // Whether the walker's screen check reads its last step tap as a // step: one that moved the player from `before`, but for // SimScript::unseen_step_taps, or a turn tap since `turn_taps_before` @@ -178,7 +174,7 @@ class OverworldSim{ // if there is none or the Card Key is missing. bool open_gate(); bool press_switch(); - // Reads each map's gate tiles through m_gates. + // 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. @@ -208,7 +204,6 @@ class OverworldSim{ std::vector m_maps; // The maps as loaded, with the gates closed or open as the map says. std::vector m_source_maps; - Pokemon::GateState m_gates; SimScript m_script; int m_map = 0; PlayerState m_player; @@ -448,6 +443,8 @@ class OverworldSimWalker{ // 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 diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp index e5625e48de..afbe8ab05c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp @@ -13,8 +13,10 @@ #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" @@ -145,9 +147,12 @@ bool OverworldSim::start_surf(){ 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_gates); + m_maps[c].tiles = Pokemon::resolve_tiles(m_source_maps[c], m_state.gates); } } } @@ -158,7 +163,7 @@ bool OverworldSim::open_gate(){ 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_gates); + 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 {}{}.", @@ -168,7 +173,7 @@ bool OverworldSim::open_gate(){ } // "Opened the door with the CARD KEY!", then the door. advance_to(m_now + m_script.timing.message); - m_gates.opened.insert(Pokemon::gate_key(source.name, gate->id)); + 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; @@ -184,11 +189,11 @@ bool OverworldSim::press_switch(){ } // The prompt, YES, and the text after it. advance_to(m_now + m_script.timing.message); - const bool now_on = pressed->toggle ? !m_gates.switch_on(pressed->id) : true; + const bool now_on = pressed->toggle ? !m_state.gates.switch_on(pressed->id) : true; if (now_on){ - m_gates.switches_on.insert(pressed->id); + m_state.gates.switches_on.insert(pressed->id); }else{ - m_gates.switches_on.erase(pressed->id); + m_state.gates.switches_on.erase(pressed->id); } read_gates(); note(std::format("switch {} is {}.", pressed->id, now_on ? "on" : "off")); @@ -220,6 +225,20 @@ 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); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h index 691bea014d..a848c4988e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h @@ -136,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 56e053d61f..3dcbaaa052 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -1044,7 +1044,6 @@ void add_tests_OverworldSim(UnitTestDatabase& 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 6c84d427bb..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" @@ -916,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 @@ -936,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); @@ -958,12 +968,13 @@ void walk_overworld_route( 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); + 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 && step.action != RouteAction::OPEN_GATE && step.action != RouteAction::PRESS_SWITCH){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h index 9dfefa8fee..93b700d365 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h @@ -110,15 +110,6 @@ void clear_open_message( // Facing `direction` (turning first unless `facing_water`), starts Surf. void start_surf(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_water); -// 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 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/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index ae1561e3e1..ebbd911441 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -137,10 +137,6 @@ OverworldInterruptSet walk_interrupts(StoryEnv& env, const StoryStep& step){ // `maps`: where the route is planned; the story's but where a step knows // better (the trash cans' walks, past trainers who have walked up). -Pokemon::GateRules gate_rules(const RunState& state){ - return Pokemon::GateRules{.card_key_held = state.flags.contains("card_key_held")}; -} - Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step, const std::vector& maps = story_maps()){ const std::vector tiles = Pokemon::tiles_of(state.pose); const bool known = state.pose.certainty == Pokemon::PoseCertainty::TILE @@ -162,7 +158,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, state.gates, gate_rules(state)); + 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)); } @@ -171,10 +167,8 @@ 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. - RoutePlanning planning{.maps = &maps, .costs = story_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; - planning.gates = state.gates; + // 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); @@ -458,10 +452,7 @@ std::optional> plan_story_route( if (!holds->empty()){ facing = holds->back().facing_after; } - // Maps without gates plan as ever (with the open legs' stop risk). - std::optional> route = has_gates(maps) - ? plan_overworld_route_gated(maps, from, goal, gates, rules, story_route_costs(), facing) - : 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()); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h index 4fe75de077..6fac86baf3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h @@ -47,7 +47,7 @@ const RouteCosts& story_route_costs(); std::optional> plan_story_route( const std::vector& maps, const Pokemon::Pose& pose, std::optional facing, const RouteGoal& goal, - const Pokemon::GateState& gates = {}, const Pokemon::GateRules& rules = {} + const Pokemon::GateState& gates = Pokemon::GateState(), const Pokemon::GateRules& rules = Pokemon::GateRules() ); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a2d88cf33a..3b38604e26 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2052,6 +2052,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 From 8f4ad4e4152b88a71f61ad29a7a40632f9c5d497 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 19:10:45 -0800 Subject: [PATCH 07/15] FRLG AutoStory 19.01: Viridian Mart, then the Route 22 rival by PokeGuy's C2 policy Adds the Route 22 north entrance, Route 23, Victory Road 1F-3F and Indigo Plateau maps to the loaded set, the 19.01 plan (Potions to 4, the lead at Lv49, the trigger step at (33, 5), the rival with setup goals and foe_threats), its golden and a sim test of the walk to the trigger. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldMaps.cpp | 9 ++ .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../PokemonFRLG_AutoStoryPlanGolden19.h | 43 ++++++ .../PokemonFRLG_AutoStoryRows19_Tests.h | 27 ++++ .../PokemonFRLG_AutoStoryRunPlan_Tests.cpp | 8 +- .../AutoStory/PokemonFRLG_AutoStoryTable.cpp | 2 +- ...PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp | 135 ++++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 6 +- .../AutoStory/StoryData/frlg-19.01.plan.json | 106 ++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 3 + 10 files changed, 334 insertions(+), 7 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.01.plan.json diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp index 914232693b..b53d20f46f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp @@ -175,6 +175,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/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 15b95fdbbf..918c71f98f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -60,6 +60,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" @@ -345,6 +346,7 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& database){ add_tests_AutoStorySilph(database); add_tests_AutoStoryMansion(database); add_tests_AutoStoryViridian(database); + add_tests_AutoStoryVictoryRoad(database); } void add_tests(UnitTestDatabase& database){ 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..0bc8da17f9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h @@ -0,0 +1,43 @@ +/* FRLG AutoStory Plan Golden, Segment 19 + * + * From: https://github.com/PokemonAutomation/ + * + * The golden's lines for 19.01 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.01 and after. +inline constexpr std::string_view FRLG_PLAN_GOLDEN_19[] = { + "19.01 viridian_mart_clerk from ViridianCity_PokemonCenter_1F (7, 4) facing north to ViridianCity_Mart (4, 3) facing west", + "19.01 walk south 5 (warp) -> ViridianCity (26, 27) [walk only]", + "19.01 walk south 2 -> ViridianCity (26, 29)", + "19.01 walk east 10 -> ViridianCity (36, 29)", + "19.01 walk north 10 (warp) -> ViridianCity_Mart (4, 7)", + "19.01 walk north 4 -> ViridianCity_Mart (4, 3) [walk only]", + "19.01 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)", +}; + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif 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..64bff583ba --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h @@ -0,0 +1,27 @@ +/* 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.01 and after on the overworld sim (PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp). +void add_tests_AutoStoryVictoryRoad(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 7df7365d23..48ec88f70e 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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04"; +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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01"; 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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04"}, + .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01"}, }, { .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04"}, + .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01"}, }, { .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04"}, + .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01"}, }, { .input = { .name = "Starter RNG first, with both on", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index d9f653efa5..d9cdb2642a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -235,7 +235,7 @@ constexpr std::string_view STORY_ORDER[] = { "06.03", "06.04", "07.01", "07.02", "08.01", "08.02", "08.03", "09.01", "09.02", "09.03", "09.04", "10.01", "10.02", "10.03", "10.04", "10.05", "10.06", "11.01", "11.02", "11.03", "12.01", "12.02", "12.03", "14.03", "14.04", "15.01", "16.01", "17.01", "13.01", "13.02", "13.03", "13.04", "14.01", "14.02", - "17.02", "17.03", "17.04", + "17.02", "17.03", "17.04", "19.01", }; // `checkpoints` in STORY_ORDER's order. Throws ParseException for a 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..68b81f5282 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp @@ -0,0 +1,135 @@ +/* AutoStory Victory Road Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Rows 19.01 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 "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_AutoStoryRooms.h" +#include "PokemonFRLG_AutoStoryRowSim.h" +#include "PokemonFRLG_AutoStoryRows_Tests.h" +#include "PokemonFRLG_AutoStoryRows19_Tests.h" +#include "PokemonFRLG_AutoStoryTable.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`; the steps that are not walks (the +// Mart, the level check, the battle) are the console's. +std::string walk_row_until(OverworldSim& sim, StoryPose& at, const StoryCheckpoint& row, std::string_view until){ + 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; + } + } + return std::format("{}: no step {}.", row.id, until); +} + +// 19.01: 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& row = checkpoint("19.01"); + 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_until(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; +} + +const AutoStoryVictoryRoadCase AUTO_STORY_VICTORY_ROAD_CASES[] = { + { + .input = {.name = "19.01 Viridian to the Route 22 rival's trigger", .body = test_route22_rival_trigger}, + .expectation = {.description = "Route 22 (33, 5), no trainer met"}, + }, +}; + +} // 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 47051ed575..e106476d07 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() != 67 || checkpoints[0].start){ - return "Expected 67 checkpoints, the first from a new game."; + if (checkpoints.size() != 68 || checkpoints[0].start){ + return "Expected 68 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_13), std::end(FRLG_PLAN_GOLDEN_13)); golden.insert(golden.end(), std::begin(FRLG_PLAN_GOLDEN_14), std::end(FRLG_PLAN_GOLDEN_14)); 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]){ 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..e6f6365c4d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.01.plan.json @@ -0,0 +1,106 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "19.01", + "title": "Viridian to Route 22: potions, and the rival at the road's east end", + "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" + }, + { + "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, 30, 22, 63, 33, 0, 0], + [35, 30, 23, 62, 32, 0, 0], + [86, 18, 12, 37, 19, 0, 0], + [67, 26, 17, 54, 28, 0, 0], + [126, 64, 64, 129, 66, 0, 0], + [105, 80, 76, 162, 84, 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 Gen 3 damage on his Blastoise (Lv49, Def 105, Sp. Def 119) from the doc's foe stats, one row per foe: Rhyhorn's Horn Drill fails (Lv45 against Lv49), Venusaur's Razor Leaf and crit can take 153 HP. Then he walks off and the player stays facing west" + } + ] + }, + "execution": { + "menu": "full", + "notes": { + "checkpoint": [ + "Starts where 17.04 ends: Viridian's nurse. 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.04 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/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 25d87480f6..e72f26a13b 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2102,8 +2102,10 @@ 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_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 @@ -2194,6 +2196,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 From 0e1042713a9bf1bd557adf053f236e7d66ea4070 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 19:21:43 -0800 Subject: [PATCH 08/15] FRLG AutoStory 19.02: Route 22's ledge and north gate guard, onto Route 23 The rival's trigger area reaches the gate's side of Route 22 over the ledge row (15..21, 8); the guard at the gate is a trigger at (7, 2), one message with the Boulder Badge. Route 22 gets a save card place (route-22). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 1 + .../PokemonFRLG_AutoStoryPlanGolden19.h | 16 ++++ .../PokemonFRLG_AutoStoryRunPlan_Tests.cpp | 8 +- .../AutoStory/PokemonFRLG_AutoStoryTable.cpp | 2 +- ...PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp | 47 ++++++++++-- .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 8 +- .../AutoStory/StoryData/frlg-19.02.plan.json | 75 +++++++++++++++++++ 7 files changed, 143 insertions(+), 14 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.02.plan.json diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 18bc4398cf..7a46b9802e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -363,6 +363,7 @@ std::string save_card_place(const std::string& map){ {"CeruleanCity", "cerulean-city"}, {"Route24", "route-24"}, {"Route25", "route-25"}, + {"Route22", "route-22"}, {"VermilionCity", "vermilion-city"}, {"Route10", "route-10"}, {"LavenderTown", "lavender-town"}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h index 0bc8da17f9..b95267c340 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h @@ -35,6 +35,22 @@ inline constexpr std::string_view FRLG_PLAN_GOLDEN_19[] = { "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]", }; } // namespace PokemonFRLG 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 48ec88f70e..ef73287d37 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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01"; +const std::string TODAY = "01.01 01.03 01.04 01.05 02.01 02.02 02.03 03.01 03.02 03.03 04.01 04.02 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01 19.02"; 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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01 19.02"}, }, { .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01"}, + .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01 19.02"}, }, { .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01"}, + .expectation = {.expected_ids = "04.03 04.04 04.05 04.06 05.01 05.02 05.03 05.04 05.05 05.06 05.07 05.08 05.09 05.10 06.01 06.02 06.03 06.04 07.01 07.02 08.01 08.02 08.03 09.01 09.02 09.03 10.01 10.02 10.03 10.04 10.05 10.06 11.01 11.02 11.03 12.01 12.02 12.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01 19.02"}, }, { .input = { .name = "Starter RNG first, with both on", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index d9cdb2642a..52d47defdc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -235,7 +235,7 @@ constexpr std::string_view STORY_ORDER[] = { "06.03", "06.04", "07.01", "07.02", "08.01", "08.02", "08.03", "09.01", "09.02", "09.03", "09.04", "10.01", "10.02", "10.03", "10.04", "10.05", "10.06", "11.01", "11.02", "11.03", "12.01", "12.02", "12.03", "14.03", "14.04", "15.01", "16.01", "17.01", "13.01", "13.02", "13.03", "13.04", "14.01", "14.02", - "17.02", "17.03", "17.04", "19.01", + "17.02", "17.03", "17.04", "19.01", "19.02", }; // `checkpoints` in STORY_ORDER's order. Throws ParseException for a diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp index 68b81f5282..f139e3f03a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp @@ -75,9 +75,14 @@ const StoryCheckpoint& checkpoint(std::string_view id){ } // Runs the walking steps of `row` on the sim from its start, up to (not -// including) the step named `until`; the steps that are not walks (the -// Mart, the level check, the battle) are the console's. -std::string walk_row_until(OverworldSim& sim, StoryPose& at, const StoryCheckpoint& row, std::string_view until){ +// 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 ""; @@ -88,8 +93,11 @@ std::string walk_row_until(OverworldSim& sim, StoryPose& at, const StoryCheckpoi 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 std::format("{}: no step {}.", row.id, until); + return until.empty() ? "" : std::format("{}: no step {}.", row.id, until); } // 19.01: the street to Route 22 and along it to the rival's trigger column, @@ -99,7 +107,7 @@ UnitTestResult test_route22_rival_trigger(){ const StoryCheckpoint& row = checkpoint("19.01"); 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_until(sim, at, row, "rival_route22"); !failure.empty()){ + if (const std::string failure = walk_row(sim, at, row, "rival_route22"); !failure.empty()){ return failure; } const MapPosition trigger{"Route22", {33, 5}}; @@ -112,11 +120,40 @@ UnitTestResult test_route22_rival_trigger(){ 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; +} + const AutoStoryVictoryRoadCase AUTO_STORY_VICTORY_ROAD_CASES[] = { { .input = {.name = "19.01 Viridian 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"}, + }, }; } // namespace 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 e106476d07..309e28cce0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -293,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() != 68 || checkpoints[0].start){ - return "Expected 68 checkpoints, the first from a new game."; + if (checkpoints.size() != 69 || checkpoints[0].start){ + return "Expected 69 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ @@ -1079,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; @@ -1101,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.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"} + } + } +} From d61eb5e4acc749af98ed927a1585b25401c5c3b5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 19:32:06 -0800 Subject: [PATCH 09/15] FRLG 19.01: rival foe_threats from PokemonSimulation planning_risk, pinned by a test Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp | 36 +++++++++++++++++++ .../AutoStory/StoryData/frlg-19.01.plan.json | 14 ++++---- 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp index f139e3f03a..5e95b99f37 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp @@ -145,6 +145,38 @@ UnitTestResult test_gate_guard_trigger_and_route23(){ 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; +} + const AutoStoryVictoryRoadCase AUTO_STORY_VICTORY_ROAD_CASES[] = { { .input = {.name = "19.01 Viridian to the Route 22 rival's trigger", .body = test_route22_rival_trigger}, @@ -154,6 +186,10 @@ const AutoStoryVictoryRoadCase AUTO_STORY_VICTORY_ROAD_CASES[] = { .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"}, + }, }; } // namespace 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 index e6f6365c4d..3454f990f9 100644 --- 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 @@ -75,16 +75,16 @@ "setup_outspeed": true, "setup_guard_accuracy": true, "foe_threats": [ - [99, 30, 22, 63, 33, 0, 0], - [35, 30, 23, 62, 32, 0, 0], - [86, 18, 12, 37, 19, 0, 0], - [67, 26, 17, 54, 28, 0, 0], - [126, 64, 64, 129, 66, 0, 0], - [105, 80, 76, 162, 84, 0, 0] + [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 Gen 3 damage on his Blastoise (Lv49, Def 105, Sp. Def 119) from the doc's foe stats, one row per foe: Rhyhorn's Horn Drill fails (Lv45 against Lv49), Venusaur's Razor Leaf and crit can take 153 HP. Then he walks off and the player stays 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" } ] }, From d71d34afc54d0d948df648571137c9987b038c2f Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 19:51:11 -0800 Subject: [PATCH 10/15] FRLG 19.03 to 19.05: Route 23's guards and Surf stretch, Strength into Victory Road, Indigo Plateau's Center Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 1 + .../PokemonFRLG_AutoStoryPlanGolden19.h | 63 ++++++ .../PokemonFRLG_AutoStoryRunPlan_Tests.cpp | 8 +- .../AutoStory/PokemonFRLG_AutoStoryTable.cpp | 2 +- ...emonFRLG_AutoStoryUnauthoredStarts_Tests.h | 5 +- ...PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp | 107 ++++++++++ .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 4 +- .../AutoStory/StoryData/frlg-19.03.plan.json | 196 ++++++++++++++++++ .../AutoStory/StoryData/frlg-19.04.plan.json | 45 ++++ .../AutoStory/StoryData/frlg-19.05.plan.json | 49 +++++ 10 files changed, 471 insertions(+), 9 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.03.plan.json create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.04.plan.json create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.05.plan.json diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 7a46b9802e..be5e6ea1f3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -364,6 +364,7 @@ std::string save_card_place(const std::string& map){ {"Route24", "route-24"}, {"Route25", "route-25"}, {"Route22", "route-22"}, + {"Route23", "route-23"}, {"VermilionCity", "vermilion-city"}, {"Route10", "route-10"}, {"LavenderTown", "lavender-town"}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h index b95267c340..b318417fd0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h @@ -51,6 +51,69 @@ inline constexpr std::string_view FRLG_PLAN_GOLDEN_19[] = { "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 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 ef73287d37..b3ee8043a4 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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01 19.02"; +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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01 19.02"}, + .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01 19.02"}, + .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 19.01 19.02"}, + .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.03 14.03 14.04 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 17.02 17.03 17.04 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_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index 52d47defdc..ece9c16952 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -235,7 +235,7 @@ constexpr std::string_view STORY_ORDER[] = { "06.03", "06.04", "07.01", "07.02", "08.01", "08.02", "08.03", "09.01", "09.02", "09.03", "09.04", "10.01", "10.02", "10.03", "10.04", "10.05", "10.06", "11.01", "11.02", "11.03", "12.01", "12.02", "12.03", "14.03", "14.04", "15.01", "16.01", "17.01", "13.01", "13.02", "13.03", "13.04", "14.01", "14.02", - "17.02", "17.03", "17.04", "19.01", "19.02", + "17.02", "17.03", "17.04", "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 7fad93580f..9ec6862f5f 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.01 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.01" || id == "14.01"; + return id == "17.01" || 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 index 5e95b99f37..5459d66e76 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -20,11 +21,13 @@ #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{ @@ -177,6 +180,98 @@ UnitTestResult test_rival_foe_threats_are_the_generators(){ 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.01 Viridian to the Route 22 rival's trigger", .body = test_route22_rival_trigger}, @@ -190,6 +285,18 @@ const AutoStoryVictoryRoadCase AUTO_STORY_VICTORY_ROAD_CASES[] = { .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 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 309e28cce0..e76d3f81ed 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -293,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() != 69 || checkpoints[0].start){ - return "Expected 69 checkpoints, the first from a new game."; + if (checkpoints.size() != 72 || checkpoints[0].start){ + return "Expected 72 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ 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"} + } + } +} From e6ceb4e97eed685d43dbd8228ae90f854c4b1169 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 20:02:30 -0800 Subject: [PATCH 11/15] FRLG: push_boulder step and sim boulders, Victory Road 1F boulder solver fixture Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldSim.h | 1003 +++++++++-------- .../PokemonFRLG_OverworldSimField.cpp | 28 + .../Overworld/PokemonFRLG_OverworldSimField.h | 5 + .../PokemonFRLG/PokemonFRLG_Tests.cpp | 1 + .../PokemonFRLG_AutoStoryBoulders_Tests.cpp | 301 +++++ .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 29 + .../AutoStory/PokemonFRLG_AutoStoryPoses.h | 8 + .../AutoStory/PokemonFRLG_AutoStoryRowSim.cpp | 25 + .../AutoStory/PokemonFRLG_AutoStoryRowSim.h | 1 + .../PokemonFRLG_AutoStoryRows19_Tests.h | 2 + .../PokemonFRLG_AutoStoryStepTable.cpp | 7 + .../PokemonFRLG_AutoStoryStepTable.h | 2 + .../PokemonFRLG_AutoStoryStepTable_Tests.cpp | 3 + SerialPrograms/cmake/SourceFiles.cmake | 1 + 14 files changed, 918 insertions(+), 498 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBoulders_Tests.cpp diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 5e419e1ed3..c79eceb693 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -1,498 +1,505 @@ -/* Overworld Sim - * - * From: https://github.com/PokemonAutomation/ - * - * A whole-tile model of FireRed's overworld, for running the walker - * (run_route(), Pokemon::walk_leg_with()) without a console. The player - * moves a tile per 16 frames while the D-pad is held, by the maps' step - * rules (classify_step()), and also hops ledges the way they face, takes - * warps with a fade, reads signs walked into moving north or south, and is - * seen by trainers along their sight. Wild battles start on the steps a - * test chooses. Each of these shows a screen at a time after the step's - * press, which the walker's watchers see or miss as the console's do. - * - * Every console failure of the walker becomes a test here (red first). - * OverworldSimWalker is the console side of run_route() (RouteCalls) on - * the sim, step for step as walk_overworld_route_with_recovery() does it, - * with the walker's rules as switches, so a test can show a failure with - * the rule that was missing and its absence with the rule. - * - * A step onto a connected map waits a tile first, as the console does - * while the game loads the map. - * - * Not modelled: running, HP and status, and wild battles on the water. - * Surf and Fly are (SimField::SURF, SimField::FLY). Wandering people stand on - * their tile. The Bicycle is: its pace, its taps (each a tile, some - * dropped when they come too fast), SELECT and doors taking the player - * off it. - * - */ - -#ifndef PokemonAutomation_PokemonFRLG_OverworldSim_H -#define PokemonAutomation_PokemonFRLG_OverworldSim_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" -#include "PokemonFRLG_MovementMechanics.h" -#include "PokemonFRLG_BikeSpinPresses.h" -#include "PokemonFRLG_BikeSpinMechanics.h" -#include "PokemonFRLG_OverworldBikeTaps.h" -#include "PokemonFRLG_OverworldRecovery.h" -#include "PokemonFRLG_OverworldRoute.h" -#include "PokemonFRLG_OverworldSimField.h" -#include "PokemonFRLG_OverworldWalk.h" -#include "PokemonFRLG_OverworldSpin.h" -#include "PokemonFRLG_OverworldSimState.h" -#include "PokemonFRLG_OverworldSimScreens.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -// Simulates overworld movement, encounters and dialogs. -class OverworldSim{ -public: - OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script = {}); - - const SimState& state() const{ return m_state; } - - // Whether the walker's screen check reads its last step tap as a - // step: one that moved the player from `before`, but for - // SimScript::unseen_step_taps, or a turn tap since `turn_taps_before` - // (SimState::turn_taps) that SimScript::seen_turn_taps names. - bool reads_step_tap_as_step(const MapPosition& before, int turn_taps_before); - - // Holds `direction` for `duration` then lets go for `release`, while - // `watchers` watch until `watch` (at least the hold and release) from - // the start. Returns the first that saw its screen, as run_until(). - std::optional hold( - Direction direction, Milliseconds duration, Milliseconds release, Milliseconds watch, - const std::vector& watchers - ); - - // A press of `direction` for `duration` (at most MovementMechanics:: - // LONGEST_TAP), then `release`, as the console measured it: a player - // facing another way only turns; one facing that way steps once, - // unless the tap starts inside the lockout after the last step tap - // (STEP_TAP_LOCKOUT), which the game ignores, as it does any tap - // inside the lockout after a battle (BATTLE_EXIT_LOCKOUT); holds - // aren't held up by that lockout yet. A tap that starts as - // the last one ends, with no release between, holds it on. A turn may - // be dropped by fault injection (SimScript::dropped_turn_taps). - void tap( - Direction direction, - Milliseconds duration = MovementMechanics::TURN_TAP, - Milliseconds release = MovementMechanics::TURN_SETTLE - ); - - // Watches `watchers` for `duration`, as wait_until(). - std::optional watch(const std::vector& watchers, Milliseconds duration); - - // Runs from or fights the battle on screen, back to the overworld. A - // trainer's battle can't be run from; a battle that isn't there is - // waited out (the story's battle loop gives up after 15 s). - SimBattleEnd handle_battle(SimBattleChoice choice); - - // Closes the message on screen with B. Returns whether a trainer's - // battle follows it. - bool close_message(); - - // 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); - -private: - // A screen that shows at `at`; `unfreeze`: the player can move again. - struct Pending{ - Milliseconds at; - SimScreen screen; - bool unfreeze; - }; - // Where one press of the D-pad takes the player. - struct Step{ - int map = 0; - PlayerState player; - bool warped = false; - // The way the warp left the player facing (arrival_facing()), if - // not the way they moved. - std::optional facing = std::nullopt; - bool ledge = false; - // The step landed on a spinner, which slid the player to `player`. - std::optional spin = {}; - }; - - void advance_to(Milliseconds time); - void show(SimScreen screen, Milliseconds at); - void schedule(Milliseconds at, SimScreen screen, bool unfreeze); - bool sees(SimWatcher watcher, SimScreen screen) const; - std::optional first_seen(SimWatcher watcher, Milliseconds from, Milliseconds to) const; - std::optional watch_until(const std::vector& watchers, Milliseconds from, Milliseconds to); - // A tap, for the next one's lockout and to hold on: when it started - // and ended, the player's facing before it and the steps it took. - struct TapPress{ - Direction direction = Direction::NORTH; - Milliseconds start{0}; - Milliseconds end{0}; - Direction facing_before = Direction::NORTH; - int steps = 0; - }; - void walk_hold(Direction direction, Milliseconds duration, int short_by); - void take_steps(Direction direction, Milliseconds pressed, Milliseconds end, int left); - void step_tap(Direction direction, Milliseconds duration); - void hold_on(Direction direction, Milliseconds end); - void stuck_hold(Direction direction); - void bump(Direction direction, Milliseconds pressed); - std::optional press(Direction direction) const; - std::optional take_warp(int map_index, const TilePos& tile) const; - std::optional cross_edge(Direction direction) const; - // The lift's door to the floor picked, if `map_index` is a lift and - // one was picked. - std::optional lift_warp(int map_index) const; - // A step that landed on a spinner slides on to the slide's end; false - // if the slide never stops. - bool slide_on(Step& step) const; - // The slide's time after `step`, and its facing; 0 for no slide. - Milliseconds after_slide(const Step& step); - // What the maps can't say, from code (add_coded_objects()). - void add_coded_field(); - bool cut_tree(); - bool choose_lift_floor(size_t floor); - bool push_poster_switch(); - 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(); - bool after_step(const Step& step, Milliseconds pressed); - bool wild_battle(Milliseconds pressed); - std::optional next_encounter(); - bool rolls_encounter(int rate); - bool drops_turn_tap(); - bool press_select(); - // Whether the Bicycle tap starting at `start` is dropped, too soon - // after the last one. - bool drops_bike_tap(Milliseconds start); - // How long a tile takes: on the water, on the Bicycle or on foot. - Milliseconds tile_time() const{ - if (m_player.surfing){ - return m_script.timing.surf_tile; - } - return m_state.on_bike ? m_script.timing.bike_tile : m_script.timing.tile; - } - bool trainer_sees(Milliseconds pressed); - void update_view(); - void note(const std::string& line); - void violation(const std::string& line); - 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; - Milliseconds m_now{0}; - std::vector m_pending; // in time order - // The game has stopped the player: a battle, a message, a warp. - bool m_frozen = false; - // A battle is on screen or about to show. - bool m_battle_pending = false; - // The trainer (an object of the player's map) whose message is up or - // about to show, and whose battle follows it. - std::optional m_trainer_speaking; - // The trainer whose battle is on screen or about to show. - std::optional m_trainer; - // The trees cut since the last warp, and their maps. - std::vector> m_cut_trees; - // The floor picked on the lift's panel, if any. - std::optional m_lift_floor; - int m_grass_steps = 0; - // The game's wild encounter state (SimScript::encounter_rates). - std::mt19937 m_encounter_rng; - int m_steps_since_encounter = 0; - int m_encounter_rate_buff = 0; - // The turn taps so far, for SimScript::dropped_turn_taps. - // Steps onto a warp so far, and the fault on one - // (SimScript::black_without_warp): its black without the warp. - int m_warp_steps = 0; - bool black_without_warp(Milliseconds pressed); - // The last tap, until a hold. - std::optional m_last_tap; - // When the last Bicycle tap started, and how many came too soon. - std::optional m_last_bike_tap; - int m_fast_bike_taps = 0; - // A hold of `direction` for `duration`: counts the leg a tap on the - // Bicycle starts (SimState::bike_legs), and takes the player off the - // Bicycle if SimScript::off_bike_at_legs names it. - void count_bike_leg(Direction direction, Milliseconds duration); - // The way of the last Bicycle tap, unless another press came since. - std::optional m_bike_leg_direction; - // When the last tap that stepped started. - std::optional m_last_step_tap; - // The end of the lockout after the last battle. - Milliseconds m_battle_lockout_end{0}; - Milliseconds m_wild_battle_from{0}; - int m_holds = 0; - SimState m_state; -}; - - -// The walker's rules that console failures added, each on unless a test -// turns it off to show the failure it fixed. -struct SimWalkerRules{ - // Fail before a step unless the overworld is up (START menu left open, - // console B, 2026-11-01, Viridian Forest). - bool check_overworld = true; - // A battle needs an HP box or the battle menu: black below a small room - // isn't one (console B, 2026-11-01, Viridian Forest's north gate). - bool battle_needs_hp_box = true; - // A trainer's battle after their message is fought, not taken for a - // wild one and run from (console B, 2026-11-01, Viridian Forest). - bool fight_trainer_after_message = true; - // How long the walker watches after a leg through grass for a battle - // whose flashes it missed. It watched 500 ms, and walked the next leg - // into the battle (console B, 2026-11-01, Route 1, run 7 and r14). - Milliseconds after_wild_leg_watch = OverworldWalkSteps::AFTER_WILD_LEG_WATCH; - // A leg to a wall held again after an interrupt stops when it is - // interrupted again right away: by a sign it is held into. Without it - // the walker read the sign 6 times (console B, 2026-11-01, r16). - bool stop_if_blocked = true; - // How long a hold's watch goes on past the hold and its release. 0 as - // now; the tile-at-a-time build watched each step for 900 ms, and saw - // the warp's fade on the step onto the forest's north gate as a battle. - Milliseconds watch_past_hold{0}; - // A leg onto a warp whose fade was a wild battle's (its wipe passes for - // the fade) stops before the warp, and the player is found again on it. - // Without it the walker stopped as off the route (console B, - // 2026-11-03, Mt. Moon 1F, row 04.05). - bool find_player_after_warp_battle = true; - // After a leg's watch saw nothing, a battle's text box on screen (its - // HP boxes still to come) is watched on for, and the leg taken as - // stopped part-way. Without it the walker took "south 15 (to wall)" - // as walked and the next leg into the battle (console B, 2026-11-03, - // Mt. Moon B1F, row 04.05). - bool watch_on_for_unseen_battle = true; - // The same after a leg the maps see no wild tiles on (RouteStep::wild), - // which the leg and its watch don't watch for battles: on Mt. Moon - // B2F's tiles closed on one side, which the maps don't mark as wild, a - // battle on "east 7 (to wall)" left black after the leg, the leg was - // taken as walked and the next one held from where the battle was - // (console B, 2026-11-03, row 04.05). - bool watch_on_after_unmarked_leg = true; - // Before a step, a battle on its way (its text box or wipe) is watched - // on for, and the step before it taken as stopped part-way, not the - // step held from where the battle left the player. - bool battle_before_step = true; - // A hold over a step onto a connected map is a tile longer for it - // (RouteStep::connection_steps). Without it the open leg north from - // Cerulean City onto Nugget Bridge ended a tile short (console B, - // 2026-11-03, rows 05.05 and 05.09). - bool hold_over_connections = true; - // An open leg after whose hold a wild battle was seen is placed by the - // battle's first timed screen event (place_late_stop()). Without it the - // player may be anywhere on the leg: on Route 10, "east 11" was found - // again from all 12 of its tiles (console B, 2026-11-09, 07.02 run 2). - bool place_late_battle = true; - // A message after the hold of an open leg that ends below a sign - // (RouteStep::sign_ahead) places the player on its end. Without it - // the walker found the player at walls and held the same leg into the - // sign 9 times (console B, 2026-11-12, 11.03, Safari Zone West). - bool place_by_sign = true; - // The watch for a warp's fade starts with the hold onto the warp - // (Pokemon::WatchAlong), not when it ends. Without it a fade over - // before the hold ended was missed, and the walk stopped on "no fade in - // and out after walking onto the warp" though it had warped (console B, - // 2026-11-09 01:41, 07.02, the warp to CeruleanCity: the watch started - // about 1.3 s into the hold). - bool watch_fade_along_hold = true; - // A warp's fade is taken as the warp only once the screen after it - // shows the player off the map they held from (warp_left_scene()). - // Without it a black that cleared with the player where they were was - // taken as the warp (console B, 2026-11-10 01:44, 09.01 run 4). - bool confirm_warp_destination = true; - // A warp whose fade was over before the watch for it began is taken by - // the screen after it: another scene than before the hold, held still - // (OverworldWalkSteps::arrived_without_fade()). Without it the walker - // tapped twice into the Department Store lift's back wall and failed - // on "no fade in and out after walking onto the warp" with the player - // inside the lift (console B, 2026-11-12 00:39, 10.01 lift_to_1f): the - // lift room is mostly black, so a watch started after the fade never - // sees black end. - bool scene_confirms_missed_fade = true; - // A turn tap is checked by the facing on screen, and tapped again - // while the player faces another way (OverworldWalkSteps::turn_to()). - // Without it a dropped tap left a one-tile leg turning the player - // only, taken as walked (console B, 2026-11-09, 08.01 run 2). - bool confirm_turn = true; - // The speed the walker goes at: its turn taps - // (OverworldWalkSteps::turns_first()) and its holds' tile time. - MoveSpeed speed = MoveSpeed::WALK; - // An open leg on the Bicycle is counted out a tap at a time, each a - // tile (count_bike_taps()), and one that doesn't move finds the player - // ahead of a block. Without it the leg is one hold, and a start off - // along the leg ends it off with nothing to show it (console B, - // 2026-11-09, 08.03: three runs 3 tiles east after Route 8's legs). - bool count_bike_taps = true; - // How far apart, start to start, the counted taps are - // (MovementMechanics::BIKE_TAP_PERIOD). - Milliseconds bike_tap_period = MovementMechanics::BIKE_TAP_PERIOD; - // After a warp, which takes the player off the Bicycle, the next leg - // where it may be ridden gets on again with SELECT. Without it the - // walker held on-foot legs at the Bicycle's pace. - bool get_back_on_bike = true; - // A dark cave's overworld isn't a battle on its way - // (OverworldWalkSteps::dark_cave_screen()). Without it the check - // before each step watched for a battle on it (console B, 2026-11-09, - // 08.01: "running from a wild Pokemon", then "not a battle"). - bool dark_cave_not_battle = true; - // A stop on an open leg that started in a dark cave may be anywhere on - // the leg (whole_leg()). Without it the stop is placed by the dark - // screen's black, read as the battle at the hold's start: a battle at - // the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 tiles in, - // and the player was found again at a wall 5 tiles off (console B, - // 2026-11-09, 08.01). - bool whole_leg_in_dark = true; - // The end of a trainer's battle the walker fought, as the story's - // battle loop takes it on the screen the sim shows after it: its - // failure, or empty. By default the battle just ends. - std::function trainer_battle_end = [](const OverworldSim&){ - return std::string(); - }; -}; - -// OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the -// overworld only; with `confirm` false, the one tap before it. -void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm = SimWalkerRules{}.confirm_turn); - -// AutoStory's step_once() on `sim`: turns the player if they face another -// way, then one step tap. -void sim_step_once(OverworldSim& sim, Direction direction); - -// The console side of run_route() on an OverworldSim, as -// walk_overworld_route_with_recovery() does it, with the story's -// interrupts: a wild battle (flashes, or seen late) is fought or run from, -// a message is closed and a trainer's battle after it fought. -class OverworldSimWalker{ -public: - // `interrupts`: whose detection delays place a stopped leg, the - // walker's own or a caller's (story_interrupts()). Each set lists a - // wild battle, one seen late and a message for `wild`, and a message - // for `other`, in that order. - OverworldSimWalker( - OverworldSim& sim, SimWalkerRules rules = {}, - const OverworldInterruptSet& interrupts = default_overworld_interrupts() - ); - - // RouteCalls whose `fail` throws OperationFailedException, as the - // console's does. - RouteCalls calls(); - - // run_route() from the sim's facing, planned with `planning`. Returns - // the failure's message, or empty if the route was walked. - std::string run(const std::vector& route, const RoutePlanning& planning); - - const std::vector& log() const{ return m_log; } - -private: - // One of the story's interrupts (story_interrupts()), with the - // walker's detection delay for it. - struct Interrupt{ - std::string name; - SimWatcher watcher; - Milliseconds delay; - bool battle; - }; - StepOutcome walk(const RouteStep& step, std::optional facing); - StepOutcome walk_ridden(const RouteStep& step, std::optional facing); - // count_bike_taps() on the sim. - StepOutcome walk_bike_taps(const RouteStep& step); - BikeTap bike_tap(const RouteStep& step); - // count_bike_taps() on foot (counts_step_taps()). - StepOutcome walk_step_taps(const RouteStep& step); - BikeTap step_tap(const RouteStep& step, int tap); - std::optional late_stop(const RouteStep& step); - // stop_tiles(); without SimWalkerRules::whole_leg_in_dark, the dark - // screen places the stop at the hold's start. - WalkedTiles dark_stop(const RouteStep& step, WalkedTiles timed) const{ - if (m_leg_dark && !m_rules.whole_leg_in_dark){ - return walked_near(step, 0, MovementMechanics::TILE_TIME); - } - return stop_tiles(step, timed, m_leg_dark); - } - std::optional walk_step(const RouteStep& step, std::optional facing); - // start_surf(): turned to the water, A, YES, and the jump onto it. - // 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 - // SimWalkerRules::confirm_warp_destination off, takes it as the warp. - bool black_without_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); - [[noreturn]] void fail_off_route(const RouteStep& step); - std::optional hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts); - size_t clear_late(const std::vector& interrupts, Milliseconds watch, size_t max); - size_t clear_unseen_battle(const RouteStep& step); - bool battle_on_its_way() const; - void clear(const Interrupt& interrupt); - void hold_to_warp(const RouteStep& step); - StepEnd watch_for_trainer(const RouteStep& step, int approach_tiles); - bool moved_past_wall(const RouteStep& step); - void check_overworld(const RouteStep& step); - // After a leg onto a spinner: the slide's time. - void wait_out_slide(const RouteStep& step); - const std::vector& interrupts(const RouteStep& step) const; - std::vector watchers(const std::vector& interrupts) const; - [[noreturn]] void fail(const std::string& message); - - OverworldSim& m_sim; - SimWalkerRules m_rules; - std::vector m_wild; - std::vector m_other; - std::vector m_log; - // When the last WALK leg's first hold started, on the sim's clock, - // and whether its map was dark then. - Milliseconds m_leg_start{0}; - bool m_leg_dark = false; - // Whether the walker takes the player to ride the Bicycle, and the - // speed of the step under way. - bool m_riding = false; - MoveSpeed m_speed = MoveSpeed::WALK; -}; - - -// Register overworld simulation unit tests. -void add_tests_OverworldSim(UnitTestDatabase& database); -// Register the tests of a warp's fade over before the hold onto it ends. -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 -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif +/* Overworld Sim + * + * From: https://github.com/PokemonAutomation/ + * + * A whole-tile model of FireRed's overworld, for running the walker + * (run_route(), Pokemon::walk_leg_with()) without a console. The player + * moves a tile per 16 frames while the D-pad is held, by the maps' step + * rules (classify_step()), and also hops ledges the way they face, takes + * warps with a fade, reads signs walked into moving north or south, and is + * seen by trainers along their sight. Wild battles start on the steps a + * test chooses. Each of these shows a screen at a time after the step's + * press, which the walker's watchers see or miss as the console's do. + * + * Every console failure of the walker becomes a test here (red first). + * OverworldSimWalker is the console side of run_route() (RouteCalls) on + * the sim, step for step as walk_overworld_route_with_recovery() does it, + * with the walker's rules as switches, so a test can show a failure with + * the rule that was missing and its absence with the rule. + * + * A step onto a connected map waits a tile first, as the console does + * while the game loads the map. + * + * Not modelled: running, HP and status, and wild battles on the water. + * Surf and Fly are (SimField::SURF, SimField::FLY). Wandering people stand on + * their tile. The Bicycle is: its pace, its taps (each a tile, some + * dropped when they come too fast), SELECT and doors taking the player + * off it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldSim_H +#define PokemonAutomation_PokemonFRLG_OverworldSim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "PokemonFRLG_MovementMechanics.h" +#include "PokemonFRLG_BikeSpinPresses.h" +#include "PokemonFRLG_BikeSpinMechanics.h" +#include "PokemonFRLG_OverworldBikeTaps.h" +#include "PokemonFRLG_OverworldRecovery.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldSimField.h" +#include "PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_OverworldSpin.h" +#include "PokemonFRLG_OverworldSimState.h" +#include "PokemonFRLG_OverworldSimScreens.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Simulates overworld movement, encounters and dialogs. +class OverworldSim{ +public: + OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script = {}); + + const SimState& state() const{ return m_state; } + + // Whether the walker's screen check reads its last step tap as a + // step: one that moved the player from `before`, but for + // SimScript::unseen_step_taps, or a turn tap since `turn_taps_before` + // (SimState::turn_taps) that SimScript::seen_turn_taps names. + bool reads_step_tap_as_step(const MapPosition& before, int turn_taps_before); + + // Holds `direction` for `duration` then lets go for `release`, while + // `watchers` watch until `watch` (at least the hold and release) from + // the start. Returns the first that saw its screen, as run_until(). + std::optional hold( + Direction direction, Milliseconds duration, Milliseconds release, Milliseconds watch, + const std::vector& watchers + ); + + // A press of `direction` for `duration` (at most MovementMechanics:: + // LONGEST_TAP), then `release`, as the console measured it: a player + // facing another way only turns; one facing that way steps once, + // unless the tap starts inside the lockout after the last step tap + // (STEP_TAP_LOCKOUT), which the game ignores, as it does any tap + // inside the lockout after a battle (BATTLE_EXIT_LOCKOUT); holds + // aren't held up by that lockout yet. A tap that starts as + // the last one ends, with no release between, holds it on. A turn may + // be dropped by fault injection (SimScript::dropped_turn_taps). + void tap( + Direction direction, + Milliseconds duration = MovementMechanics::TURN_TAP, + Milliseconds release = MovementMechanics::TURN_SETTLE + ); + + // Watches `watchers` for `duration`, as wait_until(). + std::optional watch(const std::vector& watchers, Milliseconds duration); + + // Runs from or fights the battle on screen, back to the overworld. A + // trainer's battle can't be run from; a battle that isn't there is + // waited out (the story's battle loop gives up after 15 s). + SimBattleEnd handle_battle(SimBattleChoice choice); + + // Closes the message on screen with B. Returns whether a trainer's + // battle follows it. + bool close_message(); + + // 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. + struct Pending{ + Milliseconds at; + SimScreen screen; + bool unfreeze; + }; + // Where one press of the D-pad takes the player. + struct Step{ + int map = 0; + PlayerState player; + bool warped = false; + // The way the warp left the player facing (arrival_facing()), if + // not the way they moved. + std::optional facing = std::nullopt; + bool ledge = false; + // The step landed on a spinner, which slid the player to `player`. + std::optional spin = {}; + }; + + void advance_to(Milliseconds time); + void show(SimScreen screen, Milliseconds at); + void schedule(Milliseconds at, SimScreen screen, bool unfreeze); + bool sees(SimWatcher watcher, SimScreen screen) const; + std::optional first_seen(SimWatcher watcher, Milliseconds from, Milliseconds to) const; + std::optional watch_until(const std::vector& watchers, Milliseconds from, Milliseconds to); + // A tap, for the next one's lockout and to hold on: when it started + // and ended, the player's facing before it and the steps it took. + struct TapPress{ + Direction direction = Direction::NORTH; + Milliseconds start{0}; + Milliseconds end{0}; + Direction facing_before = Direction::NORTH; + int steps = 0; + }; + void walk_hold(Direction direction, Milliseconds duration, int short_by); + void take_steps(Direction direction, Milliseconds pressed, Milliseconds end, int left); + void step_tap(Direction direction, Milliseconds duration); + void hold_on(Direction direction, Milliseconds end); + void stuck_hold(Direction direction); + void bump(Direction direction, Milliseconds pressed); + std::optional press(Direction direction) const; + std::optional take_warp(int map_index, const TilePos& tile) const; + std::optional cross_edge(Direction direction) const; + // The lift's door to the floor picked, if `map_index` is a lift and + // one was picked. + std::optional lift_warp(int map_index) const; + // A step that landed on a spinner slides on to the slide's end; false + // if the slide never stops. + bool slide_on(Step& step) const; + // The slide's time after `step`, and its facing; 0 for no slide. + Milliseconds after_slide(const Step& step); + // What the maps can't say, from code (add_coded_objects()). + void add_coded_field(); + 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(); + bool after_step(const Step& step, Milliseconds pressed); + bool wild_battle(Milliseconds pressed); + std::optional next_encounter(); + bool rolls_encounter(int rate); + bool drops_turn_tap(); + bool press_select(); + // Whether the Bicycle tap starting at `start` is dropped, too soon + // after the last one. + bool drops_bike_tap(Milliseconds start); + // How long a tile takes: on the water, on the Bicycle or on foot. + Milliseconds tile_time() const{ + if (m_player.surfing){ + return m_script.timing.surf_tile; + } + return m_state.on_bike ? m_script.timing.bike_tile : m_script.timing.tile; + } + bool trainer_sees(Milliseconds pressed); + void update_view(); + void note(const std::string& line); + void violation(const std::string& line); + 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; + Milliseconds m_now{0}; + std::vector m_pending; // in time order + // The game has stopped the player: a battle, a message, a warp. + bool m_frozen = false; + // A battle is on screen or about to show. + bool m_battle_pending = false; + // The trainer (an object of the player's map) whose message is up or + // about to show, and whose battle follows it. + std::optional m_trainer_speaking; + // The trainer whose battle is on screen or about to show. + std::optional m_trainer; + // The trees cut since the last warp, and their maps. + std::vector> m_cut_trees; + // The floor picked on the lift's panel, if any. + std::optional m_lift_floor; + int m_grass_steps = 0; + // The game's wild encounter state (SimScript::encounter_rates). + std::mt19937 m_encounter_rng; + int m_steps_since_encounter = 0; + int m_encounter_rate_buff = 0; + // The turn taps so far, for SimScript::dropped_turn_taps. + // Steps onto a warp so far, and the fault on one + // (SimScript::black_without_warp): its black without the warp. + int m_warp_steps = 0; + bool black_without_warp(Milliseconds pressed); + // The last tap, until a hold. + std::optional m_last_tap; + // When the last Bicycle tap started, and how many came too soon. + std::optional m_last_bike_tap; + int m_fast_bike_taps = 0; + // A hold of `direction` for `duration`: counts the leg a tap on the + // Bicycle starts (SimState::bike_legs), and takes the player off the + // Bicycle if SimScript::off_bike_at_legs names it. + void count_bike_leg(Direction direction, Milliseconds duration); + // The way of the last Bicycle tap, unless another press came since. + std::optional m_bike_leg_direction; + // When the last tap that stepped started. + std::optional m_last_step_tap; + // The end of the lockout after the last battle. + Milliseconds m_battle_lockout_end{0}; + Milliseconds m_wild_battle_from{0}; + int m_holds = 0; + SimState m_state; +}; + + +// The walker's rules that console failures added, each on unless a test +// turns it off to show the failure it fixed. +struct SimWalkerRules{ + // Fail before a step unless the overworld is up (START menu left open, + // console B, 2026-11-01, Viridian Forest). + bool check_overworld = true; + // A battle needs an HP box or the battle menu: black below a small room + // isn't one (console B, 2026-11-01, Viridian Forest's north gate). + bool battle_needs_hp_box = true; + // A trainer's battle after their message is fought, not taken for a + // wild one and run from (console B, 2026-11-01, Viridian Forest). + bool fight_trainer_after_message = true; + // How long the walker watches after a leg through grass for a battle + // whose flashes it missed. It watched 500 ms, and walked the next leg + // into the battle (console B, 2026-11-01, Route 1, run 7 and r14). + Milliseconds after_wild_leg_watch = OverworldWalkSteps::AFTER_WILD_LEG_WATCH; + // A leg to a wall held again after an interrupt stops when it is + // interrupted again right away: by a sign it is held into. Without it + // the walker read the sign 6 times (console B, 2026-11-01, r16). + bool stop_if_blocked = true; + // How long a hold's watch goes on past the hold and its release. 0 as + // now; the tile-at-a-time build watched each step for 900 ms, and saw + // the warp's fade on the step onto the forest's north gate as a battle. + Milliseconds watch_past_hold{0}; + // A leg onto a warp whose fade was a wild battle's (its wipe passes for + // the fade) stops before the warp, and the player is found again on it. + // Without it the walker stopped as off the route (console B, + // 2026-11-03, Mt. Moon 1F, row 04.05). + bool find_player_after_warp_battle = true; + // After a leg's watch saw nothing, a battle's text box on screen (its + // HP boxes still to come) is watched on for, and the leg taken as + // stopped part-way. Without it the walker took "south 15 (to wall)" + // as walked and the next leg into the battle (console B, 2026-11-03, + // Mt. Moon B1F, row 04.05). + bool watch_on_for_unseen_battle = true; + // The same after a leg the maps see no wild tiles on (RouteStep::wild), + // which the leg and its watch don't watch for battles: on Mt. Moon + // B2F's tiles closed on one side, which the maps don't mark as wild, a + // battle on "east 7 (to wall)" left black after the leg, the leg was + // taken as walked and the next one held from where the battle was + // (console B, 2026-11-03, row 04.05). + bool watch_on_after_unmarked_leg = true; + // Before a step, a battle on its way (its text box or wipe) is watched + // on for, and the step before it taken as stopped part-way, not the + // step held from where the battle left the player. + bool battle_before_step = true; + // A hold over a step onto a connected map is a tile longer for it + // (RouteStep::connection_steps). Without it the open leg north from + // Cerulean City onto Nugget Bridge ended a tile short (console B, + // 2026-11-03, rows 05.05 and 05.09). + bool hold_over_connections = true; + // An open leg after whose hold a wild battle was seen is placed by the + // battle's first timed screen event (place_late_stop()). Without it the + // player may be anywhere on the leg: on Route 10, "east 11" was found + // again from all 12 of its tiles (console B, 2026-11-09, 07.02 run 2). + bool place_late_battle = true; + // A message after the hold of an open leg that ends below a sign + // (RouteStep::sign_ahead) places the player on its end. Without it + // the walker found the player at walls and held the same leg into the + // sign 9 times (console B, 2026-11-12, 11.03, Safari Zone West). + bool place_by_sign = true; + // The watch for a warp's fade starts with the hold onto the warp + // (Pokemon::WatchAlong), not when it ends. Without it a fade over + // before the hold ended was missed, and the walk stopped on "no fade in + // and out after walking onto the warp" though it had warped (console B, + // 2026-11-09 01:41, 07.02, the warp to CeruleanCity: the watch started + // about 1.3 s into the hold). + bool watch_fade_along_hold = true; + // A warp's fade is taken as the warp only once the screen after it + // shows the player off the map they held from (warp_left_scene()). + // Without it a black that cleared with the player where they were was + // taken as the warp (console B, 2026-11-10 01:44, 09.01 run 4). + bool confirm_warp_destination = true; + // A warp whose fade was over before the watch for it began is taken by + // the screen after it: another scene than before the hold, held still + // (OverworldWalkSteps::arrived_without_fade()). Without it the walker + // tapped twice into the Department Store lift's back wall and failed + // on "no fade in and out after walking onto the warp" with the player + // inside the lift (console B, 2026-11-12 00:39, 10.01 lift_to_1f): the + // lift room is mostly black, so a watch started after the fade never + // sees black end. + bool scene_confirms_missed_fade = true; + // A turn tap is checked by the facing on screen, and tapped again + // while the player faces another way (OverworldWalkSteps::turn_to()). + // Without it a dropped tap left a one-tile leg turning the player + // only, taken as walked (console B, 2026-11-09, 08.01 run 2). + bool confirm_turn = true; + // The speed the walker goes at: its turn taps + // (OverworldWalkSteps::turns_first()) and its holds' tile time. + MoveSpeed speed = MoveSpeed::WALK; + // An open leg on the Bicycle is counted out a tap at a time, each a + // tile (count_bike_taps()), and one that doesn't move finds the player + // ahead of a block. Without it the leg is one hold, and a start off + // along the leg ends it off with nothing to show it (console B, + // 2026-11-09, 08.03: three runs 3 tiles east after Route 8's legs). + bool count_bike_taps = true; + // How far apart, start to start, the counted taps are + // (MovementMechanics::BIKE_TAP_PERIOD). + Milliseconds bike_tap_period = MovementMechanics::BIKE_TAP_PERIOD; + // After a warp, which takes the player off the Bicycle, the next leg + // where it may be ridden gets on again with SELECT. Without it the + // walker held on-foot legs at the Bicycle's pace. + bool get_back_on_bike = true; + // A dark cave's overworld isn't a battle on its way + // (OverworldWalkSteps::dark_cave_screen()). Without it the check + // before each step watched for a battle on it (console B, 2026-11-09, + // 08.01: "running from a wild Pokemon", then "not a battle"). + bool dark_cave_not_battle = true; + // A stop on an open leg that started in a dark cave may be anywhere on + // the leg (whole_leg()). Without it the stop is placed by the dark + // screen's black, read as the battle at the hold's start: a battle at + // the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 tiles in, + // and the player was found again at a wall 5 tiles off (console B, + // 2026-11-09, 08.01). + bool whole_leg_in_dark = true; + // The end of a trainer's battle the walker fought, as the story's + // battle loop takes it on the screen the sim shows after it: its + // failure, or empty. By default the battle just ends. + std::function trainer_battle_end = [](const OverworldSim&){ + return std::string(); + }; +}; + +// OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the +// overworld only; with `confirm` false, the one tap before it. +void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm = SimWalkerRules{}.confirm_turn); + +// AutoStory's step_once() on `sim`: turns the player if they face another +// way, then one step tap. +void sim_step_once(OverworldSim& sim, Direction direction); + +// The console side of run_route() on an OverworldSim, as +// walk_overworld_route_with_recovery() does it, with the story's +// interrupts: a wild battle (flashes, or seen late) is fought or run from, +// a message is closed and a trainer's battle after it fought. +class OverworldSimWalker{ +public: + // `interrupts`: whose detection delays place a stopped leg, the + // walker's own or a caller's (story_interrupts()). Each set lists a + // wild battle, one seen late and a message for `wild`, and a message + // for `other`, in that order. + OverworldSimWalker( + OverworldSim& sim, SimWalkerRules rules = {}, + const OverworldInterruptSet& interrupts = default_overworld_interrupts() + ); + + // RouteCalls whose `fail` throws OperationFailedException, as the + // console's does. + RouteCalls calls(); + + // run_route() from the sim's facing, planned with `planning`. Returns + // the failure's message, or empty if the route was walked. + std::string run(const std::vector& route, const RoutePlanning& planning); + + const std::vector& log() const{ return m_log; } + +private: + // One of the story's interrupts (story_interrupts()), with the + // walker's detection delay for it. + struct Interrupt{ + std::string name; + SimWatcher watcher; + Milliseconds delay; + bool battle; + }; + StepOutcome walk(const RouteStep& step, std::optional facing); + StepOutcome walk_ridden(const RouteStep& step, std::optional facing); + // count_bike_taps() on the sim. + StepOutcome walk_bike_taps(const RouteStep& step); + BikeTap bike_tap(const RouteStep& step); + // count_bike_taps() on foot (counts_step_taps()). + StepOutcome walk_step_taps(const RouteStep& step); + BikeTap step_tap(const RouteStep& step, int tap); + std::optional late_stop(const RouteStep& step); + // stop_tiles(); without SimWalkerRules::whole_leg_in_dark, the dark + // screen places the stop at the hold's start. + WalkedTiles dark_stop(const RouteStep& step, WalkedTiles timed) const{ + if (m_leg_dark && !m_rules.whole_leg_in_dark){ + return walked_near(step, 0, MovementMechanics::TILE_TIME); + } + return stop_tiles(step, timed, m_leg_dark); + } + std::optional walk_step(const RouteStep& step, std::optional facing); + // start_surf(): turned to the water, A, YES, and the jump onto it. + // 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 + // SimWalkerRules::confirm_warp_destination off, takes it as the warp. + bool black_without_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); + [[noreturn]] void fail_off_route(const RouteStep& step); + std::optional hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts); + size_t clear_late(const std::vector& interrupts, Milliseconds watch, size_t max); + size_t clear_unseen_battle(const RouteStep& step); + bool battle_on_its_way() const; + void clear(const Interrupt& interrupt); + void hold_to_warp(const RouteStep& step); + StepEnd watch_for_trainer(const RouteStep& step, int approach_tiles); + bool moved_past_wall(const RouteStep& step); + void check_overworld(const RouteStep& step); + // After a leg onto a spinner: the slide's time. + void wait_out_slide(const RouteStep& step); + const std::vector& interrupts(const RouteStep& step) const; + std::vector watchers(const std::vector& interrupts) const; + [[noreturn]] void fail(const std::string& message); + + OverworldSim& m_sim; + SimWalkerRules m_rules; + std::vector m_wild; + std::vector m_other; + std::vector m_log; + // When the last WALK leg's first hold started, on the sim's clock, + // and whether its map was dark then. + Milliseconds m_leg_start{0}; + bool m_leg_dark = false; + // Whether the walker takes the player to ride the Bicycle, and the + // speed of the step under way. + bool m_riding = false; + MoveSpeed m_speed = MoveSpeed::WALK; +}; + + +// Register overworld simulation unit tests. +void add_tests_OverworldSim(UnitTestDatabase& database); +// Register the tests of a warp's fade over before the hold onto it ends. +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 +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp index afbe8ab05c..cc3b4a836d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp @@ -29,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 @@ -39,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: @@ -115,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){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h index f2d8a29fe6..ffaa1bd629 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h @@ -41,6 +41,11 @@ 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. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 918c71f98f..b96f9aeff5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -347,6 +347,7 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& 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 be5e6ea1f3..0100ed32bf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -613,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{ @@ -717,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_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 102739fb16..1d1d2d7b97 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 index 64bff583ba..1dcaf8b44d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h @@ -19,6 +19,8 @@ namespace PokemonFRLG{ // Rows 19.01 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 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/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index e72f26a13b..f737b94097 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2105,6 +2105,7 @@ file(GLOB LIBRARY_SOURCES 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 From c99ee726e8f2bef02d5daf1c570211495744e96c Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 20:47:30 -0800 Subject: [PATCH 12/15] FRLG AutoStory: the chain test expects 75 checkpoints (the split's merge counted one twice) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 c433a25d0f..7258d6b92b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -293,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() != 74 || checkpoints[0].start){ - return "Expected 74 checkpoints, the first from a new game."; + if (checkpoints.size() != 75 || checkpoints[0].start){ + return "Expected 75 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ From 4af8b7d1c6be898ede666237d87e3c032a954acc Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 20:55:14 -0800 Subject: [PATCH 13/15] FRLG 19.01: the Mart is 19.01a; 19.01 is the Route 22 rival alone A boss battle is its own checkpoint (user, 2026-11-12). The potions at Viridian's Mart come first in the new 19.01a, which starts at the nurse and ends at the Mart's counter; 19.01 starts there, walks to Route 22 and ends after the rival's battle. Ids are not renumbered; the golden, run-plan, table, count and Victory Road tests follow. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryPlanGolden19.h | 18 +++---- .../PokemonFRLG_AutoStoryRows19_Tests.h | 2 +- .../PokemonFRLG_AutoStoryRunPlan_Tests.cpp | 8 +-- .../AutoStory/PokemonFRLG_AutoStoryTable.cpp | 2 +- ...PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp | 27 +++++++--- .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 4 +- .../AutoStory/StoryData/frlg-19.01.plan.json | 30 ++--------- .../AutoStory/StoryData/frlg-19.01a.plan.json | 50 +++++++++++++++++++ 8 files changed, 90 insertions(+), 51 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-19.01a.plan.json diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h index b318417fd0..872c365fae 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden19.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * The golden's lines for 19.01 and after (Route 22's rival, Route 23, + * 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. * @@ -17,15 +17,15 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ -// The stored plan lines of 19.01 and after. +// The stored plan lines of 19.01a and after. inline constexpr std::string_view FRLG_PLAN_GOLDEN_19[] = { - "19.01 viridian_mart_clerk from ViridianCity_PokemonCenter_1F (7, 4) facing north to ViridianCity_Mart (4, 3) facing west", - "19.01 walk south 5 (warp) -> ViridianCity (26, 27) [walk only]", - "19.01 walk south 2 -> ViridianCity (26, 29)", - "19.01 walk east 10 -> ViridianCity (36, 29)", - "19.01 walk north 10 (warp) -> ViridianCity_Mart (4, 7)", - "19.01 walk north 4 -> ViridianCity_Mart (4, 3) [walk only]", - "19.01 face west -> ViridianCity_Mart (4, 3) [walk only]", + "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)", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h index 1dcaf8b44d..f0680bbc25 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows19_Tests.h @@ -17,7 +17,7 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -// Rows 19.01 and after on the overworld sim (PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp). +// 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); 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 fdd39a50fd..9b98204838 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 14.03 14.04 14.04b 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 17.02 17.03 17.04 17.04b 19.01 19.02 19.03 19.04 19.05"; +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 14.03 14.04 14.04b 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 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 14.03 14.04 14.04b 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 17.02 17.03 17.04 17.04b 19.01 19.02 19.03 19.04 19.05"}, + .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 14.03 14.04 14.04b 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 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 14.03 14.04 14.04b 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 17.02 17.03 17.04 17.04b 19.01 19.02 19.03 19.04 19.05"}, + .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 14.03 14.04 14.04b 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 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 14.03 14.04 14.04b 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 17.02 17.03 17.04 17.04b 19.01 19.02 19.03 19.04 19.05"}, + .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 14.03 14.04 14.04b 15.01 16.01 17.01 13.01 13.02 13.03 13.04 14.01 14.02 14.02b 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_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index 9d8ff009f4..7c86f7edf0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -235,7 +235,7 @@ constexpr std::string_view STORY_ORDER[] = { "06.03", "06.04", "07.01", "07.02", "08.01", "08.02", "08.03", "09.01", "09.02", "09.03", "09.04", "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", "14.03", "14.04", "14.04b", "15.01", "16.01", "17.01", "13.01", "13.02", "13.03", "13.04", "14.01", "14.02", "14.02b", - "17.02", "17.03", "17.04", "17.04b", "19.01", "19.02", "19.03", "19.04", "19.05", + "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_AutoStoryVictoryRoad_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp index 5459d66e76..ac2fa55d56 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVictoryRoad_Tests.cpp @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Rows 19.01 and after (StoryData/frlg-19.0N.plan.json) on the overworld + * 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. * @@ -103,13 +103,26 @@ std::string walk_row( return until.empty() ? "" : std::format("{}: no step {}.", row.id, until); } -// 19.01: 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. +// 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& row = checkpoint("19.01"); - StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + 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; } @@ -274,7 +287,7 @@ UnitTestResult test_indigo_center_walk(){ const AutoStoryVictoryRoadCase AUTO_STORY_VICTORY_ROAD_CASES[] = { { - .input = {.name = "19.01 Viridian to the Route 22 rival's trigger", .body = test_route22_rival_trigger}, + .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"}, }, { 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 286ee81e8e..b3283f457c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -293,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() != 76 || checkpoints[0].start){ - return "Expected 76 checkpoints, the first from a new game."; + if (checkpoints.size() != 77 || checkpoints[0].start){ + return "Expected 77 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ 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 index 3454f990f9..68715f1332 100644 --- 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 @@ -3,33 +3,9 @@ "game": "frlg", "checkpoint": { "id": "19.01", - "title": "Viridian to Route 22: potions, and the rival at the road's east end", - "start": { - "map": "ViridianCity_PokemonCenter_1F", - "tiles": [[7, 4]], - "facing": "north" - }, + "title": "The rival on Route 22, at the road's east end", + "start": {"map": "ViridianCity_Mart", "tiles": [[4, 3]], "facing": "west"}, "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" - }, { "id": "lead_lv49_for_rival_route22", "kind": "game_action", @@ -92,7 +68,7 @@ "menu": "full", "notes": { "checkpoint": [ - "Starts where 17.04 ends: Viridian's nurse. 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.04 is that entry.", + "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." ] } 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"} + } + } +} From c0fee6ba992f5d10f0528c86f12e6082f7167105 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 14:55:47 -0800 Subject: [PATCH 14/15] Gates: switch keys per floor, boulder buttons, and the stop risks through GatedModel Moved from the FRLG stack, where they were edited in game PRs: - f1aad341e: switch_key() (a switch one map owns is keyed by that map), switch_with_button() and MapSwitch::buttons read from the map JSON; - bc6a55867: GatedModel passes open_stop_risk() through to the inner model; - 9411b936a: GatedModel passes tap_stop_risk() through as well. The four headers and GateTiles.cpp are taken unchanged from frlg/stage20-league; MapData.cpp takes f1aad341e's buttons hunks only. (cherry picked from commits f1aad341e, bc6a55867 and 9411b936a, Pokemon/Navigation gate files only) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/Navigation/Pokemon_GateTiles.cpp | 19 +++++++++- .../Pokemon/Navigation/Pokemon_GateTiles.h | 10 ++++++ .../Pokemon/Navigation/Pokemon_GatedPlanner.h | 35 +++++++++++++++++-- .../Pokemon/Navigation/Pokemon_MapData.cpp | 8 +++++ .../Pokemon/Navigation/Pokemon_MapGates.h | 5 ++- 5 files changed, 72 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp index 2c3053b27d..bca7bbbdd8 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp @@ -10,6 +10,21 @@ 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){ @@ -23,7 +38,9 @@ const MapGate* gate_at(const MapData& map, const TilePos& pos){ bool gate_is_open(const MapData& map, const MapGate& gate, const GateState& state){ if (gate.kind == GateKind::SWITCH){ - return state.switch_on(gate.switch_id) == gate.open_when_on; + 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)); } diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h index 89a0c4fcd7..6a413df2a3 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h @@ -10,6 +10,7 @@ #ifndef PokemonAutomation_Pokemon_GateTiles_H #define PokemonAutomation_Pokemon_GateTiles_H +#include #include "Pokemon_GateState.h" #include "Pokemon_Grid.h" #include "Pokemon_MapData.h" @@ -18,6 +19,15 @@ 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); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h index fde399180f..1528831b52 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h @@ -23,6 +23,10 @@ * 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 @@ -33,8 +37,10 @@ #ifndef PokemonAutomation_Pokemon_GatedPlanner_H #define PokemonAutomation_Pokemon_GatedPlanner_H +#include #include #include +#include #include #include "Pokemon_ConnectedMaps.h" #include "Pokemon_GateTiles.h" @@ -45,6 +51,19 @@ 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{ @@ -86,6 +105,15 @@ class GatedModel{ 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; @@ -115,11 +143,12 @@ class GatedModel{ Step press_switch(const State& state, const MapSwitch& pressed, Direction direction) const{ Step step; step.next = state; - const bool now_on = pressed.toggle ? !state.gates.switch_on(pressed.id) : true; + 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(pressed.id); + step.next.gates.switches_on.insert(key); }else{ - step.next.gates.switches_on.erase(pressed.id); + step.next.gates.switches_on.erase(key); } step.action = ACTION_PRESS_SWITCH; step.ends_leg = true; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp index c47971e71f..e22233548a 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp @@ -565,6 +565,10 @@ MapStatue read_statue(const JsonObject& object, const std::string& 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; @@ -586,6 +590,7 @@ MapSwitch read_switch(const std::string& id, const JsonObject& object, const std 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; } @@ -675,6 +680,9 @@ void check_gates(const MapData& map, const std::string& where){ 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)); + } } } diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h index 8c2ef63083..11f902b09f 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h @@ -54,13 +54,16 @@ struct MapStatue{ // 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. +// `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 = {}; }; From 62a89d11e5df74bea6d44015db72218795351b44 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 14:59:59 -0800 Subject: [PATCH 15/15] Gates: OPEN_GATE and PRESS_SWITCH route leg actions, with their log text Moved from the FRLG stack, where 5f81d2a22 added them inside a game PR: a gated plan's legs that open a card-key gate or press a statue are logged as "open gate " and "press switch ". (cherry picked from commit 5f81d2a22, Pokemon_RouteLog.cpp and Pokemon_RouteLogTypes.h only) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp | 4 ++++ .../Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h | 4 ++++ 2 files changed, 8 insertions(+) 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.