From 71246afd0c702f447d6bb4a2737b2831d0c1ec43 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 09:28:24 -0800 Subject: [PATCH 1/6] FRLG AutoStory stage 4: Cerulean City Squash of fork PRs #211 and #212 (frlg/cerulean-gym at 3ad4d2477). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Menus/PokemonFRLG_SaveCardReader.cpp | 1 + .../Menus/PokemonFRLG_SaveCardReader.h | 8 +- .../Overworld/Maps/CeruleanCity.json | 10 +- .../Overworld/Maps/CeruleanCity_Gym.json | 116 ++++++++ .../Overworld/Maps/CeruleanCity_Mart.json | 86 ++++++ .../PokemonFRLG/Overworld/Maps/Route24.json | 5 + .../PokemonFRLG/Overworld/Maps/Route25.json | 200 ++++++++++++++ .../Overworld/Maps/Route25_SeaCottage.json | 66 +++++ .../Overworld/PokemonFRLG_OverworldMaps.cpp | 5 + .../Overworld/PokemonFRLG_OverworldMaps.h | 7 +- .../PokemonFRLG_OverworldMaps_Tests.cpp | 37 +++ .../PokemonFRLG_OverworldSim_Tests.cpp | 144 ++++++++++ .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 1 + .../PokemonFRLG_AutoStoryRunPlan_Tests.cpp | 249 +++++++++++++++++- .../PokemonFRLG_AutoStorySimulation_Tests.cpp | 81 ++++++ .../AutoStory/PokemonFRLG_AutoStoryTable.cpp | 222 ++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryTable.h | 16 +- .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 131 ++++++++- devtools/maps/frlg_maps.py | 4 + 19 files changed, 1357 insertions(+), 32 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity_Gym.json create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity_Mart.json create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route25.json create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route25_SeaCottage.json diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.cpp index 0793744ff9..9ec73b734a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.cpp @@ -70,6 +70,7 @@ class PlaceNameMatcher : public OCR::SmallDictionaryMatcher{ {"route-2", "Route 2"}, {"route-3", "Route 3"}, {"route-4", "Route 4"}, + {"cerulean-city", "Cerulean City"}, }){ JsonArray names; names.push_back(name); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.h index e7f81aa521..94514f94cf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.h @@ -4,9 +4,9 @@ * * Reads where the game would be saved: the place name in blue at the top * of the card the START menu's SAVE shows ("PALLET TOWN" over PLAYER, - * BADGES and TIME). It knows the places from a new game to Route 4, in - * English only so far: in another language nothing is read. Route 3 and - * Route 4 have no test capture yet. + * BADGES and TIME). It knows the places from a new game to Route 4, and + * Cerulean City, in English only so far: in another language nothing is + * read. Route 3, Route 4 and Cerulean City have no test capture yet. * */ @@ -31,7 +31,7 @@ namespace PokemonFRLG{ ImageFloatBox save_card_title_box(); // The place on the save card: "pallet-town", "viridian-city", -// "viridian-forest", "pewter-city", "route-1" to "route-4"; empty if it +// "viridian-forest", "pewter-city", "route-1" to "route-4", "cerulean-city"; empty if it // can't be read, as in a language the reader has no names for. std::string read_save_card_location(Logger& logger, Language language, const ImageViewRGB32& screen); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity.json index 10e47a673a..51f0256ec9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity.json @@ -91,6 +91,8 @@ ], "points": { "warp_3": [22, 19], + "warp_4": [31, 21], + "warp_6": [29, 28], "warp_7": [1, 12] }, "warps": [ @@ -119,7 +121,9 @@ { "x": 31, "y": 21, - "enter": "walk_into" + "enter": "walk_into", + "to_map": "CeruleanCity_Gym", + "to_point": "warp_1" }, { "x": 13, @@ -129,7 +133,9 @@ { "x": 29, "y": 28, - "enter": "walk_into" + "enter": "walk_into", + "to_map": "CeruleanCity_Mart", + "to_point": "warp_1" }, { "x": 1, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity_Gym.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity_Gym.json new file mode 100644 index 0000000000..519944eecb --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity_Gym.json @@ -0,0 +1,116 @@ +{ + "name": "CeruleanCity_Gym", + "source": { + "decomp_file": "data/maps/CeruleanCity_Gym/map.json", + "revision": "ce6406d8c2eaf46d543c8a2606de0c3cb1951982", + "date": "2026-10-31" + }, + "allow_running": false, + "tiles": [ + "#################", + "#####w#w.w#w#####", + "#################", + "#...............#", + "#......www......#", + "#.wwwwwwwwwwwww.#", + "#.wwwww...wwwww.#", + "#.ww.........ww.#", + "#.wwwww...ww.ww.#", + "#.wwwwwwwwww.ww.#", + "#.ww.........ww.#", + "#.ww.wwww.wwwww.#", + "#.ww.wwww.wwwww.#", + "#.ww......wwwww.#", + "#.wwwwwww.wwwww.#", + "#.wwwwwww.wwwww.#", + "#.wwww.....wwww.#", + "#.wwwwS...Swwww.#", + "#...............#", + "#################" + ], + "elevation": [ + "00000000000000000", + "00000000000000000", + "00000000000000000", + "03333333333333330", + "03333331113333330", + "03111111111111130", + "03111113331111130", + "03113333333331130", + "03111113331131130", + "03111111111131130", + "03113333333331130", + "03113111131111130", + "03113111130111130", + "03113333331111130", + "03111111131111130", + "03111111131111130", + "03111133333111130", + "03111103330111130", + "03333333333333330", + "00000000000000000" + ], + "points": { + "misty_front": [8, 7], + "warp_1": [8, 18] + }, + "warps": [ + { + "x": 7, + "y": 18, + "enter": "walk_into", + "to_map": "CeruleanCity", + "to_point": "warp_4" + }, + { + "x": 8, + "y": 18, + "enter": "walk_south", + "to_map": "CeruleanCity", + "to_point": "warp_4" + }, + { + "x": 9, + "y": 18, + "enter": "walk_into", + "to_map": "CeruleanCity", + "to_point": "warp_4" + } + ], + "objects": [ + { + "name": "swimmer_m_water", + "kind": "npc", + "x": 10, + "y": 12, + "facing": "west", + "trainer": { + "sight": 1 + } + }, + { + "name": "picnicker", + "kind": "npc", + "x": 4, + "y": 7, + "facing": "east", + "trainer": { + "sight": 4 + } + }, + { + "name": "misty", + "kind": "npc", + "x": 8, + "y": 6 + }, + { + "name": "gym_guy", + "kind": "npc", + "x": 7, + "y": 16 + } + ], + "flag_sets": {}, + "connections": [] +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity_Mart.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity_Mart.json new file mode 100644 index 0000000000..db4c9defee --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/CeruleanCity_Mart.json @@ -0,0 +1,86 @@ +{ + "name": "CeruleanCity_Mart", + "source": { + "decomp_file": "data/maps/CeruleanCity_Mart/map.json", + "revision": "ce6406d8c2eaf46d543c8a2606de0c3cb1951982", + "date": "2026-10-31" + }, + "allow_running": false, + "tiles": [ + "###########", + "###########", + "##.#......#", + "...#.......", + "####...##.#", + ".......##.#", + ".##....##.#", + "...........", + "###########" + ], + "elevation": [ + "00000000000", + "00000000000", + "00303333330", + "33003333333", + "00003330030", + "33333330030", + "30033330030", + "33333333333", + "00000000000" + ], + "points": { + "clerk_front": [4, 3], + "warp_1": [4, 7] + }, + "warps": [ + { + "x": 3, + "y": 7, + "enter": "walk_into", + "to_map": "CeruleanCity", + "to_point": "warp_6" + }, + { + "x": 4, + "y": 7, + "enter": "walk_south", + "to_map": "CeruleanCity", + "to_point": "warp_6" + }, + { + "x": 5, + "y": 7, + "enter": "walk_into", + "to_map": "CeruleanCity", + "to_point": "warp_6" + } + ], + "objects": [ + { + "name": "clerk", + "kind": "npc", + "x": 2, + "y": 3 + }, + { + "name": "woman_1", + "kind": "npc", + "x": 9, + "y": 2, + "wander": { + "x0": 5, + "y0": 2, + "x1": 10, + "y1": 2 + } + }, + { + "name": "youngster", + "kind": "npc", + "x": 1, + "y": 7 + } + ], + "flag_sets": {}, + "connections": [] +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route24.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route24.json index 2c3bd7ee03..c8402d903e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route24.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route24.json @@ -173,6 +173,11 @@ "side": "south", "to_map": "CeruleanCity", "offset": -12 + }, + { + "side": "east", + "to_map": "Route25", + "offset": 0 } ] } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route25.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route25.json new file mode 100644 index 0000000000..29dcb02843 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route25.json @@ -0,0 +1,200 @@ +{ + "name": "Route25", + "source": { + "decomp_file": "data/maps/Route25/map.json", + "revision": "ce6406d8c2eaf46d543c8a2606de0c3cb1951982", + "date": "2026-10-31" + }, + "tiles": [ + "########################################################################", + "########################################################################", + "############...#...#.....#.....#..........##############################", + ".~~~~~~~~......#...#.....#.....#..........####################wwww######", + ".~~~~~~~~................###.#............######S##D##########wwww######", + "................#.#.#....#...#.....#.........................#wwww######", + "vvvvvvvvvv##..##....#.##.#.........#.........................#wwwww#####", + "................#...#....#......##...........................#wwwwwww###", + ".............#..##..#...........#............................#wwwwwwwwww", + ".............#......#.#.........#..........wwwwww.....wwwwww.#wwwwwwwwww", + "###########################################wwwwww.....wwwwww.#wwwwwwwwww", + "...........................................wwwwww.....wwwwww.#wwwwwwwwww", + "#########################################....................#wwwwwwwwww", + "##############################################################wwwwwwwwww", + "#########################################wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww", + "#########################################wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww", + "#########################################wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww", + "#########################################wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww", + "#########################################wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww", + "#########################################wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww" + ], + "elevation": [ + "000000000000000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000000000000000000", + "000000000000333033303333303333303333333333000000000000000000000000000000", + "333333333333333033303333303333303333333333000000000000000000001111000000", + "333333333333333333333333300030333333333333000000000000000000001001000000", + "333333333333333303030333303330333330333333333333333333333333301001000000", + "000000000000330033330300303333333330333333333333333333333333301001100000", + "333333333333333303330333303333330033333333333333333333333333301000111000", + "333333333333303300330333333333330333333333333333333333333333301000001111", + "333333333333303333330303333333330333333333311111133333111111301000000000", + "000000000000000000000000000000000000000000011111133333111111301000000000", + "333333333333333333333333333333333333333333311111133333111111301000000000", + "000000000000000000000000000000000000000003333333333333333333301000000000", + "000000000000000000000000000000000000000000000000000000000000001000000000", + "000000000000000000000000000000000000000001111111111111111111111000000000", + "000000000000000000000000000000000000000001100000000000000000000000000000", + "000000000000000000000000000000000000000001000000000000000000000000000000", + "000000000000000000000000000000000000000001000000000000000000000000000000", + "000000000000000000000000000000000000000001000000000000000000000000000000", + "000000000000000000000000000000000000000001000000000000000000000000000000" + ], + "points": { + "warp_0": [51, 4] + }, + "warps": [ + { + "x": 51, + "y": 4, + "enter": "walk_into", + "to_map": "Route25_SeaCottage", + "to_point": "warp_1" + } + ], + "objects": [ + { + "name": "hiker", + "kind": "npc", + "x": 11, + "y": 4, + "facing": "east", + "trainer": { + "sight": 4 + } + }, + { + "name": "youngster", + "kind": "npc", + "x": 18, + "y": 2, + "facing": "south", + "trainer": { + "sight": 2 + } + }, + { + "name": "hiker", + "kind": "npc", + "x": 17, + "y": 7, + "facing": "east", + "trainer": { + "sight": 2 + } + }, + { + "name": "youngster", + "kind": "npc", + "x": 22, + "y": 4, + "trainer": { + "sight": 2, + "looks": [ + "north", + "east", + "south", + "west" + ] + } + }, + { + "name": "picnicker", + "kind": "npc", + "x": 22, + "y": 8, + "facing": "east", + "trainer": { + "sight": 2 + } + }, + { + "name": "hiker", + "kind": "npc", + "x": 27, + "y": 9, + "facing": "north", + "trainer": { + "sight": 3 + } + }, + { + "name": "camper", + "kind": "npc", + "x": 28, + "y": 4, + "facing": "south", + "trainer": { + "sight": 3 + } + }, + { + "name": "youngster", + "kind": "npc", + "x": 36, + "y": 4, + "trainer": { + "sight": 2, + "looks": [ + "north", + "east", + "south", + "west" + ] + } + }, + { + "name": "lass", + "kind": "npc", + "x": 42, + "y": 5, + "facing": "south", + "trainer": { + "sight": 3 + } + }, + { + "name": "item_ball", + "kind": "item", + "x": 26, + "y": 2, + "hide_flag": "FLAG_HIDE_ROUTE25_TM43" + }, + { + "name": "cut_tree", + "kind": "npc", + "x": 30, + "y": 3, + "hide_flag": "FLAG_TEMP_12" + }, + { + "name": "beauty", + "kind": "npc", + "x": 49, + "y": 10 + }, + { + "name": "man", + "kind": "npc", + "x": 49, + "y": 11 + } + ], + "flag_sets": {}, + "connections": [ + { + "side": "west", + "to_map": "Route24", + "offset": 0 + } + ] +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route25_SeaCottage.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route25_SeaCottage.json new file mode 100644 index 0000000000..0ec5259806 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/Maps/Route25_SeaCottage.json @@ -0,0 +1,66 @@ +{ + "name": "Route25_SeaCottage", + "source": { + "decomp_file": "data/maps/Route25_SeaCottage/map.json", + "revision": "ce6406d8c2eaf46d543c8a2606de0c3cb1951982", + "date": "2026-10-31" + }, + "allow_running": false, + "tiles": [ + "###############", + "###############", + "#.##########..#", + "###D######D#.##", + "..............#", + "....##........#", + "..............#", + "#.............#", + "#..............", + "###..........##", + "###############" + ], + "points": { + "warp_1": [7, 9] + }, + "warps": [ + { + "x": 6, + "y": 9, + "enter": "walk_into", + "to_map": "Route25", + "to_point": "warp_0" + }, + { + "x": 7, + "y": 9, + "enter": "walk_south", + "to_map": "Route25", + "to_point": "warp_0" + }, + { + "x": 8, + "y": 9, + "enter": "walk_into", + "to_map": "Route25", + "to_point": "warp_0" + } + ], + "objects": [ + { + "name": "bill", + "kind": "npc", + "x": 7, + "y": 5, + "hide_flag": "FLAG_HIDE_BILL_HUMAN_SEA_COTTAGE" + }, + { + "name": "clefairy", + "kind": "npc", + "x": 10, + "y": 6, + "hide_flag": "FLAG_HIDE_BILL_CLEFAIRY" + } + ], + "flag_sets": {}, + "connections": [] +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp index 96954b03cc..c859069ceb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp @@ -49,6 +49,11 @@ const char* const MAP_NAMES[] = { "CeruleanCity_PokemonCenter_1F", "CeruleanCity", "Route24", + // Cerulean City's Mart and Gym, and Route 25 to Bill's Sea Cottage. + "CeruleanCity_Mart", + "CeruleanCity_Gym", + "Route25", + "Route25_SeaCottage", "CeruleanCave_1F", "CeruleanCave_2F", "CeruleanCave_B1F", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h index cff0668eb5..76a83fa212 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h @@ -4,9 +4,10 @@ * * The FRLG maps the overworld routes know about so far: every map from a * new game in Pallet Town through Viridian City, Route 2 and Viridian - * Forest to Brock's gym in Pewter City; and Cerulean City, its Pokemon - * Center, Route 24 to its north, and the three floors of Cerulean Cave, - * where Mewtwo waits on B1F. + * Forest to Brock's gym in Pewter City, Route 3, Mt. Moon and Route 4; + * and Cerulean City, its Pokemon Center, Mart and Gym, Route 24 (Nugget + * Bridge) and Route 25 to Bill's Sea Cottage, and the three floors of + * Cerulean Cave, where Mewtwo waits on B1F. * * Each map is a JSON file, Maps/.json next to this file, generated by * devtools/maps/frlg_maps.py and built into the program by CMake diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp index d8083fe067..3777318e59 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp @@ -311,6 +311,42 @@ UnitTestResult test_mt_moon_closed_floor_wild(){ return true; } +// Whether a route plans from Cerulean's Pokemon Center, at its nurse, to +// `goal` on `maps`. +bool plans_from_cerulean_nurse(const std::vector& maps, const RouteGoal& goal){ + const MapPosition nurse{"CeruleanCity_PokemonCenter_1F", map_point(maps, "CeruleanCity_PokemonCenter_1F", "nurse_front")}; + return plan_overworld_route(maps, nurse, goal, default_route_costs(), Direction::NORTH).has_value(); +} + +// Cerulean City's Mart and Gym and Route 25's Sea Cottage load with the +// points the story walks to, and join the city: from its Pokemon Center +// a route plans to the Mart's clerk, to Misty, and north over Nugget +// Bridge (Route 24) and east along Route 25 into Bill's Sea Cottage. +UnitTestResult test_cerulean_maps(){ + const std::vector maps = overworld_maps(); + for (const char* name : {"CeruleanCity_Mart", "CeruleanCity_Gym", "Route25", "Route25_SeaCottage"}){ + if (built_in(maps, name) == nullptr){ + return std::string("Missing map ") + name + "."; + } + } + const MapPosition clerk{"CeruleanCity_Mart", map_point(maps, "CeruleanCity_Mart", "clerk_front")}; + const MapPosition misty{"CeruleanCity_Gym", map_point(maps, "CeruleanCity_Gym", "misty_front")}; + if (clerk.point != TilePos{4, 3} || misty.point != TilePos{8, 7}){ + return "Unexpected clerk_front or misty_front."; + } + if (!plans_from_cerulean_nurse(maps, RouteGoal{clerk, Direction::WEST})){ + return "No route from Cerulean's Pokemon Center to the Mart's clerk."; + } + if (!plans_from_cerulean_nurse(maps, RouteGoal{misty, Direction::NORTH})){ + return "No route from Cerulean's Pokemon Center to Misty."; + } + const MapPosition bill_front{"Route25_SeaCottage", {7, 7}}; + if (!plans_from_cerulean_nurse(maps, RouteGoal{bill_front, Direction::NORTH})){ + return "No route from Cerulean's Pokemon Center over Nugget Bridge and Route 25 into Bill's Sea Cottage."; + } + return true; +} + // A planned step walks where its map doesn't let the player run, and only // there: out of Pewter's Pokemon Center to the Gym. UnitTestResult test_walk_only_indoors(){ @@ -512,6 +548,7 @@ void add_tests_OverworldMaps(UnitTestDatabase& database){ database.add("Route 3, Route 4 and its Pokemon Center", test_route3_route4_maps); database.add("Mt. Moon joins Route 4's cave mouths", test_mt_moon_maps); database.add("Mt. Moon's floor closed on one side is wild", test_mt_moon_closed_floor_wild); + database.add("Cerulean's Mart and Gym, Route 25 and Bill's Sea Cottage", test_cerulean_maps); database.add("walks where running isn't allowed", test_walk_only_indoors); database.add("Route 4's Pokemon Center escalator", test_route4_center_escalator); database.add("trainer sight", test_trainer_sight); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index b1a6852e36..d50094c97d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -773,6 +773,145 @@ UnitTestResult test_mt_moon_way_out(){ return true; } +// Story row 00.14: from Route 4 east of Mt. Moon along the upper road to +// above the ledge row 9, out of Lass Crissy's line (75, 3); one step +// south hops the ledge onto the lower road two tiles down; from there +// into Cerulean City and its Pokemon Center by one door. No route plans +// past the ledge: the upper road reaches the city only by water. +UnitTestResult test_route4_to_cerulean(){ + const SimCase upper{.start = at("Route4", 32, 6), .facing = Direction::SOUTH, .goal = at("Route4", 93, 8)}; + const SimRun walk = run_case(upper); + if (!arrived(walk, upper.goal) || !walk.state.trainers_beaten.empty()){ + return "Expected the upper road walked to above the ledge, no trainer met:" + describe(walk); + } + OverworldSim sim(maps(), at("Route4", 93, 8), Direction::SOUTH); + sim.tap(Direction::SOUTH); + sim.watch({SimWatcher::MESSAGE}, std::chrono::milliseconds(2000)); + if (!(sim.state().position == at("Route4", 93, 10))){ + return "Expected the step south to hop the ledge onto (93, 10), not " + to_string(sim.state().position) + "."; + } + const SimCase lower{.start = at("Route4", 93, 10), .facing = Direction::SOUTH, .goal = at("CeruleanCity_PokemonCenter_1F", 7, 4)}; + const SimRun now = run_case(lower); + if (!arrived(now, lower.goal) || now.state.warps != 1 || !now.state.trainers_beaten.empty()){ + return "Expected Cerulean's Pokemon Center reached by its door, no trainer met:" + describe(now); + } + return true; +} + +// Story rows 00.14b and 00.14c in Cerulean Gym (pokefirered map.json): +// from the Center into the Gym, up column 9 to (9, 13), west to (4, 13), +// then to walls round the pool's west and north sides and west to (9, 7) +// below Misty's platform, meeting no one; and back from beside her (9, 6) +// the same way round to (9, 13) and out to the Center. +UnitTestResult test_cerulean_gym_walks(){ + const SimCase in{.start = at("CeruleanCity_PokemonCenter_1F", 7, 4), .facing = Direction::NORTH, .goal = at("CeruleanCity_Gym", 9, 13)}; + const SimRun entered = run_case(in); + if (!arrived(entered, in.goal) || entered.state.warps != 2 || !entered.state.trainers_beaten.empty()){ + return "Expected the Gym entered and (9, 13) reached, no trainer met:" + describe(entered); + } + SimCase west{.start = in.goal, .facing = Direction::NORTH, .goal = at("CeruleanCity_Gym", 4, 13)}; + west.route = std::vector{leg(Direction::WEST, 5, west.goal, true)}; + const SimRun walkway = run_case(west); + if (!arrived(walkway, west.goal) || !walkway.state.trainers_beaten.empty()){ + return "Expected the wall (4, 13) reached west from (9, 13), no trainer met:" + describe(walkway); + } + SimCase up{.start = west.goal, .facing = Direction::WEST, .goal = at("CeruleanCity_Gym", 9, 7)}; + up.route = std::vector{ + leg(Direction::NORTH, 3, at("CeruleanCity_Gym", 4, 10), true), + leg(Direction::EAST, 8, at("CeruleanCity_Gym", 12, 10), true), + leg(Direction::NORTH, 3, at("CeruleanCity_Gym", 12, 7), true), + leg(Direction::WEST, 3, up.goal, false), + }; + const SimRun walk = run_case(up); + if (!arrived(walk, up.goal) || !walk.state.trainers_beaten.empty()){ + return "Expected (9, 7) below Misty's platform reached round the pool, no trainer met:" + describe(walk); + } + SimCase out{.start = at("CeruleanCity_Gym", 9, 6), .facing = Direction::WEST, .goal = at("CeruleanCity_Gym", 9, 13)}; + out.route = std::vector{ + leg(Direction::SOUTH, 1, at("CeruleanCity_Gym", 9, 7), false), + leg(Direction::EAST, 3, at("CeruleanCity_Gym", 12, 7), true), + leg(Direction::SOUTH, 3, at("CeruleanCity_Gym", 12, 10), true), + leg(Direction::WEST, 8, at("CeruleanCity_Gym", 4, 10), true), + leg(Direction::SOUTH, 3, at("CeruleanCity_Gym", 4, 13), true), + leg(Direction::EAST, 5, out.goal, true), + }; + const SimRun back = run_case(out); + if (!arrived(back, out.goal) || !back.state.trainers_beaten.empty()){ + return "Expected (9, 13) reached from beside Misty round the pool, no trainer met:" + describe(back); + } + const SimCase nurse{.start = out.goal, .facing = Direction::EAST, .goal = at("CeruleanCity_PokemonCenter_1F", 7, 4)}; + const SimRun healed = run_case(nurse); + if (!arrived(healed, nurse.goal) || healed.state.warps != 2 || !healed.state.trainers_beaten.empty()){ + return "Expected the Center reached from (9, 13), no trainer met:" + describe(healed); + } + return true; +} + +// The straight ways in Cerulean Gym that 00.14b and 00.14c keep off: the +// step onto (9, 12) meets Swimmer Luis, and the step onto (8, 7), +// misty_front, Picnicker Diana. +UnitTestResult test_cerulean_gym_lines(){ + const struct{ + MapPosition from; + Direction direction; + MapPosition onto; + const char* trainer; + } LINES[] = { + {at("CeruleanCity_Gym", 9, 13), Direction::NORTH, at("CeruleanCity_Gym", 9, 12), "swimmer_m_water"}, + {at("CeruleanCity_Gym", 9, 7), Direction::WEST, at("CeruleanCity_Gym", 8, 7), "picnicker"}, + }; + for (const auto& line : LINES){ + SimCase c{.start = line.from, .facing = line.direction, .goal = line.onto}; + c.route = std::vector{leg(line.direction, 1, c.goal, false)}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal) || now.state.trainers_beaten != std::vector{line.trainer}){ + return std::format("Expected the {} fought on the step onto {}:", line.trainer, to_string(line.onto)) + describe(now); + } + } + return true; +} + +// Story rows 00.15 and 00.16: out of Cerulean's Pokemon Center by its mat +// to below the rival's trigger row, and on north across the city's edge +// onto Nugget Bridge, below Cale's row, meeting no one. +UnitTestResult test_cerulean_to_bridge(){ + const MapPosition nurse = at("CeruleanCity_PokemonCenter_1F", 7, 4); + for (const MapPosition& goal : {at("CeruleanCity", 23, 7), at("Route24", 11, 32)}){ + const SimCase c{.start = nurse, .facing = Direction::NORTH, .goal = goal}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal) || now.state.warps != 1 || !now.state.trainers_beaten.empty()){ + return "Expected " + to_string(goal) + " reached by the Center's mat, no trainer met:" + describe(now); + } + } + return true; +} + +// Story row 00.16 up Nugget Bridge: the short legs between the five +// trainers' rows meet no one; and the step from the tile below each row +// onto it is in that trainer's sight, beside them, so they fight there +// without walking: Cale, Ali, Timmy, Reli and Ethan. +UnitTestResult test_nugget_bridge_legs(){ + SimCase between{.start = at("Route24", 11, 31), .facing = Direction::NORTH, .goal = at("Route24", 11, 29)}; + between.route = std::vector{leg(Direction::NORTH, 2, between.goal, false)}; + const SimRun walk = run_case(between); + if (!arrived(walk, between.goal) || !walk.state.trainers_beaten.empty()){ + return "Expected the leg between two rows walked, no trainer met:" + describe(walk); + } + const struct{ + int row; + const char* trainer; + } LINES[] = {{31, "bug_catcher"}, {28, "lass"}, {25, "youngster"}, {22, "lass"}, {19, "camper"}}; + for (const auto& line : LINES){ + SimCase c{.start = at("Route24", 11, line.row + 1), .facing = Direction::NORTH, .goal = at("Route24", 11, line.row)}; + c.route = std::vector{leg(Direction::NORTH, 1, c.goal, false)}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal) || now.state.trainers_beaten != std::vector{line.trainer}){ + return std::format("Expected the {} on row {} fought beside the player:", line.trainer, line.row) + describe(now); + } + } + return true; +} + } @@ -798,6 +937,11 @@ void add_tests_OverworldSim(UnitTestDatabase& database){ database.add("Mt. Moon: a battle seen only after a leg to a wall", test_mt_moon_battle_seen_after_wall_leg); database.add("Mt. Moon: black after a leg not marked wild", test_mt_moon_black_after_unmarked_leg); database.add("Mt. Moon: a battle seen only before the next leg", test_mt_moon_battle_before_next_leg); + database.add("Route 4 east, down its ledge, to Cerulean's Pokemon Center", test_route4_to_cerulean); + database.add("Cerulean Gym: to Misty and back round the pool, no trainer met", test_cerulean_gym_walks); + database.add("Cerulean Gym: the straight ways meet Luis and Diana", test_cerulean_gym_lines); + database.add("Cerulean: the Center to the rival's row and Nugget Bridge", test_cerulean_to_bridge); + database.add("Nugget Bridge: each trainer met on the step onto their row", test_nugget_bridge_legs); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index a25dcbe4e2..9037adbee4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -324,6 +324,7 @@ std::string save_card_place(const std::string& map){ {"PewterCity", "pewter-city"}, {"Route3", "route-3"}, {"Route4", "route-4"}, + {"CeruleanCity", "cerulean-city"}, }; for (const auto& [prefix, place] : PLACES){ if (map == prefix || map.rfind(prefix + "_", 0) == 0){ 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 6036ac956f..59c7c827fa 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp @@ -3,18 +3,24 @@ * From: https://github.com/PokemonAutomation/ * * Which rows of the story table a run takes (plan_story_run()) with the - * RNG programs' handoffs on and off, and the rows the handoffs split or - * join. + * RNG programs' handoffs on and off, the rows the handoffs split or + * join, Misty in Cerulean Gym, and what 00.15 runs before the rival. * */ #include +#include #include #include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryGrind.h" +#include "PokemonFRLG_AutoStoryMart.h" #include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryTeach.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -111,10 +117,11 @@ class Test_RunPlan : public UnitTest{ }; void add_tests_RunPlan(UnitTestDatabase& database){ - const std::string TODAY = "00.01 00.02 00.03 00.04 00.05 00.06 00.07 00.08 00.09 00.10 00.11 00.12 00.12c 00.13"; + const std::string TODAY = "00.01 00.02 00.03 00.04 00.05 00.06 00.07 00.08 00.09 00.10 00.11 00.12 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16"; const RunPlanScenario scenarios[] = { {.name = "handoffs off: the story as before", .first = "00.01", .expected_ids = TODAY}, {.name = "handoffs off: a range", .first = "00.02", .last = "00.04", .expected_ids = "00.02 00.03 00.04"}, + {.name = "handoffs off: Mt. Moon to Nugget Bridge", .first = "00.13", .last = "00.16", .expected_ids = "00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16"}, { .name = "SID Helper: 00.01 stops on the keyboard", .first = "00.01", @@ -163,8 +170,8 @@ void add_tests_GiftRunPlan(UnitTestDatabase& database){ .expected_ids = "00.11 00.12", .expected_stop = StoryHandoff::GIFT_RNG, }, - {.name = "Gift RNG off: 00.12b is passed over", .first = "00.11", .expected_ids = "00.11 00.12 00.12c 00.13"}, - {.name = "Gift RNG off: 00.12b runs when started at", .first = "00.12b", .expected_ids = "00.12b 00.12c 00.13"}, + {.name = "Gift RNG off: 00.12b is passed over", .first = "00.11", .expected_ids = "00.11 00.12 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16"}, + {.name = "Gift RNG off: 00.12b runs when started at", .first = "00.12b", .expected_ids = "00.12b 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16"}, { .name = "Gift RNG: started at 00.12b, from the save beside the salesman", .first = "00.12b", @@ -179,7 +186,7 @@ void add_tests_GiftRunPlan(UnitTestDatabase& database){ .expected_ids = "", .expected_stop = StoryHandoff::GIFT_RNG, }, - {.name = "Starter RNG alone: 00.12b runs when started at", .first = "00.12b", .handoffs = {.starter_rng = true}, .expected_ids = "00.12b 00.12c 00.13"}, + {.name = "Starter RNG alone: 00.12b runs when started at", .first = "00.12b", .handoffs = {.starter_rng = true}, .expected_ids = "00.12b 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16"}, { .name = "Starter RNG first, with both on", .first = "00.03", @@ -248,6 +255,232 @@ UnitTestResult test_after_sid_helper_row(){ return true; } +// The index of the first step of `steps` from `from` that `matches`, or +// steps.size(). +size_t find_step(const std::vector& steps, size_t from, const std::function& matches){ + for (size_t c = from; c < steps.size(); c++){ + if (matches(steps[c])){ + return c; + } + } + return steps.size(); +} + +// Whether a route plans from `from` to `to` (ending facing as `to` does). +bool plans(const Pokemon::Pose& from, const Pokemon::Pose& to){ + const std::optional start = story_pose(from); + const std::optional goal = story_pose(to); + if (!start || !goal){ + return false; + } + return plan_overworld_route( + story_maps(), MapPosition{start->map, start->tile}, RouteGoal{MapPosition{goal->map, goal->tile}, goal->facing}, + default_route_costs(), start->facing.value_or(Direction::NORTH) + ).has_value(); +} + +// 00.15, before the rival, from the Center: first TM03 Water Pulse over +// Tail Whip if the lead doesn't know it, so the sim plays it in the +// GRIND; Potions from Cerulean's Mart (a loaded save's bag may hold too +// few for the wild battles a GRIND fights); then a GRIND on Route 4's +// grass east of Mt. Moon until the sim beats the rival 00.15b fights 70% +// or more, healing at Cerulean's Center; its trip there plans both ways. +UnitTestResult test_cerulean_mart_and_grind(){ + const StoryCheckpoint& row = story_checkpoints()[row_index("00.15")]; + const std::vector& steps = row.steps; + const std::optional start = row.start ? story_pose(*row.start) : std::nullopt; + if (!start || start->map != "CeruleanCity_PokemonCenter_1F"){ + return "00.15: expected it to start in Cerulean's Center."; + } + const std::optional teach = steps.empty() ? std::nullopt : parse_teach_variant(steps[0].variant); + if (!teach || teach->item != "tm03" || teach->move != "water-pulse" || teach->member != 0 || teach->forget_move != "tail-whip"){ + return "00.15: expected it to start with TM03 Water Pulse over the lead's Tail Whip."; + } + const size_t mart = find_step(steps, 0, [](const StoryStep& step){ + const std::optional plan = parse_mart_variant(step.variant); + return plan && plan->map == "CeruleanCity_Mart" && !plan->lines.empty() && plan->lines[0].item == "potion"; + }); + const std::optional rival = story_trainer("CeruleanCity", "rival_cerulean"); + const size_t grind = find_step(steps, mart, [&](const StoryStep& step){ + const std::optional plan = parse_grind_variant(step.variant); + return plan && plan->member == 0 && rival && plan->trainer == *rival && plan->min_chance == MIN_WIN_CHANCE + && plan->level > 25; + }); + if (mart == steps.size() || grind == steps.size()){ + return "00.15: expected a Cerulean Mart step buying Potions, then a GRIND of the lead until the rival is 70%, capped above Lv25."; + } + const std::optional clerk = mart > 0 && steps[mart - 1].target ? story_pose(*steps[mart - 1].target) : std::nullopt; + if (!clerk || clerk->map != "CeruleanCity_Mart"){ + return "00.15: expected the Mart step right after a route to the clerk."; + } + if (grind == 0 || !steps[grind - 1].target || !steps[grind].target){ + return "00.15: expected the GRIND right after a route to its patch, with the nurse as its target."; + } + const Pokemon::Pose& patch = *steps[grind - 1].target; + const Pokemon::Pose& nurse = *steps[grind].target; + const std::optional nurse_pose = story_pose(nurse); + if (!nurse_pose || nurse_pose->map != "CeruleanCity_PokemonCenter_1F" || !plans(patch, nurse) || !plans(nurse, patch)){ + return "00.15: expected the GRIND's trips to Cerulean's nurse and back to plan."; + } + return true; +} + +// 00.15b, the rival's battle as its own checkpoint, as every battle lost +// twice or more gets: it starts from a save, 00.15's on (23, 7) below his +// trigger with the nurse just before, so a verify run or a retry reloads +// right before him; and his is its only battle. First Water Pulse over +// Tail Whip if the lead doesn't know it: console B's save (2026-11-03) is +// past the TEACH that failed there, which does nothing once it is known. +UnitTestResult test_cerulean_rival_row(){ + const std::vector& checkpoints = story_checkpoints(); + const size_t index = row_index("00.15b"); + const StoryCheckpoint& rival = checkpoints[index]; + const std::optional start = rival.start ? story_pose(*rival.start) : std::nullopt; + if (!start || rival.live_start || start->map != "CeruleanCity" || !(start->tile == TilePos{23, 7}) + || save_card_place(start->map).empty() + ){ + return "00.15b: expected it to start from a save on (23, 7) in Cerulean City."; + } + std::string battles; + for (const StoryStep& step : rival.steps){ + battles += step.kind == StoryStepKind::BATTLE ? " " + step.name : ""; + } + if (battles != " rival_cerulean" || rival.steps.size() != 3 || rival.steps[1].name != "rival_trigger"){ + return "00.15b: expected a TEACH, the step onto his trigger and his battle; its battles:" + battles; + } + const std::optional teach = parse_teach_variant(rival.steps[0].variant); + if (rival.steps[0].kind != StoryStepKind::GAME || !teach || teach->item != "tm03" || teach->move != "water-pulse" + || teach->member != 0 || teach->forget_move != "tail-whip" + ){ + return "00.15b: expected it to start with TM03 Water Pulse over the lead's Tail Whip."; + } + const StoryCheckpoint& before = checkpoints[index - 1]; + const size_t n = before.steps.size(); + const std::optional end = n > 0 && before.steps[n - 1].target ? story_pose(*before.steps[n - 1].target) : std::nullopt; + if (before.id != "00.15" || n < 2 || before.steps[n - 2].kind != StoryStepKind::HEAL + || !end || end->map != start->map || !(end->tile == start->tile) + ){ + return "00.15: expected it to end with the nurse, then the walk to (23, 7) where 00.15b starts."; + } + for (const StoryStep& step : before.steps){ + if (step.kind == StoryStepKind::BATTLE){ + return "00.15: expected no trainer battle before its save; found " + step.name + "."; + } + } + return true; +} + +// The battles in `row`, each name after a space. +std::string battle_names(const StoryCheckpoint& row){ + std::string battles; + for (const StoryStep& step : row.steps){ + battles += step.kind == StoryStepKind::BATTLE ? " " + step.name : ""; + } + return battles; +} + +// 00.14b, before Misty: Potions at Cerulean's Mart, then into the Gym to +// a save on (9, 7), below her platform; no battle. 00.14c, Misty's battle +// as its own checkpoint: it starts from that save, talks to her from +// beside her, (9, 6), and hers is its only battle; then TM03 Water Pulse +// in place of Tail Whip. +UnitTestResult test_misty_rows(){ + const std::vector& checkpoints = story_checkpoints(); + const StoryCheckpoint& gym = checkpoints[row_index("00.14b")]; + const StoryCheckpoint& misty = checkpoints[row_index("00.14c")]; + if (checkpoints[row_index("00.14b") - 1].id != "00.14" || checkpoints[row_index("00.14c") + 1].id != "00.15"){ + return "Expected 00.14b and 00.14c between 00.14 and 00.15."; + } + const std::vector& steps = gym.steps; + const size_t mart = find_step(steps, 0, [](const StoryStep& step){ + const std::optional plan = parse_mart_variant(step.variant); + return plan && plan->map == "CeruleanCity_Mart" && !plan->lines.empty() && plan->lines[0].item == "potion"; + }); + if (mart == steps.size() || !battle_names(gym).empty()){ + return "00.14b: expected a Cerulean Mart step buying Potions and no battle; its battles:" + battle_names(gym); + } + const std::optional start = misty.start ? story_pose(*misty.start) : std::nullopt; + if (!start || misty.live_start || start->map != "CeruleanCity_Gym" || !(start->tile == TilePos{9, 7}) + || save_card_place(start->map).empty() + ){ + return "00.14c: expected it to start from a save on (9, 7) in Cerulean Gym."; + } + if (battle_names(misty) != " misty" || misty.steps.size() < 3 || misty.steps[1].kind != StoryStepKind::TALK + || misty.steps[2].name != "misty" + ){ + return "00.14c: expected a walk beside Misty, the talk and her battle, the only one; its battles:" + battle_names(misty); + } + const std::optional beside = misty.steps[0].target ? story_pose(*misty.steps[0].target) : std::nullopt; + if (!beside || !(beside->tile == TilePos{9, 6}) || beside->facing != Direction::WEST){ + return "00.14c: expected the talk from (9, 6), facing Misty (8, 6)."; + } + const size_t teach = find_step(misty.steps, 0, [](const StoryStep& step){ + const std::optional plan = parse_teach_variant(step.variant); + return plan && plan->item == "tm03" && plan->move == "water-pulse" && plan->member == 0 && plan->forget_move == "tail-whip"; + }); + if (teach == misty.steps.size()){ + return "00.14c: expected TM03 Water Pulse taught to the lead in place of Tail Whip."; + } + return true; +} + +// 00.14b in order (Misty lost to at Lv20, console B, run m51): the Mart +// first, Potions then Super Potions, the Potions enough for the GRIND's +// wild battles at the table's money floor and at least one Super Potion +// after them; a GRIND of the lead to Lv23 on Route 4, from a route to its +// patch, with Cerulean's nurse as its target; the nurse; then the walk +// into the Gym, ending on (9, 7). +UnitTestResult test_misty_grind_order(){ + const std::vector& steps = story_checkpoints()[row_index("00.14b")].steps; + std::optional plan; + const size_t mart = find_step(steps, 0, [&](const StoryStep& step){ + plan = parse_mart_variant(step.variant); + return plan && plan->map == "CeruleanCity_Mart"; + }); + if (mart == steps.size() || plan->lines.size() < 2 || plan->lines[0].item != "potion" || plan->lines[1].item != "super-potion" + || !plan->money_floor + ){ + return "00.14b: expected a Cerulean Mart step buying Potions, then Super Potions, with a money floor."; + } + const std::optional> buys = plan_mart_buys(mart_stock(plan->map), *plan, *plan->money_floor); + if (!buys || buys->size() < 2 || (*buys)[0].quantity < 2 || (*buys)[1].item != "super-potion"){ + return "00.14b: expected the money floor to buy 2 or more Potions and a Super Potion."; + } + const size_t grind = find_step(steps, mart, [](const StoryStep& step){ + const std::optional grind_plan = parse_grind_variant(step.variant); + return grind_plan && grind_plan->member == 0 && grind_plan->level >= 23; + }); + if (grind == steps.size() || !steps[grind - 1].target || !steps[grind].target){ + return "00.14b: expected a GRIND of the lead to Lv23 after the Mart, right after a route to its patch, the nurse its target."; + } + const std::optional patch = story_pose(*steps[grind - 1].target); + const std::optional nurse = story_pose(*steps[grind].target); + if (!patch || patch->map != "Route4" || !nurse || nurse->map != "CeruleanCity_PokemonCenter_1F" + || !plans(*steps[grind - 1].target, *steps[grind].target) || !plans(*steps[grind].target, *steps[grind - 1].target) + ){ + return "00.14b: expected the GRIND on Route 4, its trips to Cerulean's nurse and back planning."; + } + const size_t heal = find_step(steps, grind + 1, [](const StoryStep& step){ + return step.name == "heal_cerulean"; + }); + const size_t gym = find_step(steps, grind + 1, [](const StoryStep& step){ + const std::optional pose = step.target ? story_pose(*step.target) : std::nullopt; + return pose && pose->map == "CeruleanCity_Gym"; + }); + if (heal == steps.size() || gym == steps.size() || heal > gym){ + return "00.14b: expected the nurse after the GRIND, then the walk into the Gym."; + } + StoryPose end; + for (const StoryStep& step : steps){ + const std::optional pose = step.target ? story_pose(*step.target) : std::nullopt; + end = pose ? *pose : end; + } + if (end.map != "CeruleanCity_Gym"){ + return "00.14b: expected the row to end in Cerulean Gym."; + } + return true; +} + } @@ -256,6 +489,10 @@ void add_tests_AutoStoryRunPlan(UnitTestDatabase& database){ add_tests_GiftRunPlan(database); database.add("00.01b and 00.12b: back in after SID Helper and Gift RNG", test_after_sid_helper_row); database.add("00.04 and 00.04b: one checkpoint with Starter RNG off", test_starter_rows_joined); + database.add("00.15: Potions at Cerulean's Mart and a GRIND before the rival", test_cerulean_mart_and_grind); + database.add("00.15b: the rival's battle alone, from a save before him", test_cerulean_rival_row); + database.add("00.14b and 00.14c: Cerulean Gym, then Misty alone from a save before her", test_misty_rows); + database.add("00.14b: Potions and Super Potions, a GRIND to Lv23, the nurse, then the Gym", test_misty_grind_order); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp index 53b2da73ad..23353dc736 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include "Common/Cpp/Exceptions.h" @@ -24,6 +25,7 @@ #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_AutoStoryTable.h" namespace PokemonAutomation{ @@ -378,6 +380,84 @@ UnitTestResult test_gives_up_after_attempts(){ return true; } +// The route the program walks for `step`, a ROUTE or LEGS, from `at`: +// planned, or the legs laid out. +std::optional> walked_route(const StoryPose& at, const StoryStep& step){ + const MapPosition start{at.map, at.tile}; + if (step.kind == StoryStepKind::LEGS){ + return fixed_route(story_maps(), start, step.legs); + } + const std::optional target = story_pose(*step.target); + const RouteGoal goal{{target->map, target->tile}, target->facing}; + return plan_overworld_route(story_maps(), start, goal, default_route_costs(), at.facing); +} + +// Walks `step` of 00.14 on `sim` from `at`, where the table says the +// player stands, and moves `at` to where it says the step ends. Returns +// the failure, or empty. +std::string walk_on_sim(OverworldSim& sim, StoryPose& at, const StoryStep& step){ + const std::string where = "00.14/" + step.name + ": "; + // A walk that ends on an open leg may leave the player short of it. + bool open_end = false; + if (step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS){ + const std::optional> route = walked_route(at, step); + if (!route || route->empty()){ + return where + "no route from " + to_string(MapPosition{at.map, at.tile}) + "."; + } + const RoutePlanning planning{.maps = &story_maps(), .start = MapPosition{at.map, at.tile}, .label = step.name}; + const std::string failure = OverworldSimWalker(sim).run(*route, planning); + if (!failure.empty()){ + return where + failure + " On " + to_string(sim.state().position) + "."; + } + const RouteStep& last = route->back(); + open_end = last.action == RouteAction::WALK && !last.to_wall && !last.warps; + at = StoryPose{last.end.map, last.end.point, last.facing_after}; + }else if (step.kind == StoryStepKind::STEP){ + if (sim.state().facing != step.direction){ + sim.tap(step.direction); + } + sim.tap(step.direction); + sim.watch({SimWatcher::MESSAGE}, std::chrono::milliseconds(2000)); + at = *story_pose(*step.pose_after); + } + if (!open_end && !(sim.state().position == MapPosition{at.map, at.tile})){ + return where + "expected " + to_string(MapPosition{at.map, at.tile}) + ", but on " + to_string(sim.state().position) + "."; + } + return ""; +} + +// Console B, 2026-11-03 (row 00.14): the open leg east from Route 4 +// into Cerulean City ended a tile short, on (6, 20), with nothing on +// screen. No hold to a wall finds the player there, and the walk went on +// a column off, the hold south stopped by the fence on (6, 23), to a +// wall below a row of houses, not the Pokemon Center's door. From the +// foot of Route 4's ledge, the row's walks on the sim reach the nurse +// with that leg whole or a tile short. +UnitTestResult test_cerulean_entry_short(){ + const std::vector& rows = story_checkpoints(); + const auto row = std::find_if(rows.begin(), rows.end(), [](const StoryCheckpoint& data){ return data.id == "00.14"; }); + if (row == rows.end()){ + return "No checkpoint 00.14."; + } + const auto hop = std::find_if(row->steps.begin(), row->steps.end(), [](const StoryStep& step){ return step.name == "ledge_hop"; }); + if (hop == row->steps.end() || !hop->pose_after){ + return "00.14: no ledge_hop."; + } + for (int short_by : {0, 1}){ + StoryPose at = *story_pose(*hop->pose_after); + SimScript script; + script.short_holds[1] = short_by; + OverworldSim sim(story_maps(), MapPosition{at.map, at.tile}, *at.facing, script); + for (auto step = hop + 1; step != row->steps.end() && step->kind != StoryStepKind::HEAL; ++step){ + const std::string failure = walk_on_sim(sim, at, *step); + if (!failure.empty()){ + return std::format("Entry {} tile(s) short: ", short_by) + failure; + } + } + } + return true; +} + } @@ -389,6 +469,7 @@ void add_tests_AutoStorySimulation(UnitTestDatabase& database){ add("start and end checkpoints", test_start_and_end); add("a failed walk reloads its checkpoint's save", test_retry_from_save); add("a battle lost every time stops after 3 attempts", test_gives_up_after_attempts); + add("00.14 into Cerulean, the entry leg a tile short", test_cerulean_entry_short); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index 91d4112d97..0a7e4a6f87 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -6,8 +6,11 @@ #include "PokemonFRLG_AutoStoryCapture.h" #include "PokemonFRLG_AutoStoryChoice.h" +#include "PokemonFRLG_AutoStoryGrind.h" +#include "PokemonFRLG_AutoStoryMart.h" #include "PokemonFRLG_AutoStoryPcStorage.h" #include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryTeach.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -37,6 +40,11 @@ const char* const ROUTE4 = "Route4"; const char* const ROUTE4_CENTER = "Route4_PokemonCenter_1F"; const char* const MT_MOON_1F = "MtMoon_1F"; const char* const MT_MOON_B2F = "MtMoon_B2F"; +const char* const CERULEAN = "CeruleanCity"; +const char* const CERULEAN_CENTER = "CeruleanCity_PokemonCenter_1F"; +const char* const CERULEAN_MART = "CeruleanCity_Mart"; +const char* const CERULEAN_GYM = "CeruleanCity_Gym"; +const char* const ROUTE24 = "Route24"; Pokemon::Pose at(const char* map, int x, int y, std::optional facing = std::nullopt){ return to_pose(StoryPose{map, {x, y}, facing}); @@ -94,6 +102,16 @@ StoryStep step_into(std::string name, Direction direction, std::string why){ return step; } +// A step the way a ledge faces, from the tile before it: the player hops +// it and lands on `landing`, two tiles on. Planned routes never hop a +// ledge (they hold into walls, and a held ledge hops), so where the only +// way on is down a ledge the table takes it as this one step. +StoryStep hop(std::string name, Direction direction, Pokemon::Pose landing, std::string why){ + StoryStep step = step_into(std::move(name), direction, std::move(why)); + step.pose_after = std::move(landing); + return step; +} + StoryStep answer(std::string name, bool yes, std::string why){ StoryStep step = make(StoryStepKind::ANSWER, std::move(name), std::move(why)); step.yes = yes; @@ -468,6 +486,209 @@ StoryCheckpoint mt_moon(){ }); } +// Route 4 east of Mt. Moon (Route4 map.json) joins Cerulean City at its +// east end (x 107; Route 4's row 3 is the city's row 13). Its upper road +// (rows 2..8) reaches the city only by water: the way on by land is down +// the ledge row 9 at x 90..96 to the lower road (rows 10..12), which +// joins the city's rows 20..22. Lass Crissy (75, 3) faces east, sight 4, +// over row 3 from x 76 to 79; the way east keeps out of her line and off +// the grass south of the road (75..87, 11..17). +// +// The open leg east across the city's edge ended a tile short on the +// console (2026-11-03: on (6, 20), not (7, 20)), and no hold to a wall +// in the city's west end finds the player from there: the next hold +// south met the fence on (6, 23) and the walk went on a column off. So +// the entry ends on (9, 20), and only legs to walls follow: north up +// column 9 (or 8, a tile short) to row 12, west to (8, 12), east to +// (30, 12) beside the policeman (31, 12), south to (30, 17), west to +// (25, 17), and down the ledge row 18 to (25, 19), a few tiles from the +// door (22, 19). The way keeps out of the boy's (16, 18..24) and the +// balding man's (8..10, 22..24) wander boxes. +StoryCheckpoint route4_to_cerulean(){ + return row("00.14", "Route 4 east to Cerulean's Pokemon Center", at(ROUTE4, 32, 6, SOUTH), after_brock(), StartMenu::FULL, { + running(route("above_ledge", at(ROUTE4, 93, 8, SOUTH), "east along Route 4's upper road to above the ledge row 9")), + hop("ledge_hop", SOUTH, at(ROUTE4, 93, 10, SOUTH), "down the ledge (93, 9) to the lower road"), + running(route("cerulean_entry", at(CERULEAN, 9, 20, EAST), "east into Cerulean City, to (9, 20) below column 9")), + running(legs("above_city_ledge", {{NORTH, 8}, {WEST, 1}, {EAST, 22}, {SOUTH, 5}, {WEST, 5}}, "to walls: (9, 12), (8, 12), (30, 12), (30, 17), (25, 17)")), + hop("city_ledge_hop", SOUTH, at(CERULEAN, 25, 19, SOUTH), "down the ledge (25, 18)"), + running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "west along row 20 to the Pokemon Center's door (22, 19)")), + heal("heal_cerulean"), + }); +} + +// Cerulean Gym (pokefirered CeruleanCity_Gym map.json and scripts.inc): +// a pool with walkways. Misty (8, 6) stands on a platform (7..9, 6) above +// row 7. Picnicker Diana (4, 7) faces east, sight 4, over (5..8, 7), so +// misty_front (8, 7) is in her line; Swimmer Luis (10, 12) in the water +// faces west, sight 1, over (9, 12), on column 9 north of the door. No +// gym trainer has to be fought for Misty, so neither is: from the door up +// column 9 to row 13 (a route there, so the planner's walk to a wall +// doesn't run on past it through (9, 12)), west to (4, 13), and to walls +// round the pool's west and north sides, (4, 10), (12, 10), (12, 7), then +// west to (9, 7), the tile below the platform's east end, out of Diana's +// line. 00.14c steps up onto (9, 6) and talks to Misty from beside her. +// +// Misty beat a Lv20 Wartortle (console B, run m51), so first a GRIND to +// Lv23 on 00.15's patch. Gen 3 numbers (pokefirered: her mons have IV 0; +// Wartortle taken at IV 15, no EVs): Starmie Lv21 has 56 HP, Atk 36, SpA +// 47, SpD 40. Bite is Dark, special in Gen 3, no STAB, x2 on Psychic: at +// Lv23 (SpA 39) it does 23..28, three hits (two on top rolls); at Lv20, +// 20..24. Her Swift (physical, 60) does 9..11 to a Lv23 Wartortle (about +// 67 HP, Def 45) and Water Pulse (STAB, resisted) 8..10: 6 or more hits, +// though m51 saw about 20 a turn. Her Recover (28) and Super Potion undo +// a Bite, so the margin is in Bite's damage. +// +// The Mart comes before the GRIND: its wild battles are fought only with +// 2 or more Potions, and 00.14's save has none (m51 met Misty with only +// the 5 this row bought). 5 Potions (row 3, 300 each), then up to 3 Super +// Potions (row 2, 700), last so they take the Items pocket's last row; +// the battle doesn't use them yet. The money box can't be read, so the +// floor stands for it, and a floor above the money fails the step (the +// quantity box wraps). Prizes (pokefirered: 4 x last level x the class's +// factor) from a new game's 3000, less Viridian's 2000 and the Magikarp's +// 500: Liam 220, Brock 1400, Route 3's bug catchers 360, the Mt. Moon +// grunt 416 and Miguel 288 (the first rival's 80 only if won), at least +// 3184 here. Floor and budget 3000: 5 Potions and 2 Super Potions, 2900. +// Misty's 2100 (4 x 21 x 25) then leaves 00.15 its floor of 1500. Then the +// nurse, and the save before Misty, so her battle is its own checkpoint, +// 00.14c, verified and retried from it. 00.15's GRIND then fights +// until the sim beats the Cerulean rival often enough. +StoryCheckpoint cerulean_gym(){ + const MartPlan supplies{ + .map = CERULEAN_MART, + .lines = {{.item = "potion", .quantity = 5}, {.item = "super-potion", .quantity = 3}}, + .budget = 3000, + .money_floor = 3000, + }; + const GrindPlan to_lv23{.member = 0, .level = 23, .max_encounters = 100, .pace = WEST, .heal_every = 0}; + return row("00.14b", "Cerulean: Potions, a GRIND to Lv23, then into the Gym, saved below Misty's platform", at(CERULEAN_CENTER, 7, 4, NORTH), after_brock(), StartMenu::FULL, { + running(route("mart_clerk", at(CERULEAN_MART, 4, 3, WEST), "out of the Center to the Mart's clerk")), + mart_step("buy_potions", "5 Potions for the GRIND's wild battles, then Super Potions as the money allows", supplies), + running(route("grind_patch", at(ROUTE4, 86, 16, WEST), "west out of the city along Route 4's lower road onto its grass's east edge")), + grind_step("grind_to_lv23", "wild battles until the lead is Lv23, where Bite takes Starmie in three", to_lv23, at(CERULEAN_CENTER, 7, 4, NORTH)), + running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "back to the Center: Misty's battle starts at full HP and PP")), + heal("heal_cerulean"), + running(route("gym_below_luis", at(CERULEAN_GYM, 9, 13), "into the Gym, up column 9 to row 13, short of Luis's (9, 12)")), + running(legs("gym_west_walkway", {{WEST, 5}}, "west to the wall (4, 13)")), + running(legs("below_misty_platform", {{NORTH, 3}, {EAST, 8}, {NORTH, 3}, {WEST, 3}}, "walls (4, 10), (12, 10), (12, 7), then to (9, 7), out of Diana's line")), + }); +} + +// Misty (TRAINER_LEADER_MISTY: Staryu Lv18, Starmie Lv21), talked to from +// (9, 6), beside her on the platform. Her win text runs on to the CASCADE +// BADGE, TM03 (Water Pulse) and its explanation, all read with the +// battle's. Bite is chosen against her party (Starmie is Water/Psychic). +// Back to the nurse round the pool's west side, out of Luis's line; then +// Water Pulse in place of Tail Whip, last, at the Center, from the bag's +// TM CASE. Ends where 00.15 starts. +StoryCheckpoint misty(){ + const TeachPlan water_pulse{.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}; + return row("00.14c", "Cerulean Gym: Misty, then Water Pulse", at(CERULEAN_GYM, 9, 7, WEST), after_brock(), StartMenu::FULL, { + running(route("beside_misty", at(CERULEAN_GYM, 9, 6, WEST), "up onto (9, 6), facing Misty (8, 6)")), + talk("challenge_misty", "Misty's speech"), + battle("misty", at(CERULEAN_GYM, 9, 6, WEST), false, "Staryu and Starmie, with Bite; CASCADE BADGE and TM03"), + running(legs("gym_way_out", {{SOUTH, 1}, {EAST, 3}, {SOUTH, 3}, {WEST, 8}, {SOUTH, 3}, {EAST, 5}}, "walls (12, 7), (12, 10), (4, 10), (4, 13), (9, 13), round Luis's (9, 12)")), + running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "down column 9 out of the Gym, to the Center")), + heal("heal_cerulean"), + teach_step("teach_water_pulse", "TM03 Water Pulse in place of Tail Whip", water_pulse), + }); +} + +// Before the rival north of Cerulean (cerulean_rival()), from the +// Center: first TM03 Water Pulse over Tail Whip, if the lead doesn't know +// it yet, so the GRIND's sim plays it (a run without TM03 from Misty +// skips the step). Then 5 Potions at the Mart +// (CeruleanCity_Mart_Items: POTION is row 3, 300 each; Mt. Moon's +// trainers leave well over the floor), then a GRIND on Route 4's grass +// east of Mt. Moon (75..86, 11..17; Spearow, Rattata, Ekans and Mankey +// around Lv10, about 80 EXP each), healing at the Center, until the +// battle sim beats the rival 00.15b fights 70% or more: the win chance +// his battle refuses below. Console B's Wartortle (Lv22, 65 HP, Water +// Pulse) is about 42% there and 76% at Lv25; Lv28 (about 88%, some 120 +// battles from Lv22) is the cap. Then the nurse, and the save on (23, 7), +// the tile below his trigger: his battle is its own checkpoint, 00.15b, +// verified and retried from this save. +StoryCheckpoint cerulean_grind(){ + const TeachPlan water_pulse{.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}; + const MartPlan potions{.map = CERULEAN_MART, .lines = {{.item = "potion", .quantity = 5}}, .budget = 1500, .money_floor = 1500}; + const GrindPlan for_rival{ + .member = 0, .level = 28, .max_encounters = 150, .pace = WEST, .heal_every = 0, + .trainer = std::string(story_trainer(CERULEAN, "rival_cerulean").value_or("")), .min_chance = MIN_WIN_CHANCE, + }; + return row("00.15", "Cerulean: Water Pulse, Potions, a GRIND until the rival is winnable, then saved below his trigger", at(CERULEAN_CENTER, 7, 4, NORTH), after_brock(), StartMenu::FULL, { + teach_step("teach_water_pulse", "TM03 Water Pulse in place of Tail Whip, unless the lead knows it or there is no TM03", water_pulse), + running(route("mart_clerk", at(CERULEAN_MART, 4, 3, WEST), "out of the Center to the Mart's clerk")), + mart_step("buy_potions", "5 Potions: the GRIND fights wild battles only with 2 or more", potions), + running(route("grind_patch", at(ROUTE4, 86, 16, WEST), "west out of the city along Route 4's lower road onto its grass's east edge")), + grind_step("grind_for_rival", "wild battles until the sim beats the rival 70% or more, Lv28 at most; the nurse when hurt or low on PP", for_rival, at(CERULEAN_CENTER, 7, 4, NORTH)), + running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "back to the Center: the rival's battle starts at full HP and PP")), + heal("heal_cerulean"), + running(route("below_rival_trigger", at(CERULEAN, 23, 7, NORTH), "out of the Center, north up to (23, 7), short of the trigger row 6")), + }); +} + +// The rival north of Cerulean (CeruleanCity scripts.inc): the only way +// north to Nugget Bridge is columns 22..24, and a step onto row 6 there +// (CeruleanCity_EventScript_RivalTrigger*, VAR_MAP_SCENE_CERULEAN_CITY_RIVAL +// 0) brings him down to the player. From the middle, (23, 6), he stops +// at (23, 5); after the battle he walks round the player and off south, +// and the player, turning to watch him, ends facing south. His FAME +// CHECKER's text is read to the overworld with the battle's. For a player +// who took Squirtle he has Pidgeotto Lv17, Abra Lv16, Rattata Lv15 and +// Bulbasaur Lv18 (sParty_RivalCeruleanBulbasaur), whose Vine Whip and +// Sleep Powder are the danger. The row starts from 00.15's save below the +// trigger, and saves after him. First TM03 Water Pulse over Tail Whip (from +// the bag, where the player stands), if the lead doesn't know it yet: +// console B's save (2026-11-03) is past Misty's TEACH, which failed there. +// Where she taught it, the step reads the moves and does nothing. +StoryCheckpoint cerulean_rival(){ + const TeachPlan water_pulse{.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}; + return row("00.15b", "Cerulean: Water Pulse if not known, then the rival north of the city", at(CERULEAN, 23, 7, NORTH), after_brock(), StartMenu::FULL, { + teach_step("teach_water_pulse", "TM03 Water Pulse in place of Tail Whip, unless the lead knows it", water_pulse), + step_into("rival_trigger", NORTH, "onto (23, 6), the middle trigger: \"Yo! !\""), + battle("rival_cerulean", at(CERULEAN, 23, 6, SOUTH), false, "Pidgeotto, Abra, Rattata and Bulbasaur; then the FAME CHECKER"), + }); +} + +// Nugget Bridge (Route24 map.json) is x 10..12 from row 32 north to row +// 16, the city's columns 22..24 (offset 12). Its five trainers stand on +// it facing across, sight 2, so each line crosses the middle column 11 +// on the trainer's row: Bug Catcher Cale (12, 31), Lass Ali (10, 28), +// Youngster Timmy (12, 25), Lass Reli (10, 22) and Camper Ethan (12, 19). +// Each is fought on the step onto their row, beside them: they don't +// walk, and the player keeps facing north. Two tiles separate the rows, +// walked as one short leg. Then the Rocket (12, 15): the step onto +// (11, 15) (Route24_EventScript_RocketTriggerRight, VAR_MAP_SCENE_ROUTE24 +// 0) gives the NUGGET, "join Team Rocket", and his battle; he only turns, +// and the player turns east to him. Camper Shane (5, 21) looks north +// from the west bank, off the way. +StoryCheckpoint nugget_bridge(){ + return row("00.16", "Nugget Bridge: the nurse, five trainers and the Rocket", at(CERULEAN, 23, 6, SOUTH), after_brock(), StartMenu::FULL, { + running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "back to the Center after the rival, before Nugget Bridge")), + heal("heal_cerulean"), + running(route("below_cale_line", at(ROUTE24, 11, 32, NORTH), "out of the Center, north past the rival's row onto the bridge, below Cale's row")), + step_into("cale_line", NORTH, "onto (11, 31), beside Cale"), + battle("bug_catcher_cale", at(ROUTE24, 11, 31, NORTH), false, "his Bug Pokemon"), + running(legs("below_ali_line", {{NORTH, 2}}, "up to (11, 29)")), + step_into("ali_line", NORTH, "onto (11, 28), beside Ali"), + battle("lass_ali", at(ROUTE24, 11, 28, NORTH), false, "her Pokemon"), + running(legs("below_timmy_line", {{NORTH, 2}}, "up to (11, 26)")), + step_into("timmy_line", NORTH, "onto (11, 25), beside Timmy"), + battle("youngster_timmy", at(ROUTE24, 11, 25, NORTH), false, "his Pokemon"), + running(legs("below_reli_line", {{NORTH, 2}}, "up to (11, 23)")), + step_into("reli_line", NORTH, "onto (11, 22), beside Reli"), + battle("lass_reli", at(ROUTE24, 11, 22, NORTH), false, "her Pokemon"), + running(legs("below_ethan_line", {{NORTH, 2}}, "up to (11, 20)")), + step_into("ethan_line", NORTH, "onto (11, 19), beside Ethan"), + battle("camper_ethan", at(ROUTE24, 11, 19, NORTH), false, "his Pokemon"), + // A route, not legs: the nurse may have been needed. + ready("ready_for_rocket", at(CERULEAN_CENTER, 7, 4, NORTH), "items for a status or low HP; the nurse only if they can't"), + running(route("below_rocket_trigger", at(ROUTE24, 11, 16, NORTH), "up the bridge to below the Rocket's trigger (11, 15)")), + step_into("rocket_trigger", NORTH, "onto (11, 15), beside the Rocket"), + battle("rocket_grunt", at(ROUTE24, 11, 15, EAST), false, "the NUGGET, then Ekans and Zubat, Lv15"), + }); +} + } @@ -475,6 +696,7 @@ const std::vector& story_checkpoints(){ static const std::vector checkpoints{ new_game(), after_sid_helper(), leave_house(), oaks_trigger(), to_starter_ball(), starter(), parcel(), pokedex(), shopping(), forest(), brock(), running_shoes(), route3(), magikarp_salesman(), after_gift_rng(), magikarp_to_box(), mt_moon(), + route4_to_cerulean(), cerulean_gym(), misty(), cerulean_grind(), cerulean_rival(), nugget_bridge(), }; return checkpoints; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h index d7421214f1..153a4f1e8b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h @@ -3,10 +3,11 @@ * From: https://github.com/PokemonAutomation/ * * FireRed from a new game to the Boulder Badge, the Running Shoes, Route - * 3 to the Magikarp salesman in Route 4's Pokemon Center, and through Mt. - * Moon to Route 4 east of it, as story checkpoints 00.01 to 00.13, each - * saved at its end. After 00.10 every route and leg runs. Taken from a - * by-hand run on console B (2026-11-01) and the pokefirered map scripts. + * 3 to the Magikarp salesman in Route 4's Pokemon Center, through Mt. + * Moon to Route 4 east of it, and on to Cerulean City, Misty, its rival + * and Nugget Bridge, as story checkpoints 00.01 to 00.16, each saved at its + * end. After 00.10 every route and leg runs. Taken from a by-hand run on + * console B (2026-11-01) and the pokefirered map scripts. * */ @@ -22,10 +23,13 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -// Checkpoints 00.01 to 00.13, in order, with 00.01b, the way back in after +// Checkpoints 00.01 to 00.16, in order, with 00.01b, the way back in after // SID Helper, after 00.01, 00.04 split in two at Squirtle's ball for // Starter RNG: 00.04 and 00.04b, 00.12b, the way back in after Gift RNG, -// after 00.12, and 00.12c, the Magikarp put in BOX 1, after it. +// after 00.12, 00.12c, the Magikarp put in BOX 1, after it, 00.14b and +// 00.14c, Cerulean Gym to a save below Misty's platform and Misty alone +// from it, and 00.15b, the rival in Cerulean alone, from 00.15's save +// below his trigger. const std::vector& story_checkpoints(); 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 cd22061a59..af9c26cf8e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -23,6 +23,7 @@ #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" #include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryGrind.h" #include "PokemonFRLG_AutoStoryPcStorage.h" #include "PokemonFRLG_AutoStoryTable.h" @@ -215,8 +216,8 @@ UnitTestResult check_checkpoint(const StoryCheckpoint& checkpoint, StoryPose& po UnitTestResult test_routes_and_chain(){ const std::vector& checkpoints = story_checkpoints(); - if (checkpoints.size() != 17 || checkpoints[0].start){ - return "Expected 17 checkpoints, the first from a new game."; + if (checkpoints.size() != 23 || checkpoints[0].start){ + return "Expected 23 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ @@ -524,8 +525,12 @@ UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::set{}){ - if (const std::string problem = tile_problem(tile, beaten); !problem.empty()){ + const StoryPose end = to_patch ? one_tile(*step.target) : StoryPose{}; + const bool patch = to_patch && tile.map == end.map && tile.point == end.tile; + if (const std::string problem = tile_problem(tile, beaten); !problem.empty() && !(patch && problem.starts_with("in the grass"))){ return where + problem; } } @@ -552,12 +557,12 @@ UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::set beaten; bool has_shoes = false; @@ -569,8 +574,8 @@ UnitTestResult test_trainer_lines(){ } has_shoes = has_shoes || checkpoint.id == "00.10"; } - if (beaten.size() != 4){ - return "Expected to fight Colton, Greg and James on Route 3 and the Grunt at (12, 20) in Mt. Moon; the table fights " + if (beaten.size() != 9){ + return "Expected to fight Colton, Greg and James on Route 3, the Grunt at (12, 20) in Mt. Moon and Nugget Bridge's five; the table fights " + std::to_string(beaten.size()) + " trainers."; } return true; @@ -594,6 +599,105 @@ UnitTestResult test_robin_crossing(){ return "No step 00.12/route4_nurse."; } +// A scene the table starts on a step onto its trigger, and the walks of +// its checkpoint before that step, which keep off the trigger's tiles: +// the maps have no triggers, so a route over one would start the scene +// part-way. +struct TriggerCase{ + std::string checkpoint; + std::string step; + std::string map; + // The trigger's tiles: row `y` from `x0` to `x1`. + int y = 0; + int x0 = 0; + int x1 = 0; + // The tile the step lands on. + int onto_x = 0; +}; + +const StoryCheckpoint* find_checkpoint(const std::string& id){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + if (checkpoint.id == id){ + return &checkpoint; + } + } + return nullptr; +} + +UnitTestResult check_trigger(const TriggerCase& c){ + const StoryCheckpoint* checkpoint = find_checkpoint(c.checkpoint); + if (checkpoint == nullptr){ + return "No checkpoint " + c.checkpoint + "."; + } + const MapPosition onto{c.map, {c.onto_x, c.y}}; + StoryPose pose = one_tile(*checkpoint->start); + for (const StoryStep& step : checkpoint->steps){ + const std::string where = c.checkpoint + "/" + step.name + ": "; + if (step.name == c.step && step.kind == StoryStepKind::STEP && onto == MapPosition{pose.map, pose.tile.next(step.direction)}){ + return true; + } + if (step.name == c.step){ + return where + "expected a step onto " + to_string(onto) + ", from " + describe(pose) + "."; + } + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS; + for (const MapPosition& tile : walks ? tiles_walked(pose, step) : std::vector{}){ + if (tile.map == c.map && tile.point.y == c.y && tile.point.x >= c.x0 && tile.point.x <= c.x1){ + return where + "walks over the trigger at " + to_string(tile) + "."; + } + } + if (UnitTestResult result = advance(pose, step); result.result != UnitTestResult::PASSED){ + return c.checkpoint + " " + result.message; + } + } + return "No step " + c.checkpoint + "/" + c.step + "."; +} + +// 00.15b meets the rival on the middle of his three trigger tiles, row 6 +// at x 22..24 north of Cerulean (VAR_MAP_SCENE_CERULEAN_CITY_RIVAL 0), +// and 00.16 the Rocket on the east one of his two, (10..11, 15) on Nugget +// Bridge (VAR_MAP_SCENE_ROUTE24 0), each from the tile below. +UnitTestResult test_cerulean_triggers(){ + const TriggerCase CASES[] = { + {.checkpoint = "00.15b", .step = "rival_trigger", .map = "CeruleanCity", .y = 6, .x0 = 22, .x1 = 24, .onto_x = 23}, + {.checkpoint = "00.16", .step = "rocket_trigger", .map = "Route24", .y = 15, .x0 = 10, .x1 = 11, .onto_x = 11}, + }; + for (const TriggerCase& c : CASES){ + if (UnitTestResult result = check_trigger(c); result.result != UnitTestResult::PASSED){ + return result; + } + } + return true; +} + +// 00.16 steps beside Nugget Bridge's five trainers from the south, one +// step at a time, each battle right after its step: Cale, Ali, Timmy, +// Reli and Ethan, by where they stand. +UnitTestResult test_nugget_bridge_order(){ + const StoryCheckpoint* checkpoint = find_checkpoint("00.16"); + if (checkpoint == nullptr){ + return "No checkpoint 00.16."; + } + const std::vector& steps = checkpoint->steps; + std::string met; + StoryPose pose = one_tile(*checkpoint->start); + for (size_t c = 0; c < steps.size(); c++){ + const MapData* map = find_map_named(pose.map); + const MapObject* trainer = steps[c].kind == StoryStepKind::STEP && map ? trainer_seeing(*map, pose.tile.next(steps[c].direction), {}) : nullptr; + if (trainer != nullptr && (c + 1 == steps.size() || steps[c + 1].kind != StoryStepKind::BATTLE)){ + return "00.16/" + steps[c].name + ": no battle right after the step."; + } + met += trainer ? " " + to_string(TilePos{trainer->x, trainer->y}) : ""; + if (UnitTestResult result = advance(pose, steps[c]); result.result != UnitTestResult::PASSED){ + return "00.16 " + result.message; + } + } + const std::string expected = " (12, 31) (10, 28) (12, 25) (10, 22) (12, 19)"; + if (met != expected){ + return "00.16: expected the five bridge trainers south to north," + expected + "; met" + met + "."; + } + return true; +} + // Every checkpoint that starts from a save has a place the save card // names, so a save left elsewhere is caught before it runs; and the // places of the starts that matter differ. @@ -611,6 +715,9 @@ UnitTestResult test_save_places(){ if (save_card_place("Route3") != "route-3" || save_card_place("Route4_PokemonCenter_1F") != "route-4"){ return "Wrong save card places on Route 3 and 4."; } + if (save_card_place("CeruleanCity_PokemonCenter_1F") != "cerulean-city"){ + return "Wrong save card place in Cerulean City."; + } // Not Route 2's or Route 4's: a map name is a place's or a building's in it. if (!save_card_place("Route22").empty() || !save_card_place("Route24").empty() || !save_card_place("Route2").empty()){ return "A place for a map the table doesn't use."; @@ -847,6 +954,8 @@ void add_tests_AutoStory(UnitTestDatabase& database){ database.add("routes run after the Running Shoes", test_runs_after_shoes); database.add("Route 3: only the planned trainers' lines", test_trainer_lines); database.add("Route 3: Lass Robin stops the walk on (40, 9)", test_robin_crossing); + database.add("Cerulean: the rival's and the Rocket's triggers", test_cerulean_triggers); + database.add("Nugget Bridge: its five trainers, south to north", test_nugget_bridge_order); database.add("intro: names, the rival's from the list", test_intro_names); database.add("options: RIGHT presses from the shown value", test_option_presses); database.add("00.12c: the Magikarp's deposit is skipped without Gift RNG", test_magikarp_deposit_skippable); diff --git a/devtools/maps/frlg_maps.py b/devtools/maps/frlg_maps.py index f72a9ecca0..e7bc65e726 100644 --- a/devtools/maps/frlg_maps.py +++ b/devtools/maps/frlg_maps.py @@ -86,6 +86,10 @@ 'Route4_PokemonCenter_1F': {'nurse_front': (7, 4), 'salesman_front': (2, 3)}, # The tile in front of the PC. 'CeruleanCity_PokemonCenter_1F': {'pc': (11, 2), 'nurse_front': (7, 4)}, + # The clerk (2, 3) is across the counter to the west. + 'CeruleanCity_Mart': {'clerk_front': (4, 3)}, + # Below Misty (8, 6). + 'CeruleanCity_Gym': {'misty_front': (8, 7)}, # Where the player stands after entering from Cerulean City. 'CeruleanCave_1F': {'entrance': (33, 21)}, # Mewtwo's tile. Its battle starts by talking to it from the south. From 8d2da7e2eac4d41f3289e3564fcaaefeb99a4a2c Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 10:00:26 -0800 Subject: [PATCH 2/6] FRLG AutoStory battle: read SLP, use Awakenings, log each heal choice The status badge read Sleep Powder's SLP as "a status" (console B, m56, 00.15b run 2). SLP is now its own StatusCondition, from the badge's mean color on that run's turn 6 and 7 captures. Awakenings are a counted supply (bag reader name, Supplies, bag read, Mart count). In a trainer's battle the lead uses one when asleep, the foe can hurt it, and it outlasts the hit the item's turn costs; the sim plays the same rule (awakening_now()) and the win chance counts them. 00.15's Cerulean Mart step buys 3 Potions and 2 Awakenings within its 1500 floor. The turn 7 move at 13/65 HP with 15 Potions was the Potion rule: the last turn took 21 HP (Vine Whip and Leech Seed), more than a Potion heals, and an item's turn doesn't count sleep down. Each turn now logs why a Potion was or wasn't used. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Menus/PokemonFRLG_ItemListReader.cpp | 1 + .../Menus/PokemonFRLG_ItemListReader.h | 2 +- .../AutoStory/PokemonFRLG_AutoStoryBattle.cpp | 88 ++++++----- .../AutoStory/PokemonFRLG_AutoStoryBattle.h | 18 ++- .../PokemonFRLG_AutoStoryBattleDecisions.cpp | 111 +++++++++++--- .../PokemonFRLG_AutoStoryBattleDecisions.h | 5 + .../PokemonFRLG_AutoStoryBattleSim.cpp | 16 +- .../PokemonFRLG_AutoStoryBattleSim.h | 26 +++- .../PokemonFRLG_AutoStoryBattleSim_Tests.cpp | 139 +++++++++++++++++- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 3 +- .../AutoStory/PokemonFRLG_AutoStoryGrind.cpp | 6 +- .../AutoStory/PokemonFRLG_AutoStoryGrind.h | 4 +- .../PokemonFRLG_AutoStoryGrind_Tests.cpp | 2 +- .../PokemonFRLG_AutoStoryItems_Tests.cpp | 41 ++++++ .../AutoStory/PokemonFRLG_AutoStoryMart.cpp | 2 + .../AutoStory/PokemonFRLG_AutoStoryMart.h | 6 +- .../PokemonFRLG_AutoStoryMart_Tests.cpp | 11 +- .../PokemonFRLG_AutoStoryRunPlan_Tests.cpp | 14 +- .../AutoStory/PokemonFRLG_AutoStoryTable.cpp | 16 +- .../PokemonFRLG_AutoStoryWinChance.cpp | 31 ++-- .../PokemonFRLG_AutoStoryWinChance.h | 16 +- 21 files changed, 445 insertions(+), 113 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp index b37226995b..0f6045996e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.cpp @@ -68,6 +68,7 @@ class ItemNameMatcher : public OCR::SmallDictionaryMatcher{ std::pair{"potion", "Potion"}, {"antidote", "Antidote"}, {"parlyz-heal", "Parlyz Heal"}, + {"awakening", "Awakening"}, {"poke-ball", "Poke Ball"}, {"cancel", "Cancel"}, }){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h index cddeb636c6..bfe92bd4ca 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h @@ -35,7 +35,7 @@ ImageFloatBox item_list_name_box(int row); ImageFloatBox bag_item_count_box(int row); // The item named in row `row`: a slug such as "potion", "antidote", -// "parlyz-heal", "poke-ball", or "cancel" for the list's last row, in a +// "parlyz-heal", "awakening", "poke-ball", or "cancel" for the list's last row, in a // game in `language`; empty if it can't be read, as in a language the // reader has no names for. std::string read_item_list_name(Logger& logger, Language language, const ImageViewRGB32& screen, int row); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index 43702b6b96..23e10c53b4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -75,25 +75,6 @@ constexpr Milliseconds MOVE_LIST_TIMEOUT = 5000ms; // pixel inside. const ImageFloatBox STATUS_BADGE_BOX(146.0 / 240, 99.0 / 160, 12.0 / 240, 4.0 / 160); -StatusCondition read_status_badge(const ImageViewRGB32& badge){ - const ImageStats stats = image_stats(badge); - const double r = stats.average.r; - const double g = stats.average.g; - const double b = stats.average.b; - const double off_white = std::abs(r - 255) + std::abs(g - 255) + std::abs(b - 217); - if (off_white < 60){ - return StatusCondition::NONE; - } - if (r > 200 && g < 200 && b > 180){ - return StatusCondition::POISON; - } - // Not measured yet: PAR's badge is taken to be the yellow one. - if (r > 180 && g > 150 && b < 140){ - return StatusCondition::PARALYSIS; - } - return StatusCondition::OTHER; -} - enum class BattleScreen{ // Keep in step with screen_name(). @@ -614,10 +595,13 @@ class BattleLoop{ const TurnAction action = m_decisions.turn(status); m_evolution.turn_taken(action.choice); m_console.log(std::format( - "Battle: turn {}, HP {} ({:.0f}% of the bar), {}, {} Potions, {} Antidotes, {} Parlyz Heals.", + "Battle: turn {}, HP {} ({:.0f}% of the bar), {}, {} Potions, {} Antidotes, {} Parlyz Heals, {} Awakenings.", m_decisions.turns(), status.hp_red ? "red" : status.hp_yellow ? "yellow" : "green", 100 * status.hp_fill, - status_name(status.status), m_supplies.potions, m_supplies.antidotes, m_supplies.parlyz_heals + status_name(status.status), m_supplies.potions, m_supplies.antidotes, m_supplies.parlyz_heals, m_supplies.awakenings )); + if (!action.heal_reason.empty()){ + m_console.log("Battle: " + action.heal_reason + "."); + } dump_debug_image(m_console, "AutoStory/battle", std::format("turn{}-menu", m_decisions.turns()), screen); switch (action.choice){ case TurnChoice::RUN: @@ -630,6 +614,9 @@ class BattleLoop{ case TurnChoice::ANTIDOTE: m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, item_row(m_supplies, "antidote"), "antidote", m_checks, m_language))); return; + case TurnChoice::AWAKENING: + m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, item_row(m_supplies, "awakening"), "awakening", m_checks, m_language))); + return; case TurnChoice::MOVE: m_console.log(std::format("Battle: move {}.", action.slot + 1)); m_refusal.move_chosen(current_time()); @@ -808,12 +795,38 @@ const char* status_name(StatusCondition status){ return "PSN"; case StatusCondition::PARALYSIS: return "PAR"; + case StatusCondition::SLEEP: + return "SLP"; case StatusCondition::OTHER: return "a status"; } return "?"; } +StatusCondition read_status_badge(const ImageViewRGB32& badge){ + const ImageStats stats = image_stats(badge); + const double r = stats.average.r; + const double g = stats.average.g; + const double b = stats.average.b; + const double off_white = std::abs(r - 255) + std::abs(g - 255) + std::abs(b - 217); + if (off_white < 60){ + return StatusCondition::NONE; + } + if (r > 200 && g < 200 && b > 180){ + return StatusCondition::POISON; + } + // SLP's grey-olive badge with its cream letters: red and green even, + // blue lower but above the yellow taken for PAR. + if (std::abs(r - g) < 20 && b < g - 15 && b > 140 && r < 235){ + return StatusCondition::SLEEP; + } + // Not measured yet: PAR's badge is taken to be the yellow one. + if (r > 180 && g > 150 && b < 140){ + return StatusCondition::PARALYSIS; + } + return StatusCondition::OTHER; +} + PartyStatus read_party_status(const ImageViewRGB32& screen){ const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); const HpBarReading bar = read_player_hp_bar(game); @@ -832,36 +845,35 @@ bool battle_shows(const ImageViewRGB32& screen){ } // The count the story keeps for `item`, or null for an item it doesn't count. -static int* count_slot(Supplies& supplies, const std::string& item){ +static int Supplies::* count_member(const std::string& item){ if (item == "potion"){ - return &supplies.potions; + return &Supplies::potions; } if (item == "antidote"){ - return &supplies.antidotes; + return &Supplies::antidotes; } if (item == "parlyz-heal"){ - return &supplies.parlyz_heals; + return &Supplies::parlyz_heals; + } + if (item == "awakening"){ + return &Supplies::awakenings; } return nullptr; } +static int* count_slot(Supplies& supplies, const std::string& item){ + int Supplies::* const member = count_member(item); + return member == nullptr ? nullptr : &(supplies.*member); +} + int item_count(const Supplies& supplies, const std::string& item){ - if (item == "potion"){ - return supplies.potions; - } - if (item == "antidote"){ - return supplies.antidotes; - } - if (item == "parlyz-heal"){ - return supplies.parlyz_heals; - } - return 0; + int Supplies::* const member = count_member(item); + return member == nullptr ? 0 : supplies.*member; } // Whether the story keeps a count for `item`. static bool counted(const std::string& item){ - Supplies probe; - return count_slot(probe, item) != nullptr; + return count_member(item) != nullptr; } int item_row(const Supplies& supplies, const std::string& item){ @@ -883,6 +895,7 @@ std::vector set_from_bag(Supplies& supplies, const std::vector unread; for (const BagRow& row : rows){ @@ -911,6 +924,7 @@ std::vector set_from_loaded_bag(Supplies& supplies, Supplies& saved saved.potions = supplies.potions; saved.antidotes = supplies.antidotes; saved.parlyz_heals = supplies.parlyz_heals; + saved.awakenings = supplies.awakenings; saved.pocket = supplies.pocket; return unread; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h index 7b16b43608..50cffc65a4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h @@ -7,7 +7,9 @@ * is put back on FIGHT and the move list's top left, since the game * remembers both, then onto the move BattleDecisions picks. A Potion is * used when the HP bar turns yellow or red, an Antidote (once a battle) - * when the status reads PSN at two turns in a row; after the battle, PSN + * when the status reads PSN at two turns in a row, an Awakening in a + * trainer's battle when it reads SLP; each turn's reason for a Potion or + * none is logged. After the battle, PSN * and PAR are cured from the bag. Move prompts, an evolution after the * battle and a fainted lead are as PokemonFRLG_AutoStoryBattleDecisions.h * says. @@ -40,22 +42,24 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -// A status condition, as far as the story treats them: the two it carries +// A status condition, as far as the story treats them: the ones it carries // items for, and the rest, which only a nurse cures. enum class StatusCondition{ NONE, POISON, PARALYSIS, - OTHER, // SLP, BRN, FRZ + SLEEP, + OTHER, // BRN, FRZ }; const char* status_name(StatusCondition status); // The healing items in the Items pocket, in the order they were bought: -// Potions, Antidotes, then Parlyz Heals. +// Potions, Antidotes, then Parlyz Heals; Awakenings from Cerulean's Mart. struct Supplies{ int potions = 0; int antidotes = 0; int parlyz_heals = 0; + int awakenings = 0; // The Items pocket's order, by slug (see read_item_list_name()): the // order bought, or as read from the bag, with "" for a row whose name // couldn't be read. A counted item with none left takes no row; the @@ -146,10 +150,14 @@ std::vector set_from_loaded_bag(Supplies& supplies, Supplies& saved std::vector read_items_pocket(ConsoleHandle& console, ProControllerContext& context, Language language); +// The status badge left of the player's HP numbers, by its mean color. +StatusCondition read_status_badge(const ImageViewRGB32& badge); + // What the HP bar (read_player_hp_bar()) and the status badge of the // player's Pokemon show, on a battle screen with its box. The badge's // place measured on console B's captures (2026-11-01): off-white -// (255, 255, 217) with no status, (228, 168, 212) for PSN. +// (255, 255, 217) with no status, (228, 168, 212) for PSN, (202, 203, 168) +// for SLP (2026-11-03, after the Cerulean rival's Sleep Powder). struct PartyStatus{ bool hp_seen = false; bool hp_yellow = false; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp index 145b9e8c5f..71a2af1940 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp @@ -5,7 +5,9 @@ */ #include +#include #include +#include #include "PokemonFRLG_AutoStoryBattleDecisions.h" #include "PokemonFRLG_AutoStoryBattleSim.h" @@ -76,24 +78,88 @@ std::optional trainer_attack_slot(const PartyMember& usable, const Suppl return slot ? slot : attack_slot_against(usable, supplies.foes); } -// A Potion this turn, against a known foe (`seen_hit` the HP its last hit -// took, 0 if not seen): at BattleRisk::HIGH when its next hit could faint -// the lead (potion_now(), the HP from the bar's share) or the bar is red, -// at LOW whenever the bar isn't green; either only if potion_pays(). -// Against a foe not known, whenever the bar isn't green, unless the last -// hit took a Potion's worth or more. -bool wants_potion(const Supplies& supplies, const PartyStatus& status, double seen_hit){ +// The item a turn uses, if any, and why one was or wasn't, for the log. +struct ItemTurn{ + TurnChoice choice = TurnChoice::MOVE; + std::string reason = {}; +}; + +const char* bar_name(const PartyStatus& status){ + return status.hp_red ? "red" : status.hp_yellow ? "yellow" : "green"; +} + +// Against a foe not known (`seen_hit` the HP its last hit took, 0 if not +// seen): a Potion whenever the bar isn't green, unless the last hit took +// a Potion's worth or more; asleep, an Awakening unless the bar is red. +ItemTurn unknown_foe_items(const Supplies& supplies, const PartyStatus& status, double seen_hit, int awakenings){ const bool hurt = status.hp_red || status.hp_yellow; + const bool asleep = status.status == StatusCondition::SLEEP; + if (hurt && supplies.potions > 0 && seen_hit < POTION_HP){ + return {TurnChoice::POTION, std::format("a Potion: HP {}, the foe not known, its last hit {:.0f} HP", bar_name(status), seen_hit)}; + } + if (asleep && awakenings > 0 && !status.hp_red){ + return {TurnChoice::AWAKENING, std::format("an Awakening: asleep at HP {}, the foe not known", bar_name(status))}; + } + if (!hurt){ + return {}; + } + return {TurnChoice::MOVE, supplies.potions <= 0 + ? std::string("no Potion: none left") + : std::format("no Potion: the foe not known, its last hit {:.0f} HP would undo one", seen_hit) + }; +} + +// Why no Potion against a known foe, at `c`. +std::string no_potion_reason(const Supplies& supplies, const PartyStatus& status, const PotionCase& c){ + if (supplies.potions <= 0){ + return "none left"; + } + const bool asked = supplies.risk == BattleRisk::HIGH ? status.hp_red : status.hp_red || status.hp_yellow; + if (!asked){ + return std::format("HP {} and the next hit can't faint the lead", bar_name(status)); + } + return std::format("the next hit (about {:.0f}) undoes it and it outlasts the foe no longer", c.expected_hit); +} + +// Against a known foe: a Potion at BattleRisk::HIGH when its next hit +// could faint the lead (potion_now(), the HP from the bar's share) or the +// bar is red, at LOW whenever the bar isn't green; either only if +// potion_pays(). Else, asleep, an Awakening if awakening_now(). +ItemTurn known_foe_items( + const Supplies& supplies, const PartyStatus& status, double seen_hit, + const SimBattler& own, const SimBattler& foe, int awakenings +){ + const bool hurt = status.hp_red || status.hp_yellow; + const PotionCase c = potion_case(own, foe, seen_hit); + const std::string numbers = std::format( + "{}/{} HP, the foe's next hit about {:.0f} (up to {}), {} of them before the lead's attacks faint it", + c.hp, c.max_hp, c.expected_hit, c.max_hit, c.hits_to_ko + ); + const bool high = supplies.risk == BattleRisk::HIGH; + if (supplies.potions > 0 && high && potion_now(own, foe, supplies.potions, seen_hit)){ + return {TurnChoice::POTION, "a Potion: the next hit could faint the lead, not after it; " + numbers}; + } + if (supplies.potions > 0 && (high ? status.hp_red : hurt) && potion_pays(c)){ + return {TurnChoice::POTION, "a Potion: it outheals the next hit, or outlasts the foe; " + numbers}; + } + if (awakening_now(own, foe, awakenings, seen_hit)){ + return {TurnChoice::AWAKENING, "an Awakening: asleep, and the lead outlasts the hit its turn costs; " + numbers}; + } + if (!hurt && own.status != SimStatus::SLEEP){ + return {}; + } + return {TurnChoice::MOVE, "no Potion: " + no_potion_reason(supplies, status, c) + "; " + numbers}; +} + +// The item this turn, from the bar and the badge as read. +ItemTurn item_turn(const Supplies& supplies, const PartyStatus& status, double seen_hit, int awakenings){ const std::optional foe = foe_out(supplies); - const std::optional own = own_battler(supplies.lead, status.hp_seen ? status.hp_fill : 1.0); + std::optional own = own_battler(supplies.lead, status.hp_seen ? status.hp_fill : 1.0); if (!foe || !own){ - return hurt && seen_hit < POTION_HP; + return unknown_foe_items(supplies, status, seen_hit, awakenings); } - if (supplies.risk == BattleRisk::HIGH && potion_now(*own, *foe, supplies.potions, seen_hit)){ - return true; - } - const bool asked = supplies.risk == BattleRisk::HIGH ? status.hp_red : hurt; - return asked && potion_pays(potion_case(*own, *foe, seen_hit)); + own->status = status.status == StatusCondition::SLEEP ? SimStatus::SLEEP : SimStatus::NONE; + return known_foe_items(supplies, status, seen_hit, *own, *foe, awakenings); } // The lead's HP from the bar's share, if it showed. @@ -165,14 +231,19 @@ TurnAction BattleDecisions::lead_turn(const PartyStatus& status){ return TurnAction{.choice = TurnChoice::RUN}; } see_hit(status); - if (!m_items_off && m_supplies.potions > 0 && wants_potion(m_supplies, status, m_seen_hit)){ - return TurnAction{.choice = TurnChoice::POTION}; + // Awakenings are kept for trainers: a wild battle with a status is run from. + const int awakenings = m_kind == BattleKind::TRAINER ? m_supplies.awakenings : 0; + const ItemTurn items = m_items_off ? ItemTurn{} : item_turn(m_supplies, status, m_seen_hit, awakenings); + if (items.choice != TurnChoice::MOVE){ + return TurnAction{.choice = items.choice, .heal_reason = items.reason}; } if (!m_items_off && m_psn_reads >= PSN_READS && !m_antidote_used && m_supplies.antidotes > 0){ m_antidote_used = true; - return TurnAction{.choice = TurnChoice::ANTIDOTE}; + return TurnAction{.choice = TurnChoice::ANTIDOTE, .heal_reason = items.reason}; } - return move_turn(); + TurnAction action = move_turn(); + action.heal_reason = items.reason; + return action; } void BattleDecisions::see_hit(const PartyStatus& status){ @@ -259,6 +330,10 @@ void BattleDecisions::turn_done(TurnChoice choice, TurnResult result){ case TurnChoice::ANTIDOTE: m_supplies.antidotes--; return; + case TurnChoice::AWAKENING: + m_supplies.awakenings--; + m_supplies.status = StatusCondition::NONE; + return; case TurnChoice::RUN: case TurnChoice::MOVE: return; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h index 7d5e8e1736..5db4217cb5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h @@ -23,6 +23,7 @@ #include #include #include +#include #include "Common/Cpp/Time.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "PokemonFRLG_AutoStoryBattle.h" @@ -37,6 +38,7 @@ enum class TurnChoice{ RUN, POTION, ANTIDOTE, + AWAKENING, MOVE, }; @@ -44,6 +46,9 @@ struct TurnAction{ TurnChoice choice = TurnChoice::MOVE; // For MOVE, the move list's slot. size_t slot = BOTTOM_LEFT_MOVE; + // Why a Potion was or wasn't used, for the log; empty when none was + // weighed (green HP, awake). + std::string heal_reason = {}; }; // What came of a TurnAction. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.cpp index 23e7f10f78..f278090652 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.cpp @@ -547,12 +547,21 @@ bool potion_now(const SimBattler& own, const SimBattler& foe, int potions, doubl return c.max_hit >= own.hp && healed > c.max_hit && potion_pays(c); } +bool awakening_now(const SimBattler& own, const SimBattler& foe, int awakenings, double seen_hit){ + if (awakenings <= 0 || own.status != SimStatus::SLEEP){ + return false; + } + const PotionCase c = potion_case(own, foe, seen_hit); + return (c.expected_hit > 0 || own.seeded) && own.hp > c.expected_hit; +} + OwnTurn own_turn( - const SimBattler& own, int potions, const SimBattler& foe, + const SimBattler& own, const SimItems& own_items, const SimBattler& foe, const std::vector& items, size_t foes_left ){ + const int potions = own_items.potions; const std::optional slot = planned_attack_slot(own, foe, items, foes_left); - if (slot){ + if (slot && own.status != SimStatus::SLEEP){ const MoveData& move = data_of(own.moves[*slot].move); const bool foe_priority = std::ranges::any_of(foe.moves, [](const SimMove& known){ return known.pp > 0 && data_of(known.move).priority > 0; @@ -566,6 +575,9 @@ OwnTurn own_turn( if (potion_now(own, foe, potions)){ return OwnTurn{.potion = true, .slot = std::nullopt}; } + if (awakening_now(own, foe, own_items.awakenings)){ + return OwnTurn{.potion = false, .slot = std::nullopt, .awakening = true}; + } return OwnTurn{.potion = false, .slot = slot}; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.h index d5e142d2b7..ba062de56c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.h @@ -64,6 +64,12 @@ inline constexpr Genes OWN_GENES{.iv = 15, .ev = 0, .nature = 0}; // HP a Potion heals. inline constexpr uint16_t POTION_HP = 20; +// The lead's items in the bag that the sim plays. +struct SimItems{ + int potions = 0; + int awakenings = 0; +}; + enum class SimStatus{ NONE, SLEEP, @@ -173,17 +179,29 @@ bool potion_pays(const PotionCase& c); // after the Potion it couldn't, and potion_pays(). bool potion_now(const SimBattler& own, const SimBattler& foe, int potions, double seen_hit = 0); +// At either BattleRisk, `own` asleep with an Awakening left: one now if +// `foe` can hurt it (a damaging move with PP left, or Leech Seed on it) +// and it outlasts the hit the item's turn costs (potion_case()'s, with +// `seen_hit`). The game counts sleep down only on turns the lead tries to +// move (pret battle_util.c AtkCanceller_UnableToUseMove), so the turn +// saves the rest of the 1 to 4 asleep. Below that hit the lead's move is +// tried instead, to wake and attack, or a Potion as the Potion rules say. +bool awakening_now(const SimBattler& own, const SimBattler& foe, int awakenings, double seen_hit = 0); + // The lead's turn at BattleRisk::HIGH. struct OwnTurn{ bool potion = false; - // Not a Potion: the move's slot, none if no move does damage. + // Not a Potion or an Awakening: the move's slot, none if no move does + // damage. std::optional slot = std::nullopt; + bool awakening = false; }; // planned_attack_slot()'s move when it surely faints `foe` first (the -// lead is faster, the lowest roll faints it, it never misses and the AI -// won't heal first), else a Potion if potion_now(), else that move. +// lead is awake and faster, the lowest roll faints it, it never misses and +// the AI won't heal first), else a Potion if potion_now(), else an +// Awakening if awakening_now(), else that move. OwnTurn own_turn( - const SimBattler& own, int potions, const SimBattler& foe, + const SimBattler& own, const SimItems& own_items, const SimBattler& foe, const std::vector& items, size_t foes_left ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp index 375d088738..86fd74652d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp @@ -275,7 +275,7 @@ UnitTestResult test_risks(){ // Potions that 00.15's GRIND plans for wins about a quarter of the sim's // battles, and is refused with the reason; at Lv30 it wins over 90%. UnitTestResult test_rival_win_chance(){ - const std::optional planned = story_win_chance(grown_to(new_member("squirtle", 5), 22), 5, 1.0, RIVAL); + const std::optional planned = story_win_chance(grown_to(new_member("squirtle", 5), 22), SimItems{.potions = 5}, 1.0, RIVAL); const std::optional refusal = planned ? win_chance_refusal(*planned) : std::nullopt; if (!planned || planned->chance < 0.15 || planned->chance > 0.40){ return std::format("Lv22, 5 Potions: expected 15% to 40%, got {:.1f}%.", planned ? 100 * planned->chance : 0.0); @@ -283,7 +283,7 @@ UnitTestResult test_rival_win_chance(){ if (refusal != std::format("win chance {:.0f}% < 70% with {}: grind first", std::floor(100 * planned->chance), planned->inputs)){ return "Lv22, 5 Potions: expected a refusal with the chance, got \"" + refusal.value_or("") + "\"."; } - const std::optional ground = story_win_chance(grown_to(new_member("squirtle", 5), 30), 5, 1.0, RIVAL); + const std::optional ground = story_win_chance(grown_to(new_member("squirtle", 5), 30), SimItems{.potions = 5}, 1.0, RIVAL); if (!ground || ground->chance < 0.90 || win_chance_refusal(*ground)){ return std::format("Lv30, 5 Potions: expected over 90% and no refusal, got {:.1f}%.", ground ? 100 * ground->chance : 0.0); } @@ -363,7 +363,7 @@ UnitTestResult test_sim_potion_rule(){ if (potion_case(own, starmie).expected_hit < POTION_HP){ return std::format("Expected Starmie's mean hit at 20 or more, got {:.1f}.", potion_case(own, starmie).expected_hit); } - const OwnTurn sim = own_turn(own, 5, starmie, misty.items, 1); + const OwnTurn sim = own_turn(own, SimItems{.potions = 5}, starmie, misty.items, 1); if (sim.potion || sim.slot != size_t(0)){ return std::format( "Sim at 8/60 against Starmie (max hit {}): expected Bite (slot 0), got {}.", @@ -376,7 +376,7 @@ UnitTestResult test_sim_potion_rule(){ if (hit < 6 || hit >= POTION_HP){ return std::format("Expected Staryu's best hit on the Wartortle from 6 to 19, got {}.", hit); } - if (!own_turn(low, 5, staryu, misty.items, 2).potion){ + if (!own_turn(low, SimItems{.potions = 5}, staryu, misty.items, 2).potion){ return std::format("At 6/60 against Staryu (max hit {}): expected a Potion.", hit); } return true; @@ -389,8 +389,8 @@ UnitTestResult test_sim_potion_rule(){ // about 94%, from other inputs. m51 lost: the sim leaves out Water // Pulse's confusion, among others (PokemonFRLG_AutoStoryWinChance.h). UnitTestResult test_misty_real_lead(){ - const std::optional real = story_win_chance(m51_lead(20), 5, 1.0, MISTY); - const std::optional story = story_win_chance(grown_to(new_member("squirtle", 5), 20), 5, 1.0, MISTY); + const std::optional real = story_win_chance(m51_lead(20), SimItems{.potions = 5}, 1.0, MISTY); + const std::optional story = story_win_chance(grown_to(new_member("squirtle", 5), 20), SimItems{.potions = 5}, 1.0, MISTY); if (!real || !story){ return "Expected win chances for both leads."; } @@ -416,7 +416,7 @@ UnitTestResult test_rival_real_moves(){ {20, 0.20, 0.45}, {22, 0.25, 0.50}, {25, 0.50, 0.70}, {30, 0.90, 1.00}, }; for (const auto& [level, low, high] : cases){ - const std::optional estimate = story_win_chance(m51_lead(level), 5, 1.0, RIVAL); + const std::optional estimate = story_win_chance(m51_lead(level), SimItems{.potions = 5}, 1.0, RIVAL); if (!estimate || estimate->chance < low || estimate->chance >= high){ return std::format("Lv{}: expected {:.0f}% to {:.0f}%, got {:.1f}%.", level, 100 * low, 100 * high, estimate ? 100 * estimate->chance : 0.0); } @@ -425,13 +425,133 @@ UnitTestResult test_rival_real_moves(){ return std::format("Lv{} at {:.1f}%: expected {}.", level, 100 * estimate->chance, level < 30 ? "a refusal" : "no refusal"); } } - const std::optional lv22 = story_win_chance(m51_lead(22), 5, 1.0, RIVAL); + const std::optional lv22 = story_win_chance(m51_lead(22), SimItems{.potions = 5}, 1.0, RIVAL); const std::string refusal = win_chance_refusal(*lv22).value_or(""); if (refusal.find("wartortle Lv22 65/65 HP: bite") == std::string::npos || refusal.find("; 5 Potions") == std::string::npos){ return "Lv22: expected the refusal to name the lead's level, HP, moves and Potions, got \"" + refusal + "\"."; } return true; } + + +// Console B, 2026-11-03 (m56, 00.15b, run 2): the Wartortle Lv22, 65 HP, +// Bite, Water Pulse, Bubble and Withdraw. +PartyMember m56_lead(){ + Stats stats = combatant("wartortle", 22, OWN_GENES)->stats; + stats.hp = 65; + std::vector moves; + for (const char* move : {"bite", "water-pulse", "bubble", "withdraw"}){ + moves.push_back(SummaryMove{.move = move, .pp = max_pp(move), .max_pp = max_pp(move)}); + } + return member_from_summary("wartortle", 22, moves, stats); +} + +// m56's supplies against the rival's Bulbasaur (slot 3), at HIGH risk. +Supplies m56_supplies(int awakenings){ + Supplies supplies; + supplies.lead = m56_lead(); + supplies.potions = 15; + supplies.parlyz_heals = 1; + supplies.awakenings = awakenings; + supplies.trainer = std::string(RIVAL); + supplies.foes = trainer_party(RIVAL); + supplies.risk = BattleRisk::HIGH; + supplies.foe_out = 3; + return supplies; +} + +// m56's bar at `hp` of 65, with `status`. +PartyStatus m56_bar(int hp, StatusCondition status){ + const double fill = hp / 65.0; + return PartyStatus{.hp_seen = true, .hp_yellow = fill <= 0.5 && fill > 0.2, .hp_red = fill <= 0.2, .hp_fill = fill, .status = status}; +} + +// m56 run 2 against the rival's Bulbasaur (Sleep Powder, Leech Seed, +// Vine Whip): 49, 42, then 34/65 asleep, then 13/65 asleep, Bite every +// turn and no Potion; it fainted. The 21 HP of turn 6 were Vine Whip and +// Leech Seed, more than a Potion's 20, and an item's turn doesn't count +// sleep down (pret battle_util.c AtkCanceller_UnableToUseMove), so a +// Potion at 13 HP is undone each turn while the lead stays asleep: the +// move is right there, and the log says why. With an Awakening, it is +// used on turn 6, while the lead outlasts the hit its turn costs. +UnitTestResult test_rival_sleep_turns(){ + const std::vector turns = { + m56_bar(49, StatusCondition::NONE), m56_bar(42, StatusCondition::NONE), + m56_bar(34, StatusCondition::SLEEP), m56_bar(13, StatusCondition::SLEEP), + }; + Supplies played = m56_supplies(0); + BattleDecisions as_played(played, BattleKind::TRAINER); + TurnAction action; + for (const PartyStatus& status : turns){ + action = as_played.turn(status); + as_played.turn_done(action.choice, TurnResult::DONE); + } + if (action.choice != TurnChoice::MOVE || action.heal_reason.find("undoes it") == std::string::npos){ + return std::format( + "No Awakening, turn 7 at 13/65 asleep: expected a move and a reason naming the Potion undone, got choice {} and \"{}\".", + static_cast(action.choice), action.heal_reason + ); + } + Supplies supplied = m56_supplies(2); + BattleDecisions with_awakenings(supplied, BattleKind::TRAINER); + for (size_t turn = 0; turn < 3; turn++){ + action = with_awakenings.turn(turns[turn]); + with_awakenings.turn_done(action.choice, TurnResult::DONE); + } + if (action.choice != TurnChoice::AWAKENING || supplied.awakenings != 1 || action.heal_reason.empty()){ + return std::format( + "2 Awakenings, turn 6 at 34/65 asleep: expected an Awakening, with a reason, got choice {}, {} left, \"{}\".", + static_cast(action.choice), supplied.awakenings, action.heal_reason + ); + } + return true; +} + +// The sim's lead asleep, as the battle loop decides: an Awakening while it +// outlasts the foe's next hit; below that, not (its turn would only let +// the foe faint it); none against a foe that can't hurt it. +UnitTestResult test_sim_awakening_rule(){ + const SimTrainer rival = *sim_trainer(RIVAL); + const SimBattler& bulbasaur = rival.party[3]; + SimBattler own = *own_battler(m56_lead()); + own.status = SimStatus::SLEEP; + own.sleep = 4; + own.hp = 34; + if (!own_turn(own, SimItems{.potions = 15, .awakenings = 2}, bulbasaur, rival.items, 1).awakening){ + return "Asleep at 34/65 against the Bulbasaur with 2 Awakenings: expected one."; + } + if (own_turn(own, SimItems{.potions = 15, .awakenings = 0}, bulbasaur, rival.items, 1).awakening){ + return "Asleep with no Awakenings: expected none used."; + } + own.hp = 8; + if (own_turn(own, SimItems{.potions = 0, .awakenings = 2}, bulbasaur, rival.items, 1).awakening){ + return "Asleep at 8/65, below the Bulbasaur's hit: expected no Awakening."; + } + own.hp = 34; + const SimBattler& abra = rival.party[1]; + if (own_turn(own, SimItems{.potions = 15, .awakenings = 2}, abra, rival.items, 4).awakening){ + return "Asleep against Abra (Teleport only): expected no Awakening."; + } + return true; +} + +// m56's Wartortle Lv22 with 15 Potions against the rival: Awakenings +// against the Bulbasaur's Sleep Powder win more battles (about 44% with +// none, 52% with 2, 53% with 3), and the inputs name them. +UnitTestResult test_rival_awakenings(){ + const std::optional none = story_win_chance(m56_lead(), SimItems{.potions = 15}, 1.0, RIVAL); + const std::optional three = story_win_chance(m56_lead(), SimItems{.potions = 15, .awakenings = 3}, 1.0, RIVAL); + if (!none || !three || three->chance < none->chance + 0.05){ + return std::format( + "Lv22, 15 Potions: expected 3 Awakenings to win at least 5 points more than none, got {:.1f}% and {:.1f}%.", + none ? 100 * none->chance : 0.0, three ? 100 * three->chance : 0.0 + ); + } + if (three->inputs.find("; 15 Potions, 3 Awakenings") == std::string::npos){ + return "Expected the inputs to name the Awakenings, got \"" + three->inputs + "\"."; + } + return true; +} } @@ -447,6 +567,9 @@ void add_tests_AutoStoryBattleSim(UnitTestDatabase& database){ database.add("the sim's Potion: only when it outheals the hit", test_sim_potion_rule); database.add("Misty: m51's lead as the summary showed it", test_misty_real_lead); database.add("Cerulean rival with m51's moves at Lv20 to 30", test_rival_real_moves); + database.add("m56: asleep at red HP, a Potion undone; an Awakening first", test_rival_sleep_turns); + database.add("the sim's Awakening: asleep, outlasting the next hit", test_sim_awakening_rule); + database.add("Cerulean rival: Awakenings raise the win chance", test_rival_awakenings); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 9037adbee4..52b2d4e820 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -161,7 +161,8 @@ std::optional refuse_battle(StoryEnv& env, const StoryStep& step, s if (step.may_lose || supplies.risk != BattleRisk::HIGH){ return std::nullopt; } - const std::optional estimate = story_win_chance(supplies.lead, supplies.potions, supplies.hp_fill, trainer); + const SimItems items{.potions = supplies.potions, .awakenings = supplies.awakenings}; + const std::optional estimate = story_win_chance(supplies.lead, items, supplies.hp_fill, trainer); if (!estimate){ return std::nullopt; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp index 6393acf42b..132e54b268 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp @@ -308,9 +308,9 @@ PartyMember lead_as_read(const MemberInfo& read, const PartyMember& tracked){ return member_from_summary(read.species.empty() ? tracked.species : read.species, level, moves, read.stats); } -std::optional healed_win_chance(PartyMember lead, int potions, std::string_view trainer){ +std::optional healed_win_chance(PartyMember lead, const SimItems& items, std::string_view trainer){ restore_pp(lead); - return story_win_chance(lead, potions, 1.0, trainer); + return story_win_chance(lead, items, 1.0, trainer); } @@ -354,7 +354,7 @@ bool ConsoleGrindActions::needs_heal(){ std::optional ConsoleGrindActions::win_chance(const MemberInfo& member, std::string_view trainer){ m_supplies.lead = lead_as_read(member, m_supplies.lead); - return healed_win_chance(m_supplies.lead, m_supplies.potions, trainer); + return healed_win_chance(m_supplies.lead, SimItems{.potions = m_supplies.potions, .awakenings = m_supplies.awakenings}, trainer); } bool ConsoleGrindActions::heal_trip(){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h index 408278cfae..7487bbc861 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h @@ -157,9 +157,9 @@ std::string grind_message(const GrindPlan& plan, const GrindResult& result); // full. PartyMember lead_as_read(const MemberInfo& read, const PartyMember& tracked); -// The sim's chance for `lead` with `potions` against `trainer`, once the +// The sim's chance for `lead` with `items` against `trainer`, once the // nurse has healed it (full HP and PP). -std::optional healed_win_chance(PartyMember lead, int potions, std::string_view trainer); +std::optional healed_win_chance(PartyMember lead, const SimItems& items, std::string_view trainer); // Where pacing left the player, for the trip to the nurse. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp index 16e871eb9f..05c7ed1fda 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp @@ -404,7 +404,7 @@ UnitTestResult test_console_party(){ for (uint8_t level = 22; level <= 25; level++){ PartyMember lead = at22; lead.moves_through_level = level; - const std::optional estimate = healed_win_chance(lead, 10, RIVAL); + const std::optional estimate = healed_win_chance(lead, SimItems{.potions = 10}, RIVAL); if (!estimate || (estimate->chance >= MIN_WIN_CHANCE) != (level == 25)){ return std::format( "Lv{}: {:.1f}%; expected the first at {:.0f}% or more at Lv25.", diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp index 0aea6c90a0..b2a9db0751 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp @@ -8,11 +8,14 @@ */ #include +#include #include #include #include #include +#include #include +#include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/TestRunners/UnitTest.h" @@ -188,6 +191,42 @@ UnitTestResult test_loaded_bag_other_items(Logger&){ return true; } +// Awakenings, bought at Cerulean after a MOON STONE took its row: counted +// from the bag and found in their row. +UnitTestResult test_loaded_bag_awakenings(Logger&){ + Supplies row; + Supplies saved = row; + set_from_loaded_bag(row, saved, {{"", 1}, {"parlyz-heal", 1}, {"potion", 15}, {"awakening", 3}}); + if (row.awakenings != 3 || saved.awakenings != 3 || item_count(row, "awakening") != 3 || item_row(row, "awakening") != 3){ + return std::format( + "Expected 3 Awakenings in row 3, now and for a reload; got {} and {}, row {}.", + row.awakenings, saved.awakenings, item_row(row, "awakening") + ); + } + return true; +} + +// The status badge's mean color on console B's captures: none and PSN +// (2026-11-01), and SLP after the Cerulean rival's Sleep Powder +// (2026-11-03, m56 run 2, turns 6 and 7 at 34/65 and 13/65 HP), which +// read as "a status". +UnitTestResult test_status_badge(Logger&){ + const std::vector> cases = { + {combine_rgb(255, 255, 217), StatusCondition::NONE}, + {combine_rgb(228, 168, 212), StatusCondition::POISON}, + {combine_rgb(202, 203, 168), StatusCondition::SLEEP}, + }; + for (const auto& [color, expected] : cases){ + ImageRGB32 badge(12, 4); + badge.fill(color); + const StatusCondition read = read_status_badge(badge); + if (read != expected){ + return std::format("Badge 0x{:08x}: expected {}, got {}.", color, status_name(expected), status_name(read)); + } + } + return true; +} + // The pocket's rows as read: an unread name keeps its row, so the rows // below it are still read; the rows end at CANCEL, or at the last name read. UnitTestResult test_pocket_rows_unread(Logger&){ @@ -345,6 +384,8 @@ void add_tests_AutoStoryItems(UnitTestDatabase& database){ database.add("Items pocket rows", test_pocket_rows); database.add("a loaded save's counts come from the bag", test_loaded_bag); database.add("an item the story doesn't count keeps its row", test_loaded_bag_other_items); + database.add("Awakenings counted from the bag", test_loaded_bag_awakenings); + database.add("the status badge: none, PSN, SLP", test_status_badge); database.add("an unread item name keeps its row", test_pocket_rows_unread); database.add("unread bag counts count as some", test_unread_counts); database.add("no item names read in a language without them", test_unread_language); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp index 39cab8c78f..abbaf071c5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp @@ -415,6 +415,8 @@ void count_supplies(Supplies& supplies, std::string_view item, size_t quantity){ count = &Supplies::antidotes; }else if (item == "parlyz-heal"){ count = &Supplies::parlyz_heals; + }else if (item == "awakening"){ + count = &Supplies::awakenings; } if (count == nullptr){ return; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h index 28de24cd5b..ce308b31ab 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h @@ -183,15 +183,15 @@ std::string mart_message(const MartPlan& plan, const MartResult& result); // Counts `quantity` of `item` into `supplies`, if it is one the battles -// use (Potions, Antidotes, Parlyz Heals); a new one goes to the end of the +// use (Potions, Antidotes, Parlyz Heals, Awakenings); a new one goes to the end of the // pocket, where the bag adds it. void count_supplies(Supplies& supplies, std::string_view item, size_t quantity); // The console's Mart. The money box and the quantity box have no reader // yet, so the money is the table's floor and the quantity is typed by -// presses. Potions, Antidotes and Parlyz Heals bought are counted into -// `supplies`. +// presses. Potions, Antidotes, Parlyz Heals and Awakenings bought are +// counted into `supplies`. class ConsoleMartActions : public MartActions{ public: ConsoleMartActions(ConsoleHandle& console, ProControllerContext& context, Language language, Supplies& supplies); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp index 78bcf52cb5..fee028a378 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart_Tests.cpp @@ -364,7 +364,8 @@ UnitTestResult test_mart_stock(){ } -// Potions, Antidotes and Parlyz Heals bought go into the battles' supplies. +// Potions, Antidotes, Parlyz Heals and Awakenings bought go into the +// battles' supplies. UnitTestResult test_count_supplies(){ Supplies supplies; supplies.pocket = {"potion"}; @@ -373,9 +374,11 @@ UnitTestResult test_count_supplies(){ count_supplies(supplies, "potion", 2); count_supplies(supplies, "repel", 4); count_supplies(supplies, "poke-ball", 5); - if (supplies.potions != 3 || supplies.antidotes != 3 || supplies.pocket != std::vector{"potion", "antidote"}){ - return std::format("Supplies {} potions, {} antidotes, {} pocket rows.", - supplies.potions, supplies.antidotes, supplies.pocket.size()); + count_supplies(supplies, "awakening", 3); + const std::vector pocket{"potion", "antidote", "awakening"}; + if (supplies.potions != 3 || supplies.antidotes != 3 || supplies.awakenings != 3 || supplies.pocket != pocket){ + return std::format("Supplies {} potions, {} antidotes, {} awakenings, {} pocket rows.", + supplies.potions, supplies.antidotes, supplies.awakenings, supplies.pocket.size()); } return true; } 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 59c7c827fa..c81e5d361d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp @@ -8,6 +8,7 @@ * */ +#include #include #include #include @@ -282,7 +283,8 @@ bool plans(const Pokemon::Pose& from, const Pokemon::Pose& to){ // 00.15, before the rival, from the Center: first TM03 Water Pulse over // Tail Whip if the lead doesn't know it, so the sim plays it in the // GRIND; Potions from Cerulean's Mart (a loaded save's bag may hold too -// few for the wild battles a GRIND fights); then a GRIND on Route 4's +// few for the wild battles a GRIND fights), and at its money floor 2 or +// more Awakenings for the rival's Sleep Powder; then a GRIND on Route 4's // grass east of Mt. Moon until the sim beats the rival 00.15b fights 70% // or more, healing at Cerulean's Center; its trip there plans both ways. UnitTestResult test_cerulean_mart_and_grind(){ @@ -309,6 +311,16 @@ UnitTestResult test_cerulean_mart_and_grind(){ if (mart == steps.size() || grind == steps.size()){ return "00.15: expected a Cerulean Mart step buying Potions, then a GRIND of the lead until the rival is 70%, capped above Lv25."; } + const MartPlan plan = *parse_mart_variant(steps[mart].variant); + const std::optional> buys = plan.money_floor + ? plan_mart_buys(mart_stock(plan.map), plan, *plan.money_floor) + : std::nullopt; + const bool awakenings = buys && std::ranges::any_of(*buys, [](const MartBuy& buy){ + return buy.item == "awakening" && buy.quantity >= 2; + }); + if (!awakenings){ + return "00.15: expected the Mart step to buy 2 or more Awakenings at its money floor."; + } const std::optional clerk = mart > 0 && steps[mart - 1].target ? story_pose(*steps[mart - 1].target) : std::nullopt; if (!clerk || clerk->map != "CeruleanCity_Mart"){ return "00.15: expected the Mart step right after a route to the clerk."; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index 0a7e4a6f87..d76ec4f992 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -597,9 +597,12 @@ StoryCheckpoint misty(){ // Before the rival north of Cerulean (cerulean_rival()), from the // Center: first TM03 Water Pulse over Tail Whip, if the lead doesn't know // it yet, so the GRIND's sim plays it (a run without TM03 from Misty -// skips the step). Then 5 Potions at the Mart +// skips the step). Then 3 Potions at the Mart // (CeruleanCity_Mart_Items: POTION is row 3, 300 each; Mt. Moon's -// trainers leave well over the floor), then a GRIND on Route 4's grass +// trainers leave well over the floor) and 2 Awakenings (row 6, 250 each; +// pokefirered items.json) for the rival's Bulbasaur's Sleep Powder +// (console B, m56: asleep at 34/65 HP, it fainted two turns later with +// 15 Potions), 1400 of the floor's 1500. Then a GRIND on Route 4's grass // east of Mt. Moon (75..86, 11..17; Spearow, Rattata, Ekans and Mankey // around Lv10, about 80 EXP each), healing at the Center, until the // battle sim beats the rival 00.15b fights 70% or more: the win chance @@ -610,7 +613,12 @@ StoryCheckpoint misty(){ // verified and retried from this save. StoryCheckpoint cerulean_grind(){ const TeachPlan water_pulse{.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}; - const MartPlan potions{.map = CERULEAN_MART, .lines = {{.item = "potion", .quantity = 5}}, .budget = 1500, .money_floor = 1500}; + const MartPlan potions{ + .map = CERULEAN_MART, + .lines = {{.item = "potion", .quantity = 3}, {.item = "awakening", .quantity = 2}}, + .budget = 1500, + .money_floor = 1500, + }; const GrindPlan for_rival{ .member = 0, .level = 28, .max_encounters = 150, .pace = WEST, .heal_every = 0, .trainer = std::string(story_trainer(CERULEAN, "rival_cerulean").value_or("")), .min_chance = MIN_WIN_CHANCE, @@ -618,7 +626,7 @@ StoryCheckpoint cerulean_grind(){ return row("00.15", "Cerulean: Water Pulse, Potions, a GRIND until the rival is winnable, then saved below his trigger", at(CERULEAN_CENTER, 7, 4, NORTH), after_brock(), StartMenu::FULL, { teach_step("teach_water_pulse", "TM03 Water Pulse in place of Tail Whip, unless the lead knows it or there is no TM03", water_pulse), running(route("mart_clerk", at(CERULEAN_MART, 4, 3, WEST), "out of the Center to the Mart's clerk")), - mart_step("buy_potions", "5 Potions: the GRIND fights wild battles only with 2 or more", potions), + mart_step("buy_potions", "3 Potions: the GRIND fights wild battles only with 2 or more; 2 Awakenings for the rival's Sleep Powder", potions), running(route("grind_patch", at(ROUTE4, 86, 16, WEST), "west out of the city along Route 4's lower road onto its grass's east edge")), grind_step("grind_for_rival", "wild battles until the sim beats the rival 70% or more, Lv28 at most; the nurse when hurt or low on PP", for_rival, at(CERULEAN_CENTER, 7, 4, NORTH)), running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "back to the Center: the rival's battle starts at full HP and PP")), diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp index 5a636778dd..7d38a1aa2e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp @@ -90,9 +90,9 @@ void change_stage(SimBattler& user, SimBattler& target, std::string_view effect) // One battle, played once. class SimBattle{ public: - SimBattle(const SimBattler& own, int potions, const SimTrainer& trainer, std::mt19937& rng) + SimBattle(const SimBattler& own, const SimItems& items, const SimTrainer& trainer, std::mt19937& rng) : m_own(own) - , m_potions(potions) + , m_items(items) , m_trainer(trainer) , m_rng(rng) {} @@ -151,18 +151,24 @@ class SimBattle{ void play_turn(){ const size_t left = foes_left(); - const OwnTurn own = own_turn(m_own, m_potions, foe(), m_trainer.items, left); + const OwnTurn own = own_turn(m_own, m_items, foe(), m_trainer.items, left); const std::optional item = ai_item_choice(foe(), m_trainer.items, left); const std::optional foe_slot = item ? std::nullopt : foe_move(); if (own.potion){ gain_hp(m_own, POTION_HP); - m_potions--; + m_items.potions--; + } + if (own.awakening){ + m_own.status = SimStatus::NONE; + m_own.sleep = 0; + m_items.awakenings--; } if (item){ gain_hp(foe(), ai_item_hp(m_trainer.items[*item])); m_trainer.items[*item].clear(); } - const std::string own_move = own.potion ? "" : own.slot ? m_own.moves[*own.slot].move : "struggle"; + const bool item_used = own.potion || own.awakening; + const std::string own_move = item_used ? "" : own.slot ? m_own.moves[*own.slot].move : "struggle"; const std::string foe_used = item ? "" : foe_slot ? foe().moves[*foe_slot].move : "struggle"; play_moves(own_move, own.slot, foe_used, foe_slot); end_of_turn(); @@ -341,7 +347,7 @@ class SimBattle{ } SimBattler m_own; - int m_potions; + SimItems m_items; SimTrainer m_trainer; std::mt19937& m_rng; size_t m_out = 0; @@ -351,31 +357,34 @@ class SimBattle{ } -WinEstimate estimate_win_chance(const SimBattler& own, int potions, const SimTrainer& trainer, size_t battles, uint32_t seed){ +WinEstimate estimate_win_chance(const SimBattler& own, const SimItems& items, const SimTrainer& trainer, size_t battles, uint32_t seed){ std::mt19937 rng(seed); WinEstimate estimate{.battles = battles, .wins = 0, .chance = 0}; for (size_t i = 0; i < battles; i++){ - SimBattle battle(own, potions, trainer, rng); + SimBattle battle(own, items, trainer, rng); estimate.wins += battle.won() ? 1 : 0; } estimate.chance = battles == 0 ? 0 : static_cast(estimate.wins) / battles; return estimate; } -std::optional story_win_chance(const PartyMember& lead, int potions, double hp_share, std::string_view trainer){ +std::optional story_win_chance(const PartyMember& lead, const SimItems& items, double hp_share, std::string_view trainer){ const std::optional own = own_battler(lead, hp_share); const std::optional sim = sim_trainer(trainer); if (!own || !sim){ return std::nullopt; } - WinEstimate estimate = estimate_win_chance(*own, potions, *sim); + WinEstimate estimate = estimate_win_chance(*own, items, *sim); estimate.inputs = std::format("{} Lv{} {}/{} HP:", own->species, own->body.level, own->hp, own->body.stats.hp); for (size_t slot = 0; slot < own->moves.size(); slot++){ estimate.inputs += std::format( "{} {} {}/{}", slot == 0 ? "" : ",", own->moves[slot].move, own->moves[slot].pp, max_pp(own->moves[slot].move) ); } - estimate.inputs += std::format("; {} Potions", potions); + estimate.inputs += std::format("; {} Potions", items.potions); + if (items.awakenings > 0){ + estimate.inputs += std::format(", {} Awakenings", items.awakenings); + } return estimate; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h index 9056a41f83..7404364a47 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h @@ -10,7 +10,7 @@ * AI's ties. Too low a chance stops the story before the fight, for a * GRIND or the nurse first. * - * Each turn: the Potion and the AI's item first, then the moves by + * Each turn: the Potion or Awakening and the AI's item first, then the moves by * priority and speed (a quarter with PARALYSIS). Sleep (2 to 5 on the * game's counter), poison (1/8 HP a turn), paralysis (1/4 no move), Leech * Seed (1/8 a turn to the other side), flinch, one- and two-stage stat @@ -41,18 +41,18 @@ struct WinEstimate{ size_t wins = 0; // wins / battles double chance = 0; - // The lead and Potions the battles were played with, for the log: - // "wartortle Lv20 60/60 HP: bite 25/25, ...; 5 Potions". + // The lead and items the battles were played with, for the log: + // "wartortle Lv20 60/60 HP: bite 25/25, ...; 5 Potions, 2 Awakenings". std::string inputs = {}; }; -// `own` with `potions` Potions against `trainer`, `battles` times, from a -// fixed `seed` so the same inputs give the same estimate. -WinEstimate estimate_win_chance(const SimBattler& own, int potions, const SimTrainer& trainer, size_t battles = 1000, uint32_t seed = 1); +// `own` with `items` against `trainer`, `battles` times, from a fixed +// `seed` so the same inputs give the same estimate. +WinEstimate estimate_win_chance(const SimBattler& own, const SimItems& items, const SimTrainer& trainer, size_t battles = 1000, uint32_t seed = 1); -// The story's lead (`hp_share` of its HP) with `potions` against +// The story's lead (`hp_share` of its HP) with `items` against // `trainer`. None if the data lacks the lead's species or the trainer. -std::optional story_win_chance(const PartyMember& lead, int potions, double hp_share, std::string_view trainer); +std::optional story_win_chance(const PartyMember& lead, const SimItems& items, double hp_share, std::string_view trainer); // Why not to fight: "win chance 41% < 70% with : grind first", or // none at `minimum` or above. From 2148c9615d8f2e38e310396bcfd2c76f12a63f8d Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 10:22:40 -0800 Subject: [PATCH 3/6] FRLG AutoStory: bridge trainer lines, preparation once per save, 50% win chance Nugget Bridge (00.16) failed twice on console B with "bug_catcher_cale: no_battle": the open leg onto the bridge ended on (11, 33), a tile short, and the one step onto Cale's row reached only (11, 32), out of his sight. A STEP of the new TRAINER_LINE_VARIANT (into_line() in the table) now steps a tile at a time, at most 3, until a trainer's message or battle shows (step_until_seen()), and the five bridge lines use it. The battle's end pose stays the trainer's row. A story sim test walks the row on the OverworldSim from the walk's end whole and a tile short; it failed with the console's error before. Preparation runs once per save. StoryStep::once_per_save marks a step that a retry after a reload of the same save skips once it succeeded changing nothing (the new Outcome::changed_nothing); one that changed the game runs again, as the reload undid it. build_story_checkpoint() takes the PreparedSteps memory, which FRLG keeps in StoryEnv across reloads and empties on a save. TEACH and MART steps are once per save, and report changed_nothing for a move already known, no TM, or nothing to buy. The reload hook reads the bag only until one read is complete. Runner tests cover a retry after a loss and verify mode's three runs. MIN_WIN_CHANCE is 0.50: the Cerulean rival at a sim chance of 56% passed console verification 2 of 3 (m56), and verify mode is the backstop for HIGH battles. Tests that assumed 70% now use 50%. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Pokemon/AutoStory/Pokemon_StoryEvents.cpp | 5 + .../Pokemon/AutoStory/Pokemon_StoryEvents.h | 6 + .../Pokemon/AutoStory/Pokemon_StorySteps.cpp | 36 ++++++ .../Pokemon/AutoStory/Pokemon_StorySteps.h | 18 +++ .../AutoStory/Pokemon_StorySteps_Tests.cpp | 115 +++++++++++++++++- .../AutoStory/PokemonFRLG_AutoStory.cpp | 11 +- .../PokemonFRLG_AutoStoryAbilities.cpp | 15 ++- .../PokemonFRLG_AutoStoryAbilities.h | 3 +- .../PokemonFRLG_AutoStoryAbilities_Tests.cpp | 40 ++++-- .../PokemonFRLG_AutoStoryActions.cpp | 28 +++++ .../AutoStory/PokemonFRLG_AutoStoryActions.h | 22 ++++ .../PokemonFRLG_AutoStoryBattleData.h | 7 +- .../PokemonFRLG_AutoStoryBattleSim_Tests.cpp | 29 ++++- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 26 +++- .../AutoStory/PokemonFRLG_AutoStoryEvents.h | 16 ++- .../PokemonFRLG_AutoStoryGrind_Tests.cpp | 20 +-- .../AutoStory/PokemonFRLG_AutoStoryMart.cpp | 1 + .../AutoStory/PokemonFRLG_AutoStoryMart.h | 3 +- .../PokemonFRLG_AutoStoryRunPlan_Tests.cpp | 4 +- .../PokemonFRLG_AutoStorySimulation_Tests.cpp | 97 ++++++++++++++- .../AutoStory/PokemonFRLG_AutoStoryTable.cpp | 39 ++++-- .../AutoStory/PokemonFRLG_AutoStoryTeach.cpp | 1 + .../AutoStory/PokemonFRLG_AutoStoryTeach.h | 3 + .../PokemonFRLG_AutoStoryWinChance.h | 2 +- .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 24 +++- 25 files changed, 509 insertions(+), 62 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp index fcbada5a5a..239ecf5d3b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -68,6 +68,11 @@ Outcome outcome_ok(Pose pose){ outcome.pose = std::move(pose); return outcome; } +Outcome outcome_unchanged(){ + Outcome outcome; + outcome.changed_nothing = true; + return outcome; +} Outcome outcome_failed(std::string failure, std::string detail){ Outcome outcome; outcome.failure = std::move(failure); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h index 6ff7dd4141..f2251513a2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -95,11 +95,17 @@ struct Outcome{ std::string failure; std::string detail; std::optional pose; + // A succeeded action that left the game as it found it: a read, a + // check, a TM the lead already knows. A reload of the same save undoes + // nothing it did. + bool changed_nothing = false; bool succeeded() const; }; Outcome outcome_ok(); Outcome outcome_ok(Pose pose); +// outcome_ok() with `changed_nothing`. +Outcome outcome_unchanged(); Outcome outcome_failed(std::string failure, std::string detail = ""); // "probe_exhausted: 4 rows": the failure and its detail, if any. std::string to_string(const Outcome& outcome); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp index 2d6a0e9383..17bd688abf 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp @@ -203,6 +203,38 @@ Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor return checkpoint; } +namespace{ + +// `event`, for a once_per_save step known in `prepared` as `key`: skipped +// while `prepared` has it, and added to it when it succeeds changing +// nothing. +void run_once_per_save(Event& event, std::string key, PreparedSteps& prepared){ + event.skip_if.push_back(condition("done_from_this_save", [&prepared, key](RunState&){ + return prepared.contains(key); + })); + event.act = [act = std::move(event.act), &prepared, key](RunState& state) mutable{ + Outcome outcome = act(state); + if (outcome.succeeded() && outcome.changed_nothing){ + prepared.insert(key); + } + return outcome; + }; +} + +} + +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps& prepared){ + Checkpoint checkpoint = build_story_checkpoint(data, executor); + // After "from_save", the events are the steps in order. + const size_t first = data.start ? 1 : 0; + for (size_t c = 0; c < data.steps.size(); c++){ + if (data.steps[c].once_per_save){ + run_once_per_save(checkpoint.events[first + c], data.id + "/" + data.steps[c].name, prepared); + } + } + return checkpoint; +} + namespace{ @@ -253,6 +285,10 @@ std::vector lint_story_checkpoint(const StoryCheckpoint& data){ if (!missing.empty()){ problems.emplace_back(std::format("{} {}: {} {}", where, step.name, story_step_kind_name(step.kind), missing)); } + // skip_if's conditions must all hold; once per save is one more. + if (step.once_per_save && !step.skip_if.empty()){ + problems.emplace_back(std::format("{} {}: once per save with skip_if", where, step.name)); + } } return problems; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h index d32868aeef..cc9607e135 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h @@ -33,6 +33,7 @@ #include #include +#include #include #include #include "CommonFramework/Language.h" @@ -119,6 +120,13 @@ struct StoryStep{ // the game's executor answers (StoryStepExecutor::holds()), run flags // unless the game reads them off the screen. std::vector skip_if; + // Preparation for what follows, done once per save: a TEACH, a check, + // a read. Once it has succeeded and changed nothing + // (Outcome::changed_nothing), the attempts after a reload of the same + // save skip it, so a retry goes from the reload straight to the + // battle. One that changed the game (a TM taught) runs again, as the + // reload undid it. Only with build_story_checkpoint()'s PreparedSteps. + bool once_per_save = false; // 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; @@ -213,6 +221,16 @@ Event story_event(const StoryStep& step, StoryStepExecutor& executor); // game's: it sets the checkpoint's save, or adds a SAVE step. Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor); +// The once_per_save steps done from the save the game is on that changed +// nothing, as "/". The game keeps it across reloads and +// empties it when it saves or loads another save. +using PreparedSteps = std::set; + +// As above, and each once_per_save step is skipped while `prepared` has +// it, and added to it when it succeeds changing nothing. `prepared` must +// outlive the checkpoint. +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps& prepared); + // Problems an author should fix before running: an empty id, unnamed or // repeated steps, a route or READY without a target, empty legs, a GAME // step without a variant, TRAIN without battles, SHOP without items. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp index 321362a126..eb42435652 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp @@ -46,6 +46,8 @@ class FakeExecutor : public StoryStepExecutor{ std::vector> poses_seen; // The checkpoints begun, one per attempt. std::vector attempts; + // Game steps by name that change nothing in the game. + std::set unchanged; virtual void begin_attempt(const StoryCheckpoint& data) override{ attempts.push_back(data.id); @@ -99,7 +101,7 @@ class FakeExecutor : public StoryStepExecutor{ virtual Outcome game(RunState& state, const StoryStep& step) override{ trace.push_back(" game " + step.variant); state.flags.insert(step.variant); - return outcome_ok(); + return unchanged.contains(step.name) ? outcome_unchanged() : outcome_ok(); } }; @@ -466,6 +468,115 @@ UnitTestResult test_policy_recovers_in_place(){ return true; } +// A boss's checkpoint: a TEACH of a move the lead knows (changes +// nothing), a TEACH that teaches, both once per save, then the battle, +// lost on the first attempt. The segment's saves empty `prepared`. +struct BossLab{ + StoryCheckpoint table{ + .id = "00.15b", + .title = "the rival", + .start = tile_pose("Cerulean", {{23, 7}}, Direction::NORTH), + .steps = {once("teach_known"), once("teach_new"), make(StoryStepKind::BATTLE, "rival")}, + }; + FakeExecutor executor; + PreparedSteps prepared; + std::vector lines; + + static StoryStep once(std::string name){ + StoryStep step = make(StoryStepKind::GAME, name); + step.variant = name; + step.once_per_save = true; + return step; + } + BossLab(){ + executor.unchanged = {"teach_known"}; + } + Segment segment(){ + Segment segment; + segment.id = "00"; + segment.checkpoints.push_back(CheckpointSpec{ + .id = table.id, .title = table.title, .saves = true, + .build = [this]{ return build_story_checkpoint(table, executor, prepared); }, + }); + return segment; + } + SegmentHooks hooks(){ + SegmentHooks hooks; + hooks.save = [this](RunState&){ + executor.trace.push_back("save"); + prepared.clear(); + return outcome_ok(); + }; + hooks.reload = [this](RunState&){ + executor.trace.push_back("reload"); + return outcome_ok(); + }; + hooks.log = [this](const std::string& line){ lines.push_back(line); }; + return hooks; + } + size_t count(const std::string& item) const{ + return (size_t)std::count(executor.trace.begin(), executor.trace.end(), item); + } +}; + +// A retry after a reload of the same save skips the preparation that +// changed nothing and goes to the battle; the TEACH that taught runs +// again, as the reload undid it. The save at the end empties the memory. +UnitTestResult test_once_per_save_retry(){ + BossLab lab; + StoryStep battle = make(StoryStepKind::BATTLE, "rival"); + battle.may_lose = true; + lab.table.steps.back() = battle; + lab.executor.failures_left = {{"rival", 1}}; + Segment segment = lab.segment(); + SegmentHooks hooks = lab.hooks(); + RunState state; + const SegmentReport report = run_segment(state, segment, SegmentRange{}, SegmentPolicy{}, hooks); + if (!report.completed || report.reloads != 1 || lab.count("GAME teach_known") != 1 + || lab.count("GAME teach_new") != 2 || lab.count("BATTLE rival") != 2 + ){ + return "Expected the known TEACH once, the new one twice, the battle twice:" + joined(lab.executor.trace) + joined(lab.lines); + } + if (!lab.prepared.empty()){ + return "Expected the save to empty the prepared steps."; + } + return true; +} + +// Verify mode: three runs from one save; the preparation that changed +// nothing runs in the first only. +UnitTestResult test_once_per_save_verify(){ + BossLab lab; + StoryStep battle = make(StoryStepKind::BATTLE, "rival"); + battle.may_lose = true; + lab.table.steps.back() = battle; + Segment segment = lab.segment(); + SegmentHooks hooks = lab.hooks(); + RunState state; + const VerifyReport report = verify_checkpoint(state, segment, "00.15b", VerifyPolicy{}, hooks); + if (!report.verified || report.runs != 3 || lab.count("GAME teach_known") != 1 + || lab.count("GAME teach_new") != 3 || lab.count("BATTLE rival") != 3 + ){ + return "Expected the known TEACH once in 3 runs, the new one each run:" + joined(lab.executor.trace) + joined(lab.lines); + } + // Without the memory, every run prepares. + FakeExecutor plain; + plain.unchanged = {"teach_known"}; + Segment without; + without.id = "00"; + without.checkpoints.push_back(CheckpointSpec{ + .id = lab.table.id, .title = "", .saves = true, + .build = [&]{ return build_story_checkpoint(lab.table, plain); }, + }); + RunState again; + verify_checkpoint(again, without, "00.15b", VerifyPolicy{}, hooks); + if (std::count(plain.trace.begin(), plain.trace.end(), "GAME teach_known") != 3){ + return "Expected every run to prepare without PreparedSteps:" + joined(plain.trace); + } + return true; +} + + // The checks level: THOROUGH by default, and what the program sets is // what a step reads. UnitTestResult test_checks_level(){ @@ -662,6 +773,8 @@ void add_tests_StorySteps(UnitTestDatabase& database){ database.add("policy: attempts per checkpoint, then fail", test_policy_attempts_then_fail); database.add("policy: stop at the first failure", test_policy_stop_at_first_failure); database.add("policy: recover in place before reloading", test_policy_recovers_in_place); + database.add("once per save: a retry skips what changed nothing", test_once_per_save_retry); + database.add("once per save: verify runs prepare once", test_once_per_save_verify); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index b033fca258..e823df801c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -177,10 +177,13 @@ Pokemon::SegmentHooks story_hooks(SingleSwitchProgramEnvironment& env, StoryEnv& return Pokemon::outcome_failed("wrong_save", error); } story.supplies = story.saved_supplies; - // Every reload, so each verify run starts from the bag as the - // save holds it, not from a count once read wrong or not at - // all (console B, 2026-11-03: 0 Potions in all 3 runs). - read_bag_supplies(story, story.start_menu); + // Until read in full, so each verify run starts from the bag + // as the save holds it, not from a count once read wrong or + // not at all (console B, 2026-11-03: 0 Potions in all 3 + // runs). Once read, a reload of the same save restores it. + if (!story.bag_read){ + read_bag_supplies(story, story.start_menu); + } }catch (OperationFailedException& e){ return Pokemon::outcome_failed("reload_failed", e.message()); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp index d02816e771..c73861fcf1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.cpp @@ -19,17 +19,22 @@ namespace{ Outcome mart(Logger& logger, const MartPlan& plan, StoryAbilities& abilities){ const MartResult result = run_mart(logger, abilities.mart, plan); const std::string message = mart_message(plan, result); - const bool ok = result.end == MartEnd::DONE || result.end == MartEnd::NOTHING_TO_BUY; logger.log(message, result.end == MartEnd::DONE ? COLOR_BLACK : COLOR_RED); - return ok ? Pokemon::outcome_ok() : Pokemon::outcome_failed(std::string("mart_") + mart_end_name(result.end), message); + if (result.end == MartEnd::NOTHING_TO_BUY){ + return Pokemon::outcome_unchanged(); + } + return result.end == MartEnd::DONE ? Pokemon::outcome_ok() : Pokemon::outcome_failed(std::string("mart_") + mart_end_name(result.end), message); } Outcome teach(Logger& logger, const TeachPlan& plan, StoryAbilities& abilities){ const TeachResult result = run_teach(logger, abilities.teach, abilities.members, plan); - // NO_ITEM: skipped, with run_teach()'s log line. - if (result.end == TeachEnd::LEARNED || result.end == TeachEnd::ALREADY_KNOWN || result.end == TeachEnd::NO_ITEM){ + if (result.end == TeachEnd::LEARNED){ return Pokemon::outcome_ok(); } + // NO_ITEM: skipped, with run_teach()'s log line. + if (result.end == TeachEnd::ALREADY_KNOWN || result.end == TeachEnd::NO_ITEM){ + return Pokemon::outcome_unchanged(); + } return Pokemon::outcome_failed(std::string("teach_") + teach_end_name(result.end), teach_message(plan, result)); } @@ -37,7 +42,7 @@ Outcome level(Logger& logger, const LevelCheck& check, StoryAbilities& abilities const LevelResult result = run_level_check(logger, abilities.members, check); switch (result.end){ case LevelEnd::REACHED: - return Pokemon::outcome_ok(); + return Pokemon::outcome_unchanged(); case LevelEnd::BELOW: return Pokemon::outcome_failed("level_below", std::to_string(*result.level) + " < " + std::to_string(check.level)); case LevelEnd::UNREAD: diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h index 2a61bfb467..89a47e486b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h @@ -44,7 +44,8 @@ struct StoryAbilities{ // the segment stops without reloading. Any other end but success is a // failed Outcome; a MART that buys nothing because the money doesn't // cover it, and a TEACH whose TM isn't in the TM CASE, succeed, with the -// reason logged. +// reason logged. Those, a TEACH of a move the member knows and a LEVEL +// reached change nothing in the game (Outcome::changed_nothing). std::optional run_ability_game_step( Logger& logger, VideoStream* stream, const Pokemon::StoryStep& step, StoryAbilities& abilities ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp index a0f06a450f..ce94f5c82f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryAbilities_Tests.cpp @@ -110,8 +110,9 @@ Pokemon::StoryStep game_step(std::string variant){ return step; } -// The failure name the step ends with ("" for success); "none" if it -// isn't one of these steps. +// The failure name the step ends with ("" for success, "unchanged" for +// one that changed nothing in the game); "none" if it isn't one of these +// steps. std::string run_step(StubGame& game, const Pokemon::StoryStep& step){ QuietLogger logger; const MemberReader members = [&game](size_t slot) -> std::optional{ @@ -122,7 +123,10 @@ std::string run_step(StubGame& game, const Pokemon::StoryStep& step){ }; StoryAbilities abilities{members, game.mart, game.teach, game.patch, game.fossils}; const std::optional outcome = run_ability_game_step(logger, nullptr, step, abilities); - return outcome ? outcome->failure : "none"; + if (!outcome){ + return "none"; + } + return outcome->changed_nothing ? "unchanged" : outcome->failure; } struct StepCase{ @@ -136,13 +140,13 @@ std::vector step_cases(){ const auto none = [](StubGame&){}; const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); return { - {"level reached", none, level_step("check", "", {.slot = 0, .level = 16}), ""}, + {"level reached", none, level_step("check", "", {.slot = 0, .level = 16}), "unchanged"}, {"level below", none, level_step("check", "", {.slot = 0, .level = 17}), "level_below"}, {"level unread", [](StubGame& game){ game.level.reset(); }, level_step("check", "", {.slot = 0, .level = 16}), "level_unread"}, - {"a Mart with too little money succeeds", [](StubGame& game){ game.mart.money = 100; }, game_step("mart PewterCity_Mart budget=2000 potion=5"), ""}, + {"a Mart with too little money succeeds", [](StubGame& game){ game.mart.money = 100; }, game_step("mart PewterCity_Mart budget=2000 potion=5"), "unchanged"}, {"a Mart purchase that fails", none, game_step("mart PewterCity_Mart budget=2000 potion=5"), "mart_failed"}, - {"a move it knows already succeeds", none, game_step("teach hm03 surf slot=1"), ""}, - {"a TM not in the TM Case is skipped", none, game_step("teach tm03 water-pulse slot=1 forget=water-gun"), ""}, + {"a move it knows already succeeds", none, game_step("teach hm03 surf slot=1"), "unchanged"}, + {"a TM not in the TM Case is skipped", none, game_step("teach tm03 water-pulse slot=1 forget=water-gun"), "unchanged"}, {"a level that can't be read stops a GRIND", [](StubGame& game){ game.level.reset(); }, grind, "grind_unread"}, {"a GRIND without a nurse", none, game_step("grind slot=1 level=20"), "bad_variant"}, {"no YES/NO at the fossil", none, fossil_step("fossil", "", Fossil::HELIX), "fossil_failed"}, @@ -164,6 +168,27 @@ UnitTestResult test_ability_steps(){ } +// TEACH and MART steps are preparation, once per save: a retry from the +// same save skips one that changed nothing. A LEVEL check, which follows +// a GRIND, and the GRIND run every attempt. +UnitTestResult test_once_per_save_steps(){ + const std::vector once{ + teach_step("teach", "", {.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}), + mart_step("mart", "", {.map = "CeruleanCity_Mart", .lines = {{.item = "potion", .quantity = 3}}, .budget = 1500, .money_floor = 1500}), + }; + for (const Pokemon::StoryStep& step : once){ + if (!step.once_per_save){ + return step.name + ": expected once per save."; + } + } + const Pokemon::StoryStep grind = grind_step("grind", "", {.member = 0, .level = 20, .max_encounters = 5, .pace = Pokemon::Direction::EAST, .heal_every = 0}, {}); + if (grind.once_per_save || level_step("level", "", {.slot = 0, .level = 16}).once_per_save){ + return "GRIND and LEVEL: expected every attempt."; + } + return true; +} + + // A shiny in a GRIND stops the program, not the checkpoint: a reload // would lose it. UnitTestResult test_grind_shiny_stops(){ @@ -201,6 +226,7 @@ void add_tests_AutoStoryAbilities(UnitTestDatabase& database){ database.add(std::move(name), body); }; add("the steps' ends as outcomes", test_ability_steps); + add("TEACH and MART run once per save", test_once_per_save_steps); add("a shiny in a GRIND stops the program", test_grind_shiny_stops); add("the LEVEL step's variant", test_level_variant); add_tests_AutoStoryMart(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 6512c02174..586e5a01c1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -564,6 +564,34 @@ void step_once(ProControllerContext& context, Direction direction, std::optional context.wait_for_all_requests(); } +std::optional step_until_seen(int max_tiles, const std::function& step, const std::function& seen){ + for (int tiles = 1; tiles <= max_tiles; tiles++){ + step(); + if (seen()){ + return tiles; + } + } + return std::nullopt; +} + +std::optional step_into_line( + ConsoleHandle& console, ProControllerContext& context, + Direction direction, std::optional facing, int max_tiles +){ + return step_until_seen( + max_tiles, + [&]{ + step_once(context, direction, facing); + facing = direction; + }, + [&]{ + WhiteDialogWatcher message(COLOR_RED); + BattleScreenWatcher battle(COLOR_RED); + return wait_until(console, context, TRAINER_LINE_WATCH, {message, battle}) >= 0; + } + ); +} + void face_wall(ProControllerContext& context, Direction direction){ pbf_press_dpad(context, dpad(direction), TURN_TAP, TURN_SETTLE); context.wait_for_all_requests(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h index 5e07d1cd4c..e555294448 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h @@ -15,6 +15,7 @@ #define PokemonAutomation_PokemonFRLG_AutoStoryActions_H #include +#include #include #include #include @@ -111,6 +112,27 @@ void answer_yes_no(ConsoleHandle& console, ProControllerContext& context, bool y // way is turned first. void step_once(ProControllerContext& context, Pokemon::Direction direction, std::optional facing); +// Steps with `step` a tile at a time, at most `max_tiles`, until `seen` +// says a trainer saw the player. Returns the tiles stepped, or nothing +// if no trainer did. A walk that ended a tile short of a trainer's line +// still meets them (console B, 2026-11-03, Nugget Bridge: the walk ended +// on (11, 33), one step reached (11, 32), and Cale on row 31 never saw +// the player). +std::optional step_until_seen(int max_tiles, const std::function& step, const std::function& seen); + +// How long after a step into a trainer's line their message shows: the +// "!", then their words, as the route walker watches for a trainer +// with no tiles to walk up (PokemonFRLG_OverworldRecoveryWalk.cpp). +inline constexpr Milliseconds TRAINER_LINE_WATCH(2500); + +// From the overworld: step_until_seen() `direction`, turning first +// unless `facing` is `direction`, each step watched TRAINER_LINE_WATCH +// for a trainer's message or battle. +std::optional step_into_line( + ConsoleHandle& console, ProControllerContext& context, + Pokemon::Direction direction, std::optional facing, int max_tiles +); + // From the overworld, turns to face `direction` without stepping: the // player must have a wall that way. void face_wall(ProControllerContext& context, Pokemon::Direction direction); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h index cc15a6b446..58c554e8ff 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h @@ -158,8 +158,11 @@ BattleRisk default_battle_risk(std::string_view trainer); // else its trainer's default. LOW for a battle the table doesn't name. BattleRisk story_battle_risk(std::string_view map, std::string_view battle); -// A HIGH battle is fought only if the sim wins at least this often. -inline constexpr double MIN_WIN_CHANCE = 0.70; +// A HIGH battle is fought only if the sim wins at least this often. Half: +// the Cerulean rival at a sim chance of 56% passed console verification +// 2 of 3 (console B, 2026-11-03, m56), and verify mode, run from a save +// right before the battle, is the backstop for HIGH battles. +inline constexpr double MIN_WIN_CHANCE = 0.50; // (name, JSON text) of each file in BattleData/, sorted by name. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp index 86fd74652d..14f9a31293 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp @@ -280,7 +280,7 @@ UnitTestResult test_rival_win_chance(){ if (!planned || planned->chance < 0.15 || planned->chance > 0.40){ return std::format("Lv22, 5 Potions: expected 15% to 40%, got {:.1f}%.", planned ? 100 * planned->chance : 0.0); } - if (refusal != std::format("win chance {:.0f}% < 70% with {}: grind first", std::floor(100 * planned->chance), planned->inputs)){ + if (refusal != std::format("win chance {:.0f}% < 50% with {}: grind first", std::floor(100 * planned->chance), planned->inputs)){ return "Lv22, 5 Potions: expected a refusal with the chance, got \"" + refusal.value_or("") + "\"."; } const std::optional ground = story_win_chance(grown_to(new_member("squirtle", 5), 30), SimItems{.potions = 5}, 1.0, RIVAL); @@ -291,6 +291,22 @@ UnitTestResult test_rival_win_chance(){ } +// Console B, 2026-11-03 (m56): the Cerulean rival at a sim chance of +// 56% was won 2 of 3 in verify mode, so a battle that close is fought, +// with verify mode as the backstop; one under half is still refused. +UnitTestResult test_threshold_m56(){ + const WinEstimate m56{.battles = 1000, .wins = 560, .chance = 0.56, .inputs = "m56"}; + if (const std::optional refusal = win_chance_refusal(m56)){ + return "56%: expected the battle fought, got \"" + *refusal + "\"."; + } + const WinEstimate close{.battles = 1000, .wins = 490, .chance = 0.49, .inputs = "close"}; + if (win_chance_refusal(close) != "win chance 49% < 50% with close: grind first"){ + return "49%: expected a refusal naming 50%, got \"" + win_chance_refusal(close).value_or("") + "\"."; + } + return true; +} + + // Console B, 2026-11-03 (run m51), Misty: the Wartortle's moves, Bite, // Tail Whip, Bubble, Withdraw (Water Gun was lost earlier). std::vector m51_moves(){ @@ -408,9 +424,9 @@ UnitTestResult test_misty_real_lead(){ } // The Cerulean rival against m51's moves (no Water Gun), the levels -// since the summary added to its stats: refused at Lv20, 22 and 25 (about -// 32%, 37%, 66%), fought at Lv30 (about 95%). The refusal names the -// chance and the lead it was played with. +// since the summary added to its stats: refused at Lv20 and 22 (about +// 32%, 37%), fought at Lv25 and 30 (about 66%, 95%). The refusal names +// the chance and the lead it was played with. UnitTestResult test_rival_real_moves(){ const std::vector> cases = { {20, 0.20, 0.45}, {22, 0.25, 0.50}, {25, 0.50, 0.70}, {30, 0.90, 1.00}, @@ -421,8 +437,8 @@ UnitTestResult test_rival_real_moves(){ return std::format("Lv{}: expected {:.0f}% to {:.0f}%, got {:.1f}%.", level, 100 * low, 100 * high, estimate ? 100 * estimate->chance : 0.0); } const bool refused = win_chance_refusal(*estimate).has_value(); - if (refused != (level < 30)){ - return std::format("Lv{} at {:.1f}%: expected {}.", level, 100 * estimate->chance, level < 30 ? "a refusal" : "no refusal"); + if (refused != (level < 25)){ + return std::format("Lv{} at {:.1f}%: expected {}.", level, 100 * estimate->chance, level < 25 ? "a refusal" : "no refusal"); } } const std::optional lv22 = story_win_chance(m51_lead(22), SimItems{.potions = 5}, 1.0, RIVAL); @@ -563,6 +579,7 @@ void add_tests_AutoStoryBattleSim(UnitTestDatabase& database){ database.add("the rival's next Pokemon when no name is read", test_next_foe); database.add("battle risks by trainer", test_risks); database.add("Cerulean rival: refused at Lv22, fought at Lv30", test_rival_win_chance); + database.add("m56: a 56% battle is fought, 49% refused", test_threshold_m56); database.add("m51: no Potion the foe's hit undoes", test_m51_potion_loop); database.add("the sim's Potion: only when it outheals the hit", test_sim_potion_rule); database.add("Misty: m51's lead as the summary showed it", test_misty_real_lead); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 52b2d4e820..af964ce8d3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -146,12 +146,26 @@ Outcome walk_legs(StoryEnv& env, RunState& state, const StoryStep& step){ } Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ - step_once(env.context, step.direction, facing_of(state.pose)); + int tiles_stepped = 1; + if (step.variant == TRAINER_LINE_VARIANT){ + const std::optional stepped = step_into_line(env.console, env.context, step.direction, facing_of(state.pose), TRAINER_LINE_TILES); + if (!stepped){ + return Pokemon::outcome_failed("no_trainer", std::format("{} tiles {}", TRAINER_LINE_TILES, direction_name(step.direction))); + } + env.console.log(std::format("Story: {}: a trainer saw the player after {} tile(s).", step.name, *stepped)); + tiles_stepped = *stepped; + }else{ + step_once(env.context, step.direction, facing_of(state.pose)); + } const std::vector tiles = Pokemon::tiles_of(state.pose); if (tiles.size() != 1){ return Pokemon::outcome_ok(); } - return Pokemon::outcome_ok(to_pose(StoryPose{state.pose.map, tiles[0].next(step.direction), step.direction})); + TilePos onto = tiles[0]; + for (int c = 0; c < tiles_stepped; c++){ + onto = onto.next(step.direction); + } + return Pokemon::outcome_ok(to_pose(StoryPose{state.pose.map, onto, step.direction})); } // Before a BattleRisk::HIGH battle the story may lose: the sim's win @@ -633,17 +647,19 @@ void read_bag_supplies(StoryEnv& env, StartMenu menu){ env.console.log("Couldn't read the Items pocket; going on with the checkpoint's items.", COLOR_ORANGE); return; } - for (const std::string& item : set_from_loaded_bag(env.supplies, env.saved_supplies, rows)){ + const std::vector unread = set_from_loaded_bag(env.supplies, env.saved_supplies, rows); + for (const std::string& item : unread){ env.console.log(std::format( "Story: couldn't read how many {} the bag holds; counting {}.", item, item_count(env.supplies, item) ), COLOR_ORANGE); } + env.bag_read = unread.empty(); } Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryExecutor& executor){ executor.set_menu(data.menu); - Pokemon::Checkpoint checkpoint = Pokemon::build_story_checkpoint(data, executor); StoryEnv& env = executor.env(); + Pokemon::Checkpoint checkpoint = Pokemon::build_story_checkpoint(data, executor, env.prepared); env.start_map = data.start ? data.start->map : ""; env.start_menu = data.menu; const StartMenu menu = data.menu; @@ -652,6 +668,8 @@ Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryExecutor& save_game(env.console, env.context, menu); env.has_save = true; env.saved_supplies = env.supplies; + env.prepared.clear(); + env.bag_read = false; return Pokemon::outcome_ok(); }); }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index a0000f2d66..b847e23204 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -56,6 +56,13 @@ struct StoryPose{ // has the Running Shoes (00.10 on). inline const std::string RUN_VARIANT = "run"; +// The variant of a STEP into a trainer's line: a tile at a time, at most +// TRAINER_LINE_TILES, until the trainer sees the player +// (step_until_seen()). The battle after it starts on the trainer's row +// whether the walk before ended on its tile or a tile short. +inline const std::string TRAINER_LINE_VARIANT = "trainer_line"; +inline constexpr int TRAINER_LINE_TILES = 3; + // The GAME step that closes the Trainer Card SID Helper leaves open. inline const std::string CLOSE_TRAINER_CARD = "close_trainer_card"; @@ -185,6 +192,12 @@ struct StoryEnv{ std::string start_map = {}; // That checkpoint's START menu: a reload reads the bag again with it. StartMenu start_menu = StartMenu::BEFORE_POKEMON; + // The once_per_save steps done from the last save that changed + // nothing: a retry after a reload skips them. Emptied by a save. + Pokemon::PreparedSteps prepared = {}; + // The last save's Items pocket was read in full (read_bag_supplies()): + // a reload restores `saved_supplies` without reading it again. + bool bag_read = false; }; // After a save is loaded for a checkpoint that starts on `start_map`: the @@ -202,7 +215,8 @@ void read_lead_moves(StoryEnv& env, StartMenu menu); // After a save is loaded, with START's menu `menu`: the Items pocket's // counts as read (set_from_loaded_bag()), in place of the row's, which // are kept if nothing can be read. Only with the full menu: the rows -// before it carry the items they have. +// before it carry the items they have. Sets `bag_read` when every count +// was read. void read_bag_supplies(StoryEnv& env, StartMenu menu); // Does FRLG's kinds of story step on the console. A console step that diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp index 05c7ed1fda..8fa4003a7e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp @@ -164,21 +164,21 @@ GrindPlan squirtle_to(unsigned level){ return {.member = 0, .level = level, .max_encounters = 20, .pace = Pokemon::Direction::EAST, .heal_every = 0}; } -// Until the rival is 70%, Lv`cap` at most. +// Until the rival is 50%, Lv`cap` at most. GrindPlan beat_rival(unsigned cap){ GrindPlan plan = squirtle_to(cap); plan.trainer = std::string(RIVAL); return plan; } -// 40% at Lv16, 5% more a level, 72% from Lv19. +// 30% at Lv16, 5% more a level, 72% from Lv19. void winnable_from_19(FakePatch& patch){ patch.chance_at = [](unsigned level) -> std::optional{ - return level >= 19 ? 0.72 : 0.40 + 0.05 * (level - 16); + return level >= 19 ? 0.72 : 0.30 + 0.05 * (level - 16); }; } void never_winnable(FakePatch& patch){ - patch.chance_at = [](unsigned) -> std::optional{ return 0.50; }; + patch.chance_at = [](unsigned) -> std::optional{ return 0.40; }; } std::vector grind_cases_1(){ @@ -255,7 +255,7 @@ std::vector grind_cases_2(){ std::vector grind_cases_3(){ return { { - .name = "until 70% against the rival: the first level that is", + .name = "until 50% against the rival: the first level that is", .plan = beat_rival(30), .setup = winnable_from_19, .encounters = 6, .fights = 6, .heals = 2, @@ -357,7 +357,7 @@ UnitTestResult test_grind_cap_message(){ }, plan); const std::string message = grind_message(plan, result); const std::string expected = - "Grind slot 1: level_cap: Lv18 is the cap, short of the win chance: level 18 of 18, win chance 50% of 70%" + "Grind slot 1: level_cap: Lv18 is the cap, short of the win chance: level 18 of 18, win chance 40% of 50%" " against TRAINER_RIVAL_CERULEAN_BULBASAUR, 4 encounters, 1 trips to the nurse."; if (message != expected){ return "Expected \"" + expected + "\", got \"" + message + "\"."; @@ -395,7 +395,7 @@ UnitTestResult test_lead_as_read(){ // with Water Pulse taught over Tail Whip, and 10 Potions. The sim, the // levels since the summary added to its stats, wins against the // Cerulean rival about 42% at Lv22, 62% at Lv23, 66% at Lv24 and 76% at -// Lv25: a GRIND to 70% stops at Lv25. +// Lv25: a GRIND to 50% stops at Lv23. UnitTestResult test_console_party(){ Stats stats = combatant("wartortle", 22, OWN_GENES)->stats; stats.hp = 65; @@ -405,9 +405,9 @@ UnitTestResult test_console_party(){ PartyMember lead = at22; lead.moves_through_level = level; const std::optional estimate = healed_win_chance(lead, SimItems{.potions = 10}, RIVAL); - if (!estimate || (estimate->chance >= MIN_WIN_CHANCE) != (level == 25)){ + if (!estimate || (estimate->chance >= MIN_WIN_CHANCE) != (level >= 23)){ return std::format( - "Lv{}: {:.1f}%; expected the first at {:.0f}% or more at Lv25.", + "Lv{}: {:.1f}%; expected {:.0f}% or more from Lv23.", level, estimate ? 100 * estimate->chance : 0.0, 100 * MIN_WIN_CHANCE ); } @@ -435,7 +435,7 @@ UnitTestResult test_grind_variant(){ rival.max_encounters = 100; rival.pace = Pokemon::Direction::WEST; const std::string rival_variant = grind_variant(rival); - if (rival_variant != "grind slot=1 level=30 encounters=100 pace=west heal_every=0 beat=TRAINER_RIVAL_CERULEAN_BULBASAUR chance=70"){ + if (rival_variant != "grind slot=1 level=30 encounters=100 pace=west heal_every=0 beat=TRAINER_RIVAL_CERULEAN_BULBASAUR chance=50"){ return "Unexpected variant \"" + rival_variant + "\"."; } const std::optional rival_back = parse_grind_variant(rival_variant + " chance=75"); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp index abbaf071c5..36130f6cff 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp @@ -156,6 +156,7 @@ Pokemon::StoryStep mart_step(std::string name, std::string why, const MartPlan& step.name = std::move(name); step.why = std::move(why); step.variant = mart_variant(plan); + step.once_per_save = true; return step; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h index ce308b31ab..f06d1dedfe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h @@ -94,7 +94,8 @@ std::string mart_variant(const MartPlan& plan); // names an item its Mart doesn't sell. std::optional parse_mart_variant(std::string_view variant); -// The table's Mart step. +// The table's Mart step, once per save (StoryStep::once_per_save): a +// retry from the same save skips it when it had nothing to buy. Pokemon::StoryStep mart_step(std::string name, std::string why, const MartPlan& plan); 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 c81e5d361d..f231fda015 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp @@ -285,7 +285,7 @@ bool plans(const Pokemon::Pose& from, const Pokemon::Pose& to){ // GRIND; Potions from Cerulean's Mart (a loaded save's bag may hold too // few for the wild battles a GRIND fights), and at its money floor 2 or // more Awakenings for the rival's Sleep Powder; then a GRIND on Route 4's -// grass east of Mt. Moon until the sim beats the rival 00.15b fights 70% +// grass east of Mt. Moon until the sim beats the rival 00.15b fights 50% // or more, healing at Cerulean's Center; its trip there plans both ways. UnitTestResult test_cerulean_mart_and_grind(){ const StoryCheckpoint& row = story_checkpoints()[row_index("00.15")]; @@ -309,7 +309,7 @@ UnitTestResult test_cerulean_mart_and_grind(){ && plan->level > 25; }); if (mart == steps.size() || grind == steps.size()){ - return "00.15: expected a Cerulean Mart step buying Potions, then a GRIND of the lead until the rival is 70%, capped above Lv25."; + return "00.15: expected a Cerulean Mart step buying Potions, then a GRIND of the lead until the rival is 50%, capped above Lv25."; } const MartPlan plan = *parse_mart_variant(steps[mart].variant); const std::optional> buys = plan.money_floor diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp index 23353dc736..94eaf61b27 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -26,6 +26,8 @@ #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryTable.h" namespace PokemonAutomation{ @@ -149,12 +151,31 @@ class FakeGame : public Pokemon::StoryStepExecutor{ } return Pokemon::outcome_ok(to_pose(StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after})); } + // A step into a trainer's line goes on until a trainer can see the + // player, as step_until_seen() does on the console. virtual Outcome step(RunState& state, const StoryStep& step) override{ const std::optional at = story_pose(state.pose); if (!at){ return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); } - return Pokemon::outcome_ok(to_pose(StoryPose{at->map, at->tile.next(step.direction), step.direction})); + const MapData* map = map_named(at->map); + if (step.variant != TRAINER_LINE_VARIANT || map == nullptr){ + return Pokemon::outcome_ok(to_pose(StoryPose{at->map, at->tile.next(step.direction), step.direction})); + } + TilePos onto = at->tile; + const std::optional stepped = step_until_seen( + TRAINER_LINE_TILES, + [&]{ onto = onto.next(step.direction); }, + [&]{ + return std::any_of(map->objects.begin(), map->objects.end(), [&](const MapObject& object){ + return object.trainer && trainer_may_see(*map, object, onto); + }); + } + ); + if (!stepped){ + return Pokemon::outcome_failed("no_trainer", to_string(MapPosition{at->map, onto})); + } + return Pokemon::outcome_ok(to_pose(StoryPose{at->map, onto, step.direction})); } // The nurse's way must plan too, but the run goes on from where it stands. virtual Outcome ready(RunState& state, const StoryStep& step) override{ @@ -458,6 +479,79 @@ UnitTestResult test_cerulean_entry_short(){ return true; } +// Runs `step` of 00.16 on `sim` as the program does: legs by the sim's +// walker from `at`, where the table says the player stands; a step one +// tap at a time, or for a step into a trainer's line by +// step_until_seen(), each watched for the trainer; a battle from the +// trainer's message, which must be up. Moves `at` to where the table +// says the step ends. Returns the failure, or empty. +std::string bridge_step_on_sim(OverworldSim& sim, StoryPose& at, const StoryStep& step){ + const std::string where = "00.16/" + step.name + ": "; + const auto on = [&sim]{ return " On " + to_string(sim.state().position) + "."; }; + if (step.kind == StoryStepKind::LEGS){ + const std::optional> route = walked_route(at, step); + const RoutePlanning planning{.maps = &story_maps(), .start = MapPosition{at.map, at.tile}, .label = step.name}; + const std::string failure = route ? OverworldSimWalker(sim).run(*route, planning) : "no legs."; + at = route ? StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after} : at; + return failure.empty() ? "" : where + failure + on(); + } + if (step.kind == StoryStepKind::STEP){ + const auto tap = [&sim, &step]{ + if (sim.state().facing != step.direction){ + sim.tap(step.direction); + } + sim.tap(step.direction); + }; + const auto seen = [&sim]{ + return sim.watch({SimWatcher::MESSAGE, SimWatcher::BATTLE_SCREEN}, TRAINER_LINE_WATCH).has_value(); + }; + const int tiles = step.variant == TRAINER_LINE_VARIANT ? TRAINER_LINE_TILES : 1; + return step_until_seen(tiles, tap, seen) ? "" : where + "no trainer saw the player." + on(); + } + if (step.kind == StoryStepKind::BATTLE){ + if (!sim.close_message() || sim.handle_battle(SimBattleChoice::FIGHT) != SimBattleEnd::ENDED){ + return where + "no_battle." + on(); + } + at = *story_pose(*step.pose_after); + if (!(sim.state().position == MapPosition{at.map, at.tile})){ + return where + "expected " + to_string(MapPosition{at.map, at.tile}) + "." + on(); + } + } + return ""; +} + +// Console B, 2026-11-03 (row 00.16), twice: the open leg north from +// Cerulean City onto Nugget Bridge ended on (11, 33), a tile short of +// (11, 32), and the one step onto Cale's row reached only (11, 32), out +// of his sight: "bug_catcher_cale: failed: no_battle". From the walk's +// end, whole or a tile short, the five trainers are met and beaten on +// the sim, each battle on the trainer's row. +UnitTestResult test_nugget_bridge_short(){ + const std::vector& rows = story_checkpoints(); + const auto row = std::find_if(rows.begin(), rows.end(), [](const StoryCheckpoint& data){ return data.id == "00.16"; }); + if (row == rows.end()){ + return "No checkpoint 00.16."; + } + const auto walk = std::find_if(row->steps.begin(), row->steps.end(), [](const StoryStep& step){ return step.name == "below_cale_line"; }); + if (walk == row->steps.end() || !walk->target){ + return "No step 00.16/below_cale_line."; + } + for (int short_by : {0, 1}){ + StoryPose at = *story_pose(*walk->target); + OverworldSim sim(story_maps(), MapPosition{at.map, {at.tile.x, at.tile.y + short_by}}, Direction::NORTH); + for (auto step = walk + 1; step != row->steps.end() && step->kind != StoryStepKind::READY; ++step){ + const std::string failure = bridge_step_on_sim(sim, at, *step); + if (!failure.empty()){ + return std::format("Walk {} tile(s) short: ", short_by) + failure; + } + } + if (sim.state().trainers_beaten.size() != 5){ + return std::format("Walk {} tile(s) short: expected 5 trainers beaten, got {}.", short_by, sim.state().trainers_beaten.size()); + } + } + return true; +} + } @@ -470,6 +564,7 @@ void add_tests_AutoStorySimulation(UnitTestDatabase& database){ add("a failed walk reloads its checkpoint's save", test_retry_from_save); add("a battle lost every time stops after 3 attempts", test_gives_up_after_attempts); add("00.14 into Cerulean, the entry leg a tile short", test_cerulean_entry_short); + add("00.16 Nugget Bridge, the walk onto it a tile short", test_nugget_bridge_short); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index d76ec4f992..1fc3a6f2af 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -106,6 +106,15 @@ StoryStep step_into(std::string name, Direction direction, std::string why){ // it and lands on `landing`, two tiles on. Planned routes never hop a // ledge (they hold into walls, and a held ledge hops), so where the only // way on is down a ledge the table takes it as this one step. +// A step `direction` into a trainer's line, a tile at a time until the +// trainer sees the player (TRAINER_LINE_VARIANT): the battle after it +// starts whether the walk before ended on its tile or a tile short. +StoryStep into_line(std::string name, Direction direction, std::string why){ + StoryStep step = step_into(std::move(name), direction, std::move(why)); + step.variant = TRAINER_LINE_VARIANT; + return step; +} + StoryStep hop(std::string name, Direction direction, Pokemon::Pose landing, std::string why){ StoryStep step = step_into(std::move(name), direction, std::move(why)); step.pose_after = std::move(landing); @@ -605,9 +614,9 @@ StoryCheckpoint misty(){ // 15 Potions), 1400 of the floor's 1500. Then a GRIND on Route 4's grass // east of Mt. Moon (75..86, 11..17; Spearow, Rattata, Ekans and Mankey // around Lv10, about 80 EXP each), healing at the Center, until the -// battle sim beats the rival 00.15b fights 70% or more: the win chance +// battle sim beats the rival 00.15b fights 50% or more: the win chance // his battle refuses below. Console B's Wartortle (Lv22, 65 HP, Water -// Pulse) is about 42% there and 76% at Lv25; Lv28 (about 88%, some 120 +// Pulse) is about 42% there and 62% at Lv23; Lv28 (about 88%, some 120 // battles from Lv22) is the cap. Then the nurse, and the save on (23, 7), // the tile below his trigger: his battle is its own checkpoint, 00.15b, // verified and retried from this save. @@ -628,7 +637,7 @@ StoryCheckpoint cerulean_grind(){ running(route("mart_clerk", at(CERULEAN_MART, 4, 3, WEST), "out of the Center to the Mart's clerk")), mart_step("buy_potions", "3 Potions: the GRIND fights wild battles only with 2 or more; 2 Awakenings for the rival's Sleep Powder", potions), running(route("grind_patch", at(ROUTE4, 86, 16, WEST), "west out of the city along Route 4's lower road onto its grass's east edge")), - grind_step("grind_for_rival", "wild battles until the sim beats the rival 70% or more, Lv28 at most; the nurse when hurt or low on PP", for_rival, at(CERULEAN_CENTER, 7, 4, NORTH)), + grind_step("grind_for_rival", "wild battles until the sim beats the rival 50% or more, Lv28 at most; the nurse when hurt or low on PP", for_rival, at(CERULEAN_CENTER, 7, 4, NORTH)), running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "back to the Center: the rival's battle starts at full HP and PP")), heal("heal_cerulean"), running(route("below_rival_trigger", at(CERULEAN, 23, 7, NORTH), "out of the Center, north up to (23, 7), short of the trigger row 6")), @@ -665,29 +674,33 @@ StoryCheckpoint cerulean_rival(){ // Youngster Timmy (12, 25), Lass Reli (10, 22) and Camper Ethan (12, 19). // Each is fought on the step onto their row, beside them: they don't // walk, and the player keeps facing north. Two tiles separate the rows, -// walked as one short leg. Then the Rocket (12, 15): the step onto -// (11, 15) (Route24_EventScript_RocketTriggerRight, VAR_MAP_SCENE_ROUTE24 -// 0) gives the NUGGET, "join Team Rocket", and his battle; he only turns, -// and the player turns east to him. Camper Shane (5, 21) looks north -// from the west bank, off the way. +// walked as one short leg; the step onto a row goes on a tile at a time +// until the trainer sees the player (into_line()), as the open leg onto +// the bridge ended a tile short twice on console B (2026-11-03), on +// (11, 33), and one step left the player out of Cale's sight. Then the +// Rocket (12, 15): the step onto (11, 15) +// (Route24_EventScript_RocketTriggerRight, VAR_MAP_SCENE_ROUTE24 0) gives +// the NUGGET, "join Team Rocket", and his battle; he only turns, and the +// player turns east to him. Camper Shane (5, 21) looks north from the +// west bank, off the way. StoryCheckpoint nugget_bridge(){ return row("00.16", "Nugget Bridge: the nurse, five trainers and the Rocket", at(CERULEAN, 23, 6, SOUTH), after_brock(), StartMenu::FULL, { running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "back to the Center after the rival, before Nugget Bridge")), heal("heal_cerulean"), running(route("below_cale_line", at(ROUTE24, 11, 32, NORTH), "out of the Center, north past the rival's row onto the bridge, below Cale's row")), - step_into("cale_line", NORTH, "onto (11, 31), beside Cale"), + into_line("cale_line", NORTH, "onto (11, 31), beside Cale"), battle("bug_catcher_cale", at(ROUTE24, 11, 31, NORTH), false, "his Bug Pokemon"), running(legs("below_ali_line", {{NORTH, 2}}, "up to (11, 29)")), - step_into("ali_line", NORTH, "onto (11, 28), beside Ali"), + into_line("ali_line", NORTH, "onto (11, 28), beside Ali"), battle("lass_ali", at(ROUTE24, 11, 28, NORTH), false, "her Pokemon"), running(legs("below_timmy_line", {{NORTH, 2}}, "up to (11, 26)")), - step_into("timmy_line", NORTH, "onto (11, 25), beside Timmy"), + into_line("timmy_line", NORTH, "onto (11, 25), beside Timmy"), battle("youngster_timmy", at(ROUTE24, 11, 25, NORTH), false, "his Pokemon"), running(legs("below_reli_line", {{NORTH, 2}}, "up to (11, 23)")), - step_into("reli_line", NORTH, "onto (11, 22), beside Reli"), + into_line("reli_line", NORTH, "onto (11, 22), beside Reli"), battle("lass_reli", at(ROUTE24, 11, 22, NORTH), false, "her Pokemon"), running(legs("below_ethan_line", {{NORTH, 2}}, "up to (11, 20)")), - step_into("ethan_line", NORTH, "onto (11, 19), beside Ethan"), + into_line("ethan_line", NORTH, "onto (11, 19), beside Ethan"), battle("camper_ethan", at(ROUTE24, 11, 19, NORTH), false, "his Pokemon"), // A route, not legs: the nurse may have been needed. ready("ready_for_rocket", at(CERULEAN_CENTER, 7, 4, NORTH), "items for a status or low HP; the nurse only if they can't"), diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp index 8e1e45b00a..392ce78949 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp @@ -105,6 +105,7 @@ Pokemon::StoryStep teach_step(std::string name, std::string why, const TeachPlan step.name = std::move(name); step.why = std::move(why); step.variant = teach_variant(plan); + step.once_per_save = true; return step; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h index 3756cc3fc0..27ba63fcef 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h @@ -79,6 +79,9 @@ inline constexpr std::string_view TEACH_VARIANT_PREFIX = "teach "; std::string teach_variant(const TeachPlan& plan); std::optional parse_teach_variant(std::string_view variant); +// The table's TEACH step, once per save (StoryStep::once_per_save): a +// retry from the same save skips it when the lead knew the move or there +// was no TM. Pokemon::StoryStep teach_step(std::string name, std::string why, const TeachPlan& plan); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h index 7404364a47..9553ceac5a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h @@ -54,7 +54,7 @@ WinEstimate estimate_win_chance(const SimBattler& own, const SimItems& items, co // `trainer`. None if the data lacks the lead's species or the trainer. std::optional story_win_chance(const PartyMember& lead, const SimItems& items, double hp_share, std::string_view trainer); -// Why not to fight: "win chance 41% < 70% with : grind first", or +// Why not to fight: "win chance 41% < 50% with : grind first", or // none at `minimum` or above. std::optional win_chance_refusal(const WinEstimate& estimate, double minimum = MIN_WIN_CHANCE); 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 af9c26cf8e..c7924fa06d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -379,6 +379,24 @@ const MapObject* trainer_seeing(const MapData& map, const TilePos& tile, const s return nullptr; } +// The tile a STEP from `pose` ends on: the next one; for a step into a +// trainer's line, the first within TRAINER_LINE_TILES that a trainer +// other than the `beaten` sees, where step_until_seen() stops, else the +// last. +TilePos step_end(const StoryPose& pose, const StoryStep& step, const std::set& beaten){ + const MapData* map = find_map_named(pose.map); + if (step.variant != TRAINER_LINE_VARIANT || map == nullptr){ + return pose.tile.next(step.direction); + } + TilePos tile = pose.tile; + step_until_seen( + TRAINER_LINE_TILES, + [&]{ tile = tile.next(step.direction); }, + [&]{ return trainer_seeing(*map, tile, beaten) != nullptr; } + ); + return tile; +} + // Whether every floor tile of `map` has wild encounters, as in a cave: // every open tile is tall grass, but for warps. No route keeps out of // its grass. @@ -509,7 +527,7 @@ UnitTestResult advance(StoryPose& pose, const StoryStep& step){ return check_legs(pose, step); } if (step.kind == StoryStepKind::STEP){ - pose = StoryPose{pose.map, pose.tile.next(step.direction), step.direction}; + pose = StoryPose{pose.map, step_end(pose, step, {}), step.direction}; } if (step.pose_after){ pose = one_tile(*step.pose_after); @@ -542,7 +560,7 @@ UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::setstart); for (size_t c = 0; c < steps.size(); c++){ const MapData* map = find_map_named(pose.map); - const MapObject* trainer = steps[c].kind == StoryStepKind::STEP && map ? trainer_seeing(*map, pose.tile.next(steps[c].direction), {}) : nullptr; + const MapObject* trainer = steps[c].kind == StoryStepKind::STEP && map ? trainer_seeing(*map, step_end(pose, steps[c], {}), {}) : nullptr; if (trainer != nullptr && (c + 1 == steps.size() || steps[c + 1].kind != StoryStepKind::BATTLE)){ return "00.16/" + steps[c].name + ": no battle right after the step."; } From 831a22c423fc0ab1918fba85fb667d18c31c1691 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 11:08:28 -0800 Subject: [PATCH 4/6] FRLG AutoStory battle: size the Potion on the foe AI's likely turn The Potion rule compared a Potion's 20 HP to the foe's biggest hit, so against the Cerulean rival's Bulbasaur (Vine Whip, or Leech Seed, Sleep Powder and Poison Powder) it rarely healed. The sim now draws the AI's move scores 1000 times from a fixed seed for each move's chance, mixes each move's rolls, crits and accuracy with the end-of-turn poison and Leech Seed into the next turn's damage, and heals when a Potion's HP beats its 80th percentile (POTION_COVER_PERCENTILE). The Awakening rule uses the same figure and now comes before a Potion. The console battle and the win-chance sim share the rule; the log names the percentile and the move chances. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG_AutoStoryBattleDecisions.cpp | 44 ++-- .../PokemonFRLG_AutoStoryBattleSim.cpp | 221 +++++++++++++++--- .../PokemonFRLG_AutoStoryBattleSim.h | 95 ++++++-- .../PokemonFRLG_AutoStoryBattleSim_Tests.cpp | 112 +++++++-- .../PokemonFRLG_AutoStoryGrind_Tests.cpp | 15 +- .../PokemonFRLG_AutoStoryWinChance.cpp | 19 +- 6 files changed, 401 insertions(+), 105 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp index 71a2af1940..f8bdc2957a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp @@ -118,32 +118,45 @@ std::string no_potion_reason(const Supplies& supplies, const PartyStatus& status if (!asked){ return std::format("HP {} and the next hit can't faint the lead", bar_name(status)); } - return std::format("the next hit (about {:.0f}) undoes it and it outlasts the foe no longer", c.expected_hit); + return std::format( + "the next turn ({:.0f}% of the time {} HP or less) undoes it and it outlasts the foe no longer", + 100 * POTION_COVER_PERCENTILE, c.likely_hit + ); } -// Against a known foe: a Potion at BattleRisk::HIGH when its next hit +// The foe's move chances, for the log: "vine-whip 42%, sleep-powder 42%". +std::string move_chances_text(const PotionCase& c){ + std::string text; + for (const auto& [move, chance] : c.move_chances){ + if (chance > 0){ + text += std::format("{}{} {:.0f}%", text.empty() ? "" : ", ", move, 100 * chance); + } + } + return text.empty() ? "none" : text; +} + +// Against a known foe: a Potion at BattleRisk::HIGH when its next turn // could faint the lead (potion_now(), the HP from the bar's share) or the // bar is red, at LOW whenever the bar isn't green; either only if // potion_pays(). Else, asleep, an Awakening if awakening_now(). ItemTurn known_foe_items( - const Supplies& supplies, const PartyStatus& status, double seen_hit, - const SimBattler& own, const SimBattler& foe, int awakenings + const Supplies& supplies, const PartyStatus& status, int awakenings, + const SimBattler& own, const PotionCase& c ){ const bool hurt = status.hp_red || status.hp_yellow; - const PotionCase c = potion_case(own, foe, seen_hit); const std::string numbers = std::format( - "{}/{} HP, the foe's next hit about {:.0f} (up to {}), {} of them before the lead's attacks faint it", - c.hp, c.max_hp, c.expected_hit, c.max_hit, c.hits_to_ko + "{}/{} HP, the foe's next turn {} HP or less {:.0f}% of the time (mean {:.0f}, up to {}; {}), {} of them before the lead's attacks faint it", + c.hp, c.max_hp, c.likely_hit, 100 * POTION_COVER_PERCENTILE, c.expected_hit, c.max_hit, move_chances_text(c), c.hits_to_ko ); + if (awakening_now(c, own, awakenings)){ + return {TurnChoice::AWAKENING, "an Awakening: asleep, and the lead outlasts the turn it costs; " + numbers}; + } const bool high = supplies.risk == BattleRisk::HIGH; - if (supplies.potions > 0 && high && potion_now(own, foe, supplies.potions, seen_hit)){ - return {TurnChoice::POTION, "a Potion: the next hit could faint the lead, not after it; " + numbers}; + if (high && potion_now(c, supplies.potions)){ + return {TurnChoice::POTION, "a Potion: the next turn could faint the lead, and it covers that turn; " + numbers}; } if (supplies.potions > 0 && (high ? status.hp_red : hurt) && potion_pays(c)){ - return {TurnChoice::POTION, "a Potion: it outheals the next hit, or outlasts the foe; " + numbers}; - } - if (awakening_now(own, foe, awakenings, seen_hit)){ - return {TurnChoice::AWAKENING, "an Awakening: asleep, and the lead outlasts the hit its turn costs; " + numbers}; + return {TurnChoice::POTION, "a Potion: it covers the next turn, or outlasts the foe; " + numbers}; } if (!hurt && own.status != SimStatus::SLEEP){ return {}; @@ -155,11 +168,12 @@ ItemTurn known_foe_items( ItemTurn item_turn(const Supplies& supplies, const PartyStatus& status, double seen_hit, int awakenings){ const std::optional foe = foe_out(supplies); std::optional own = own_battler(supplies.lead, status.hp_seen ? status.hp_fill : 1.0); - if (!foe || !own){ + const std::optional trainer = sim_trainer(supplies.trainer); + if (!foe || !own || !trainer){ return unknown_foe_items(supplies, status, seen_hit, awakenings); } own->status = status.status == StatusCondition::SLEEP ? SimStatus::SLEEP : SimStatus::NONE; - return known_foe_items(supplies, status, seen_hit, *own, *foe, awakenings); + return known_foe_items(supplies, status, awakenings, *own, potion_case(*own, *foe, *trainer, seen_hit)); } // The lead's HP from the bar's share, if it showed. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.cpp index f278090652..9ac8679470 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.cpp @@ -27,6 +27,13 @@ constexpr int MAX_STAGE = 6; constexpr size_t TURNS_CAP = 30; // The hits a multi-hit move is taken to land when sizing a foe's hit. constexpr uint32_t MULTI_HITS = 3; +constexpr uint32_t CRIT_CHANCE = 16; +constexpr uint32_t HIGH_CRIT_CHANCE = 8; +// sAccuracyStageRatios, -6 to +6, in hundredths. +constexpr uint32_t ACCURACY_RATIOS[] = {33, 36, 43, 50, 60, 75, 100, 133, 166, 200, 233, 266, 300}; +// ai_move_chances()'s fixed seed. +constexpr uint32_t AI_SAMPLE_SEED = 1; +constexpr size_t DAMAGE_ROLLS = 16; const MoveData& data_of(std::string_view move){ static const MoveData NONE; @@ -314,6 +321,83 @@ size_t turns_to_faint(SimBattler foe, std::vector items, size_t foe return TURNS_CAP + 1; } +uint16_t eighth(const SimBattler& battler){ + return std::max(battler.body.stats.hp / 8, 1); +} + +bool poison_proof(const Combatant& body){ + return has_type(body, PokemonType::POISON) || has_type(body, PokemonType::STEEL); +} + +// The chance that `foe` moves this turn: not while asleep (it moves on +// the turn its counter reaches 0), 3 in 4 paralysed. +double moves_this_turn(const SimBattler& foe){ + if (foe.status == SimStatus::SLEEP && foe.sleep > 1){ + return 0; + } + return foe.status == SimStatus::PARALYSIS ? 0.75 : 1.0; +} + +// The end-of-turn HP a status move that lands adds: a new poison or +// Leech Seed, 1/8 HP. +uint32_t status_toll(const MoveData& move, const SimBattler& own){ + const bool poisons = (move.effect == "poison" || move.effect == "toxic") + && own.status == SimStatus::NONE && !poison_proof(own.body); + const bool seeds = move.effect == "leech-seed" && !own.seeded && !has_type(own.body, PokemonType::GRASS); + return poisons || seeds ? eighth(own) : 0; +} + +// One hit's damage and its chance: the 16 rolls, or the one fixed value. +std::vector> one_hit_values(const SimBattler& foe, const SimBattler& own, const MoveData& move, bool crit){ + if (move.effect == "super-fang"){ + return {{std::max(own.hp / 2, 1), 1.0}}; + } + const uint32_t before = damage_before_roll(foe.body, own.body, move, crit); + if (before == 0 || fixed_damage(move, foe.body)){ + return {{before, 1.0}}; + } + std::vector> values; + for (uint32_t roll = 0; roll < DAMAGE_ROLLS; roll++){ + values.emplace_back(rolled_damage(before, 100 - roll), 1.0 / DAMAGE_ROLLS); + } + return values; +} + +// A move's hit counts and their chances (Cmd_setmultihitcounter: 2 or 3 +// at 3/8 each, 4 or 5 at 1/8 each). +std::vector> hit_counts(const MoveData& move){ + if (move.effect == "multi-hit"){ + return {{2, 0.375}, {3, 0.375}, {4, 0.125}, {5, 0.125}}; + } + return {{hits_of(move), 1.0}}; +} + +void add_chance(std::vector& hp_lost, uint32_t damage, double chance){ + if (hp_lost.size() <= damage){ + hp_lost.resize(damage + 1, 0); + } + hp_lost[damage] += chance; +} + +// `move` used with `chance`, on top of `toll` at the end of the turn. +void add_move(std::vector& hp_lost, const SimBattler& foe, const SimBattler& own, const MoveData& move, double chance, uint32_t toll){ + const double hit = std::min(hit_percent(foe, own, move), 100u) / 100.0; + add_chance(hp_lost, toll, chance * (1 - hit)); + if (move.power == 0){ + add_chance(hp_lost, toll + status_toll(move, own), chance * hit); + return; + } + const double crit = 1.0 / crit_odds(move); + for (const bool crits : {false, true}){ + const double crit_share = crits ? crit : 1 - crit; + for (const auto& [count, count_share] : hit_counts(move)){ + for (const auto& [damage, damage_share] : one_hit_values(foe, own, move, crits)){ + add_chance(hp_lost, toll + damage * count, chance * hit * crit_share * count_share * damage_share); + } + } + } +} + // The slots with PP left that do damage to `foe`. std::vector damaging_slots(const SimBattler& own, const SimBattler& foe){ std::vector slots; @@ -435,6 +519,90 @@ std::vector ai_move_scores(const SimTrainer& trainer, const SimBattler& foe return scores; } +std::vector ai_move_chances(const SimTrainer& trainer, const SimBattler& foe, const SimBattler& target){ + std::vector chances(foe.moves.size(), 0); + std::mt19937 rng(AI_SAMPLE_SEED); + const std::mt19937 start = rng; + size_t samples = AI_MOVE_SAMPLES; + for (size_t i = 0; i < samples; i++){ + const std::vector scores = ai_move_scores(trainer, foe, target, rng); + if (i == 0 && rng == start){ + // Nothing random drawn: one sample is the answer. + samples = 1; + } + const int best = scores.empty() ? 0 : *std::ranges::max_element(scores); + const double ties = static_cast(std::ranges::count(scores, best)); + for (size_t slot = 0; slot < scores.size(); slot++){ + chances[slot] += best > 0 && scores[slot] == best ? 1 / ties : 0; + } + } + for (double& chance : chances){ + chance /= static_cast(samples); + } + return chances; +} + +uint32_t hit_percent(const SimBattler& user, const SimBattler& target, const MoveData& move){ + if (move.accuracy == 0){ + return 100; + } + const int buff = std::clamp( + user.body.stages[static_cast(Stage::ACCURACY)] - target.body.stages[static_cast(Stage::EVASION)], + -MAX_STAGE, MAX_STAGE + ); + return move.accuracy * ACCURACY_RATIOS[buff + MAX_STAGE] / 100; +} + +uint32_t crit_odds(const MoveData& move){ + return move.effect == "high-critical" ? HIGH_CRIT_CHANCE : CRIT_CHANCE; +} + +double NextTurnDamage::mean() const{ + double sum = 0; + for (size_t damage = 0; damage < hp_lost.size(); damage++){ + sum += static_cast(damage) * hp_lost[damage]; + } + return sum; +} + +uint32_t NextTurnDamage::percentile(double share) const{ + // Rounding in the sums: a share reached within this counts. + constexpr double SLACK = 1e-9; + double below = 0; + for (size_t damage = 0; damage < hp_lost.size(); damage++){ + below += hp_lost[damage]; + if (below + SLACK >= share){ + return static_cast(damage); + } + } + return most(); +} + +uint32_t NextTurnDamage::most() const{ + for (size_t damage = hp_lost.size(); damage > 0; damage--){ + if (hp_lost[damage - 1] > 0){ + return static_cast(damage - 1); + } + } + return 0; +} + +NextTurnDamage next_turn_damage(const SimTrainer& trainer, const SimBattler& foe, const SimBattler& own){ + NextTurnDamage next{.move_chances = ai_move_chances(trainer, foe, own), .hp_lost = {}}; + const uint32_t toll = (own.status == SimStatus::POISON ? eighth(own) : 0) + (own.seeded ? eighth(own) : 0); + const double moves = moves_this_turn(foe); + double placed = 0; + for (size_t slot = 0; slot < foe.moves.size(); slot++){ + const double chance = next.move_chances[slot] * moves; + if (chance > 0){ + add_move(next.hp_lost, foe, own, data_of(foe.moves[slot].move), chance, toll); + placed += chance; + } + } + add_chance(next.hp_lost, toll, std::max(0.0, 1 - placed)); + return next; +} + size_t ai_next_foe(const std::vector& party, size_t fainted, const SimBattler& lead){ std::vector left; for (size_t slot = 0; slot < party.size(); slot++){ @@ -500,12 +668,12 @@ uint32_t foe_max_hit(const SimBattler& foe, const SimBattler& own){ return most; } -PotionCase potion_case(const SimBattler& own, const SimBattler& foe, double seen_hit){ - double expected = 0; - for (const SimMove& known : foe.moves){ - if (known.pp > 0){ - expected = std::max(expected, mean_per_turn(foe, own, data_of(known.move))); - } +PotionCase potion_case(const SimBattler& own, const SimBattler& foe, const SimTrainer& trainer, double seen_hit){ + const NextTurnDamage next = next_turn_damage(trainer, foe, own); + const uint32_t seen = static_cast(std::ceil(seen_hit)); + std::vector> chances; + for (size_t slot = 0; slot < foe.moves.size(); slot++){ + chances.emplace_back(foe.moves[slot].move, next.move_chances[slot]); } const std::optional slot = planned_attack_slot(own, foe, {}, 1); const size_t turns = slot @@ -517,9 +685,11 @@ PotionCase potion_case(const SimBattler& own, const SimBattler& foe, double seen return PotionCase{ .hp = own.hp, .max_hp = own.body.stats.hp, - .expected_hit = std::max(expected, seen_hit), - .max_hit = std::max(foe_max_hit(foe, own), static_cast(std::ceil(seen_hit))), + .expected_hit = std::max(next.mean(), seen_hit), + .likely_hit = std::max(next.percentile(POTION_COVER_PERCENTILE), seen), + .max_hit = std::max(next.most(), seen), .hits_to_ko = hits, + .move_chances = std::move(chances), }; } @@ -528,38 +698,31 @@ bool potion_pays(const PotionCase& c){ if (heal == 0){ return false; } - const double healed = c.hp + heal; - if (heal > c.expected_hit && healed > c.expected_hit){ + if (heal > c.likely_hit){ return true; } + const double healed = c.hp + heal; const bool lasts_if_healed = healed > c.expected_hit * static_cast(c.hits_to_ko + 1); const bool lasts_now = c.hp > c.expected_hit * static_cast(c.hits_to_ko); return lasts_if_healed && !lasts_now; } -bool potion_now(const SimBattler& own, const SimBattler& foe, int potions, double seen_hit){ - const uint16_t max_hp = own.body.stats.hp; - if (potions <= 0 || own.hp >= max_hp){ - return false; - } - const PotionCase c = potion_case(own, foe, seen_hit); - const uint32_t healed = std::min(max_hp, own.hp + POTION_HP); - return c.max_hit >= own.hp && healed > c.max_hit && potion_pays(c); +bool potion_now(const PotionCase& c, int potions){ + return potions > 0 && c.hp < c.max_hp && c.max_hit >= c.hp && potion_pays(c); } -bool awakening_now(const SimBattler& own, const SimBattler& foe, int awakenings, double seen_hit){ +bool awakening_now(const PotionCase& c, const SimBattler& own, int awakenings){ if (awakenings <= 0 || own.status != SimStatus::SLEEP){ return false; } - const PotionCase c = potion_case(own, foe, seen_hit); - return (c.expected_hit > 0 || own.seeded) && own.hp > c.expected_hit; + return c.max_hit > 0 && own.hp > c.likely_hit; } OwnTurn own_turn( const SimBattler& own, const SimItems& own_items, const SimBattler& foe, - const std::vector& items, size_t foes_left + const SimTrainer& trainer, size_t foes_left ){ - const int potions = own_items.potions; + const std::vector& items = trainer.items; const std::optional slot = planned_attack_slot(own, foe, items, foes_left); if (slot && own.status != SimStatus::SLEEP){ const MoveData& move = data_of(own.moves[*slot].move); @@ -572,12 +735,18 @@ OwnTurn own_turn( return OwnTurn{.potion = false, .slot = slot}; } } - if (potion_now(own, foe, potions)){ - return OwnTurn{.potion = true, .slot = std::nullopt}; + const bool may_heal = own_items.potions > 0 && own.hp < own.body.stats.hp; + const bool may_wake = own_items.awakenings > 0 && own.status == SimStatus::SLEEP; + if (!may_heal && !may_wake){ + return OwnTurn{.potion = false, .slot = slot}; } - if (awakening_now(own, foe, own_items.awakenings)){ + const PotionCase c = potion_case(own, foe, trainer); + if (awakening_now(c, own, own_items.awakenings)){ return OwnTurn{.potion = false, .slot = std::nullopt, .awakening = true}; } + if (potion_now(c, own_items.potions)){ + return OwnTurn{.potion = true, .slot = std::nullopt}; + } return OwnTurn{.potion = false, .slot = slot}; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.h index ba062de56c..dad7dd6207 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim.h @@ -46,6 +46,7 @@ #include #include #include +#include #include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "PokemonFRLG_AutoStoryBattleData.h" @@ -64,6 +65,11 @@ inline constexpr Genes OWN_GENES{.iv = 15, .ev = 0, .nature = 0}; // HP a Potion heals. inline constexpr uint16_t POTION_HP = 20; +// A Potion is used only when its HP covers this share of the foe's +// next-turn damage (next_turn_damage()): at 0.80, a turn that undoes it +// must be rarer than 1 in 5. +inline constexpr double POTION_COVER_PERCENTILE = 0.80; + // The lead's items in the bag that the sim plays. struct SimItems{ int potions = 0; @@ -130,6 +136,41 @@ std::optional ai_item_choice(const SimBattler& foe, const std::vector ai_move_scores(const SimTrainer& trainer, const SimBattler& foe, const SimBattler& target, std::mt19937& rng); +// How often the AI picks each of `foe`'s moves against `target` now, in +// slot order: ai_move_scores() drawn AI_MOVE_SAMPLES times from a fixed +// seed, ties split evenly. The chances change with the state (a status +// on the target, Leech Seed, stages, HP). All 0 with no PP left. +inline constexpr size_t AI_MOVE_SAMPLES = 1000; +std::vector ai_move_chances(const SimTrainer& trainer, const SimBattler& foe, const SimBattler& target); + +// The chance in percent that `user`'s `move` hits `target`: its accuracy +// at the user's accuracy and the target's evasion stages +// (sAccuracyStageRatios); 100 for a move that never misses. +uint32_t hit_percent(const SimBattler& user, const SimBattler& target, const MoveData& move); + +// A move's crit odds: 1 in 16, 1 in 8 for a high-crit move. +uint32_t crit_odds(const MoveData& move); + +// The HP `own` loses over the foe's next turn, as the AI picks its move +// (ai_move_chances()): each damaging move's 16 rolls, crit chance, +// accuracy with stages and multi-hit counts; a poison or Leech Seed that +// lands this turn and the poison and Leech Seed already on `own` (1/8 HP +// each at the end of the turn). An asleep foe doesn't move, a paralysed +// one 1 turn in 4. A Potion comes before both moves (items act first), +// so all of it lands after one. +struct NextTurnDamage{ + // ai_move_chances(). + std::vector move_chances = {}; + // hp_lost[d]: the chance of losing d HP. + std::vector hp_lost = {}; + + double mean() const; + // The least HP lost at least `share` of the time. + uint32_t percentile(double share) const; + uint32_t most() const; +}; +NextTurnDamage next_turn_damage(const SimTrainer& trainer, const SimBattler& foe, const SimBattler& own); + // The party slot the AI sends out after `fainted`, of the ones still up. size_t ai_next_foe(const std::vector& party, size_t fainted, const SimBattler& lead); @@ -155,38 +196,43 @@ uint32_t foe_max_hit(const SimBattler& foe, const SimBattler& own); struct PotionCase{ uint16_t hp = 0; uint16_t max_hp = 0; - // The foe's next hit, on average and at most. + // The HP the foe's next turn takes (next_turn_damage()): on average, + // at POTION_COVER_PERCENTILE and at most. double expected_hit = 0; + uint32_t likely_hit = 0; uint32_t max_hit = 0; // The foe's hits the lead takes before its attacks faint the foe, if // it attacks from now on. size_t hits_to_ko = 0; + // The foe's moves and ai_move_chances(), for the log. + std::vector> move_chances = {}; }; -// `own` against `foe`: the foe's strongest move at the mean roll and -// accuracy, or `seen_hit` (HP the last hit took, as the battle loop read -// it) if more; the lead's planned move against the foe at its HP now. -PotionCase potion_case(const SimBattler& own, const SimBattler& foe, double seen_hit = 0); - -// At either BattleRisk: a Potion is worth the turn only if, after it and -// the foe's expected hit, the lead has gained HP, or if it lets the lead -// last until its attacks faint the foe when attacking now wouldn't. -// Otherwise it attacks: a Potion the next hit undoes only gives the foe -// another turn (console B, 2026-11-03, m51: five Potions at 8/60 HP each -// undone by Misty's Starmie, then no Potions and a faint). +// `own` against `foe`, played by `trainer`'s AI: next_turn_damage(), each +// figure raised to `seen_hit` (HP the last hit took, as the battle loop +// read it) if more; the lead's planned move against the foe at its HP now. +PotionCase potion_case(const SimBattler& own, const SimBattler& foe, const SimTrainer& trainer, double seen_hit = 0); + +// At either BattleRisk: a Potion is worth the turn only if its HP is more +// than the foe's next turn takes at POTION_COVER_PERCENTILE, or if it lets +// the lead last until its attacks faint the foe (at the mean) when +// attacking now wouldn't. Otherwise it attacks: a Potion the next turn +// undoes only gives the foe another turn (console B, 2026-11-03, m51: five +// Potions at 8/60 HP each undone by Misty's Starmie, then no Potions and +// a faint). bool potion_pays(const PotionCase& c); -// BattleRisk::HIGH: a Potion now: `foe`'s next hit could faint `own`, -// after the Potion it couldn't, and potion_pays(). -bool potion_now(const SimBattler& own, const SimBattler& foe, int potions, double seen_hit = 0); +// BattleRisk::HIGH: a Potion now, with `potions` left: the foe's next turn +// could faint the lead (PotionCase::max_hit) and potion_pays(). +bool potion_now(const PotionCase& c, int potions); // At either BattleRisk, `own` asleep with an Awakening left: one now if -// `foe` can hurt it (a damaging move with PP left, or Leech Seed on it) -// and it outlasts the hit the item's turn costs (potion_case()'s, with -// `seen_hit`). The game counts sleep down only on turns the lead tries to -// move (pret battle_util.c AtkCanceller_UnableToUseMove), so the turn -// saves the rest of the 1 to 4 asleep. Below that hit the lead's move is -// tried instead, to wake and attack, or a Potion as the Potion rules say. -bool awakening_now(const SimBattler& own, const SimBattler& foe, int awakenings, double seen_hit = 0); +// the foe's next turn can hurt it and it outlasts that turn at +// POTION_COVER_PERCENTILE (`c`). The game counts sleep down only on turns +// the lead tries to move (pret battle_util.c AtkCanceller_UnableToUseMove), +// so the turn saves the rest of the 1 to 4 asleep. Below that the lead's +// move is tried instead, to wake and attack, or a Potion as the Potion +// rules say. +bool awakening_now(const PotionCase& c, const SimBattler& own, int awakenings); // The lead's turn at BattleRisk::HIGH. struct OwnTurn{ @@ -199,10 +245,11 @@ struct OwnTurn{ // planned_attack_slot()'s move when it surely faints `foe` first (the // lead is awake and faster, the lowest roll faints it, it never misses and // the AI won't heal first), else a Potion if potion_now(), else an -// Awakening if awakening_now(), else that move. +// Awakening if awakening_now(), else that move. `trainer`: its AI and the +// items it has left. OwnTurn own_turn( const SimBattler& own, const SimItems& own_items, const SimBattler& foe, - const std::vector& items, size_t foes_left + const SimTrainer& trainer, size_t foes_left ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp index 14f9a31293..3528e4f67d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleSim_Tests.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include "Common/Cpp/Exceptions.h" @@ -376,10 +377,11 @@ UnitTestResult test_sim_potion_rule(){ // Starmie as m51 saw it: at least the Potion's 20 a hit. starmie.body.stats.attack = static_cast(starmie.body.stats.attack * 2); starmie.body.stats.sp_attack = static_cast(starmie.body.stats.sp_attack * 2); - if (potion_case(own, starmie).expected_hit < POTION_HP){ - return std::format("Expected Starmie's mean hit at 20 or more, got {:.1f}.", potion_case(own, starmie).expected_hit); + const uint32_t likely = potion_case(own, starmie, misty).likely_hit; + if (likely < POTION_HP){ + return std::format("Expected Starmie's next turn at 20 or more {:.0f}% of the time, got {}.", 100 * POTION_COVER_PERCENTILE, likely); } - const OwnTurn sim = own_turn(own, SimItems{.potions = 5}, starmie, misty.items, 1); + const OwnTurn sim = own_turn(own, SimItems{.potions = 5}, starmie, misty, 1); if (sim.potion || sim.slot != size_t(0)){ return std::format( "Sim at 8/60 against Starmie (max hit {}): expected Bite (slot 0), got {}.", @@ -392,7 +394,7 @@ UnitTestResult test_sim_potion_rule(){ if (hit < 6 || hit >= POTION_HP){ return std::format("Expected Staryu's best hit on the Wartortle from 6 to 19, got {}.", hit); } - if (!own_turn(low, SimItems{.potions = 5}, staryu, misty.items, 2).potion){ + if (!own_turn(low, SimItems{.potions = 5}, staryu, misty, 2).potion){ return std::format("At 6/60 against Staryu (max hit {}): expected a Potion.", hit); } return true; @@ -400,17 +402,18 @@ UnitTestResult test_sim_potion_rule(){ // The sim plays the lead the summary showed, not the one the story // counts: m51's Wartortle (Lv20, 60 HP, Bite, Tail Whip, Bubble, -// Withdraw) with 5 Potions wins about 96% against Misty; the story's own +// Withdraw) with 2 Potions wins about 98% against Misty; the story's own // Wartortle Lv20 (Tackle, Bite, Water Gun, Withdraw; 56 HP at OWN_GENES) -// about 94%, from other inputs. m51 lost: the sim leaves out Water -// Pulse's confusion, among others (PokemonFRLG_AutoStoryWinChance.h). +// about 95%, from other inputs (both near 100% with 5). m51 lost: the +// sim leaves out Water Pulse's confusion, among others +// (PokemonFRLG_AutoStoryWinChance.h). UnitTestResult test_misty_real_lead(){ - const std::optional real = story_win_chance(m51_lead(20), SimItems{.potions = 5}, 1.0, MISTY); - const std::optional story = story_win_chance(grown_to(new_member("squirtle", 5), 20), SimItems{.potions = 5}, 1.0, MISTY); + const std::optional real = story_win_chance(m51_lead(20), SimItems{.potions = 2}, 1.0, MISTY); + const std::optional story = story_win_chance(grown_to(new_member("squirtle", 5), 20), SimItems{.potions = 2}, 1.0, MISTY); if (!real || !story){ return "Expected win chances for both leads."; } - const std::string expected = "wartortle Lv20 60/60 HP: bite 25/25, tail-whip 30/30, bubble 30/30, withdraw 40/40; 5 Potions"; + const std::string expected = "wartortle Lv20 60/60 HP: bite 25/25, tail-whip 30/30, bubble 30/30, withdraw 40/40; 2 Potions"; if (real->inputs != expected){ return "m51's lead: expected the inputs \"" + expected + "\", got \"" + real->inputs + "\"."; } @@ -425,11 +428,11 @@ UnitTestResult test_misty_real_lead(){ // The Cerulean rival against m51's moves (no Water Gun), the levels // since the summary added to its stats: refused at Lv20 and 22 (about -// 32%, 37%), fought at Lv25 and 30 (about 66%, 95%). The refusal names +// 30%, 43%), fought at Lv25 and 30 (about 75%, 96%). The refusal names // the chance and the lead it was played with. UnitTestResult test_rival_real_moves(){ const std::vector> cases = { - {20, 0.20, 0.45}, {22, 0.25, 0.50}, {25, 0.50, 0.70}, {30, 0.90, 1.00}, + {20, 0.20, 0.45}, {22, 0.25, 0.50}, {25, 0.50, 0.85}, {30, 0.90, 1.00}, }; for (const auto& [level, low, high] : cases){ const std::optional estimate = story_win_chance(m51_lead(level), SimItems{.potions = 5}, 1.0, RIVAL); @@ -533,27 +536,27 @@ UnitTestResult test_sim_awakening_rule(){ own.status = SimStatus::SLEEP; own.sleep = 4; own.hp = 34; - if (!own_turn(own, SimItems{.potions = 15, .awakenings = 2}, bulbasaur, rival.items, 1).awakening){ + if (!own_turn(own, SimItems{.potions = 15, .awakenings = 2}, bulbasaur, rival, 1).awakening){ return "Asleep at 34/65 against the Bulbasaur with 2 Awakenings: expected one."; } - if (own_turn(own, SimItems{.potions = 15, .awakenings = 0}, bulbasaur, rival.items, 1).awakening){ + if (own_turn(own, SimItems{.potions = 15, .awakenings = 0}, bulbasaur, rival, 1).awakening){ return "Asleep with no Awakenings: expected none used."; } own.hp = 8; - if (own_turn(own, SimItems{.potions = 0, .awakenings = 2}, bulbasaur, rival.items, 1).awakening){ + if (own_turn(own, SimItems{.potions = 0, .awakenings = 2}, bulbasaur, rival, 1).awakening){ return "Asleep at 8/65, below the Bulbasaur's hit: expected no Awakening."; } own.hp = 34; const SimBattler& abra = rival.party[1]; - if (own_turn(own, SimItems{.potions = 15, .awakenings = 2}, abra, rival.items, 4).awakening){ + if (own_turn(own, SimItems{.potions = 15, .awakenings = 2}, abra, rival, 4).awakening){ return "Asleep against Abra (Teleport only): expected no Awakening."; } return true; } // m56's Wartortle Lv22 with 15 Potions against the rival: Awakenings -// against the Bulbasaur's Sleep Powder win more battles (about 44% with -// none, 52% with 2, 53% with 3), and the inputs name them. +// against the Bulbasaur's Sleep Powder win more battles (about 54% with +// none, 59% with 2), and the inputs name them. UnitTestResult test_rival_awakenings(){ const std::optional none = story_win_chance(m56_lead(), SimItems{.potions = 15}, 1.0, RIVAL); const std::optional three = story_win_chance(m56_lead(), SimItems{.potions = 15, .awakenings = 3}, 1.0, RIVAL); @@ -568,6 +571,76 @@ UnitTestResult test_rival_awakenings(){ } return true; } + +// m56's Wartortle awake at 26/65 against the rival's Bulbasaur at full +// HP: the AI spends most turns on Sleep Powder and Leech Seed, so a +// Vine Whip that undoes a Potion is the rare turn (m56 run 2: about 8 HP +// a turn for three turns). With 15 Potions, a Potion. +UnitTestResult test_rival_bulbasaur_potion(){ + const SimTrainer rival = *sim_trainer(RIVAL); + const SimBattler& bulbasaur = rival.party[3]; + SimBattler own = *own_battler(m56_lead()); + own.hp = 26; + if (!own_turn(own, SimItems{.potions = 15}, bulbasaur, rival, 1).potion){ + return std::format("Awake at 26/65 against the Bulbasaur with 15 Potions: expected a Potion (max hit {}).", foe_max_hit(bulbasaur, own)); + } + return true; +} + +// The foe's next turn: a Bulbasaur with Vine Whip alone uses it every +// turn, from its lowest roll to its highest crit, never missing; with all +// four moves, no Sleep Powder on an asleep lead, and a seeded lead loses +// its eighth whatever the foe does. +UnitTestResult test_next_turn_damage(){ + const SimTrainer rival = *sim_trainer(RIVAL); + SimBattler bulbasaur = rival.party[3]; + SimBattler own = *own_battler(m56_lead()); + own.hp = 26; + const std::vector all = bulbasaur.moves; + bulbasaur.moves = {SimMove{.move = "vine-whip", .pp = 25}}; + const NextTurnDamage vine_whip = next_turn_damage(rival, bulbasaur, own); + const MoveData& move = *move_data("vine-whip"); + const uint32_t lowest = damage_range(bulbasaur.body, own.body, move, false).min; + const uint32_t highest = damage_range(bulbasaur.body, own.body, move, true).max; + if (vine_whip.move_chances != std::vector{1.0} || vine_whip.percentile(0.01) != lowest || vine_whip.most() != highest){ + return std::format( + "Vine Whip alone: expected it at 100%, {} to {} HP, got {:.2f}, {} to {}.", + lowest, highest, vine_whip.move_chances.empty() ? 0.0 : vine_whip.move_chances[0], vine_whip.percentile(0.01), vine_whip.most() + ); + } + bulbasaur.moves = all; + own.status = SimStatus::SLEEP; + own.sleep = 3; + const NextTurnDamage asleep = next_turn_damage(rival, bulbasaur, own); + if (asleep.move_chances[0] != 0 || std::abs(std::accumulate(asleep.move_chances.begin(), asleep.move_chances.end(), 0.0) - 1) > 1e-9){ + return std::format("Asleep: expected no Sleep Powder and chances adding to 1, got Sleep Powder {:.2f}.", asleep.move_chances[0]); + } + own.status = SimStatus::NONE; + own.seeded = true; + const uint32_t eighth = own.body.stats.hp / 8; + if (next_turn_damage(rival, bulbasaur, own).percentile(0.001) != eighth){ + return std::format("Seeded: expected at least {} HP lost, got {}.", eighth, next_turn_damage(rival, bulbasaur, own).percentile(0.001)); + } + return true; +} + +// m56's Wartortle Lv22 against the rival: with the Potions sized on the +// foe's likely turn, 15 Potions win over half the battles (about 54%; +// 44% when the Potion was sized on the Bulbasaur's biggest hit), more +// than 5 (about 51%). More Potions don't win much more: the battles lost +// are lost seeded, poisoned or asleep, where the Bulbasaur's turn and the +// drain take more than a Potion heals. +UnitTestResult test_rival_potions_raise_chance(){ + const std::optional five = story_win_chance(m56_lead(), SimItems{.potions = 5}, 1.0, RIVAL); + const std::optional fifteen = story_win_chance(m56_lead(), SimItems{.potions = 15}, 1.0, RIVAL); + if (!five || !fifteen || fifteen->chance < 0.50 || fifteen->chance <= five->chance){ + return std::format( + "m56's lead: expected 15 Potions to win over 50% and more than 5, got {:.1f}% and {:.1f}% with 5.", + fifteen ? 100 * fifteen->chance : 0.0, five ? 100 * five->chance : 0.0 + ); + } + return true; +} } @@ -587,6 +660,9 @@ void add_tests_AutoStoryBattleSim(UnitTestDatabase& database){ database.add("m56: asleep at red HP, a Potion undone; an Awakening first", test_rival_sleep_turns); database.add("the sim's Awakening: asleep, outlasting the next hit", test_sim_awakening_rule); database.add("Cerulean rival: Awakenings raise the win chance", test_rival_awakenings); + database.add("Cerulean rival: a Potion against the Bulbasaur", test_rival_bulbasaur_potion); + database.add("Cerulean rival: 15 Potions win over half", test_rival_potions_raise_chance); + database.add("the foe's next-turn damage and move chances", test_next_turn_damage); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp index 8fa4003a7e..5a80e8671c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp @@ -394,23 +394,26 @@ UnitTestResult test_lead_as_read(){ // Console B at the end of 00.15 (2026-11-03): Wartortle Lv22, 65 HP, // with Water Pulse taught over Tail Whip, and 10 Potions. The sim, the // levels since the summary added to its stats, wins against the -// Cerulean rival about 42% at Lv22, 62% at Lv23, 66% at Lv24 and 76% at -// Lv25: a GRIND to 50% stops at Lv23. +// Cerulean rival about 52% at Lv22 (42% when the sim's Potion was sized +// on the foe's biggest hit) and more at Lv25: a GRIND to 50% stops at +// Lv22. UnitTestResult test_console_party(){ Stats stats = combatant("wartortle", 22, OWN_GENES)->stats; stats.hp = 65; const MemberInfo read{.species = "wartortle", .level = 22, .moves = {"bite", "water-pulse", "bubble", "withdraw"}, .stats = stats}; const PartyMember at22 = lead_as_read(read, PartyMember{}); - for (uint8_t level = 22; level <= 25; level++){ + double previous = 0; + for (uint8_t level = 22; level <= 25; level += 3){ PartyMember lead = at22; lead.moves_through_level = level; const std::optional estimate = healed_win_chance(lead, SimItems{.potions = 10}, RIVAL); - if (!estimate || (estimate->chance >= MIN_WIN_CHANCE) != (level >= 23)){ + if (!estimate || estimate->chance < MIN_WIN_CHANCE || estimate->chance <= previous){ return std::format( - "Lv{}: {:.1f}%; expected {:.0f}% or more from Lv23.", + "Lv{}: {:.1f}%; expected {:.0f}% or more, rising with the level.", level, estimate ? 100 * estimate->chance : 0.0, 100 * MIN_WIN_CHANCE ); } + previous = estimate->chance; } return true; } @@ -465,7 +468,7 @@ void add_tests_AutoStoryGrind(UnitTestDatabase& database){ add("the table's variant", test_grind_variant); add("the level cap's message", test_grind_cap_message); add("the lead the sim plays is the one read", test_lead_as_read); - add("console B's party stops at Lv25 against the Cerulean rival", test_console_party); + add("console B's party is fought at Lv22 against the Cerulean rival", test_console_party); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp index 7d38a1aa2e..9a9b421dcc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp @@ -19,13 +19,8 @@ namespace{ // A battle still going after this many turns counts as lost. constexpr size_t MAX_TURNS = 100; -constexpr uint32_t CRIT_CHANCE = 16; -constexpr uint32_t HIGH_CRIT_CHANCE = 8; constexpr int MAX_STAGE = 6; -// sAccuracyStageRatios, -6 to +6, in hundredths. -constexpr uint32_t ACCURACY_RATIOS[] = {33, 36, 43, 50, 60, 75, 100, 133, 166, 200, 233, 266, 300}; - const MoveData& data_of(std::string_view move){ static const MoveData NONE; const MoveData* data = move_data(move); @@ -151,7 +146,7 @@ class SimBattle{ void play_turn(){ const size_t left = foes_left(); - const OwnTurn own = own_turn(m_own, m_items, foe(), m_trainer.items, left); + const OwnTurn own = own_turn(m_own, m_items, foe(), m_trainer, left); const std::optional item = ai_item_choice(foe(), m_trainer.items, left); const std::optional foe_slot = item ? std::nullopt : foe_move(); if (own.potion){ @@ -217,15 +212,7 @@ class SimBattle{ } bool hits(const SimBattler& user, const SimBattler& target, const MoveData& move){ - if (move.accuracy == 0){ - return true; - } - const int buff = std::clamp( - user.body.stages[static_cast(Stage::ACCURACY)] - target.body.stages[static_cast(Stage::EVASION)], - -MAX_STAGE, MAX_STAGE - ); - const uint32_t chance = move.accuracy * ACCURACY_RATIOS[buff + MAX_STAGE] / 100; - return random(100) + 1 <= chance; + return move.accuracy == 0 || random(100) + 1 <= hit_percent(user, target, move); } void use(SimBattler& user, SimBattler& target, const std::string& move_name, std::optional slot, bool moves_first){ @@ -262,7 +249,7 @@ class SimBattle{ if (move.effect == "super-fang"){ return std::max(target.hp / 2, 1); } - const bool crit = random(move.effect == "high-critical" ? HIGH_CRIT_CHANCE : CRIT_CHANCE) == 0; + const bool crit = random(crit_odds(move)) == 0; const uint32_t before = damage_before_roll(user.body, target.body, move, crit); return fixed_damage(move, user.body) ? before : rolled_damage(before, 100 - random(16)); } From 25ce096ea9d530dfadca1eb9b49f86a55ca623a3 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 10 Nov 2026 10:39:45 -0800 Subject: [PATCH 5/6] FRLG AutoStory: delete stage 4's C++ story rows, parity proven The parity test passed in the merge before this commit: every story file loads to the C++ row it replaces. The rows went with the merge's Table.cpp; this removes the parity test that held them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStoryTable.h | 2 - ...PokemonFRLG_AutoStoryTableParity_Tests.cpp | 783 ------------------ .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 1 - SerialPrograms/cmake/SourceFiles.cmake | 1 - 4 files changed, 787 deletions(-) delete mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h index 2d57d3c272..9aeaf0fcb3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h @@ -70,8 +70,6 @@ const std::vector& story_checkpoints(); // Registers AutoStory table validation unit tests. void add_tests_AutoStory(UnitTestDatabase& database); -// The story files against the C++ rows they replace. -void add_tests_AutoStoryTableParity(UnitTestDatabase& database); // Which rows a run takes (PokemonFRLG_AutoStoryRunPlan_Tests.cpp). void add_tests_AutoStoryRunPlan(UnitTestDatabase& database); // The table run end to end against a fake game (PokemonFRLG_AutoStorySimulation_Tests.cpp). diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp deleted file mode 100644 index 82b52f527a..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp +++ /dev/null @@ -1,783 +0,0 @@ -/* AutoStory Table Parity Tests - * - * From: https://github.com/PokemonAutomation/ - * - * The C++ rows the story table had before StoryData/, built with the - * shared step API, against the checkpoints read from the files: each - * loads to the same steps, args (with the fallbacks the reader fills in), - * poses, supplies and START menu. Removed with the C++ rows. - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/TestRunners/UnitTest.h" -#include "Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h" -#include "PokemonFRLG_AutoStoryCapture.h" -#include "PokemonFRLG_AutoStoryChoice.h" -#include "PokemonFRLG_AutoStoryBattleData.h" -#include "PokemonFRLG_AutoStoryGrind.h" -#include "PokemonFRLG_AutoStoryMart.h" -#include "PokemonFRLG_AutoStoryParty.h" -#include "PokemonFRLG_AutoStoryTable.h" -#include "PokemonFRLG_AutoStoryTeach.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -namespace{ - -constexpr Direction NORTH = Direction::NORTH; -constexpr Direction SOUTH = Direction::SOUTH; -constexpr Direction EAST = Direction::EAST; -constexpr Direction WEST = Direction::WEST; - -constexpr std::string_view BEDROOM = "PalletTown_PlayersHouse_2F"; -constexpr std::string_view PALLET = "PalletTown"; -constexpr std::string_view LAB = "PalletTown_ProfessorOaksLab"; -constexpr std::string_view VIRIDIAN = "ViridianCity"; -constexpr std::string_view VIRIDIAN_MART = "ViridianCity_Mart"; -constexpr std::string_view VIRIDIAN_CENTER = "ViridianCity_PokemonCenter_1F"; -constexpr std::string_view FOREST = "ViridianForest"; -constexpr std::string_view FOREST_GATE = "Route2_ViridianForest_NorthEntrance"; -constexpr std::string_view PEWTER = "PewterCity"; -constexpr std::string_view PEWTER_CENTER = "PewterCity_PokemonCenter_1F"; -constexpr std::string_view GYM = "PewterCity_Gym"; -constexpr std::string_view ROUTE3 = "Route3"; -constexpr std::string_view ROUTE4 = "Route4"; -constexpr std::string_view ROUTE4_CENTER = "Route4_PokemonCenter_1F"; -constexpr std::string_view MT_MOON_1F = "MtMoon_1F"; -constexpr std::string_view MT_MOON_B2F = "MtMoon_B2F"; -constexpr std::string_view CERULEAN = "CeruleanCity"; -constexpr std::string_view CERULEAN_CENTER = "CeruleanCity_PokemonCenter_1F"; -constexpr std::string_view CERULEAN_MART = "CeruleanCity_Mart"; -constexpr std::string_view CERULEAN_GYM = "CeruleanCity_Gym"; -constexpr std::string_view ROUTE24 = "Route24"; - -Pokemon::GridPose at(std::string_view map, int x, int y, std::optional facing = std::nullopt){ - return Pokemon::GridPose{std::string(map), {{x, y}}, facing}; -} - -StoryCheckpoint row( - std::string id, std::string title, std::optional start, - Supplies supplies, StartMenu menu, std::vector steps -){ - StoryCheckpoint checkpoint; - checkpoint.id = std::move(id); - checkpoint.title = std::move(title); - checkpoint.start = std::move(start); - checkpoint.steps = std::move(steps); - checkpoint.supplies = supplies; - checkpoint.menu = menu; - return checkpoint; -} - -Supplies after_brock(){ - Supplies supplies; - supplies.lead = story_lead_after_brock(); - return supplies; -} - -// What a walk does about wild Pokemon: runs, or fights them for EXP. -enum class WildBattles{ - RUN, - FIGHT, -}; - -StoryStep make(StoryStepKind kind, std::string name, std::string why, Pokemon::StoryActionArgs args = {}){ - StoryStep step; - step.kind = kind; - step.name = std::move(name); - step.why = std::move(why); - step.args = std::move(args); - return step; -} - -StoryStep route(std::string name, Pokemon::GridPose target, std::string why, WildBattles wild = WildBattles::RUN){ - return make(StoryStepKind::ROUTE, std::move(name), std::move(why), { - {"target", std::move(target)}, {"fight_wild", wild == WildBattles::FIGHT}, - }); -} - -StoryStep step_into(std::string name, Direction direction, std::string why){ - return make(StoryStepKind::STEP, std::move(name), std::move(why), {{"direction", direction}}); -} - -StoryStep into_line(std::string name, Direction direction, std::string why){ - StoryStep step = step_into(std::move(name), direction, std::move(why)); - step.action = TRAINER_LINE_VARIANT; - return step; -} - -StoryStep hop(std::string name, Direction direction, Pokemon::GridPose landing, std::string why){ - StoryStep step = step_into(std::move(name), direction, std::move(why)); - step.pose_after = std::move(landing); - return step; -} - -StoryStep answer(std::string name, bool yes, std::string why){ - return make(StoryStepKind::ANSWER, std::move(name), std::move(why), {{"yes", yes}}); -} - -StoryStep scene(std::string name, std::optional pose_after, std::string why){ - StoryStep step = make(StoryStepKind::MASH, std::move(name), std::move(why)); - step.pose_after = std::move(pose_after); - return step; -} - -StoryStep battle(std::string name, Pokemon::GridPose pose_after, bool may_lose, std::string why){ - StoryStep step = make(StoryStepKind::BATTLE, std::move(name), std::move(why), {{"may_lose", may_lose}}); - step.pose_after = std::move(pose_after); - return step; -} - -StoryStep legs(std::string name, std::vector legs, std::string why, WildBattles wild = WildBattles::RUN){ - return make(StoryStepKind::LEGS, std::move(name), std::move(why), { - {"legs", std::move(legs)}, {"fight_wild", wild == WildBattles::FIGHT}, - }); -} - -// `step`, a ROUTE or LEGS, run with B held: from the Running Shoes on. -StoryStep running(StoryStep step){ - step.action = RUN_VARIANT; - return step; -} - -StoryStep new_game_intro(Pokemon::GridPose pose_after, std::string why){ - StoryStep step = make(StoryStepKind::NEW_GAME, "intro", std::move(why)); - step.pose_after = std::move(pose_after); - return step; -} - -StoryStep talk(std::string name, std::string why){ - return make(StoryStepKind::TALK, std::move(name), std::move(why)); -} - -StoryStep ready(std::string name, Pokemon::GridPose nurse, std::string why){ - return make(StoryStepKind::READY, std::move(name), std::move(why), {{"target", std::move(nurse)}}); -} - -StoryStep heal(std::string name){ - return make(StoryStepKind::HEAL, std::move(name), "full HP"); -} - -StoryStep shop(std::string name, std::vector items, std::string why){ - return make(StoryStepKind::SHOP, std::move(name), std::move(why), {{"items", std::move(items)}}); -} - -StoryStep game_step(std::string action, Pokemon::GridPose pose_after, std::string why){ - StoryStep step = make(StoryStepKind::GAME, action, std::move(why)); - step.action = std::move(action); - step.pose_after = std::move(pose_after); - return step; -} - -StoryStep options_step(){ - return make(StoryStepKind::OPTIONS, "options", "fast text; no switch prompt between a trainer's Pokemon"); -} - - -StoryCheckpoint new_game(){ - StoryCheckpoint checkpoint = row("00.01", "new game to the bedroom", std::nullopt, {}, StartMenu::BEFORE_POKEMON, { - // new_game.c: the bedroom at (6, 6), facing the TV. - new_game_intro(at(BEDROOM, 6, 6, NORTH), "Oak's speech, BOY, the player's name (default if none is set), rival GREEN"), - options_step(), - }); - checkpoint.handoff = StoryHandoff::SID_HELPER; - return checkpoint; -} - -// SID Helper confirms the name, finishes the intro and reads the Trainer -// Card from the START menu, without moving the player or saving. -StoryCheckpoint after_sid_helper(){ - StoryCheckpoint checkpoint = row("00.01b", "after SID Helper: close the Trainer Card, save in the bedroom", at(BEDROOM, 6, 6, NORTH), {}, StartMenu::BEFORE_POKEMON, { - game_step(CLOSE_TRAINER_CARD, at(BEDROOM, 6, 6, NORTH), "the Trainer Card SID Helper left open, or HOME"), - options_step(), - }); - checkpoint.live_start = true; - return checkpoint; -} - -StoryCheckpoint leave_house(){ - return row("00.02", "bedroom to Pallet Town", at(BEDROOM, 6, 6, NORTH), {}, StartMenu::BEFORE_POKEMON, { - route("front_door", at(PALLET, 6, 8), "down the stairs and out of the house"), - }); -} - -StoryCheckpoint oaks_trigger(){ - return row("00.03", "Oak stops the player and walks them to the lab", at(PALLET, 6, 8, SOUTH), {}, StartMenu::BEFORE_POKEMON, { - route("below_oaks_trigger", at(PALLET, 12, 2, NORTH), "below the north exit, short of Oak's trigger at (12, 1)"), - step_into("oaks_trigger", NORTH, "the trigger: \"Don't go out!\""), - // PlayerEnter walks the player up 8 tiles from the lab's door. - scene("to_the_lab", at(LAB, 6, 4, NORTH), "Oak walks the player into the lab; the scene ends at the table"), - }); -} - -// Starter RNG starts from a save south of the table, facing the ball. -StoryCheckpoint to_starter_ball(){ - StoryCheckpoint checkpoint = row("00.04", "to Squirtle's ball, south of the table", at(LAB, 6, 4, NORTH), {}, StartMenu::BEFORE_POKEMON, { - route("below_squirtle", at(LAB, 9, 5, NORTH), "under Squirtle's ball (9, 4)"), - }); - checkpoint.handoff = StoryHandoff::STARTER_RNG; - return checkpoint; -} - -StoryCheckpoint starter(){ - return row("00.04b", "Squirtle, then the rival's battle", at(LAB, 9, 5, NORTH), {}, StartMenu::BEFORE_POKEDEX, { - talk("squirtle_ball", "\"So, you want the WATER POKEMON SQUIRTLE?\""), - answer("choose_squirtle", true, "take Squirtle"), - answer("no_nickname", false, "\"give a nickname?\" NO"), - scene("rival_takes_bulbasaur", at(LAB, 9, 5, NORTH), "the rival picks his ball; the player still faces the table (console B, 2026-11-01)"), - route("above_rival_trigger", at(LAB, 7, 7, SOUTH), "short of the rival's trigger row 8"), - step_into("rival_trigger", SOUTH, "\"Wait, let's check out our POKEMON!\""), - // The rival leaves; PlayerWatchRivalExitAfterBattleRight ends facing down. - battle("rival_battle", at(LAB, 7, 8, SOUTH), true, "the tutorial battle; losing goes on too"), - }); -} - -StoryCheckpoint parcel(){ - return row("00.05", "Route 1 to Viridian Mart: Oak's Parcel", at(LAB, 7, 8, SOUTH), {}, StartMenu::BEFORE_POKEDEX, { - route("below_mart_door", at(VIRIDIAN, 36, 20, NORTH), "Route 1, running from wild battles"), - step_into("mart_door", NORTH, "the clerk's scene starts on entering"), - // ApproachCounter: up 4 from the mat, then faces the clerk. - scene("parcel_from_clerk", at(VIRIDIAN_MART, 4, 3, WEST), "the clerk gives OAK'S PARCEL"), - }); -} - -StoryCheckpoint pokedex(){ - return row("00.06", "Oak's Parcel to the Pokedex", at(VIRIDIAN_MART, 4, 3, WEST), {}, StartMenu::FULL, { - route("below_oak", at(LAB, 6, 4, NORTH), "back down Route 1 to Oak"), - talk("give_parcel", "Oak takes the parcel"), - scene("pokedex_scene", at(LAB, 6, 4, SOUTH), "the rival comes in, Pokedexes from the desk; the player ends facing south (console B, 2026-11-01)"), - }); -} - -StoryCheckpoint shopping(){ - return row("00.07", "Viridian shopping, then into Viridian Forest", at(LAB, 6, 4, SOUTH), {}, StartMenu::FULL, { - route("mart_clerk", at(VIRIDIAN_MART, 4, 3, WEST), "Route 1 again"), - // 2000 of the 3000 a new game starts with, plus the rival's prize. - shop("potions_and_antidotes", {{"potion", 5}, {"antidote", 3}, {"parlyz_heal", 1}}, "5 Potions, 3 Antidotes, 1 Parlyz Heal"), - route("viridian_nurse", at(VIRIDIAN_CENTER, 7, 4, NORTH), "heal before the forest"), - heal("heal_viridian"), - route("below_old_man_trigger", at(VIRIDIAN, 20, 9, NORTH), "short of the tutorial trigger (20, 8)"), - step_into("old_man_trigger", NORTH, "the old man's catching tutorial can't be walked around"), - // TutorialTriggerLeft turns the player right, to the old man. - scene("old_man_tutorial", at(VIRIDIAN, 20, 8, EAST), "about 60 lines and his demo battle; TEACHY TV"), - // After his demo the old man stands east of the player, beside (20, 8), where - // the map doesn't have him: "east 2" from there didn't move, and the walk north - // ended under Route 2's ledge in column 8 (console B, 2026-11-01). Go north first. - route("past_old_man", at(VIRIDIAN, 20, 5, NORTH), "north along column 20, clear of the old man"), - // The gate's north warp lands on the forest's exit mat (29, 62), facing - // north. The save there keeps a forest failure from going back to Pallet. - route("forest_entrance", at(FOREST, 29, 62, NORTH), "Route 2 and the south gate, running from wild battles"), - }); -} - -StoryCheckpoint forest(){ - // The supplies bought in 00.07. - return row("00.08", "Viridian Forest to Pewter Center", at(FOREST, 29, 62, NORTH), {5, 3, 1}, StartMenu::FULL, { - // Wild battles are fought for EXP. Straight up the east side from the - // entrance, each leg ending on a wall (the Boy at (45, 58) stops the - // east one). Rick (47, 45) sees (42..46, 45), so the last leg meets - // his battle and is held on to its wall after it. The by-hand run's - // detour west to (13, 46) and back is dropped. - legs("forest_east", {{EAST, 1}, {NORTH, 4}, {EAST, 14}, {NORTH, 15}}, "up the east side to (44, 43)", WildBattles::FIGHT), - route("forest_north", at(FOREST, 39, 25), "north part", WildBattles::FIGHT), - // To the gate by legs that end on walls, which the walker holds again - // after a battle instead of estimating where it stopped: planned - // routes with open legs lost the player in the north of the forest - // (console B, 2026-11-01). The two 1-tile legs are single steps. - legs("forest_exit", { - {NORTH, 10}, {WEST, 12}, {SOUTH, 10}, {WEST, 6}, {NORTH, 20}, - {SOUTH, 1}, {WEST, 10}, {SOUTH, 27}, {WEST, 8}, {NORTH, 20}, {EAST, 1}, - }, "walls all the way to the gate's column", WildBattles::FIGHT), - route("forest_gate", at(FOREST_GATE, 7, 10, NORTH), "north onto the exit, arriving on the gate's mat", WildBattles::FIGHT), - // Out of the forest, wild battles are run from; trainers are still fought. - route("pewter_nurse", at(PEWTER_CENTER, 7, 4, NORTH), "Route 2 north to Pewter's Center"), - heal("heal_pewter"), - }); -} - -StoryCheckpoint brock(){ - // The by-hand save: 2 Potions and 1 Antidote left after the forest. - return row("00.09", "Pewter Gym: Camper Liam, then Brock", at(PEWTER_CENTER, 7, 4, NORTH), {2, 1}, StartMenu::FULL, { - // Camper Liam (3, 8) always faces east (MOVEMENT_TYPE_FACE_RIGHT, sight - // 4) and sees (4..7, 8): walking north up column 6 from the door, - // the step onto (6, 8) starts his battle. He walks up to the player, - // who stays put and keeps facing north (FRLG doesn't turn the player - // to a trainer). That step is taken on its own, so no leg is cut. - route("below_liam_line", at(GYM, 6, 9, NORTH), "in by the door, up column 6 to below Liam's row"), - step_into("liam_line", NORTH, "onto (6, 8), in Liam's line"), - battle("camper_liam", at(GYM, 6, 8, NORTH), false, "Geodude and Sandshrew; EXP before Brock"), - // On to Brock unless red HP or a status is left that no item cures. - ready("ready_for_brock", at(PEWTER_CENTER, 7, 4, NORTH), "items for a status or low HP; the nurse only if they can't"), - route("before_brock", at(GYM, 6, 6, NORTH), "below Brock (6, 5); Liam, beaten, stands at (5, 8)"), - talk("challenge_brock", "Brock's speech"), - battle("brock", at(GYM, 6, 6, NORTH), false, "Geodude and Onix, with Bubble; Boulder Badge and TM39"), - }); -} - -StoryCheckpoint running_shoes(){ - return row("00.10", "Pewter: the Running Shoes from Oak's aide", at(GYM, 6, 6, NORTH), after_brock(), StartMenu::FULL, { - // Brock's win sets VAR_MAP_SCENE_PEWTER_CITY to 1 and shows the aide at - // (46, 20); his triggers are (46, 21..23) (PewterCity map.json). The - // Gym guide's triggers at (42..43, 21..23) need the scene at 0. - route("before_aide_trigger", at(PEWTER, 45, 21, EAST), "out of the Gym, east along row 21, short of the top trigger"), - step_into("aide_trigger", EAST, "onto (46, 21), below the aide"), - // RunningShoesAideTriggerTop: the aide talks from (46, 20), no YES/NO; - // the player only turns up. He walks off and is removed; FLAG_SYS_B_DASH - // is set (console B, 2026-11-02: about 20 B presses to the overworld). - scene("shoes_from_aide", at(PEWTER, 46, 21, NORTH), "\"Oh, PLAYER!\" ... the Running Shoes; ends facing north"), - // Where the by-hand walk stopped to start 00.11 (console B, 2026-11-02). - route("below_pewter_center", at(PEWTER, 17, 26, SOUTH), "west along row 21 and down to below the Pokemon Center's door (17, 25)"), - }); -} - -// Route 3's trainers (Route3 map.json): the way east meets three of them. -// Bug Catcher Colton (12, 6) faces east, sight 3: the only way north past -// the row 7 ledges is the gap at x 14..15, below his line. Youngster Ben -// (17, 4) faces south, sight 2, so the way east keeps to row 3 past him. -// Bug Catcher Greg (25, 4) faces south, sight 2, over the way east along -// row 5. Bug Catcher James (32, 6) faces east, sight 4, over the way down -// at x 35..36. The others are kept out of: Lass Janice (19, 9) sees west -// along row 9 to x 14, Lass Sally (30, 3) west along row 3 to x 25, and -// Youngster Calvin (29, 10) west along row 10. Each line is stepped into on -// its own, so no leg is cut; the trainer walks up to the player, who stays -// put facing the way they stepped. -StoryCheckpoint route3(){ - return row("00.11", "Pewter Center, then Route 3's trainers", at(PEWTER, 17, 26, SOUTH), after_brock(), StartMenu::FULL, { - running(route("pewter_nurse", at(PEWTER_CENTER, 7, 4, NORTH), "in by the door below the player")), - heal("heal_pewter"), - // Up from row 9 west of Janice's line, which ends at x 14. - running(route("west_of_janice_line", at(ROUTE3, 13, 8), "out of Pewter by row 21, east into Route 3, short of Janice's line")), - running(legs("below_colton_line", {{EAST, 1}, {NORTH, 1}}, "to (14, 7), in the ledges' gap")), - step_into("colton_line", NORTH, "onto (14, 6), in Colton's line"), - battle("bug_catcher_colton", at(ROUTE3, 14, 6, NORTH), false, "his Bug Pokemon; Colton stops at (13, 6)"), - running(legs("past_ben", {{NORTH, 3}, {EAST, 4}, {SOUTH, 2}, {EAST, 6}}, "up to row 3 above Ben, down at x 18 east of his line, to (24, 5)")), - step_into("greg_line", EAST, "onto (25, 5), below Greg"), - battle("bug_catcher_greg", at(ROUTE3, 25, 5, EAST), false, "his Bug Pokemon; Greg is already next to the player"), - running(legs("above_james_line", {{EAST, 11}}, "along row 5 to the wall at (36, 5)")), - step_into("james_line", SOUTH, "onto (36, 6), at the end of James's line"), - battle("bug_catcher_james", at(ROUTE3, 36, 6, SOUTH), false, "his Bug Pokemon; James stops at (35, 6)"), - // Saved here, the trainers behind, so a failure on the way to Route 4 - // doesn't fight them again. - running(legs("save_spot", {{SOUTH, 2}}, "down to (36, 8), beside the wall east of it")), - }); -} - -// Route 3's north exit (x 68..75) joins Route 4 (offset 60) at x 8..15, up -// which column 12 leads to the Pokemon Center's door (12, 5). Lass Robin -// (40, 11) wanders up and down at x 40, looking north and south, sight 3. -// Rock above (y <= 8) and grass below (y >= 12) leave every way east -// across her column at y 9..11, so whether she sees the player depends on -// her facing. The walk watches for her after the leg along row 9, which -// crosses her sight on (40, 9) only; if she saw the player, her message -// goes to story_interrupts(), which fight her, and the route goes on from -// (40, 9) (run_route(); console B, 2026-11-02, she stopped the player -// there and spoke after the leg's short watch). -StoryCheckpoint magikarp_salesman(){ - StoryCheckpoint checkpoint = row("00.12", "Route 3 and 4 to the Magikarp salesman", at(ROUTE3, 36, 8, SOUTH), after_brock(), StartMenu::FULL, { - running(route("route4_nurse", at(ROUTE4_CENTER, 7, 4, NORTH), "east over Route 3, off the grass, north into Route 4 and its Pokemon Center")), - heal("heal_route4"), - // Gift RNG starts from a save facing the salesman (1, 3). - running(route("before_salesman", at(ROUTE4_CENTER, 2, 3, WEST), "beside the Magikarp salesman, facing him")), - }); - checkpoint.handoff = StoryHandoff::GIFT_RNG; - return checkpoint; -} - -// Gift RNG buys the Magikarp (500 of the money 00.12 brings) without -// moving the player and leaves its summary open, or HOME. This saves the -// shiny where 00.12 ended. A run started here with Gift RNG's handoff on -// loads the save beside the salesman and runs Gift RNG first. -StoryCheckpoint after_gift_rng(){ - StoryCheckpoint checkpoint = row("00.12b", "after Gift RNG: save with the Magikarp", at(ROUTE4_CENTER, 2, 3, WEST), after_brock(), StartMenu::FULL, { - game_step(LEAVE_GIFT_SUMMARY, at(ROUTE4_CENTER, 2, 3, WEST), "the Magikarp's summary Gift RNG left open, or HOME"), - }); - checkpoint.live_start = true; - return checkpoint; -} - -// The Magikarp goes to BOX 1 at the Center's PC (11, 1), so Mt. Moon is -// fought with the starter alone (console B, 2026-11-02: done by hand and -// saved at (11, 2), facing the PC, where this row ends). The wandering -// boy (4..6, 3..5) is walked around. The Magikarp comes from Gift RNG: -// with Gift RNG off the party is the starter alone, and the deposit is -// skipped. -StoryCheckpoint magikarp_to_box(){ - return row("00.12c", "Route 4 Center: the Magikarp into BOX 1", at(ROUTE4_CENTER, 2, 3, WEST), after_brock(), StartMenu::FULL, { - running(route("pc_front", at(ROUTE4_CENTER, 11, 2, NORTH), "below the PC (11, 1), facing it")), - pc_step("magikarp_to_box", "DEPOSIT the party's second slot into BOX 1, if it has one", PcTransfer{ - .action = PcAction::DEPOSIT, .party_slot = 1, .box = 0, .if_missing = PcMissing::SKIP, - }), - }); -} - -// Mt. Moon (pokefirered data/maps/MtMoon_1F, _B1F, _B2F). Every floor tile -// of the cave has wild encounters, which are run from, so its legs end on -// walls, ladders or someone standing still, which the walker holds again -// after a battle; the few open ones are short. The way through: up 1F's -// middle and west side, its north-west ladder, B1F's west ladder down to -// B2F's south-east, round B2F's south edge to its west, north past -// Miguel and the fossils, and the ladder up to B1F's east end, which -// leads out to Route 4 east of the mountain. -// - 1F's trainers are walked around: Youngster Josh (13, 17) sees east -// along row 17 to x 17, so the way west into the west room is down -// column 18 and up column 11; Lass Miriam walks round (32..33, 4..5), -// sight 2, so the way east keeps to row 9 and columns 38 and 40; Hiker -// Marcos wanders (5..9, 8..12) and sees one tile, so the way north is -// column 11 and row 3. -// - The Moon Stone ball (3, 2) on 1F (FLAG_HIDE_MT_MOON_1F_MOON_STONE) is -// a few tiles off the way to the ladder (5, 6). -// - The Grunt at (37, 21) on B2F looks around (sight 3) over the only way -// east round B2F. His room is crossed on legs to walls, at one tile of -// his sight each, (37, 22) and (40, 21); if he looks the player's way, -// he walks up beside the leg, story_interrupts() fights him, and the -// leg is held on to its wall. -// - The Grunt at (12, 20) faces south (sight 2) over (12, 21..22), across -// rows 21..22, the only way north to Miguel: stepped into from the -// west, he is next to the player and doesn't walk. -// - Super Nerd Miguel (13, 11) battles on the step onto (14, 11) -// (MtMoon_B2F_EventScript_MiguelTrigger, VAR_MAP_SCENE_MT_MOON_B2F 0), -// then "We'll each take one!" -// - The fossils: DOME (13, 7), HELIX (14, 7). After the HELIX, Miguel -// walks up to (13, 8) and takes the DOME, which opens the gap north. -// The save is on Route 4: the save card's places don't include Mt. Moon. -StoryCheckpoint mt_moon(){ - return row("00.13", "Mt. Moon: a Moon Stone, a Rocket, Miguel and the Helix Fossil", at(ROUTE4_CENTER, 11, 2, NORTH), after_brock(), StartMenu::FULL, { - running(route("route4_nurse", at(ROUTE4_CENTER, 7, 4, NORTH), "the nurse, below the counter")), - heal("heal_route4"), - running(route("mt_moon_entrance", at(MT_MOON_1F, 18, 37, NORTH), "out of the Center, west into Mt. Moon")), - running(legs("mt_moon_1f", { - {NORTH, 12}, {EAST, 8}, {NORTH, 12}, {EAST, 3}, {SOUTH, 1}, {EAST, 9}, - {NORTH, 1}, {EAST, 2}, {NORTH, 4}, {WEST, 24}, {EAST, 2}, {SOUTH, 12}, - {WEST, 7}, {NORTH, 18}, {WEST, 9}, {EAST, 1}, - }, "up the middle, east of Miriam, west along row 9, down column 18 past Josh, up column 11 past Marcos, to (3, 3)")), - running(route("below_moon_stone", at(MT_MOON_1F, 3, 3, NORTH), "facing the Moon Stone (3, 2)")), - talk("moon_stone_ball", "A on the item ball"), - // No reader for the text yet: the scene's end is the overworld. - scene("found_moon_stone", at(MT_MOON_1F, 3, 3, NORTH), "\" found a MOON STONE!\", then the pocket line; the ball is gone"), - running(route("b2f_ladder_foot", at(MT_MOON_B2F, 26, 21, EAST), "1F's ladder (5, 6), down B1F's west side to its ladder (22, 18), onto B2F")), - running(legs("b2f_south", { - {NORTH, 4}, {EAST, 8}, {WEST, 2}, {SOUTH, 5}, {EAST, 8}, {NORTH, 3}, {WEST, 1}, {NORTH, 5}, - {EAST, 7}, {SOUTH, 14}, {WEST, 9}, {SOUTH, 10}, {WEST, 29}, {EAST, 3}, {NORTH, 17}, - }, "through the Grunt's room at (37, 21), round the south edge, up column 11 to (11, 21)")), - step_into("grunt_line", EAST, "onto (12, 21), below the Grunt at (12, 20)"), - battle("rocket_grunt", at(MT_MOON_B2F, 12, 21, EAST), false, "Rattata and Zubat, Lv13"), - ready("ready_for_miguel", at(ROUTE4_CENTER, 7, 4, NORTH), "items for a status or low HP; the nurse, back through the cave, only if they can't"), - // Up column 13 to Miguel, who stops the leg on (13, 12), then east - // to the wall: the tile below his trigger. - running(legs("below_miguel_trigger", {{EAST, 1}, {NORTH, 9}, {EAST, 1}}, "to (14, 12), below Miguel's trigger (14, 11)")), - step_into("miguel_trigger", NORTH, "onto (14, 11), beside Miguel"), - battle("super_nerd_miguel", at(MT_MOON_B2F, 14, 11, NORTH), false, "Grimer, Voltorb and Koffing, Lv12; \"We'll each take one!\""), - running(legs("below_helix_fossil", {{NORTH, 3}}, "up column 14 to the HELIX FOSSIL (14, 7)")), - fossil_step("helix_fossil", "the HELIX FOSSIL; Miguel takes the DOME FOSSIL", Fossil::HELIX), - // The maps keep the fossils, which the game removes after the - // choice: the step onto the HELIX's tile is taken on its own. - step_into("helix_gap", NORTH, "onto (14, 7), where the HELIX FOSSIL lay"), - running(route("route4_east", at(ROUTE4, 32, 6, SOUTH), "west to B2F's ladder (5, 10), up to B1F, east to its exit onto Route 4")), - }); -} - - -// Route 4 east of Mt. Moon (Route4 map.json) joins Cerulean City at its -// east end (x 107; Route 4's row 3 is the city's row 13). Its upper road -// (rows 2..8) reaches the city only by water: the way on by land is down -// the ledge row 9 at x 90..96 to the lower road (rows 10..12), which -// joins the city's rows 20..22. Lass Crissy (75, 3) faces east, sight 4, -// over row 3 from x 76 to 79; the way east keeps out of her line and off -// the grass south of the road (75..87, 11..17). -// -// The open leg east across the city's edge ended a tile short on the -// console (2026-11-03: on (6, 20), not (7, 20)), and no hold to a wall -// in the city's west end finds the player from there: the next hold -// south met the fence on (6, 23) and the walk went on a column off. So -// the entry ends on (9, 20), and only legs to walls follow: north up -// column 9 (or 8, a tile short) to row 12, west to (8, 12), east to -// (30, 12) beside the policeman (31, 12), south to (30, 17), west to -// (25, 17), and down the ledge row 18 to (25, 19), a few tiles from the -// door (22, 19). The way keeps out of the boy's (16, 18..24) and the -// balding man's (8..10, 22..24) wander boxes. -StoryCheckpoint route4_to_cerulean(){ - return row("00.14", "Route 4 east to Cerulean's Pokemon Center", at(ROUTE4, 32, 6, SOUTH), after_brock(), StartMenu::FULL, { - running(route("above_ledge", at(ROUTE4, 93, 8, SOUTH), "east along Route 4's upper road to above the ledge row 9")), - hop("ledge_hop", SOUTH, at(ROUTE4, 93, 10, SOUTH), "down the ledge (93, 9) to the lower road"), - running(route("cerulean_entry", at(CERULEAN, 9, 20, EAST), "east into Cerulean City, to (9, 20) below column 9")), - running(legs("above_city_ledge", {{NORTH, 8}, {WEST, 1}, {EAST, 22}, {SOUTH, 5}, {WEST, 5}}, "to walls: (9, 12), (8, 12), (30, 12), (30, 17), (25, 17)")), - hop("city_ledge_hop", SOUTH, at(CERULEAN, 25, 19, SOUTH), "down the ledge (25, 18)"), - running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "west along row 20 to the Pokemon Center's door (22, 19)")), - heal("heal_cerulean"), - }); -} - -// Cerulean Gym (pokefirered CeruleanCity_Gym map.json and scripts.inc): -// a pool with walkways. Misty (8, 6) stands on a platform (7..9, 6) above -// row 7. Picnicker Diana (4, 7) faces east, sight 4, over (5..8, 7), so -// misty_front (8, 7) is in her line; Swimmer Luis (10, 12) in the water -// faces west, sight 1, over (9, 12), on column 9 north of the door. No -// gym trainer has to be fought for Misty, so neither is: from the door up -// column 9 to row 13 (a route there, so the planner's walk to a wall -// doesn't run on past it through (9, 12)), west to (4, 13), and to walls -// round the pool's west and north sides, (4, 10), (12, 10), (12, 7), then -// west to (9, 7), the tile below the platform's east end, out of Diana's -// line. 00.14c steps up onto (9, 6) and talks to Misty from beside her. -// -// Misty beat a Lv20 Wartortle (console B, run m51), so first a GRIND to -// Lv23 on 00.15's patch. Gen 3 numbers (pokefirered: her mons have IV 0; -// Wartortle taken at IV 15, no EVs): Starmie Lv21 has 56 HP, Atk 36, SpA -// 47, SpD 40. Bite is Dark, special in Gen 3, no STAB, x2 on Psychic: at -// Lv23 (SpA 39) it does 23..28, three hits (two on top rolls); at Lv20, -// 20..24. Her Swift (physical, 60) does 9..11 to a Lv23 Wartortle (about -// 67 HP, Def 45) and Water Pulse (STAB, resisted) 8..10: 6 or more hits, -// though m51 saw about 20 a turn. Her Recover (28) and Super Potion undo -// a Bite, so the margin is in Bite's damage. -// -// The Mart comes before the GRIND: its wild battles are fought only with -// 2 or more Potions, and 00.14's save has none (m51 met Misty with only -// the 5 this row bought). 5 Potions (row 3, 300 each), then up to 3 Super -// Potions (row 2, 700), last so they take the Items pocket's last row; -// the battle doesn't use them yet. The money box can't be read, so the -// floor stands for it, and a floor above the money fails the step (the -// quantity box wraps). Prizes (pokefirered: 4 x last level x the class's -// factor) from a new game's 3000, less Viridian's 2000 and the Magikarp's -// 500: Liam 220, Brock 1400, Route 3's bug catchers 360, the Mt. Moon -// grunt 416 and Miguel 288 (the first rival's 80 only if won), at least -// 3184 here. Floor and budget 3000: 5 Potions and 2 Super Potions, 2900. -// Misty's 2100 (4 x 21 x 25) then leaves 00.15 its floor of 1500. Then the -// nurse, and the save before Misty, so her battle is its own checkpoint, -// 00.14c, verified and retried from it. 00.15's GRIND then fights -// until the sim beats the Cerulean rival often enough. -StoryCheckpoint cerulean_gym(){ - const MartPlan supplies{ - .map = std::string(CERULEAN_MART), - .lines = {{.item = "potion", .quantity = 5}, {.item = "super-potion", .quantity = 3}}, - .budget = 3000, - .money_floor = 3000, - }; - const GrindPlan to_lv23{.member = 0, .level = 23, .max_encounters = 100, .pace = WEST, .heal_every = 0}; - return row("00.14b", "Cerulean: Potions, a GRIND to Lv23, then into the Gym, saved below Misty's platform", at(CERULEAN_CENTER, 7, 4, NORTH), after_brock(), StartMenu::FULL, { - running(route("mart_clerk", at(CERULEAN_MART, 4, 3, WEST), "out of the Center to the Mart's clerk")), - mart_step("buy_potions", "5 Potions for the GRIND's wild battles, then Super Potions as the money allows", supplies), - running(route("grind_patch", at(ROUTE4, 86, 16, WEST), "west out of the city along Route 4's lower road onto its grass's east edge")), - grind_step("grind_to_lv23", "wild battles until the lead is Lv23, where Bite takes Starmie in three", to_lv23, at(CERULEAN_CENTER, 7, 4, NORTH)), - running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "back to the Center: Misty's battle starts at full HP and PP")), - heal("heal_cerulean"), - running(route("gym_below_luis", at(CERULEAN_GYM, 9, 13), "into the Gym, up column 9 to row 13, short of Luis's (9, 12)")), - running(legs("gym_west_walkway", {{WEST, 5}}, "west to the wall (4, 13)")), - running(legs("below_misty_platform", {{NORTH, 3}, {EAST, 8}, {NORTH, 3}, {WEST, 3}}, "walls (4, 10), (12, 10), (12, 7), then to (9, 7), out of Diana's line")), - }); -} - -// Misty (TRAINER_LEADER_MISTY: Staryu Lv18, Starmie Lv21), talked to from -// (9, 6), beside her on the platform. Her win text runs on to the CASCADE -// BADGE, TM03 (Water Pulse) and its explanation, all read with the -// battle's. Bite is chosen against her party (Starmie is Water/Psychic). -// Back to the nurse round the pool's west side, out of Luis's line; then -// Water Pulse in place of Tail Whip, last, at the Center, from the bag's -// TM CASE. Ends where 00.15 starts. -StoryCheckpoint misty(){ - const TeachPlan water_pulse{.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}; - return row("00.14c", "Cerulean Gym: Misty, then Water Pulse", at(CERULEAN_GYM, 9, 7, WEST), after_brock(), StartMenu::FULL, { - running(route("beside_misty", at(CERULEAN_GYM, 9, 6, WEST), "up onto (9, 6), facing Misty (8, 6)")), - talk("challenge_misty", "Misty's speech"), - battle("misty", at(CERULEAN_GYM, 9, 6, WEST), false, "Staryu and Starmie, with Bite; CASCADE BADGE and TM03"), - running(legs("gym_way_out", {{SOUTH, 1}, {EAST, 3}, {SOUTH, 3}, {WEST, 8}, {SOUTH, 3}, {EAST, 5}}, "walls (12, 7), (12, 10), (4, 10), (4, 13), (9, 13), round Luis's (9, 12)")), - running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "down column 9 out of the Gym, to the Center")), - heal("heal_cerulean"), - teach_step("teach_water_pulse", "TM03 Water Pulse in place of Tail Whip", water_pulse), - }); -} - -// Before the rival north of Cerulean (cerulean_rival()), from the -// Center: first TM03 Water Pulse over Tail Whip, if the lead doesn't know -// it yet, so the GRIND's sim plays it (a run without TM03 from Misty -// skips the step). Then 3 Potions at the Mart -// (CeruleanCity_Mart_Items: POTION is row 3, 300 each; Mt. Moon's -// trainers leave well over the floor) and 2 Awakenings (row 6, 250 each; -// pokefirered items.json) for the rival's Bulbasaur's Sleep Powder -// (console B, m56: asleep at 34/65 HP, it fainted two turns later with -// 15 Potions), 1400 of the floor's 1500. Then a GRIND on Route 4's grass -// east of Mt. Moon (75..86, 11..17; Spearow, Rattata, Ekans and Mankey -// around Lv10, about 80 EXP each), healing at the Center, until the -// battle sim beats the rival 00.15b fights 50% or more: the win chance -// his battle refuses below. Console B's Wartortle (Lv22, 65 HP, Water -// Pulse) is about 42% there and 62% at Lv23; Lv28 (about 88%, some 120 -// battles from Lv22) is the cap. Then the nurse, and the save on (23, 7), -// the tile below his trigger: his battle is its own checkpoint, 00.15b, -// verified and retried from this save. -StoryCheckpoint cerulean_grind(){ - const TeachPlan water_pulse{.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}; - const MartPlan potions{ - .map = std::string(CERULEAN_MART), - .lines = {{.item = "potion", .quantity = 3}, {.item = "awakening", .quantity = 2}}, - .budget = 1500, - .money_floor = 1500, - }; - const GrindPlan for_rival{ - .member = 0, .level = 28, .max_encounters = 150, .pace = WEST, .heal_every = 0, - .trainer = std::string(story_trainer(CERULEAN, "rival_cerulean").value_or("")), .min_chance = MIN_WIN_CHANCE, - }; - return row("00.15", "Cerulean: Water Pulse, Potions, a GRIND until the rival is winnable, then saved below his trigger", at(CERULEAN_CENTER, 7, 4, NORTH), after_brock(), StartMenu::FULL, { - teach_step("teach_water_pulse", "TM03 Water Pulse in place of Tail Whip, unless the lead knows it or there is no TM03", water_pulse), - running(route("mart_clerk", at(CERULEAN_MART, 4, 3, WEST), "out of the Center to the Mart's clerk")), - mart_step("buy_potions", "3 Potions: the GRIND fights wild battles only with 2 or more; 2 Awakenings for the rival's Sleep Powder", potions), - running(route("grind_patch", at(ROUTE4, 86, 16, WEST), "west out of the city along Route 4's lower road onto its grass's east edge")), - grind_step("grind_for_rival", "wild battles until the sim beats the rival 50% or more, Lv28 at most; the nurse when hurt or low on PP", for_rival, at(CERULEAN_CENTER, 7, 4, NORTH)), - running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "back to the Center: the rival's battle starts at full HP and PP")), - heal("heal_cerulean"), - running(route("below_rival_trigger", at(CERULEAN, 23, 7, NORTH), "out of the Center, north up to (23, 7), short of the trigger row 6")), - }); -} - -// The rival north of Cerulean (CeruleanCity scripts.inc): the only way -// north to Nugget Bridge is columns 22..24, and a step onto row 6 there -// (CeruleanCity_EventScript_RivalTrigger*, VAR_MAP_SCENE_CERULEAN_CITY_RIVAL -// 0) brings him down to the player. From the middle, (23, 6), he stops -// at (23, 5); after the battle he walks round the player and off south, -// and the player, turning to watch him, ends facing south. His FAME -// CHECKER's text is read to the overworld with the battle's. For a player -// who took Squirtle he has Pidgeotto Lv17, Abra Lv16, Rattata Lv15 and -// Bulbasaur Lv18 (sParty_RivalCeruleanBulbasaur), whose Vine Whip and -// Sleep Powder are the danger. The row starts from 00.15's save below the -// trigger, and saves after him. First TM03 Water Pulse over Tail Whip (from -// the bag, where the player stands), if the lead doesn't know it yet: -// console B's save (2026-11-03) is past Misty's TEACH, which failed there. -// Where she taught it, the step reads the moves and does nothing. -StoryCheckpoint cerulean_rival(){ - const TeachPlan water_pulse{.item = "tm03", .move = "water-pulse", .member = 0, .forget_move = "tail-whip"}; - return row("00.15b", "Cerulean: Water Pulse if not known, then the rival north of the city", at(CERULEAN, 23, 7, NORTH), after_brock(), StartMenu::FULL, { - teach_step("teach_water_pulse", "TM03 Water Pulse in place of Tail Whip, unless the lead knows it", water_pulse), - step_into("rival_trigger", NORTH, "onto (23, 6), the middle trigger: \"Yo! !\""), - battle("rival_cerulean", at(CERULEAN, 23, 6, SOUTH), false, "Pidgeotto, Abra, Rattata and Bulbasaur; then the FAME CHECKER"), - }); -} - -// Nugget Bridge (Route24 map.json) is x 10..12 from row 32 north to row -// 16, the city's columns 22..24 (offset 12). Its five trainers stand on -// it facing across, sight 2, so each line crosses the middle column 11 -// on the trainer's row: Bug Catcher Cale (12, 31), Lass Ali (10, 28), -// Youngster Timmy (12, 25), Lass Reli (10, 22) and Camper Ethan (12, 19). -// Each is fought on the step onto their row, beside them: they don't -// walk, and the player keeps facing north. Two tiles separate the rows, -// walked as one short leg; the step onto a row goes on a tile at a time -// until the trainer sees the player (into_line()), as the open leg onto -// the bridge ended a tile short twice on console B (2026-11-03), on -// (11, 33), and one step left the player out of Cale's sight. Then the -// Rocket (12, 15): the step onto (11, 15) -// (Route24_EventScript_RocketTriggerRight, VAR_MAP_SCENE_ROUTE24 0) gives -// the NUGGET, "join Team Rocket", and his battle; he only turns, and the -// player turns east to him. Camper Shane (5, 21) looks north from the -// west bank, off the way. -StoryCheckpoint nugget_bridge(){ - return row("00.16", "Nugget Bridge: the nurse, five trainers and the Rocket", at(CERULEAN, 23, 6, SOUTH), after_brock(), StartMenu::FULL, { - running(route("cerulean_nurse", at(CERULEAN_CENTER, 7, 4, NORTH), "back to the Center after the rival, before Nugget Bridge")), - heal("heal_cerulean"), - running(route("below_cale_line", at(ROUTE24, 11, 32, NORTH), "out of the Center, north past the rival's row onto the bridge, below Cale's row")), - into_line("cale_line", NORTH, "onto (11, 31), beside Cale"), - battle("bug_catcher_cale", at(ROUTE24, 11, 31, NORTH), false, "his Bug Pokemon"), - running(legs("below_ali_line", {{NORTH, 2}}, "up to (11, 29)")), - into_line("ali_line", NORTH, "onto (11, 28), beside Ali"), - battle("lass_ali", at(ROUTE24, 11, 28, NORTH), false, "her Pokemon"), - running(legs("below_timmy_line", {{NORTH, 2}}, "up to (11, 26)")), - into_line("timmy_line", NORTH, "onto (11, 25), beside Timmy"), - battle("youngster_timmy", at(ROUTE24, 11, 25, NORTH), false, "his Pokemon"), - running(legs("below_reli_line", {{NORTH, 2}}, "up to (11, 23)")), - into_line("reli_line", NORTH, "onto (11, 22), beside Reli"), - battle("lass_reli", at(ROUTE24, 11, 22, NORTH), false, "her Pokemon"), - running(legs("below_ethan_line", {{NORTH, 2}}, "up to (11, 20)")), - into_line("ethan_line", NORTH, "onto (11, 19), beside Ethan"), - battle("camper_ethan", at(ROUTE24, 11, 19, NORTH), false, "his Pokemon"), - // A route, not legs: the nurse may have been needed. - ready("ready_for_rocket", at(CERULEAN_CENTER, 7, 4, NORTH), "items for a status or low HP; the nurse only if they can't"), - running(route("below_rocket_trigger", at(ROUTE24, 11, 16, NORTH), "up the bridge to below the Rocket's trigger (11, 15)")), - step_into("rocket_trigger", NORTH, "onto (11, 15), beside the Rocket"), - battle("rocket_grunt", at(ROUTE24, 11, 15, EAST), false, "the NUGGET, then Ekans and Zubat, Lv15"), - }); -} - - -std::vector cpp_rows(){ - return { - new_game(), after_sid_helper(), leave_house(), oaks_trigger(), to_starter_ball(), starter(), parcel(), pokedex(), shopping(), forest(), brock(), - running_shoes(), route3(), magikarp_salesman(), after_gift_rng(), magikarp_to_box(), mt_moon(), - route4_to_cerulean(), cerulean_gym(), misty(), cerulean_grind(), cerulean_rival(), nugget_bridge(), - }; -} - -// Why `loaded` differs from `row`, or empty. Steps compare as their -// shared JSON, which writes every field. -std::string checkpoint_difference(const StoryCheckpoint& row, const StoryCheckpoint& loaded){ - const std::string row_json = Pokemon::story_checkpoint_json(row).dump(); - const std::string loaded_json = Pokemon::story_checkpoint_json(loaded).dump(); - if (row_json != loaded_json){ - return std::format("{}: the file loads to\n{}\nbut the C++ row is\n{}", row.id, loaded_json, row_json); - } - if (row.handoff != loaded.handoff || row.live_start != loaded.live_start){ - return row.id + ": a different handoff or live start."; - } - for (size_t c = 0; c < row.steps.size() && c < loaded.steps.size(); c++){ - if (row.steps[c].once_per_save != loaded.steps[c].once_per_save){ - return row.id + "/" + row.steps[c].name + ": a different once_per_save."; - } - } - if (row.menu != loaded.menu){ - return row.id + ": a different START menu."; - } - const Supplies& a = row.supplies; - const Supplies& b = loaded.supplies; - if (a.potions != b.potions || a.antidotes != b.antidotes || a.parlyz_heals != b.parlyz_heals){ - return row.id + ": different supplies."; - } - if (a.lead.species != b.lead.species || a.lead.level != b.lead.level || a.lead.moves.size() != b.lead.moves.size()){ - return row.id + ": a different lead."; - } - for (size_t c = 0; c < a.lead.moves.size(); c++){ - if (a.lead.moves[c].move != b.lead.moves[c].move || a.lead.moves[c].pp != b.lead.moves[c].pp){ - return row.id + ": a different lead move " + std::to_string(c + 1) + "."; - } - } - return ""; -} - -class Test_AutoStoryTableParity : public UnitTest{ -public: - Test_AutoStoryTableParity() - : UnitTest("PokemonFRLG::AutoStory - the story files load to the C++ rows") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - try{ - const std::vector rows = cpp_rows(); - const std::vector& loaded = story_checkpoints(); - if (rows.size() != loaded.size()){ - return std::format("{} C++ rows, {} files.", rows.size(), loaded.size()); - } - for (size_t c = 0; c < rows.size(); c++){ - const std::string difference = checkpoint_difference(rows[c], loaded[c]); - if (!difference.empty()){ - return difference; - } - } - return true; - }catch (Exception& e){ - return std::string(e.name()) + ": " + e.message(); - } - } -}; - -} // namespace - - -void add_tests_AutoStoryTableParity(UnitTestDatabase& database){ - database.add(); -} - - - -} // 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 bab531a963..4026d032b6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -990,7 +990,6 @@ const AutoStoryTestCase AUTO_STORY_CASES[] = { void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_AutoStoryRunPlan(database); - add_tests_AutoStoryTableParity(database); for (const auto& scenario : AUTO_STORY_CASES){ database.add(scenario); } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index f8e8216b7f..b0e515e80c 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1985,7 +1985,6 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach_Tests.cpp From e2de582291df24fa405af111fee5849017d772b8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 00:29:15 -0800 Subject: [PATCH 6/6] FRLG AutoStory tests: DeclaredPose starts through grid_pose_of() Co-Authored-By: Claude Opus 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 816be5a9c2..349b0605db 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -666,7 +666,7 @@ UnitTestResult check_trigger(const TriggerCase& c){ return "No checkpoint " + c.checkpoint + "."; } const MapPosition onto{c.map, {c.onto_x, c.y}}; - StoryPose pose = one_tile(*checkpoint->start); + StoryPose pose = one_tile(Pokemon::grid_pose_of(*checkpoint->start)); for (const StoryStep& step : checkpoint->steps){ const std::string where = c.checkpoint + "/" + step.name + ": "; if (step.name == c.step && step.kind == StoryStepKind::STEP && onto == MapPosition{pose.map, pose.tile.next(Pokemon::story_arg(step.args, "direction"))}){ @@ -715,7 +715,7 @@ UnitTestResult test_nugget_bridge_order(){ } const std::vector& steps = checkpoint->steps; std::string met; - StoryPose pose = one_tile(*checkpoint->start); + StoryPose pose = one_tile(Pokemon::grid_pose_of(*checkpoint->start)); for (size_t c = 0; c < steps.size(); c++){ const MapData* map = find_map_named(pose.map); const MapObject* trainer = steps[c].kind == StoryStepKind::STEP && map ? trainer_seeing(*map, step_end(pose, steps[c], {}), {}) : nullptr;