diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp index 339f9c1729..cb57749b33 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp @@ -54,6 +54,23 @@ constexpr std::string_view MAP_NAMES[] = { "CeruleanCity_Gym", "Route25", "Route25_SeaCottage", + // The burgled house, the way south out of Cerulean; Route 5, the + // Underground Path and Route 6 to Vermilion City, and the S.S. + // Anne's way to the Captain. + "CeruleanCity_House2", + "Route5", + "UndergroundPath_NorthEntrance", + "UndergroundPath_NorthSouthTunnel", + "UndergroundPath_SouthEntrance", + "Route6", + "VermilionCity", + "VermilionCity_PokemonCenter_1F", + "SSAnne_Exterior", + "SSAnne_1F_Corridor", + "SSAnne_2F_Corridor", + "SSAnne_CaptainsOffice", + // Vermilion Gym, past the tree Cut fells. + "VermilionCity_Gym", "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 b73ca440dd..5f0b05d189 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h @@ -6,8 +6,10 @@ * new game in Pallet Town through Viridian City, Route 2 and Viridian * 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. + * Bridge) and Route 25 to Bill's Sea Cottage; the burgled house, Route 5, + * the Underground Path and Route 6 to Vermilion City and its Pokemon + * Center, and the S.S. Anne's corridors to the Captain's office; and the + * three floors of Cerulean Cave, where Mewtwo waits on B1F. * * Each map is a pinned PokemonSimulation JSON resource, prepared under * Packages/Resources/Pokemon/Maps/frlg 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 571656588f..07970fdc8b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include #include @@ -362,6 +363,107 @@ UnitTestResult test_cerulean_maps(){ return true; } +// Cerulean's burgled house, Route 5, the Underground Path, Route 6, +// Vermilion City and the S.S. Anne load and join: from Cerulean's Pokemon +// Center a route plans through the house, its back yard and the +// Underground Path to Vermilion's nurse, and from there onto +// the ship and up to the Captain. The rival a new game hides +// (FLAG_HIDE_SS_ANNE_RIVAL, flag set "new_game") stands on the Captain's +// door until then: with him there, no route reaches the Captain. With +// Surf's cost below 0, no route surfs. +UnitTestResult test_vermilion_maps(){ + const std::vector all = overworld_maps(); + for (std::string_view name : { + "CeruleanCity_House2", "Route5", "UndergroundPath_NorthEntrance", "UndergroundPath_NorthSouthTunnel", "UndergroundPath_SouthEntrance", + "Route6", "VermilionCity", "VermilionCity_PokemonCenter_1F", + "SSAnne_Exterior", "SSAnne_1F_Corridor", "SSAnne_2F_Corridor", "SSAnne_CaptainsOffice", + }){ + if (built_in(all, std::string(name)) == nullptr){ + return std::format("Missing map {}.", name); + } + } + const std::set new_game = map_flag_set(all, "new_game"); + if (new_game.count("FLAG_HIDE_SS_ANNE_RIVAL") == 0){ + return "Expected FLAG_HIDE_SS_ANNE_RIVAL in flag set new_game."; + } + const std::vector maps = overworld_maps(new_game); + const MapPosition nurse{"VermilionCity_PokemonCenter_1F", map_point(maps, "VermilionCity_PokemonCenter_1F", "nurse_front")}; + if (nurse.point != TilePos{7, 4}){ + return "Unexpected nurse_front in Vermilion's Pokemon Center."; + } + if (!plans_from_cerulean_nurse(maps, RouteGoal{nurse, Direction::NORTH})){ + return "No route from Cerulean's Pokemon Center through the burgled house and the Underground Path to Vermilion's."; + } + const RouteGoal captain{MapPosition{"SSAnne_CaptainsOffice", {5, 5}}, Direction::NORTH}; + RouteCosts walking = default_route_costs(); + walking[RouteCost::SURF] = -1; + const std::optional> aboard = plan_overworld_route(maps, nurse, captain, walking, Direction::NORTH); + if (!aboard){ + return "No route from Vermilion's Pokemon Center onto the S.S. Anne to the Captain."; + } + // The harbor's water (20..23, 23..27) is the shorter way south; a + // player without Surf walks round it. + for (const RouteStep& step : *aboard){ + if (step.action == RouteAction::SURF){ + return "Expected the way aboard on land, not " + to_string(step) + "."; + } + } + if (plan_overworld_route(all, nurse, captain, default_route_costs(), Direction::NORTH)){ + return "Expected the rival on the Captain's door to block the way while shown."; + } + return true; +} + +// Vermilion Gym loads and joins the city by its door (14, 25), behind the +// tree (19, 24), an object Cut removes: from the Center no route on land +// reaches the gym, from the tree's tile one does. The beams on rows 6 and +// 7 are written off (OPENED_TILES), so a route reaches Lt. Surge (5, 2); +// the cans on rows 10, 12 and 14 are walls. Dwayne (8, 13) and Baily +// (2, 11) look every way, sight 3; Tucker (7, 8) west. +UnitTestResult test_vermilion_gym_map(){ + const std::vector maps = overworld_maps(map_flag_set(overworld_maps(), "new_game")); + const MapData* gym = built_in(maps, "VermilionCity_Gym"); + if (gym == nullptr){ + return "Missing map VermilionCity_Gym."; + } + RouteCosts walking = default_route_costs(); + walking[RouteCost::SURF] = -1; + const MapPosition nurse{"VermilionCity_PokemonCenter_1F", {7, 4}}; + const RouteGoal door{MapPosition{"VermilionCity_Gym", {5, 18}}, std::nullopt}; + if (plan_overworld_route(maps, nurse, door, walking, Direction::NORTH)){ + return "Expected the tree (19, 24) to shut the gym off from the Center."; + } + if (!plan_overworld_route(maps, MapPosition{"VermilionCity", {19, 24}}, door, walking, Direction::SOUTH)){ + return "No route from the tree's tile into the gym."; + } + if (!plan_overworld_route(maps, MapPosition{"VermilionCity_Gym", {5, 8}}, RouteGoal{MapPosition{"VermilionCity_Gym", {5, 3}}, Direction::NORTH}, walking, Direction::NORTH)){ + return "Expected a route through the beams, off, to Lt. Surge."; + } + for (int can : {1, 3, 5, 7, 9}){ + for (int row : {10, 12, 14}){ + if (tile_at(*gym, TilePos{can, row}) != TileKind::WALL){ + return std::format("Expected a can at ({}, {}).", can, row); + } + } + } + struct Seen{ + std::string_view name; + TilePos tile; + bool seen; + }; + for (const Seen& check : std::initializer_list{ + {"sailor", {8, 15}, true}, {"sailor", {7, 15}, false}, {"sailor", {5, 13}, true}, {"sailor", {4, 13}, false}, + {"balding_man", {2, 13}, true}, {"balding_man", {3, 13}, false}, {"balding_man", {5, 11}, true}, {"balding_man", {6, 11}, false}, + {"gentleman", {4, 8}, true}, {"gentleman", {5, 9}, false}, {"gentleman", {8, 8}, false}, + }){ + const auto object = std::find_if(gym->objects.begin(), gym->objects.end(), [&](const MapObject& o){ return o.name == check.name; }); + if (object == gym->objects.end() || trainer_may_see(*gym, *object, check.tile) != check.seen){ + return std::format("{} {} ({}, {}).", check.name, check.seen ? "should see" : "shouldn't see", check.tile.x, check.tile.y); + } + } + 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(){ @@ -619,6 +721,14 @@ const OverworldMapsTestCase OVERWORLD_MAPS_CASES[] = { .input = {.name = "Cerulean's Mart and Gym, Route 25 and Bill's Sea Cottage", .body = test_cerulean_maps}, .expectation = {.description = "validates Cerulean City, Gym, Mart, Route 25 and Sea Cottage map data"}, }, + { + .input = {.name = "Route 5 and 6 to Vermilion City and the S.S. Anne", .body = test_vermilion_maps}, + .expectation = {.description = "validates Route 5, Route 6, Vermilion City and S.S. Anne maps"}, + }, + { + .input = {.name = "Vermilion Gym: behind the tree, beams, cans and trainers' sight", .body = test_vermilion_gym_map}, + .expectation = {.description = "validates Vermilion Gym layout, electric fences and trainer sightlines"}, + }, }; } // namespace diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp index 1816a97ff6..62e20d0528 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp @@ -285,6 +285,30 @@ WalkedTiles walked_near(const RouteStep& step, int estimate, Milliseconds tile_t }; } +std::vector with_warp_slack(std::vector route){ + const auto same_axis = [](Direction a, Direction b){ return (int)a % 2 == (int)b % 2; }; + std::optional further; + for (RouteStep& step : route){ + if (step.action != RouteAction::WALK){ + continue; + } + if (step.warps){ + if (further && step.direction != *further && same_axis(step.direction, *further)){ + step.warp_slack = 1; + } + further.reset(); + continue; + } + if (step.to_wall && further && same_axis(step.direction, *further)){ + further.reset(); + } + if (!step.to_wall && !step.connection_steps.empty()){ + further = step.direction; + } + } + return route; +} + WalkedTiles whole_leg(const RouteStep& step){ return WalkedTiles{.min = 0, .max = step.tiles}; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp index 1785b5687e..2c892018fe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp @@ -211,7 +211,7 @@ class RouteRun{ , m_calls(calls) , m_lines(calls, planning) , m_steps(calls, planning != nullptr ? planning->wall_check : WallCheck::TAP) - , m_plan(route) + , m_plan(with_warp_slack(route)) , m_at(planning != nullptr ? planning->start : std::nullopt) , m_facing(facing) {} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index bd24190fa1..b6953fedbe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -32,7 +32,7 @@ namespace{ Pokemon::LegSpec leg_spec(const RouteStep& step, MoveSpeed speed){ Pokemon::LegSpec leg; leg.direction = step.direction; - leg.tiles = step.tiles; + leg.tiles = step.tiles + step.warp_slack; leg.to_wall = step.to_wall; leg.tile_time = tile_time(step, speed); leg.stop_on_interrupt = !step.to_wall; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp index 7db845203a..2716f9a4a7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp @@ -288,7 +288,7 @@ class StepModel{ std::optional> press(const State& state, Direction direction) const{ const std::optional transition = PokemonFRLG::press(m_maps, state, direction); - if (!transition){ + if (!transition || (transition->action == RouteAction::SURF && route_cost(m_costs, RouteCost::SURF) < 0)){ return std::nullopt; } Pokemon::Step step; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteCosts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteCosts.h index 8d4c82b1fc..5db52ae8bb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteCosts.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteCosts.h @@ -27,7 +27,7 @@ enum class RouteCost{ TILE, TURN, // extra for a leg in a new direction WARP, // the fade in and out - SURF, // the dialog and the animation + SURF, // the dialog and the animation; below 0, never GRASS_TILE, // extra for tall grass, where wild Pokemon appear // Extra for a leg that ends where the player could keep walking: it has // to be timed, and if a message or a battle stops it part-way, where diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h index 4854922ced..1e37c0d1a5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h @@ -65,6 +65,12 @@ struct RouteStep{ // by the tiles alone ended a tile short (console B, 2026-11-03, rows // 00.14, 00.16 and 00.20). std::vector connection_steps = {}; + // WALK onto a warp: how many tiles further the player may stand from + // it than planned, which the hold goes on for, stopping at the fade. + // An open leg over a map connection before it may end a tile further + // on, when the game doesn't hold the player up there (console B, + // 2026-11-03, row 00.24). Set by with_warp_slack() when a route runs. + int warp_slack = 0; // Which way the player faces after the step. Arriving at a door or a // cave mouth, the game walks the player a tile out, facing south. Direction facing_after = Direction::NORTH; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index ff581caf21..078f718233 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -53,6 +53,8 @@ constexpr Milliseconds TAP_TIME(340); constexpr Milliseconds NO_BATTLE_WAIT(15000); constexpr Milliseconds BATTLE_TIME(10000); constexpr Milliseconds MESSAGE_CLOSE(1000); +// The questions, " used CUT!" and the tree falling. +constexpr Milliseconds CUT_TIME(4000); // Rows of black below a small room, seen from this near its bottom. constexpr int BLACK_BELOW_ROWS = 5; constexpr int SMALL_ROOM_ROWS = 20; @@ -301,6 +303,10 @@ bool OverworldSim::after_step(const Step& step, Milliseconds pressed){ update_view(); if (step.warped){ m_state.warps++; + for (auto& [index, tree] : m_cut_trees){ + m_maps[index].objects.push_back(tree); + } + m_cut_trees.clear(); m_frozen = true; schedule(pressed + timing.tile, SimScreen::FADE, false); schedule(pressed + timing.tile + timing.fade, SimScreen::OVERWORLD, true); @@ -371,7 +377,7 @@ void OverworldSim::walk_hold(Direction direction, Milliseconds duration, int sho bump(direction, pressed); return; } - if (step->map != m_map && !step->warped){ + if (m_script.connections_stall && step->map != m_map && !step->warped){ // The step onto a connected map waits a tile while the game // loads it: a hold timed by its tiles alone ended a tile short // (console B, 2026-11-03, rows 00.14, 00.16 and 00.20). @@ -478,6 +484,24 @@ bool OverworldSim::close_message(){ return true; } +bool OverworldSim::cut_tree(){ + std::vector& objects = m_maps[m_map].objects; + const TilePos ahead = m_player.position.next(m_state.facing); + for (size_t c = 0; c < objects.size(); c++){ + if (objects[c].name == "cut_tree" && objects[c].x == ahead.x && objects[c].y == ahead.y + && m_state.screen == SimScreen::OVERWORLD && !m_frozen + ){ + m_cut_trees.emplace_back(m_map, objects[c]); + objects.erase(objects.begin() + c); + advance_to(m_now + CUT_TIME); + note("cut the tree on " + to_string(MapPosition{map().name, ahead}) + "."); + return true; + } + } + violation("no tree to cut " + std::string(direction_name(m_state.facing)) + " of " + to_string(m_state.position) + "."); + return false; +} + // @@ -614,7 +638,7 @@ std::optional OverworldSimWalker::walk_step(const RouteStep& step, const std::vector& ints = interrupts(step); Pokemon::LegSpec leg; leg.direction = step.direction; - leg.tiles = step.tiles; + leg.tiles = step.tiles + step.warp_slack; leg.to_wall = step.to_wall; leg.tile_time = TILE_TIME; leg.stop_on_interrupt = !step.to_wall; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 65c4180b88..3fb3cb5c4e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include "Common/Cpp/Time.h" @@ -78,6 +79,11 @@ class OverworldSim{ // battle follows it. bool close_message(); + // Cuts the tree the player faces (an object named "cut_tree") with + // YES to the game's question: it is gone until the player next warps, + // as its hide flag is a FLAG_TEMP. Returns whether there was one. + bool cut_tree(); + private: // A screen that shows at `at`; `unfreeze`: the player can move again. struct Pending{ @@ -128,6 +134,8 @@ class OverworldSim{ std::optional m_trainer_speaking; // The trainer whose battle is on screen or about to show. std::optional m_trainer; + // The trees cut since the last warp, and their maps. + std::vector> m_cut_trees; int m_grass_steps = 0; int m_holds = 0; SimState m_state; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h index 38f8f2f7c7..cf254da5e7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h @@ -36,6 +36,11 @@ struct SimScript{ // don't mark as grass: Mt. Moon B2F's tiles closed on one side ('8') // are cave floor too (console B, 2026-11-03). std::set wild_floor_maps; + // Whether the game holds the player up a tile on a step onto a + // connected map. It did north onto Nugget Bridge (console B, + // 2026-11-03, rows 00.16 and 00.20), not south from Route 6 into + // Vermilion City (row 00.24). + bool connections_stall = true; SimTiming timing; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index c129f8367b..9a1ecbf4f8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -929,6 +929,25 @@ UnitTestResult test_nugget_bridge_legs(){ +// Story row 00.24 from Route 6 to Vermilion City's nurse: the open leg +// south 14 crosses onto Vermilion City and is held a tile longer for the +// game holding the player up there. It didn't: the player ended a tile +// south of (23, 7), the leg west on (15, 8), and the north 1 onto the +// Center's door only reached the tile below it: "no fade in and out" +// (console B, 2026-11-03). Either way the door is reached. +UnitTestResult test_route6_to_vermilion_center(){ + const MapPosition nurse = at("VermilionCity_PokemonCenter_1F", 7, 4); + for (const bool stalls : {true, false}){ + SimCase c{.start = at("Route6", 11, 33), .facing = Direction::EAST, .goal = nurse}; + c.script.connections_stall = stalls; + const SimRun now = run_case(c); + if (!arrived(now, c.goal) || now.state.warps != 1){ + return std::format("Expected the nurse reached by the Center's door, the crossing {}:", stalls ? "stalled" : "not stalled") + describe(now); + } + } + return true; +} + const OverworldSimCase OVERWORLD_SIM_CASES[] = { {.input = {"the forest's north gate: no fade or black read as a battle", test_forest_north_gate}, .expectation = {},}, {.input = {"a battle on a leg onto a warp", test_battle_on_warp_leg}, .expectation = {},}, @@ -955,7 +974,8 @@ const OverworldSimCase OVERWORLD_SIM_CASES[] = { {.input = {"Cerulean Gym: to Misty and back round the pool, no trainer met", test_cerulean_gym_walks}, .expectation = {},}, {.input = {"Cerulean Gym: the straight ways meet Luis and Diana", test_cerulean_gym_lines}, .expectation = {},}, {.input = {"Cerulean: the Center to the rival's row and Nugget Bridge", test_cerulean_to_bridge}, .expectation = {},}, - {.input = {"Nugget Bridge: each trainer met on the step onto their row", test_nugget_bridge_legs}, .expectation = {},},}; + {.input = {"Nugget Bridge: each trainer met on the step onto their row", test_nugget_bridge_legs}, .expectation = {},}, {.input = {"Route 6 into Vermilion's Pokemon Center, the crossing stalled or not", test_route6_to_vermilion_center}, .expectation = {}}, +}; void add_tests_OverworldSim(UnitTestDatabase& database){ for (const auto& item : OVERWORLD_SIM_CASES){ @@ -967,4 +987,4 @@ void add_tests_OverworldSim(UnitTestDatabase& database){ } // namespace PokemonFRLG } // namespace NintendoSwitch -} // namespace PokemonAutomation +} // namespace PokemonAutomation \ No newline at end of file diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp index 5396410f6d..5667b5729c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -147,7 +147,7 @@ class RepelWoreOffInterrupt : public MessageInterrupt{ Pokemon::LegSpec leg_spec(const RouteStep& step, MoveSpeed speed){ - Pokemon::LegSpec leg{step.direction, step.tiles, step.to_wall, tile_time(step, speed)}; + Pokemon::LegSpec leg{step.direction, step.tiles + step.warp_slack, step.to_wall, tile_time(step, speed)}; leg.stalled_steps = step.connection_steps; return leg; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h index 55c0f31082..ee0f773896 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h @@ -38,6 +38,15 @@ constexpr Milliseconds STOP_TIMING_SLACK(300); // (Pokemon::LegResult::tiles), give or take STOP_TIMING_SLACK at // `tile_time` a tile: a tile either side walking, two running. WalkedTiles walked_near(const RouteStep& step, int estimate, Milliseconds tile_time); +// `route` with RouteStep::warp_slack set. An open leg over a map +// connection is held a tile longer for the game holding the player up +// there, which it doesn't always do: south from Route 6 into Vermilion +// City it didn't, the player ended a tile further south, and the north 1 +// onto the Pokemon Center's door stopped below it (console B, 2026-11-03, +// row 00.24). Until a leg to a wall that way or a warp places the player +// again, they may stand a tile further on; a warp walked back that way is +// held a tile further for it. +std::vector with_warp_slack(std::vector route); // Anywhere on `step`, for a stop the timing doesn't place. WalkedTiles whole_leg(const RouteStep& step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 4205eae4c5..db97b4c44e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -54,6 +54,7 @@ #include "Programs/AutoStory/PokemonFRLG_AutoStoryAbilities.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.h" #include "Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.h" #include "Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h" @@ -95,6 +96,12 @@ static void add_tests_RngPlanning(UnitTestDatabase& database){ add_tests_GiftRngAttempts(database); } +// The story's rows on the overworld sim, a file of tests per stage. +static void add_tests_AutoStoryRows(UnitTestDatabase& database){ + add_tests_AutoStoryVermilion(database); + add_tests_AutoStoryVermilionGym(database); +} + void add_tests(UnitTestDatabase& database){ add_tests_AdvanceWhiteDialogDetector(database); add_tests_AdvanceBattleDialogDetector(database); @@ -136,6 +143,8 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory(database); add_tests_AutoStoryExport(database); add_tests_AutoStorySimulation(database); + add_tests_AutoStoryRows(database); + add_tests_AutoStoryTrashCans(database); add_tests_AutoStoryPaceSim(database); add_tests_AutoStoryItems(database); add_tests_AutoStoryRngLoop(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 79320faca4..dc73028a37 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -555,6 +555,30 @@ void answer_yes_no(ConsoleHandle& console, ProControllerContext& context, bool y ); } +std::optional talk_and_count_pages(ConsoleHandle& console, ProControllerContext& context){ + WhiteDialogWatcher opened(COLOR_RED); + const int shown = run_until( + console, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 160ms, 3000ms); + }, + {opened} + ); + if (shown < 0){ + return std::nullopt; + } + // Fast text prints a page in well under a second; an A before it + // ends would only finish it. + pbf_wait(context, 1500ms); + pbf_press_button(context, BUTTON_A, 160ms, 1200ms); + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + const size_t pages = screen && WhiteDialogDetector(COLOR_RED).detect(screen) ? 2 : 1; + console.log(std::format("Message: {} page(s).", pages)); + mash_until_overworld(console, context, std::chrono::seconds(20)); + return pages; +} + void step_once(ProControllerContext& context, Direction direction, std::optional facing){ if (facing != direction){ pbf_press_dpad(context, dpad(direction), TURN_TAP, TURN_SETTLE); @@ -576,7 +600,7 @@ std::optional step_until_seen(int max_tiles, const std::function& s std::optional step_into_line( ConsoleHandle& console, ProControllerContext& context, - Direction direction, std::optional facing, int max_tiles + Direction direction, std::optional facing, int max_tiles, Milliseconds watch ){ return step_until_seen( max_tiles, @@ -587,7 +611,7 @@ std::optional step_into_line( [&]{ WhiteDialogWatcher message(COLOR_RED); BattleScreenWatcher battle(COLOR_RED); - return wait_until(console, context, TRAINER_LINE_WATCH, {message, battle}) >= 0; + return wait_until(console, context, watch, {message, battle}) >= 0; } ); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index 9d7cd325a1..6f13a835e9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -106,7 +106,7 @@ BattleScreen read_battle_screen(const ImageViewRGB32& screen, bool confirmed){ if (BattleMenuDetector(COLOR_RED).detect(screen)){ return BattleScreen::MENU; } - if (BattleLearnDialogDetector(COLOR_RED).detect(screen)){ + if (battle_yes_no_shows(screen)){ return BattleScreen::LEARN; } if (!confirmed && !BattleScreenDetector(COLOR_RED).detect(screen)){ @@ -126,7 +126,7 @@ BattleTextScreen read_text_screen(const ImageViewRGB32& screen){ .text_box = BattleDialogDetector(COLOR_RED).detect(screen), .hp_box = BattleScreenDetector(COLOR_RED).detect(screen), .arrow = AdvanceBattleDialogDetector(COLOR_RED).detect(screen), - .yes_no = BattleLearnDialogDetector(COLOR_RED).detect(screen) || yes_no_cursor(screen).has_value(), + .yes_no = battle_yes_no_shows(screen) || yes_no_cursor(screen).has_value(), }; } @@ -166,8 +166,7 @@ bool bag_row_is( // From the battle menu: `item`, in `row` (from 0) of the Items pocket, on // the starter. The bag opens on the pocket used last; Items is the first. -// Returns whether it was used; if the row holds something else (THOROUGH), -// backs out to the battle menu. Not run on the console yet. +// Returns whether it was used; else (THOROUGH) backs out to the menu. bool use_item( ConsoleHandle& console, ProControllerContext& context, int row, const std::string& item, Pokemon::StoryCheckLevel checks, Language language @@ -206,8 +205,7 @@ void run_away(ProControllerContext& context){ pbf_press_button(context, BUTTON_A, 160ms, 500ms); } -// FIGHT, then the move in `slot` from the top left. The cursor doesn't -// move onto an empty slot. +// FIGHT, then the move in `slot` from the top left; the cursor stays off empty slots. void use_move(ProControllerContext& context, size_t slot){ tap(context, DPAD_LEFT); tap(context, DPAD_UP); @@ -282,12 +280,12 @@ bool forget_move(ConsoleHandle& console, ProControllerContext& context, size_t s return true; } -// The party list in battle opens on the lead: down to `slot`, then A, and -// SHIFT, the top of its menu. TurnResult item_result(bool used){ return used ? TurnResult::DONE : TurnResult::NOT_DONE; } +// The party list in battle opens on the lead: down to `slot`, then A, and +// SHIFT, the top of its menu. void send_member(ProControllerContext& context, size_t slot){ for (size_t c = 0; c < slot; c++){ pbf_press_dpad(context, DPAD_DOWN, 160ms, 400ms); @@ -389,7 +387,7 @@ class BattleLoop{ if (!m_confirmed){ return false; } - if (m_move_chosen && BattleOutOfPpDetector(COLOR_RED).detect(screen)){ + if (m_move_chosen && m_refusal.no_pp_due(now) && BattleOutOfPpDetector(COLOR_RED).detect(screen)){ m_console.log("Battle: no PP left for that move; choosing again.", COLOR_ORANGE); m_decisions.turn_done(TurnChoice::MOVE, TurnResult::NOT_DONE); m_move_chosen = false; @@ -511,9 +509,10 @@ class BattleLoop{ ErrorReportMode::SEND_ERROR_REPORT, "fight_battle(): no battle on screen.", m_console ); } - if (now - m_start > BATTLE_TIMEOUT){ + // Neither the battle nor the overworld for a minute: a stop, not 10 minutes of + and B. + if (now - m_start > BATTLE_TIMEOUT || m_end.overworld_lost(now)){ OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, "fight_battle(): the battle took over 10 minutes.", m_console + ErrorReportMode::SEND_ERROR_REPORT, now - m_start > BATTLE_TIMEOUT ? std::string("fight_battle(): the battle took over 10 minutes.") : std::format("fight_battle(): no battle screen and no START menu for 60 s after the battle (turn {}{}).", m_decisions.turns(), m_decisions.lost() ? ", the lead fainted: the battle is lost" : ""), m_console ); } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h index f0e9c7685a..4d35ab056a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h @@ -25,6 +25,7 @@ #include #include +#include #include #include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp index ad3c1eb405..b28fd5b972 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp @@ -5,6 +5,7 @@ */ #include +#include #include #include #include @@ -38,6 +39,10 @@ constexpr Milliseconds BATTLE_GONE = std::chrono::milliseconds(3000); constexpr Milliseconds OVERWORLD_CHECK = std::chrono::milliseconds(3000); // A and B pressed blind for this long with no battle menu: give up. constexpr Milliseconds BLIND_PRESSES = std::chrono::milliseconds(30000); +// No battle on screen for this long, and START has not opened the menu: +// stop. Longer than a gym leader's speech after the battle and a +// whiteout's walk to the nurse, with B pressed through them. +constexpr Milliseconds NO_OVERWORLD = std::chrono::milliseconds(60000); // Turns a move turned down is left alone: the longest Disable (pret // battle_script_commands.c Cmd_disablelastusedattack, 2 to 5 turns). constexpr int DISABLE_TURNS = 5; @@ -49,6 +54,9 @@ constexpr Milliseconds REFUSED_WITHIN = std::chrono::milliseconds(7000); constexpr size_t LOW_ATTACK_PP = 10; // The move prompts a turn can bring: two moves offered, NO then YES each. constexpr int MOVE_PROMPTS = 4; +// The levels the lead can gain in a battle, for the moves it can be +// offered: a story battle gives one or two. +constexpr uint8_t MAX_LEVELS_IN_BATTLE = 3; // The HP a Potion heals (pret src/data/items.h). constexpr double POTION_HP = 20; @@ -126,11 +134,16 @@ bool nurse_before_battle(const Supplies& supplies){ BattleDecisions::BattleDecisions(Supplies& supplies, BattleKind kind) : m_supplies(supplies) , m_kind(kind) -{} +{ + if (supplies.lead.level > 0){ + m_level_cap = static_cast(std::min(battle_level(supplies.lead) + MAX_LEVELS_IN_BATTLE, 255)); + } +} TurnAction BattleDecisions::turn(const PartyStatus& status){ m_turns++; m_move_prompts = 0; + m_declined_delete = false; m_before_forget.reset(); count_down_refused(); m_last_move_slot.reset(); @@ -243,8 +256,10 @@ void BattleDecisions::turn_done(TurnChoice choice, TurnResult result){ } const bool done = result == TurnResult::DONE; if (!done && choice == TurnChoice::MOVE){ - if (m_last_move_slot){ + if (m_last_move_slot && !m_no_pp_read.insert(*m_last_move_slot).second){ no_pp_left(m_supplies.lead, *m_last_move_slot); + }else{ + move_refused(); } return; } @@ -299,6 +314,10 @@ PromptAnswer BattleDecisions::prompt(bool lead_box_gone){ } PartyMember learning = m_supplies.lead; const LearnDecision decision = learn_move(learning); + if (!decision.move || (m_level_cap && battle_level(learning) > *m_level_cap)){ + // No move the lead can have reached: not a move prompt. + return PromptAnswer{.answer = YesNo::NO}; + } if (decision.forget_slot){ m_before_forget = m_supplies.lead; return PromptAnswer{.answer = YesNo::YES, .forget_slot = decision.forget_slot, .learned = std::move(learning)}; @@ -376,6 +395,10 @@ void MoveRefusalWatch::no_battle_screen(){ m_list_back = m_chosen.has_value(); } +bool MoveRefusalWatch::no_pp_due(WallClock now) const{ + return m_chosen && now - *m_chosen < REFUSED_WITHIN; +} + bool MoveRefusalWatch::refused(WallClock now){ const bool refused = m_chosen && m_list_back && now - *m_chosen < REFUSED_WITHIN; m_chosen.reset(); @@ -390,6 +413,10 @@ bool BattleEndWatch::pressed_blind(WallClock now){ return now - *m_blind_since >= BLIND_PRESSES; } +bool BattleEndWatch::overworld_lost(WallClock now) const{ + return m_last_battle && m_last_check && now - *m_last_battle >= NO_OVERWORLD; +} + } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h index 9d07983f3d..4c70af2530 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h @@ -20,6 +20,7 @@ #define PokemonAutomation_PokemonFRLG_AutoStoryBattleDecisions_H #include +#include #include #include #include @@ -48,11 +49,15 @@ class BattleDecisions{ // A YES/NO in or after the battle. With the lead's box gone and the // opponent's there, it is "Use next POKEMON?"; else the move prompts: - // "Delete a move to make room?", then "Stop learning?" after a NO, or - // after YES and a move list closed with nothing forgotten. Past - // MOVE_PROMPTS since the last turn, a plain YES, which ends them - // either way (console B, 2026-11-03: NO and YES out of step with the - // game went round for 75 s). + // "Delete a move to make room?", then "Stop learning?" after a NO (in + // the same turn), or after YES and a move list closed with nothing + // forgotten. Past MOVE_PROMPTS since the last turn, a plain YES, which + // ends them either way (console B, 2026-11-03: NO and YES out of step + // with the game went round for 75 s). With no move the lead can have + // reached to offer (none left, or one more than MAX_LEVELS_IN_BATTLE + // above its level read before the battle), it is no move prompt, such + // as the trainer's "Will change POKEMON?": NO, and the lead + // is left as it was. PromptAnswer prompt(bool lead_box_gone); // The party list opened with the lead fainted: the slot to send in, @@ -100,6 +105,11 @@ class BattleDecisions{ std::string m_hit_by; // The slots the game turned down, and the turns until they are tried again. std::map m_refused; + // The slots "no PP left" was read for once. + std::set m_no_pp_read; + // The highest level a move offered can be for, from the lead's level + // read before the battle; none if it wasn't read. + std::optional m_level_cap; // The members sent in after the lead fainted. std::set m_sent; }; @@ -158,6 +168,10 @@ class BattleEndWatch{ // BLIND_PRESSES with no battle menu: the loop stops, and the walker, // which finds the player again, goes on. bool pressed_blind(WallClock now); + // True once START has looked for the overworld and no battle has shown + // for NO_OVERWORLD: neither is coming back (console B, 2026-11-03, + // after losing to Lt. Surge: 8 minutes of + and B on a grey screen). + bool overworld_lost(WallClock now) const; private: std::optional m_last_battle; @@ -173,6 +187,10 @@ class BattleEndWatch{ class MoveRefusalWatch{ public: void move_chosen(WallClock now); + // Whether a "no PP left" read at `now` counts: no later than a + // refusal's menu would come (console B, 2026-11-03, m68: one read 37 s + // after the battle's last move, as the battle ended). + bool no_pp_due(WallClock now) const; // No battle screen read while the battle goes on. void no_battle_screen(); // At the battle menu: true if the move chosen before it was turned down. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index febfea600a..9d5365ca01 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -26,6 +26,7 @@ #include "PokemonFRLG_AutoStorySummary.h" #include "PokemonFRLG_AutoStoryTable.h" #include "PokemonFRLG_AutoStoryTeachScreens.h" +#include "PokemonFRLG_AutoStoryTrashCans.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -64,10 +65,7 @@ const Type& arg(const StoryStep& step, std::string_view key){ // A checkpoint's start as the engine's Pose: nothing for a new game. std::optional start_pose(const StoryCheckpoint& checkpoint){ - if (!checkpoint.start){ - return std::nullopt; - } - return Pokemon::pose_of(*checkpoint.start); + return checkpoint.start ? std::optional(Pokemon::pose_of(*checkpoint.start)) : std::nullopt; } const MapData* find_story_map(const std::string& name){ @@ -116,7 +114,9 @@ std::optional route_start(const Pokemon::Pose& pose){ return MapPosition{pose.map, tiles[0]}; } -Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step){ +// `maps`: where the route is planned; the story's but where a step knows +// better (the trash cans' walks, past trainers who have walked up). +Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step, const std::vector& maps = story_maps()){ const std::vector tiles = Pokemon::tiles_of(state.pose); const bool known = state.pose.certainty == Pokemon::PoseCertainty::TILE || (state.pose.certainty == Pokemon::PoseCertainty::SET && tiles.size() > 1); @@ -137,7 +137,7 @@ Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step){ return Pokemon::outcome_failed("bad_target", Pokemon::to_string(target_pose)); } const RouteGoal goal{{target->map, target->tile}, target->facing}; - const std::optional> route = plan_story_route(story_maps(), state.pose, facing, goal); + const std::optional> route = plan_story_route(maps, state.pose, facing, goal); if (!route){ return Pokemon::outcome_failed("no_route", Pokemon::to_string(state.pose) + " to " + to_string(goal.position)); } @@ -148,7 +148,7 @@ Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step){ // Planning lets the walker recover a stopped open leg: it plans back to // the leg's end, then walks the rest as given. From a set of tiles // the start isn't known: the walker reads the facing. - const RoutePlanning planning{.maps = &story_maps(), .costs = default_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; + const RoutePlanning planning{.maps = &maps, .costs = story_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; walk_overworld_route_with_recovery(env.console, env.context, *route, planning, facing, interrupts, move_speed(step)); log_arrival(env, step.name, target->map, target->tile); const std::optional end_facing = route->empty() ? facing : std::optional(route->back().facing_after); @@ -172,7 +172,7 @@ Outcome walk_legs(StoryEnv& env, RunState& state, const StoryStep& step){ const OverworldInterruptSet interrupts = story_interrupts(env.supplies, arg(step, "fight_wild"), env.checks, env.language); // Planning lets the walker recover a stopped open leg: it plans back to // the leg's end, then walks the rest as given. - const RoutePlanning planning{.maps = &story_maps(), .costs = default_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; + const RoutePlanning planning{.maps = &story_maps(), .costs = story_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; walk_overworld_route_with_recovery(env.console, env.context, *route, planning, facing, interrupts, move_speed(step)); log_arrival(env, step.name, route->back().end.map, route->back().end.point); return Pokemon::outcome_ok(to_pose(StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after})); @@ -188,6 +188,10 @@ Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ } env.console.log(std::format("Story: {}: a trainer saw the player after {} tile(s).", step.name, *stepped)); tiles_stepped = *stepped; + }else if (step.action == TRAINER_WAIT_VARIANT){ + if (!step_into_line(env.console, env.context, direction, facing_of(state.pose), 1, TRAINER_WAIT_WATCH)){ + return Pokemon::outcome_failed("no_trainer", std::format("{} s on the tile {}", TRAINER_WAIT_WATCH.count() / 1000, direction_name(direction))); + } }else{ step_once(env.context, direction, facing_of(state.pose)); } @@ -318,8 +322,22 @@ std::optional> viridian_mart_orders(const std::vector& story_maps(){ - static const std::vector maps = overworld_maps(map_flag_set(overworld_maps(), "after_hall_of_fame")); + static const std::vector maps = []{ + const std::vector all = overworld_maps(); + std::set flags = map_flag_set(all, "after_hall_of_fame"); + flags.merge(map_flag_set(all, "new_game")); + return overworld_maps(flags); + }(); return maps; } @@ -352,6 +370,7 @@ std::string save_card_place(const std::string& map){ {"CeruleanCity", "cerulean-city"}, {"Route24", "route-24"}, {"Route25", "route-25"}, + {"VermilionCity", "vermilion-city"}, }; for (const auto& [prefix, place] : PLACES){ if (map == prefix || map.rfind(prefix + "_", 0) == 0){ @@ -463,7 +482,7 @@ std::optional> plan_story_route( if (!holds->empty()){ facing = holds->back().facing_after; } - std::optional> route = plan_overworld_route(maps, from, goal, default_route_costs(), facing); + std::optional> route = plan_overworld_route(maps, from, goal, story_route_costs(), facing); if (route){ route->insert(route->begin(), holds->begin(), holds->end()); } @@ -480,96 +499,6 @@ std::optional wall_beside(const MapData& map, const TilePos& tile){ return std::nullopt; } -namespace{ - -// How the console does an action that needs only the env. -using ConsoleAction = Outcome (*)(StoryEnv& env, RunState& state, const StoryStep& step); - -ConsoleAction console_action_of(StoryActionId id){ - switch (id){ - case StoryActionId::NEW_GAME: - return [](StoryEnv& env, RunState&, const StoryStep&){ - play_new_game_intro(env.console, env.context, env.player_name); - return Pokemon::outcome_ok(); - }; - case StoryActionId::ROUTE: - return [](StoryEnv& env, RunState& state, const StoryStep& step){ return walk_route(env, state, step); }; - case StoryActionId::LEGS: - return walk_legs; - case StoryActionId::STEP: - return take_step; - case StoryActionId::TALK: - return [](StoryEnv& env, RunState&, const StoryStep&){ - pbf_press_button(env.context, BUTTON_A, 160ms, 800ms); - return Pokemon::outcome_ok(); - }; - case StoryActionId::ANSWER: - return [](StoryEnv& env, RunState&, const StoryStep& step){ - answer_yes_no(env.console, env.context, arg(step, "yes"), BUTTON_B, YES_NO_TIMEOUT); - return Pokemon::outcome_ok(); - }; - case StoryActionId::MASH: - return [](StoryEnv& env, RunState&, const StoryStep&){ - mash_until_overworld(env.console, env.context, SCENE_TIMEOUT); - return Pokemon::outcome_ok(); - }; - case StoryActionId::BATTLE: - return [](StoryEnv& env, RunState&, const StoryStep& step){ return battle(env, step); }; - case StoryActionId::HEAL: - return [](StoryEnv& env, RunState&, const StoryStep&){ - heal_at_center(env.console, env.context); - healed_by_nurse(env.supplies); - return Pokemon::outcome_ok(); - }; - case StoryActionId::SHOP: - return [](StoryEnv& env, RunState&, const StoryStep& step){ return shop(env, step); }; - case StoryActionId::READY: - return get_ready; - case StoryActionId::OPTIONS: - case StoryActionId::GAME: - break; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No console action for {}", story_action_name(id))); -} - -} // namespace - - -StoryExecutor::StoryExecutor(StoryEnv& env) - : m_env(env) - , m_guard(env.console.logger()) - , m_table(make_story_action_table([this](StoryActionId id){ return console_action(id); })) - , m_executor(m_table, m_guard) - , m_look(env.console, env.context) - , m_interrupts(step_interrupts( - [this](bool fresh){ return m_look.look(fresh); }, - console_interrupt_actions(env.console, env.context, [&env]{ - return story_interrupts(env.supplies, false, env.checks, env.language); - }) - )) -{ - m_executor.set_interrupts(&m_interrupts); -} - -Outcome StoryExecutor::run(const StoryStep& step, RunState& state){ - return m_executor.run(step, state); -} - -Pokemon::StoryAction StoryExecutor::console_action(StoryActionId id){ - if (id == StoryActionId::OPTIONS){ - return {.act = [this](const StoryStep&, RunState&){ - set_options(m_env.console, m_env.context, m_menu, m_env.language); - return Pokemon::outcome_ok(); - }, .needs_console = true}; - } - if (id == StoryActionId::GAME){ - return {.act = [this](const StoryStep& step, RunState& state){ return game(state, step); }, .needs_console = true}; - } - const ConsoleAction action = console_action_of(id); - return {.act = [this, action](const StoryStep& step, RunState& state){ return action(m_env, state, step); }, .needs_console = true}; -} - - namespace{ bool walked(StoryEnv& env, RunState& state, const StoryStep& step){ @@ -648,28 +577,99 @@ std::optional run_abilities(StoryEnv& env, RunState& state, const Story ); ConsoleChoiceActions choice(env.console, env.context); StoryAbilities abilities{console_member_reader(env.console, env.context, env.language), mart, teach, grind, choice}; + if (const std::optional plan = step.action == GRIND_CHECK_ACTION ? grind_plan_of(step.args) : std::nullopt){ + if (grind_reached_already(env.console.logger(), grind, abilities.members, *plan)){ + state.flags.insert(step.name); + } + return Pokemon::outcome_unchanged(); + } return run_ability_game_step(env.console.logger(), &env.console, step, abilities); } -} // namespace +// CUT_TREE_VARIANT: the tree in the step's direction, cut, and a step +// onto its tile. +Outcome cut_tree(StoryEnv& env, RunState& state, const StoryStep& step){ + const std::optional here = story_pose(state.pose); + if (!here){ + return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); + } + const Direction direction = arg(step, "direction"); + if (here->facing != direction){ + // The tree is in the way: a tap only turns the player to it. + face_wall(env.context, direction); + } + pbf_press_button(env.context, BUTTON_A, 160ms, 800ms); + answer_yes_no(env.console, env.context, true, BUTTON_B, YES_NO_TIMEOUT); + mash_until_overworld(env.console, env.context, SCENE_TIMEOUT); + step_once(env.context, direction, direction); + return Pokemon::outcome_ok(to_pose(StoryPose{here->map, here->tile.next(direction), direction})); +} + +// Vermilion Gym's trash cans on the console: a walk to each can's stand +// (a ROUTE planned on trash_can_maps()), A, and its pages counted. +class ConsoleTrashCans{ +public: + ConsoleTrashCans(StoryEnv& env, RunState& state, const StoryStep& step) + : m_env(env), m_state(state), m_step(step) + {} + + CanPages check(int can){ + const TrashCanStand stand = trash_can_stand(can); + const std::optional here = story_pose(m_state.pose); + const Pokemon::GridPose target{m_state.pose.map, {stand.tile}, stand.facing}; + if (!here || !(here->tile == stand.tile) || here->facing != stand.facing){ + StoryStep walk = m_step; + walk.kind = StoryStepKind::ROUTE; + walk.name = m_step.name + "_can" + std::to_string(can); + walk.action.clear(); + walk.args = {{"target", target}, {"fight_wild", false}}; + static const std::vector MAPS = trash_can_maps(story_maps()); + const Outcome outcome = walk_route(m_env, m_state, walk, MAPS); + if (!outcome.succeeded()){ + return CanPages::FAILED; + } + if (outcome.pose){ + m_state.pose = *outcome.pose; + } + } + const std::optional pages = talk_and_count_pages(m_env.console, m_env.context); + if (!pages){ + return CanPages::FAILED; + } + m_env.console.log(std::format("Story: {}: can {}, {} page(s).", m_step.name, can, *pages)); + return *pages == 1 ? CanPages::ONE : CanPages::TWO; + } -Outcome StoryExecutor::game(RunState& state, const StoryStep& step){ - if (step.action == CLOSE_TRAINER_CARD){ - close_trainer_card(m_env.console, m_env.context); - return Pokemon::outcome_ok(); +private: + StoryEnv& m_env; + RunState& m_state; + const StoryStep& m_step; +}; + +// TRASH_CANS_VARIANT: the search for Vermilion Gym's switches. +Outcome open_gym_door(StoryEnv& env, RunState& state, const StoryStep& step){ + if (!story_pose(state.pose)){ + return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); } - if (step.action == LEAVE_GIFT_SUMMARY){ - leave_gift_summary(m_env.console, m_env.context); - return Pokemon::outcome_ok(); + ConsoleTrashCans cans(env, state, step); + const TrashCanResult result = run_trash_cans(env.console, [&](int can){ return cans.check(can); }); + if (result.end != TrashCanEnd::OPENED){ + return Pokemon::outcome_failed(std::format("trash_cans_{}", trash_can_end_name(result.end)), std::format("{} checks", result.checks)); } + return Pokemon::outcome_ok(state.pose); +} + +// The GAME steps without a row of their own: a capture or a PC deposit or +// withdrawal, a MART, TEACH, LEVEL, GRIND or fossil CHOICE. +Outcome other_game_step(StoryEnv& env, RunState& state, const StoryStep& step){ const Pokemon::Pose patch = state.pose; - ConsoleCaptureActions capture(m_env.console, m_env.context, m_env.language, [&]{ - pace_trainer_battle(m_env, state, step, patch); + ConsoleCaptureActions capture(env.console, env.context, env.language, [&]{ + pace_trainer_battle(env, state, step, patch); }); - ConsolePcStorageActions pc(m_env.console, m_env.context); - std::optional done = run_storage_game_step(m_env.console.logger(), &m_env.console, step, capture, pc); + ConsolePcStorageActions pc(env.console, env.context); + std::optional done = run_storage_game_step(env.console.logger(), &env.console, step, capture, pc); if (!done){ - done = run_abilities(m_env, state, step); + done = run_abilities(env, state, step); } if (done && done->succeeded() && !done->pose){ // Pacing leaves the player on either of its tiles. @@ -681,6 +681,116 @@ Outcome StoryExecutor::game(RunState& state, const StoryStep& step){ return Pokemon::unsupported_step(step); } +// How the console does an action that needs only the env. +using ConsoleAction = Outcome (*)(StoryEnv& env, RunState& state, const StoryStep& step); + +// The console's GAME actions; nullptr for another id. +ConsoleAction game_console_action(StoryActionId id){ + switch (id){ + case StoryActionId::CLOSE_TRAINER_CARD: + return [](StoryEnv& env, RunState&, const StoryStep&){ + close_trainer_card(env.console, env.context); + return Pokemon::outcome_ok(); + }; + case StoryActionId::LEAVE_GIFT_SUMMARY: + return [](StoryEnv& env, RunState&, const StoryStep&){ + leave_gift_summary(env.console, env.context); + return Pokemon::outcome_ok(); + }; + case StoryActionId::CUT_TREE: + return cut_tree; + case StoryActionId::TRASH_CANS: + return open_gym_door; + case StoryActionId::GAME: + return other_game_step; + default: + return nullptr; + } +} + +ConsoleAction console_action_of(StoryActionId id){ + if (const ConsoleAction game = game_console_action(id)){ + return game; + } + switch (id){ + case StoryActionId::NEW_GAME: + return [](StoryEnv& env, RunState&, const StoryStep&){ + play_new_game_intro(env.console, env.context, env.player_name); + return Pokemon::outcome_ok(); + }; + case StoryActionId::ROUTE: + return [](StoryEnv& env, RunState& state, const StoryStep& step){ return walk_route(env, state, step); }; + case StoryActionId::LEGS: + return walk_legs; + case StoryActionId::STEP: + return take_step; + case StoryActionId::TALK: + return [](StoryEnv& env, RunState&, const StoryStep&){ + pbf_press_button(env.context, BUTTON_A, 160ms, 800ms); + return Pokemon::outcome_ok(); + }; + case StoryActionId::ANSWER: + return [](StoryEnv& env, RunState&, const StoryStep& step){ + answer_yes_no(env.console, env.context, arg(step, "yes"), BUTTON_B, YES_NO_TIMEOUT); + return Pokemon::outcome_ok(); + }; + case StoryActionId::MASH: + return [](StoryEnv& env, RunState&, const StoryStep&){ + mash_until_overworld(env.console, env.context, SCENE_TIMEOUT); + return Pokemon::outcome_ok(); + }; + case StoryActionId::BATTLE: + return [](StoryEnv& env, RunState&, const StoryStep& step){ return battle(env, step); }; + case StoryActionId::HEAL: + return [](StoryEnv& env, RunState&, const StoryStep&){ + heal_at_center(env.console, env.context); + healed_by_nurse(env.supplies); + return Pokemon::outcome_ok(); + }; + case StoryActionId::SHOP: + return [](StoryEnv& env, RunState&, const StoryStep& step){ return shop(env, step); }; + case StoryActionId::READY: + return get_ready; + default: + break; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No console action for {}", story_action_name(id))); +} + +} // namespace + + +StoryExecutor::StoryExecutor(StoryEnv& env) + : m_env(env) + , m_guard(env.console.logger()) + , m_table(make_story_action_table([this](StoryActionId id){ return console_action(id); })) + , m_executor(m_table, m_guard) + , m_look(env.console, env.context) + , m_interrupts(step_interrupts( + [this](bool fresh){ return m_look.look(fresh); }, + console_interrupt_actions(env.console, env.context, [&env]{ + return story_interrupts(env.supplies, false, env.checks, env.language); + }) + )) +{ + m_executor.set_interrupts(&m_interrupts); +} + +Outcome StoryExecutor::run(const StoryStep& step, RunState& state){ + return m_executor.run(step, state); +} + +Pokemon::StoryAction StoryExecutor::console_action(StoryActionId id){ + if (id == StoryActionId::OPTIONS){ + return {.act = [this](const StoryStep&, RunState&){ + set_options(m_env.console, m_env.context, m_menu, m_env.language); + return Pokemon::outcome_ok(); + }, .needs_console = true}; + } + const ConsoleAction action = console_action_of(id); + return {.act = [this, action](const StoryStep& step, RunState& state){ return action(m_env, state, step); }, .needs_console = true}; +} + namespace{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index 99d91818fa..aa9f8d2966 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -125,15 +125,6 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ virtual Pokemon::Outcome run(const StoryStep& step, Pokemon::RunState& state) override; private: - // A GAME step by its action. CLOSE_TRAINER_CARD: back from SID Helper - // (close_trainer_card()). LEAVE_GIFT_SUMMARY: back from Gift RNG - // (leave_gift_summary()). A capture or a PC deposit or withdrawal - // (capture_step(), pc_step() in PokemonFRLG_AutoStoryCapture.h); a - // shiny met in a capture stops the program without reloading. A MART, - // TEACH, LEVEL, GRIND or fossil CHOICE - // (PokemonFRLG_AutoStoryAbilities.h); a GRIND heals by routing to its - // nurse and back. - Pokemon::Outcome game(Pokemon::RunState& state, const StoryStep& step); // How the console does `id`. Pokemon::StoryAction console_action(StoryActionId id); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp index 5abccfc643..f80d841633 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.cpp @@ -32,18 +32,23 @@ std::string_view grind_end_name(GrindEnd end){ } -Pokemon::StoryActionArgs grind_args(const GrindPlan& plan, Pokemon::GridPose nurse){ +Pokemon::StoryActionArgs grind_check_args(const GrindPlan& plan){ Pokemon::StoryActionArgs args{ {"slot", int64_t(plan.member + 1)}, {"level", int64_t(plan.level)}, {"encounters", int64_t(plan.max_encounters)}, {"pace", plan.pace}, {"heal_every", int64_t(plan.heal_every)}, - {"nurse", std::move(nurse)}, }; return args; } +Pokemon::StoryActionArgs grind_args(const GrindPlan& plan, Pokemon::GridPose nurse){ + Pokemon::StoryActionArgs args = grind_check_args(plan); + args.emplace("nurse", std::move(nurse)); + return args; +} + std::optional grind_plan_of(const Pokemon::StoryActionArgs& args){ const std::optional member = counted_arg(args, "slot", PARTY_SLOTS); const std::optional level = number_arg(args, "level", 2, 100); @@ -69,6 +74,16 @@ Pokemon::StoryStep grind_step(std::string name, std::string why, const GrindPlan return step; } +Pokemon::StoryStep grind_check_step(std::string name, std::string why, const GrindPlan& plan){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = std::move(name); + step.why = std::move(why); + step.action = GRIND_CHECK_ACTION; + step.args = grind_check_args(plan); + return step; +} + namespace{ @@ -110,6 +125,10 @@ class GrindRun{ } } } + // The member, read, has what the plan grinds for. Nothing fought. + bool reached_already(){ + return m_plan.member == 0 && read_level() && over() && m_result.end == GrindEnd::REACHED; + } private: GrindResult end(GrindEnd end, std::string detail){ @@ -196,6 +215,12 @@ GrindResult run_grind(Logger& logger, GrindActions& actions, const MemberReader& return result; } +bool grind_reached_already(Logger& logger, GrindActions& actions, const MemberReader& reader, const GrindPlan& plan){ + const bool reached = GrindRun(logger, actions, reader, plan).reached_already(); + logger.log(reached ? "Grind: reached already; no walk out to the patch." : "Grind: not reached yet; out to the patch."); + return reached; +} + std::string grind_message(const GrindPlan& plan, const GrindResult& result){ const std::string level = result.level ? std::to_string(*result.level) : "?"; const std::string tally = std::format( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h index 088e9159d2..8cbbc577c4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h @@ -54,6 +54,11 @@ namespace PokemonFRLG{ // From the overworld in the patch: grinds as `plan` says. GrindResult run_grind(Logger& logger, GrindActions& actions, const MemberReader& reader, const GrindPlan& plan); +// Before the walk out to the patch: whether the member `plan` grinds, as +// read, already has its level. Nothing is fought. 00.24 walked to Route +// 6's grass and back at Lv29 (console B, 2026-11-03). +bool grind_reached_already(Logger& logger, GrindActions& actions, const MemberReader& reader, const GrindPlan& plan); + // Formats a log message summarizing the grind result. std::string grind_message(const GrindPlan& plan, const GrindResult& result); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrindStep.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrindStep.h index fa8e29bf97..27c3302e9b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrindStep.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrindStep.h @@ -61,6 +61,17 @@ std::optional grind_plan_of(const Pokemon::StoryActionArgs& args); // The table's GRIND step: `nurse` is where the player faces the nurse. Pokemon::StoryStep grind_step(std::string name, std::string why, const GrindPlan& plan, Pokemon::GridPose nurse); +// The GAME action that checks a GRIND step's plan before the walk out to +// its patch: GRIND_ACTION's args but the nurse. +inline const std::string GRIND_CHECK_ACTION = "grind_check"; +// `plan` as GRIND_CHECK_ACTION's args; grind_plan_of() reads them back. +Pokemon::StoryActionArgs grind_check_args(const GrindPlan& plan); + +// The table's check before the walk out to a GRIND step's patch: when the +// lead already has what `plan` grinds for, the step sets a run flag named +// `name`, which the walk out, the GRIND step and the way back skip_if. +Pokemon::StoryStep grind_check_step(std::string name, std::string why, const GrindPlan& plan); + } // namespace PokemonFRLG 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 ff3e0871bf..f240de6879 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp @@ -302,9 +302,34 @@ UnitTestResult test_grind_args(){ return true; } +// The check in the Center before the walk out: a lead already at the +// plan's level needs no trip (00.24 walked to Route 6's grass and back at +// Lv29, console B, 2026-11-03); one short of it does. Nothing is fought +// either way. +UnitTestResult test_grind_reached_already(){ + QuietLogger logger; + for (const unsigned level : {16u, 19u}){ + FakePatch patch; + patch.level = level; + const bool reached = grind_reached_already(logger, patch, [&patch](size_t slot){ + return patch.read_member(slot); + }, squirtle_to(19)); + if (reached != (level >= 19) || patch.encounters != 0 || patch.heals != 0 || !patch.error.empty()){ + return std::format("Lv{}: reached {}, {} encounters, {} heals {}.", level, reached, patch.encounters, patch.heals, patch.error); + } + } + const Pokemon::StoryStep check = grind_check_step("lead_ready", "", squirtle_to(30)); + const std::optional back = grind_plan_of(check.args); + if (check.action != GRIND_CHECK_ACTION || !back || back->level != 30 || check.args.contains("nurse")){ + return "The check's args didn't read back as its plan, or had a nurse."; + } + return true; +} + } // namespace + const AutoStoryGrindCase AUTO_STORY_GRIND_CASES[] = { { .input = {"grinding on a fake patch", test_grind}, @@ -314,6 +339,10 @@ const AutoStoryGrindCase AUTO_STORY_GRIND_CASES[] = { .input = {"the step's args", test_grind_args}, .expectation = {}, }, + { + .input = {"reached already: no walk out to the patch", test_grind_reached_already}, + .expectation = {}, + }, }; void add_tests_AutoStoryGrind(UnitTestDatabase& database){ 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 1ee305c11a..b5c81e2e7c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp @@ -26,6 +26,8 @@ #include "CommonFramework/Language.h" #include "Tests/ImageUnitTest.h" #include "Tests/TestUtils.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleHpBarReader.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" @@ -371,6 +373,52 @@ class Test_BattleShows : public ImageUnitTest{ std::optional m_expected; }; +// battle_yes_no_shows() on console B's captures named +// _.png. +class Test_BattleYesNo : public ImageUnitTest{ +public: + Test_BattleYesNo(const std::string& image) + : ImageUnitTest("PokemonFRLG::AutoStoryBattle - " + image, {image}) + {} + + virtual UnitTestResult run_on_images( + Logger& logger, CancellableScope& scope, + const std::vector& images + ) const override{ + bool expected = false; + const std::vector words = parse_words(Filesystem::Path(image_paths()[0]).stem().string()); + if (words.empty() || !parse_bool(words.back(), expected)){ + return "Error: filename must be _."; + } + return battle_yes_no_shows(images[0]) == expected; + } +}; + +// read_opponent_hp_fill() on console B's captures named +// _FoeHp_of48.png: the bar's filled share within a pixel. +class Test_FoeHp : public ImageUnitTest{ +public: + Test_FoeHp(const std::string& image) + : ImageUnitTest("PokemonFRLG::AutoStoryBattle - " + image, {image}) + {} + + virtual UnitTestResult run_on_images( + Logger& logger, CancellableScope& scope, + const std::vector& images + ) const override{ + const std::vector words = parse_words(Filesystem::Path(image_paths()[0]).stem().string()); + int pixels = -1; + if (words.empty() || words.back().find("of48") == std::string::npos || !parse_int(words.back().substr(0, words.back().find("of48")), pixels)){ + return "Error: filename must be _FoeHp_of48."; + } + const std::optional fill = read_opponent_hp_fill(images[0]); + if (!fill || std::abs(*fill - pixels / 48.0) > 1.0 / 48){ + return std::format("Expected {} of 48 pixels, got {:.1f}.", pixels, fill ? 48 * *fill : -1.0); + } + return true; + } +}; + // read_party_status() on console B's captures named // _Hp_of[_].png: the bar's color, // and its colored share within a pixel of the 48-pixel bar of hp / max hp. @@ -479,6 +527,20 @@ void add_tests_AutoStoryItems(UnitTestDatabase& database){ }){ database.add(std::format("PokemonFRLG/AutoStoryBattle/{}", image)); } + // The YES/NO to "Delete a move to make room for BITE?" (Miguel), and the + // S.S. Anne rival's and Misty's send-outs, which the move prompt's + // detector alone took for one (console B, 2026-11-03). + for (std::string_view image : { + "Miguel_DeleteMoveForBite_YesNo_True.png", + "SSAnneRival_SentOutRaticate_YesNo_False.png", + "SSAnneRival_SentOutKadabra_YesNo_False.png", + "Misty_SentOutStarmie_YesNo_False.png", + }){ + database.add(std::format("PokemonFRLG/AutoStoryBattle/{}", image)); + } + // The S.S. Anne rival's Pidgeotto at full HP, its Raticate low. + database.add("PokemonFRLG/AutoStoryBattle/SSAnneRival_Pidgeotto_FoeHp_48of48.png"); + database.add("PokemonFRLG/AutoStoryBattle/SSAnneRival_Raticate_FoeHp_7of48.png"); // The battle's choices, registered here to keep add_tests() within its size. add_tests_AutoStoryParty(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h index a0d2beeb15..46590fe54b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h @@ -28,9 +28,20 @@ namespace PokemonFRLG{ // other step, or a `patch` not on one tile. Pokemon::Pose paced_pose(const Pokemon::Pose& patch, const StoryStep& step); -// A ROUTE's legs from `pose` to `goal`: from one tile, as planned; from -// a set of tiles (paced_pose()), first the holds to walls that bring them -// all to one tile (holds_to_one_tile()), then the route from there. +// The maps the story plans on: every map to Route 4's Pokemon Center, with +// the objects the game hides after the Hall of Fame removed, as the lab's +// frlg_route does, and those a new game hides until their scene (the +// S.S. Anne's rival on the Captain's door). +const std::vector& story_maps(); +// default_route_costs() without Surf, which the story hasn't got yet: +// routes stay on land, even where water is the shorter way (Vermilion +// City's harbor). +const RouteCosts& story_route_costs(); + +// A ROUTE's legs from `pose` to `goal`, on story_route_costs(): from +// one tile, as planned; from a set of tiles (paced_pose()), first the +// holds to walls that bring them all to one tile (holds_to_one_tile()), +// then the route from there. // Nothing if either can't be planned. std::optional> plan_story_route( const std::vector& maps, const Pokemon::Pose& pose, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp index 5c33f5d41f..27961ab0ab 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include "Common/Cpp/Exceptions.h" @@ -645,6 +646,37 @@ UnitTestResult test_end_watch_timing(Logger&){ return true; } +// Console B, 2026-11-03, after losing to Lt. Surge: no battle screen and +// no START menu, and the loop pressed + and B for 8 minutes. It gives up +// 60 s after the last battle screen, once START has looked; a battle +// screen in between starts that time over. +UnitTestResult test_end_watch_gives_up(Logger&){ + const WallClock start = current_time(); + const auto at = [&](int ms){ return start + std::chrono::milliseconds(ms); }; + BattleEndWatch watch; + if (watch.overworld_lost(at(120000))){ + return "Gave up before any battle screen showed."; + } + watch.seen(BattleSeen::BATTLE, at(0)); + std::optional gave_up; + for (int ms = 300; ms <= 600000 && !gave_up; ms += 300){ + watch.seen(BattleSeen::NONE, at(ms)); + watch.check_overworld(at(ms)); + if (ms == 30000){ + watch.seen(BattleSeen::BATTLE, at(ms)); + } + if (watch.overworld_lost(at(ms))){ + gave_up = ms; + } + } + if (!gave_up || *gave_up < 90000 || *gave_up > 95000){ + return gave_up + ? std::format("Expected to give up 60 s after the battle screen at 30 s, at {} ms.", *gave_up) + : std::string("Never gave up on the overworld in 10 minutes."); + } + return true; +} + } // namespace @@ -716,6 +748,56 @@ UnitTestResult test_disabled_move(Logger&){ return true; } +// Regression, console B 2026-11-03, m68, the S.S. Anne rival: "no PP left +// for that move" read 37 s after the battle's last move, as it ended, and +// the story took the move's PP as 0. Read once, a move is left alone as a +// Disable (Kadabra's) would have it, its PP kept; read again for the same +// move, its PP is 0. +UnitTestResult test_no_pp_read_once(Logger&){ + Supplies supplies; + supplies.lead = squirtle_before_miguel(); + supplies.foes = {"grimer", "voltorb", "koffing"}; + BattleDecisions decisions(supplies, BattleKind::TRAINER); + if (decisions.turn(GREEN).slot != TOP_LEFT_MOVE){ + return "Expected Water Gun (slot 0) at turn 1."; + } + decisions.turn_done(TurnChoice::MOVE, TurnResult::NOT_DONE); + if (supplies.lead.moves[TOP_LEFT_MOVE].pp != 25){ + return std::format("Expected Water Gun's 25 PP kept after one \"no PP\" read, got {}.", supplies.lead.moves[TOP_LEFT_MOVE].pp); + } + for (int c = 0; c < 5; c++){ + if (decisions.turn(GREEN).slot == TOP_LEFT_MOVE){ + return std::format("Expected Water Gun left alone at turn {} after the read, as a Disable.", c + 1); + } + } + if (decisions.turn(GREEN).slot != TOP_LEFT_MOVE){ + return "Expected Water Gun again once a Disable would be over."; + } + decisions.turn_done(TurnChoice::MOVE, TurnResult::NOT_DONE); + if (supplies.lead.moves[TOP_LEFT_MOVE].pp != 0){ + return std::format("Expected Water Gun at 0 PP after a second read, got {}.", supplies.lead.moves[TOP_LEFT_MOVE].pp); + } + return true; +} + +// "no PP left" counts only as soon after the choice as a refusal's menu +// comes: m68's read 37 s after the battle's last move doesn't. +UnitTestResult test_no_pp_due(Logger&){ + const WallClock start = current_time(); + MoveRefusalWatch watch; + if (watch.no_pp_due(start)){ + return "Expected no \"no PP\" read counted with no move chosen."; + } + watch.move_chosen(start); + if (!watch.no_pp_due(start + 4000ms)){ + return "Expected a \"no PP\" read 4 s after the choice counted."; + } + if (watch.no_pp_due(start + 37000ms)){ + return "Expected a \"no PP\" read 37 s after the choice not counted."; + } + return true; +} + // The loop's view of a move turned down (console B, 2026-11-03): the move // list back (no battle screen) and the battle menu 5.7 s after the choice. // Not a turn (8.3 s and up, with no move list), nor a menu long after one @@ -823,86 +905,29 @@ UnitTestResult test_nurse_before_battle(Logger&){ } const AutoStoryPartyTestCase AUTO_STORY_PARTY_CASES[] = { - { - .input = {.name = "movesets the game gives and the story plays", .body = test_movesets}, - .expectation = {.description = "verifies movesets progression through early game"}, - }, - { - .input = {.name = "move offered and slot forgotten", .body = test_learn_prompts}, - .expectation = {.description = "determines move learning replacements and prompts"}, - }, - { - .input = {.name = "Mega Kick kept over later level-up moves", .body = test_mega_kick_kept}, - .expectation = {.description = "keeps Mega Kick over later level-up moves"}, - }, - { - .input = {.name = "YES/NO answers to move prompts", .body = test_prompt_answers}, - .expectation = {.description = "answers prompts when deciding to learn new moves"}, - }, - { - .input = {.name = "fainted lead runs or sends the next member", .body = test_fainted_lead}, - .expectation = {.description = "switches to next alive member when lead faints"}, - }, - { - .input = {.name = "PP: preferred attack, then Tackle; nurse restores", .body = test_pp}, - .expectation = {.description = "tracks PP depletion and replenishment"}, - }, - { - .input = {.name = "moves read off the summary, Water Gun over Tackle", .body = test_moves_from_summary}, - .expectation = {.description = "reads move list from summary screen"}, - }, - { - .input = {.name = "summary members: fewer moves, unread PP, strongest attack", .body = test_summary_members}, - .expectation = {.description = "handles party members with partial move data"}, - }, - { - .input = {.name = "no B during an evolution", .body = test_no_b_during_evolution}, - .expectation = {.description = "prevents cancelling evolution sequence"}, - }, - { - .input = {.name = "RUN, then a dark cave: no evolution wait, START soon", .body = test_run_then_overworld}, - .expectation = {.description = "handles post-battle overworld transition in dark cave"}, - }, - { - .input = {.name = "battle end: START after the battle is gone, A and B for 30 s at most", .body = test_end_watch_timing}, - .expectation = {.description = "verifies timing constraints on battle end loop"}, - }, - { - .input = {.name = "attacks by matchup: Bite on the rival's Bulbasaur and Misty", .body = test_attack_by_matchup}, - .expectation = {.description = "selects optimal attack move based on type matchup"}, - }, - { - .input = {.name = "attacks against an unknown foe: the plan's order", .body = test_attack_unknown_foe}, - .expectation = {.description = "falls back to default move preference order against unknown foe"}, - }, - { - .input = {.name = "Bite learned over Tail Whip or Withdraw", .body = test_bite_learned}, - .expectation = {.description = "prioritizes learning offensive moves over status moves"}, - }, - { - .input = {.name = "a YES/NO with no move list after it changes no move", .body = test_yes_no_without_move_list}, - .expectation = {.description = "maintains moveset when prompt completes without move selection"}, - }, - { - .input = {.name = "a disabled move: left alone while Disable lasts, PP back", .body = test_disabled_move}, - .expectation = {.description = "avoids selecting disabled moves"}, - }, - { - .input = {.name = "a move turned down: the move list, then the menu sooner than a turn", .body = test_move_refusal_watch}, - .expectation = {.description = "handles refusing a new move cleanly"}, - }, - { - .input = {.name = "the move list closed with nothing forgotten: YES to \"Stop learning?\"", .body = test_move_list_closed}, - .expectation = {.description = "confirms stopping learning when cancelling move list"}, - }, - { - .input = {.name = "move prompts after a turn: a plain YES after the first few", .body = test_move_prompts_bounded}, - .expectation = {.description = "bounds prompt handling attempts after turns"}, - }, - { - .input = {.name = "the nurse before a battle for HP not green with no Potion", .body = test_nurse_before_battle}, - .expectation = {.description = "triggers pokemon center visit when health is low and without potions"}, - }, + {.input = {.name = "movesets the game gives and the story plays", .body = test_movesets}, .expectation = {.description = "verifies movesets progression through early game"},}, + {.input = {.name = "move offered and slot forgotten", .body = test_learn_prompts}, .expectation = {.description = "determines move learning replacements and prompts"},}, + {.input = {.name = "Mega Kick kept over later level-up moves", .body = test_mega_kick_kept}, .expectation = {.description = "keeps Mega Kick over later level-up moves"},}, + {.input = {.name = "YES/NO answers to move prompts", .body = test_prompt_answers}, .expectation = {.description = "answers prompts when deciding to learn new moves"},}, + {.input = {.name = "fainted lead runs or sends the next member", .body = test_fainted_lead}, .expectation = {.description = "switches to next alive member when lead faints"},}, + {.input = {.name = "PP: preferred attack, then Tackle; nurse restores", .body = test_pp}, .expectation = {.description = "tracks PP depletion and replenishment"},}, + {.input = {.name = "moves read off the summary, Water Gun over Tackle", .body = test_moves_from_summary}, .expectation = {.description = "reads move list from summary screen"},}, + {.input = {.name = "summary members: fewer moves, unread PP, strongest attack", .body = test_summary_members}, .expectation = {.description = "handles party members with partial move data"},}, + {.input = {.name = "no B during an evolution", .body = test_no_b_during_evolution}, .expectation = {.description = "prevents cancelling evolution sequence"},}, + {.input = {.name = "RUN, then a dark cave: no evolution wait, START soon", .body = test_run_then_overworld}, .expectation = {.description = "handles post-battle overworld transition in dark cave"},}, + {.input = {.name = "battle end: START after the battle is gone, A and B for 30 s at most", .body = test_end_watch_timing}, .expectation = {.description = "verifies timing constraints on battle end loop"},}, + {.input = {.name = "attacks by matchup: Bite on the rival's Bulbasaur and Misty", .body = test_attack_by_matchup}, .expectation = {.description = "selects optimal attack move based on type matchup"},}, + {.input = {.name = "attacks against an unknown foe: the plan's order", .body = test_attack_unknown_foe}, .expectation = {.description = "falls back to default move preference order against unknown foe"},}, + {.input = {.name = "Bite learned over Tail Whip or Withdraw", .body = test_bite_learned}, .expectation = {.description = "prioritizes learning offensive moves over status moves"},}, + {.input = {.name = "a YES/NO with no move list after it changes no move", .body = test_yes_no_without_move_list}, .expectation = {.description = "maintains moveset when prompt completes without move selection"},}, + {.input = {.name = "a disabled move: left alone while Disable lasts, PP back", .body = test_disabled_move}, .expectation = {.description = "avoids selecting disabled moves"},}, + {.input = {.name = "a move turned down: the move list, then the menu sooner than a turn", .body = test_move_refusal_watch}, .expectation = {.description = "handles refusing a new move cleanly"},}, + {.input = {.name = "the move list closed with nothing forgotten: YES to \"Stop learning?\"", .body = test_move_list_closed}, .expectation = {.description = "confirms stopping learning when cancelling move list"},}, + {.input = {.name = "move prompts after a turn: a plain YES after the first few", .body = test_move_prompts_bounded}, .expectation = {.description = "bounds prompt handling attempts after turns"},}, + {.input = {.name = "the nurse before a battle for HP not green with no Potion", .body = test_nurse_before_battle}, .expectation = {.description = "triggers pokemon center visit when health is low and without potions"},}, + {.input = {.name = "battle end: no overworld 60 s after the battle, a stop", .body = test_end_watch_gives_up}, .expectation = {.description = "stops battle watch loop when overworld does not reappear within 60s"},}, + {.input = {.name = "\"no PP\" read once: left alone as a Disable; twice: PP 0", .body = test_no_pp_read_once}, .expectation = {.description = "treats first no PP message as disable and second as zero PP"},}, + {.input = {.name = "\"no PP\" counts only soon after the move chosen", .body = test_no_pp_due}, .expectation = {.description = "only attributes no PP warning to recently selected move"},}, }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h index 182f79bb87..e47e042d42 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h @@ -61,12 +61,17 @@ inline const std::string CLOSE_TRAINER_CARD = "close_trainer_card"; // the overworld. inline const std::string LEAVE_GIFT_SUMMARY = "leave_gift_summary"; +// The GAME step that cuts the tree the player faces, `direction` +// (pokefirered data/scripts/field_moves.inc, EventScript_CutTree): A, +// "This tree looks like it can be CUT down! Would you like to CUT it?" +// YES, " used CUT!", the tree falls; then a step onto its tile. With +// no Pokemon that knows Cut there is no YES/NO, and the step fails. The +// tree grows back when the player leaves the map (its hide flag is a +// FLAG_TEMP), so the walk back cuts it again. +inline const std::string CUT_TREE_VARIANT = "cut_tree"; + // How `step`, a ROUTE or LEGS, moves the player: RUN_VARIANT runs. MoveSpeed move_speed(const StoryStep& step); -// The maps the story plans on: every map to Route 4's Pokemon Center, with -// the objects the game hides after the Hall of Fame removed, as the lab's -// frlg_route does. -const std::vector& story_maps(); // Converts a StoryPose to a general navigation Pose. Pokemon::Pose to_pose(const StoryPose& pose); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h index 3d3a79aa7f..7376d5c6d9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h @@ -45,6 +45,13 @@ TextEnd advance_text(ConsoleHandle& console, ProControllerContext& context, Mill // advance_text() to the overworld. void mash_until_overworld(ConsoleHandle& console, ProControllerContext& context, Milliseconds timeout); +// From the overworld, facing something that answers A with a message (a +// sign, Vermilion Gym's trash cans): A, then how many pages the message +// has, one or two, then on to the overworld. Language-free: one A after +// the first page has printed either closes the message or shows its +// second page. Nothing if no message showed. +std::optional talk_and_count_pages(ConsoleHandle& console, ProControllerContext& context); + // Advances text with `advance` until a YES/NO shows, then answers it. B // answers NO. Throws OperationFailedException after `timeout`. void answer_yes_no(ConsoleHandle& console, ProControllerContext& context, bool yes, Button advance, Milliseconds timeout); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp new file mode 100644 index 0000000000..a3d999939d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -0,0 +1,461 @@ +/* AutoStory Row Sim + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryRowSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::Outcome; +using Pokemon::RunState; + + +void SimStubs::begin_row(std::string row){ + m_rows.push_back({std::move(row), {}}); +} +void SimStubs::record(const StoryStep& step){ + if (m_rows.empty()){ + m_rows.push_back({"", {}}); + } + m_rows.back().steps.push_back(step.name); +} +Pokemon::StoryAction SimStubs::stub(Pokemon::StoryActionFunction then){ + return { + .act = [this, then = std::move(then)](const StoryStep& step, RunState& state){ + record(step); + return then ? then(step, state) : Pokemon::outcome_ok(); + }, + .needs_console = true, + }; +} + +std::string stub_report(const std::vector& rows){ + std::string out; + for (const RowStubs& row : rows){ + out += std::format("{}: {} stubbed", row.row, row.steps.size()); + for (size_t i = 0; i < row.steps.size(); i++){ + out += (i == 0 ? ": " : ", ") + row.steps[i]; + } + out += "\n"; + } + return out; +} + + +namespace{ + +const MapData* map_named(const std::string& name){ + for (const MapData& map : story_maps()){ + if (map.name == name){ + return ↦ + } + } + return nullptr; +} + +// Whether the player, at the end of a WALK `step`, stops there holding on: +// the map's edge, a wall, or water to Surf onto, but no warp of any kind, +// even one to a map that isn't loaded. +bool stops_past_end(const RouteStep& step){ + const MapData& map = *map_named(step.end.map); + const TilePos here = step.end.point; + const TilePos ahead = here.next(step.direction); + if (!in_bounds(map, ahead)){ + return true; + } + if (warps_on_step(map, ahead) || exit_mat(map, here) == step.direction + || (step.direction == Direction::NORTH && is_door(map, ahead)) + ){ + return false; + } + const StepKind kind = classify_step(map, PlayerState{here, elevation_at(map, here), step.surfing}, step.direction); + return kind == StepKind::BLOCKED || kind == StepKind::START_SURF; +} + +// The first leg of `route` to a wall that holding on would carry past its +// end, or nothing (console B, 2026-11-02: one rode Route 4's Pokemon +// Center escalator). +std::optional overrun_wall_leg(const std::vector& route){ + for (const RouteStep& step : route){ + if (step.to_wall && !stops_past_end(step)){ + return to_string(step); + } + } + return std::nullopt; +} + +// Where the run stands, with a facing: a wall beside it when unknown. +struct Standing{ + MapPosition position; + Direction facing = Direction::NORTH; + std::string error; +}; +Standing standing(const Pokemon::Pose& pose){ + const std::optional at = story_pose(pose); + if (!at){ + return {{}, Direction::NORTH, "no one-tile pose: " + Pokemon::to_string(pose)}; + } + std::optional facing = at->facing; + if (!facing){ + const MapData* map = map_named(at->map); + facing = map ? wall_beside(*map, at->tile) : std::nullopt; + } + if (!facing){ + return {{}, Direction::NORTH, "facing unknown and no wall beside " + to_string(MapPosition{at->map, at->tile})}; + } + return {{at->map, at->tile}, *facing, ""}; +} + +// An action this simulation plays. +Pokemon::StoryAction played(Pokemon::StoryActionFunction act){ + return {.act = std::move(act), .needs_console = false}; +} + +} // namespace + + +StoryMapsSim::StoryMapsSim(StorySimKnobs knobs) + : Pokemon::TableExecutor(m_table, m_guard) + , m_table(make_story_action_table([this](StoryActionId id){ return action(id); })) + , m_knobs(std::move(knobs)) + , m_interrupts(step_interrupts([this](bool){ return look(); }, sim_interrupt_actions())) +{ + if (m_knobs.clear_interrupts){ + set_interrupts(&m_interrupts); + } +} + +void StoryMapsSim::begin_attempt(const Pokemon::StoryCheckpoint& data){ + m_stubs.begin_row(data.id); + m_row = data.id; + // A reload starts the row on the quiet overworld. + m_dialog_up = m_dialog_rose = false; +} + +Outcome StoryMapsSim::run(const StoryStep& step, RunState& state){ + if (m_knobs.dialog_before && m_knobs.dialog_before(m_row, step.name)){ + m_dialog_up = m_dialog_rose = true; + m_dialog_notes.push_back(m_row + "/" + step.name + ": a dialog pops up before it."); + } + return Pokemon::TableExecutor::run(step, state); +} + +Outcome StoryMapsSim::run_action(const StoryStep& step, RunState& state){ + if (m_dialog_up){ + if (!presses_through_text(step.kind)){ + return Pokemon::outcome_failed("dialog", step.name + ": a dialog that popped up before it is still up"); + } + m_dialog_up = false; + } + return Pokemon::TableExecutor::run_action(step, state); +} + +Pokemon::ScreenLook StoryMapsSim::look(){ + const WallClock start = WallClock() + std::chrono::hours(1); + Pokemon::ScreenLook out; + out.log.record({}, start); + if (std::exchange(m_dialog_rose, false)){ + out.log.record({ScreenEvent::DIALOG_BOX}, start + Milliseconds(33)); + } + out.window = {.start = start, .end = start + BETWEEN_STEPS_LOOK}; + return out; +} + +// Every kind closes what is up and notes it: the simulation shows only +// the dialogs it pops up. +StepInterruptActions StoryMapsSim::sim_interrupt_actions(){ + const auto cleared = [this](std::string_view what){ + return [this, what](const Pokemon::InterruptVerdict&, RunState&){ + m_dialog_notes.push_back(std::format("{} cleared before the next step.", what)); + m_dialog_up = false; + return Pokemon::outcome_ok(); + }; + }; + return StepInterruptActions{ + .wild = cleared("a wild battle"), + .trainer = cleared("a trainer's battle"), + .dialog = cleared("a dialog"), + .warp = cleared("a warp"), + }; +} + +Pokemon::StoryAction StoryMapsSim::action(StoryActionId id){ + switch (id){ + case StoryActionId::ROUTE: + return played([this](const StoryStep& step, RunState& state){ return walk_to(state.pose, step); }); + case StoryActionId::LEGS: + return played([this](const StoryStep& step, RunState& state){ return legs(state.pose, step); }); + case StoryActionId::STEP: + return played([this](const StoryStep& step, RunState& state){ return step_ahead(state.pose, step); }); + // The nurse's way must plan too, but the run goes on from where it stands. + case StoryActionId::READY: + return played([this](const StoryStep& step, RunState& state){ + const Outcome to_nurse = walk_to(state.pose, step); + return to_nurse.succeeded() ? Pokemon::outcome_ok() : to_nurse; + }); + case StoryActionId::SHOP: + return played([this](const StoryStep& step, RunState&){ return shop(step); }); + // Pacing leaves the player on either of its tiles, as on the console. + case StoryActionId::CLOSE_TRAINER_CARD: + case StoryActionId::LEAVE_GIFT_SUMMARY: + case StoryActionId::CUT_TREE: + case StoryActionId::TRASH_CANS: + case StoryActionId::GAME: + return m_stubs.stub([](const StoryStep& step, RunState& state){ + return Pokemon::outcome_ok(paced_pose(state.pose, step)); + }); + case StoryActionId::NEW_GAME: + case StoryActionId::OPTIONS: + case StoryActionId::TALK: + case StoryActionId::ANSWER: + case StoryActionId::MASH: + case StoryActionId::BATTLE: + case StoryActionId::HEAL: + return m_stubs.stub(); + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown story action."); +} + +Outcome StoryMapsSim::legs(const Pokemon::Pose& pose, const StoryStep& step) const{ + const Standing at = standing(pose); + if (!at.error.empty()){ + return Pokemon::outcome_failed("no_pose", at.error); + } + const std::optional> route = fixed_route(story_maps(), at.position, Pokemon::story_arg>(step.args, "legs")); + if (!route || route->empty()){ + return Pokemon::outcome_failed("bad_legs", to_string(at.position)); + } + return Pokemon::outcome_ok(to_pose(StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after})); +} + +// A step into a trainer's line goes on until a trainer can see the +// player, as step_until_seen() does on the console. +Outcome StoryMapsSim::step_ahead(const Pokemon::Pose& pose, const StoryStep& step) const{ + const std::optional at = story_pose(pose); + if (!at){ + return Pokemon::outcome_failed("no_pose", Pokemon::to_string(pose)); + } + const Direction direction = Pokemon::story_arg(step.args, "direction"); + const MapData* map = map_named(at->map); + if (step.action != TRAINER_LINE_VARIANT || map == nullptr){ + return Pokemon::outcome_ok(to_pose(StoryPose{at->map, at->tile.next(direction), direction})); + } + TilePos onto = at->tile; + const std::optional stepped = step_until_seen( + TRAINER_LINE_TILES, + [&]{ onto = onto.next(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, direction})); +} + +// The Viridian Mart's list as the game shows it. After a purchase the +// cursor stays on the row bought (console B, 2026-11-01), so each +// order moves it from there, as buy_items() does since ad5d40885. +Outcome StoryMapsSim::shop(const StoryStep& step){ + const std::vector& items = Pokemon::story_arg>(step.args, "items"); + static const std::vector LIST{"poke_ball", "potion", "antidote", "parlyz_heal", "cancel"}; + const std::optional> orders = viridian_mart_orders(items); + if (!orders){ + return Pokemon::outcome_failed("unknown_item", step.name); + } + int cursor = 0; + for (size_t c = 0; c < orders->size(); c++){ + const MartOrder& order = (*orders)[c]; + // The presses: down or up from where the cursor is. + cursor += order.row - cursor; + if (cursor < 0 || cursor >= (int)LIST.size() || LIST[cursor] == "cancel"){ + return Pokemon::outcome_failed("mart_cancel", std::format("order {} ends on row {}", c + 1, cursor + 1)); + } + if (LIST[cursor] != items[c].item){ + return Pokemon::outcome_failed("wrong_item", std::format("{} instead of {}", LIST[cursor], items[c].item)); + } + m_bag[LIST[cursor]] += order.quantity; + } + return Pokemon::outcome_ok(); +} + +Outcome StoryMapsSim::walk_to(const Pokemon::Pose& pose, const StoryStep& step) const{ + if (Pokemon::tiles_of(pose).size() > 1){ + // From the tiles a pacing step leaves: the route must plan, and + // test_routes_after_pacing() walks it on the sim from each. + const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target"))); + const RouteGoal goal{{target->map, target->tile}, target->facing}; + const std::optional> route = plan_story_route(story_maps(), pose, std::nullopt, goal); + if (!route || route->empty()){ + return Pokemon::outcome_failed("no_route", Pokemon::to_string(pose) + " to " + to_string(goal.position)); + } + return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, route->back().facing_after})); + } + const Standing at = standing(pose); + if (!at.error.empty()){ + return Pokemon::outcome_failed("no_pose", at.error); + } + const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target"))); + const RouteGoal goal{{target->map, target->tile}, target->facing}; + const std::optional> route = plan_overworld_route( + story_maps(), at.position, goal, story_route_costs(), at.facing + ); + if (!route){ + return Pokemon::outcome_failed("no_route", to_string(at.position) + " to " + to_string(goal.position)); + } + const MapPosition end = follow_overworld_route(story_maps(), at.position, *route); + if (!(end == goal.position)){ + return Pokemon::outcome_failed("wrong_end", to_string(end)); + } + if (const std::optional leg = overrun_wall_leg(*route)){ + return Pokemon::outcome_failed("wall_overrun", *leg); + } + const Direction facing = route->empty() ? at.facing : route->back().facing_after; + return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, facing})); +} + + +// 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, Pokemon::story_arg>(step.args, "legs")); + } + const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target"))); + const RouteGoal goal{{target->map, target->tile}, target->facing}; + return plan_overworld_route(story_maps(), start, goal, story_route_costs(), at.facing); +} + + +OverworldStepSim::OverworldStepSim(OverworldSim& sim, std::string row, StoryPose at) + : Pokemon::TableExecutor(m_table, m_guard) + , m_sim(sim) + , m_at(std::move(at)) + , m_table(make_story_action_table([this](StoryActionId id){ return action(id); })) +{ + m_stubs.begin_row(std::move(row)); +} + +Pokemon::StoryAction OverworldStepSim::action(StoryActionId id){ + using Body = std::string (OverworldStepSim::*)(const StoryStep&); + Body body = nullptr; + switch (id){ + case StoryActionId::ROUTE: + case StoryActionId::LEGS: + body = &OverworldStepSim::walk; + break; + case StoryActionId::STEP: + body = &OverworldStepSim::step_ahead; + break; + case StoryActionId::CUT_TREE: + body = &OverworldStepSim::cut; + break; + case StoryActionId::BATTLE: + body = &OverworldStepSim::battle; + break; + default: + return m_stubs.stub(); + } + return played([this, body](const StoryStep& step, RunState&){ + const std::string failure = (this->*body)(step); + return failure.empty() ? Pokemon::outcome_ok() : Pokemon::outcome_failed("sim_failure", failure); + }); +} + +// A ROUTE or LEGS by the sim's walker, fighting a trainer who sees the +// player on the way. +std::string OverworldStepSim::walk(const StoryStep& step){ + const std::optional> route = walked_route(m_at, step); + if (route && route->empty()){ + // Already there. + return ""; + } + const RoutePlanning planning{.maps = &story_maps(), .costs = story_route_costs(), .start = MapPosition{m_at.map, m_at.tile}, .label = step.name}; + const std::string failure = route ? OverworldSimWalker(m_sim).run(*route, planning) : "no legs."; + m_at = route ? StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after} : m_at; + return failure; +} + +// 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. +std::string OverworldStepSim::step_ahead(const StoryStep& step){ + const Direction direction = Pokemon::story_arg(step.args, "direction"); + const auto tap = [this, direction]{ + if (m_sim.state().facing != direction){ + m_sim.tap(direction); + } + m_sim.tap(direction); + }; + const auto seen = [this]{ + return m_sim.watch({SimWatcher::MESSAGE, SimWatcher::BATTLE_SCREEN}, TRAINER_LINE_WATCH).has_value(); + }; + const int tiles = step.action == TRAINER_LINE_VARIANT ? TRAINER_LINE_TILES : 1; + return step_until_seen(tiles, tap, seen) ? "" : "no trainer saw the player."; +} + +// A CUT_TREE_VARIANT step: turned to the tree, cut, and a step onto its +// tile. +std::string OverworldStepSim::cut(const StoryStep& step){ + const Direction direction = Pokemon::story_arg(step.args, "direction"); + if (m_sim.state().facing != direction){ + m_sim.tap(direction); + } + if (!m_sim.cut_tree()){ + return "no tree to cut."; + } + m_sim.tap(direction); + m_at = StoryPose{m_at.map, m_at.tile.next(direction), direction}; + if (!(m_sim.state().position == MapPosition{m_at.map, m_at.tile})){ + return "expected to step onto the tree's tile " + to_string(MapPosition{m_at.map, m_at.tile}) + "."; + } + return ""; +} + +// A battle from the trainer's message, which must be up, ending where the +// table says. +std::string OverworldStepSim::battle(const StoryStep& step){ + if (!m_sim.close_message() || m_sim.handle_battle(SimBattleChoice::FIGHT) != SimBattleEnd::ENDED){ + return "no_battle."; + } + m_at = *story_pose(Pokemon::pose_of(*step.pose_after)); + if (!(m_sim.state().position == MapPosition{m_at.map, m_at.tile})){ + return "expected " + to_string(MapPosition{m_at.map, m_at.tile}) + "."; + } + return ""; +} + + +std::string row_step_on_sim(OverworldSim& sim, StoryPose& at, const StoryStep& step, const std::string& id){ + OverworldStepSim executor(sim, id, at); + RunState state; + const Outcome outcome = executor.run(step, state); + at = executor.at(); + if (outcome.succeeded()){ + return ""; + } + return id + "/" + step.name + ": " + outcome.detail + " On " + to_string(sim.state().position) + "."; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h new file mode 100644 index 0000000000..e3183f1ffa --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h @@ -0,0 +1,163 @@ +/* AutoStory Row Sim + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's story on the simulation, through the same action table as the + * console (make_story_action_table()): each binding plays the actions it + * can and stubs the rest, which need the console. StoryMapsSim runs the + * whole story on the story maps; OverworldStepSim walks a row's steps on + * the OverworldSim, for the simulation tests of each stage's rows. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRowSim_H +#define PokemonAutomation_PokemonFRLG_AutoStoryRowSim_H + +#include +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRowSimStubs.h" +#include "PokemonFRLG_AutoStoryStepInterrupts.h" +#include "PokemonFRLG_AutoStoryStepTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What happens on the story maps besides the story's steps. +struct StorySimKnobs{ + // Whether a dialog pops up right before row `row`'s step `step`: + // someone walks up and talks between two steps. Until it is pressed + // through, it stops a step that walks or talks, as on the console. + std::function dialog_before = nullptr; + // Whether the executor clears what came up between steps + // (step_interrupts()), as the console does; off, as before it did. + bool clear_interrupts = true; +}; + +// The whole story on the story maps, without a walker: each ROUTE planned +// and followed from where the run stands (turning to a wall when the +// facing is unknown, as the program does), each LEGS laid out, a step +// into a trainer's line taken until a trainer can see the player, a +// READY's way to the nurse planned, the Viridian Mart's orders checked +// against its list, and a GAME leaving the player where pacing would +// (paced_pose()). The rest is stubbed. The dialogs `knobs` pops up are +// the only interrupts between steps it shows. +class StoryMapsSim : public Pokemon::TableExecutor{ +public: + // The table and guard are members, built after the base: it only keeps + // references to them until a step runs. + explicit StoryMapsSim(StorySimKnobs knobs = {}); + StoryMapsSim(const StoryMapsSim&) = delete; + void operator=(const StoryMapsSim&) = delete; + + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override; + // The step, after a dialog pops up before it if the knobs say so. + virtual Pokemon::Outcome run(const StoryStep& step, Pokemon::RunState& state) override; + // The story's actions as this simulation binds them. + const Pokemon::StoryActionTable& actions() const{ + return m_table; + } + const SimStubs& stubs() const{ + return m_stubs; + } + // What the Mart sold, by its list's names. + const std::map& bag() const{ + return m_bag; + } + // "00.03/oak: a dialog pops up before it.", and how it was cleared. + const std::vector& dialog_notes() const{ + return m_dialog_notes; + } + +protected: + // A dialog that popped up and is still up stops a step that walks or + // talks; a step that presses through text closes it. + virtual Pokemon::Outcome run_action(const StoryStep& step, Pokemon::RunState& state) override; + +private: + Pokemon::StoryAction action(StoryActionId id); + Pokemon::Outcome walk_to(const Pokemon::Pose& pose, const StoryStep& step) const; + Pokemon::Outcome legs(const Pokemon::Pose& pose, const StoryStep& step) const; + Pokemon::Outcome step_ahead(const Pokemon::Pose& pose, const StoryStep& step) const; + Pokemon::Outcome shop(const StoryStep& step); + // The screen between steps: the dialog that popped up, if one did. + Pokemon::ScreenLook look(); + StepInterruptActions sim_interrupt_actions(); + + SimStepGuard m_guard; + SimStubs m_stubs; + std::map m_bag; + Pokemon::StoryActionTable m_table; + StorySimKnobs m_knobs; + Pokemon::StoryInterrupts m_interrupts; + std::string m_row; + // A dialog popped up (StorySimKnobs::dialog_before) and is still up; + // it rose since the last look. + bool m_dialog_up = false; + bool m_dialog_rose = false; + std::vector m_dialog_notes; +}; + + +// 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); + +// A row's steps on the OverworldSim as the program does them: routes and +// legs by the sim's walker from where the table says the player stands, +// fighting a trainer who sees the player on the way; 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; a cut tree cut and stepped onto. The rest is stubbed. +class OverworldStepSim : public Pokemon::TableExecutor{ +public: + // `sim` must outlive the executor. + OverworldStepSim(OverworldSim& sim, std::string row, StoryPose at); + OverworldStepSim(const OverworldStepSim&) = delete; + void operator=(const OverworldStepSim&) = delete; + + // Where the table says the player stands: moved to where it says each + // step ends. + const StoryPose& at() const{ + return m_at; + } + const Pokemon::StoryActionTable& actions() const{ + return m_table; + } + const SimStubs& stubs() const{ + return m_stubs; + } + +private: + Pokemon::StoryAction action(StoryActionId id); + std::string walk(const StoryStep& step); + std::string step_ahead(const StoryStep& step); + std::string cut(const StoryStep& step); + std::string battle(const StoryStep& step); + + OverworldSim& m_sim; + StoryPose m_at; + SimStepGuard m_guard; + SimStubs m_stubs; + Pokemon::StoryActionTable m_table; +}; + +// Runs `step` of row `id` on `sim` through OverworldStepSim, from `at`, +// and moves `at` to where the table says the step ends. Returns the +// failure, "/: On .", or empty. +std::string row_step_on_sim(OverworldSim& sim, StoryPose& at, const StoryStep& step, const std::string& id); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSimStubs.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSimStubs.h new file mode 100644 index 0000000000..922310049e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSimStubs.h @@ -0,0 +1,65 @@ +/* AutoStory Row Sim Stubs + * + * From: https://github.com/PokemonAutomation/ + * + * What the story simulations (PokemonFRLG_AutoStoryRowSim.h) bind to the + * actions they cannot play, and how a failed step ends their run. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRowSimStubs_H +#define PokemonAutomation_PokemonFRLG_AutoStoryRowSimStubs_H + +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The steps of one attempt at a row that a simulation did not play. +struct RowStubs{ + std::string row; + std::vector steps; +}; + +// The steps a simulation stubs, by row: the stand-in it binds to each +// action it cannot play. +class SimStubs{ +public: + // An attempt at `row` begins; its stubs are listed apart from the last. + void begin_row(std::string row); + // Needs the console; adds the step to the row's stubs, then does + // `then` (what the simulation keeps of the step: where pacing leaves + // the player), or passes with the pose as it was. + Pokemon::StoryAction stub(Pokemon::StoryActionFunction then = {}); + const std::vector& rows() const{ + return m_rows; + } + +private: + void record(const Pokemon::StoryStep& step); + + std::vector m_rows; +}; + +// Each attempt's stubs, a line a row: "00.03: 2 stubbed: oak, rival". +std::string stub_report(const std::vector& rows); + +// A failed step fails the run as it threw: a simulation has no save to +// reload. +class SimStepGuard : public Pokemon::StepGuard{ +public: + virtual bool stops_on_failure(const Pokemon::StoryStep&) const override{ + return true; + } +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp index ed9a872684..9047c74ea3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp @@ -139,7 +139,7 @@ class Test_RunPlan : public UnitTest{ const RunPlanScenario m_scenario; }; -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 00.17 00.18 00.19 00.20"; +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 00.17 00.18 00.19 00.20 00.21 00.22 00.23 00.24 00.25"; const RunPlanScenario RUN_PLAN_CASES[] = { { @@ -155,8 +155,7 @@ const RunPlanScenario RUN_PLAN_CASES[] = { .expectation = {.expected_ids = "00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16"}, }, { - .input = { - .name = "SID Helper: 00.01 stops on the keyboard", + .input = { .name = "SID Helper: 00.01 stops on the keyboard", .first = "00.01", .handoffs = {.sid_helper = true}, }, @@ -231,15 +230,14 @@ const RunPlanScenario RUN_PLAN_CASES[] = { }, { .input = {.name = "Gift RNG off: 00.12b is passed over", .first = "00.11"}, - .expectation = {.expected_ids = "00.11 00.12 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16 00.17 00.18 00.19 00.20"}, + .expectation = {.expected_ids = "00.11 00.12 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16 00.17 00.18 00.19 00.20 00.21 00.22 00.23 00.24 00.25"}, }, { .input = {.name = "Gift RNG off: 00.12b runs when started at", .first = "00.12b"}, - .expectation = {.expected_ids = "00.12b 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16 00.17 00.18 00.19 00.20"}, + .expectation = {.expected_ids = "00.12b 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16 00.17 00.18 00.19 00.20 00.21 00.22 00.23 00.24 00.25"}, }, { - .input = { - .name = "Gift RNG: started at 00.12b, from the save beside the salesman", + .input = { .name = "Gift RNG: started at 00.12b, from the save beside the salesman", .first = "00.12b", .handoffs = {.gift_rng = true}, }, @@ -261,11 +259,10 @@ const RunPlanScenario RUN_PLAN_CASES[] = { }, { .input = {.name = "Starter RNG alone: 00.12b runs when started at", .first = "00.12b", .handoffs = {.starter_rng = true}}, - .expectation = {.expected_ids = "00.12b 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16 00.17 00.18 00.19 00.20"}, + .expectation = {.expected_ids = "00.12b 00.12c 00.13 00.14 00.14b 00.14c 00.15 00.15b 00.16 00.17 00.18 00.19 00.20 00.21 00.22 00.23 00.24 00.25"}, }, { - .input = { - .name = "Starter RNG first, with both on", + .input = { .name = "Starter RNG first, with both on", .first = "00.03", .handoffs = {.starter_rng = true, .gift_rng = true}, }, 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 c3a9589bdd..012da57a88 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -5,11 +5,11 @@ * A run of the whole story table, new game to the Boulder Badge, without * the console: story_checkpoints() built into engine checkpoints by the * shared builder, saving at each end as the program does, run by the - * shared runner with the program's retry policy, against a fake game. - * The fake plans each ROUTE on the story maps from where the run's pose - * says we stand (turning to a wall when the facing is unknown, as the - * program does), walks each LEGS on them, steps onto triggers, and passes - * every other step unless told to fail it. + * shared runner with the program's retry policy, on the simulation of the + * story maps (StoryMapsSim): the story's action table as the console's, + * bound to the simulation, which plans each ROUTE on the story maps from + * where the run's pose says we stand, walks each LEGS on them, steps onto + * triggers and stubs what needs the console, unless told to fail a step. * */ @@ -17,7 +17,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -32,6 +34,7 @@ #include "PokemonFRLG_AutoStoryCapture.h" #include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryPaceSim.h" +#include "PokemonFRLG_AutoStoryRowSim.h" #include "PokemonFRLG_AutoStoryStepTable.h" #include "PokemonFRLG_AutoStoryTable.h" @@ -68,70 +71,14 @@ const StoryCheckpoint& checkpoint_row(std::string_view id){ return *row; } -const MapData* map_named(const std::string& name){ - for (const MapData& map : story_maps()){ - if (map.name == name){ - return ↦ - } - } - return nullptr; -} - -// Whether the player, at the end of a WALK `step`, stops there holding on: -// the map's edge, a wall, or water to Surf onto, but no warp of any kind, -// even one to a map that isn't loaded. -bool stops_past_end(const RouteStep& step){ - const MapData& map = *map_named(step.end.map); - const TilePos here = step.end.point; - const TilePos ahead = here.next(step.direction); - if (!in_bounds(map, ahead)){ - return true; - } - if (warps_on_step(map, ahead) || exit_mat(map, here) == step.direction - || (step.direction == Direction::NORTH && is_door(map, ahead)) - ){ - return false; - } - const StepKind kind = classify_step(map, PlayerState{here, elevation_at(map, here), step.surfing}, step.direction); - return kind == StepKind::BLOCKED || kind == StepKind::START_SURF; -} - -// The first leg of `route` to a wall that holding on would carry past its -// end, or nothing (console B, 2026-11-02: one rode Route 4's Pokemon -// Center escalator). -std::optional overrun_wall_leg(const std::vector& route){ - for (const RouteStep& step : route){ - if (step.to_wall && !stops_past_end(step)){ - return to_string(step); - } - } - return std::nullopt; -} - -// Where the run stands, with a facing: a wall beside it when unknown. -struct Standing{ - MapPosition position; - Direction facing = Direction::NORTH; - std::string error; -}; -Standing standing(const Pokemon::Pose& pose){ - const std::optional at = story_pose(pose); - if (!at){ - return {{}, Direction::NORTH, "no one-tile pose: " + Pokemon::to_string(pose)}; - } - std::optional facing = at->facing; - if (!facing){ - const MapData* map = map_named(at->map); - facing = map ? wall_beside(*map, at->tile) : std::nullopt; - } - if (!facing){ - return {{}, Direction::NORTH, "facing unknown and no wall beside " + to_string(MapPosition{at->map, at->tile})}; - } - return {{at->map, at->tile}, *facing, ""}; -} - -class FakeGame : public Pokemon::StoryStepExecutor{ +// The story on the story maps (StoryMapsSim), with a trace of what ran +// and steps told to fail. +class FakeGame : public StoryMapsSim{ public: + explicit FakeGame(StorySimKnobs knobs = {}) + : StoryMapsSim(std::move(knobs)) + {} + struct Failure{ std::string failure; size_t times = 0; @@ -141,10 +88,9 @@ class FakeGame : public Pokemon::StoryStepExecutor{ std::map failures; // Where the save loaded stands, when not at its checkpoint's start. std::optional save_stands; - // What the Mart sold, by its list's names. - std::map bag; virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + StoryMapsSim::begin_attempt(data); m_row = data.id; trace.push_back("begin " + data.id); } @@ -156,136 +102,10 @@ class FakeGame : public Pokemon::StoryStepExecutor{ failure->second.times--; return Pokemon::outcome_failed(failure->second.failure, key); } - return act(state, step); - } -private: - // The step by its kind, as the console does it (StoryExecutor), with - // nothing done on a screen. - Outcome act(RunState& state, const StoryStep& step){ - switch (step.kind){ - case StoryStepKind::ROUTE: - return walk_to(state.pose, step); - case StoryStepKind::LEGS: - return legs(state, step); - case StoryStepKind::STEP: - return take_step(state, step); - case StoryStepKind::READY: - return ready(state, step); - case StoryStepKind::SHOP: - return shop(step); - case StoryStepKind::TRAIN: - case StoryStepKind::SAVE: - return Pokemon::unsupported_step(step); - default: - // Nothing on a screen; pacing leaves the player on either of - // its tiles, as on the console. - return Pokemon::outcome_ok(paced_pose(state.pose, step)); - } - } - Outcome legs(RunState& state, const StoryStep& step){ - const Standing at = standing(state.pose); - if (!at.error.empty()){ - return Pokemon::outcome_failed("no_pose", at.error); - } - const std::optional> route = fixed_route(story_maps(), at.position, Pokemon::story_arg>(step.args, "legs")); - if (!route || route->empty()){ - return Pokemon::outcome_failed("bad_legs", to_string(at.position)); - } - return Pokemon::outcome_ok(to_pose(StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after})); - } - // A step into a trainer's line goes on until a trainer can see the - // player, as step_until_seen() does on the console. - Outcome take_step(RunState& state, const StoryStep& step){ - const std::optional at = story_pose(state.pose); - if (!at){ - return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); - } - const Direction direction = Pokemon::story_arg(step.args, "direction"); - const MapData* map = map_named(at->map); - if (step.action != TRAINER_LINE_VARIANT || map == nullptr){ - return Pokemon::outcome_ok(to_pose(StoryPose{at->map, at->tile.next(direction), direction})); - } - TilePos onto = at->tile; - const std::optional stepped = step_until_seen( - TRAINER_LINE_TILES, - [&]{ onto = onto.next(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, direction})); - } - // The nurse's way must plan too, but the run goes on from where it stands. - Outcome ready(RunState& state, const StoryStep& step){ - const Outcome to_nurse = walk_to(state.pose, step); - return to_nurse.succeeded() ? Pokemon::outcome_ok() : to_nurse; - } - // The Viridian Mart's list as the game shows it. After a purchase the - // cursor stays on the row bought (console B, 2026-11-01), so each - // order moves it from there, as buy_items() does since ad5d40885. - Outcome shop(const StoryStep& step){ - const std::vector& items = Pokemon::story_arg>(step.args, "items"); - static const std::vector LIST{"poke_ball", "potion", "antidote", "parlyz_heal", "cancel"}; - const std::optional> orders = viridian_mart_orders(items); - if (!orders){ - return Pokemon::outcome_failed("unknown_item", step.name); - } - int cursor = 0; - for (size_t c = 0; c < orders->size(); c++){ - const MartOrder& order = (*orders)[c]; - // The presses: down or up from where the cursor is. - cursor += order.row - cursor; - if (cursor < 0 || cursor >= (int)LIST.size() || LIST[cursor] == "cancel"){ - return Pokemon::outcome_failed("mart_cancel", std::format("order {} ends on row {}", c + 1, cursor + 1)); - } - if (LIST[cursor] != items[c].item){ - return Pokemon::outcome_failed("wrong_item", std::format("{} instead of {}", LIST[cursor], items[c].item)); - } - bag[LIST[cursor]] += order.quantity; - } - return Pokemon::outcome_ok(); - } - - Outcome walk_to(const Pokemon::Pose& pose, const StoryStep& step){ - if (Pokemon::tiles_of(pose).size() > 1){ - // From the tiles a pacing step leaves: the route must plan, and - // test_routes_after_pacing() walks it on the sim from each. - const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target"))); - const RouteGoal goal{{target->map, target->tile}, target->facing}; - const std::optional> route = plan_story_route(story_maps(), pose, std::nullopt, goal); - if (!route || route->empty()){ - return Pokemon::outcome_failed("no_route", Pokemon::to_string(pose) + " to " + to_string(goal.position)); - } - return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, route->back().facing_after})); - } - const Standing at = standing(pose); - if (!at.error.empty()){ - return Pokemon::outcome_failed("no_pose", at.error); - } - const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target"))); - const RouteGoal goal{{target->map, target->tile}, target->facing}; - const std::optional> route = plan_overworld_route( - story_maps(), at.position, goal, default_route_costs(), at.facing - ); - if (!route){ - return Pokemon::outcome_failed("no_route", to_string(at.position) + " to " + to_string(goal.position)); - } - const MapPosition end = follow_overworld_route(story_maps(), at.position, *route); - if (!(end == goal.position)){ - return Pokemon::outcome_failed("wrong_end", to_string(end)); - } - if (const std::optional leg = overrun_wall_leg(*route)){ - return Pokemon::outcome_failed("wall_overrun", *leg); - } - const Direction facing = route->empty() ? at.facing : route->back().facing_after; - return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, facing})); + return StoryMapsSim::run(step, state); } +private: std::string m_row; }; @@ -294,6 +114,10 @@ class FakeGame : public Pokemon::StoryStepExecutor{ // run takes with every handoff off, each saving at its end (hooks.save // stands for save_game()). struct Simulation{ + explicit Simulation(StorySimKnobs knobs = {}) + : game(std::move(knobs)) + {} + std::vector rows = plan_story_run(story_checkpoints(), 0, story_checkpoints().size() - 1, StoryHandoffs{}).rows; FakeGame game; std::vector lines; @@ -354,6 +178,8 @@ struct Simulation{ struct AutoStorySimulationInput{ std::string name; UnitTestResult (*body)(); + // A body that logs, run instead of `body` if given. + UnitTestResult (*logged)(Logger&) = {}; }; struct AutoStorySimulationExpectation{ @@ -371,9 +197,9 @@ class Test_AutoStorySimulation : public UnitTest{ : UnitTest("PokemonFRLG::AutoStory - Simulation: " + scenario.input.name) , m_scenario(std::move(scenario)) {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ try{ - return m_scenario.input.body(); + return m_scenario.input.logged ? m_scenario.input.logged(logger) : m_scenario.input.body(); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } @@ -414,9 +240,9 @@ UnitTestResult test_whole_story(){ } // 00.07's shopping, with the cursor staying on each row bought. const std::map bought{{"potion", 5}, {"antidote", 3}, {"parlyz_heal", 1}}; - if (sim.game.bag != bought){ + if (sim.game.bag() != bought){ std::string text; - for (const auto& item : sim.game.bag){ + for (const auto& item : sim.game.bag()){ text += std::format(" {} {}", item.second, item.first); } return "Expected 5 Potions, 3 Antidotes and 1 Parlyz Heal; bought" + text + "."; @@ -424,6 +250,32 @@ UnitTestResult test_whole_story(){ return true; } +// The whole story through the table as the simulation binds it, each +// row's stubs logged: a step is stubbed exactly when its action needs the +// console, so no step the simulation plays is passed over. +UnitTestResult test_stubbed_steps_need_the_console(Logger& logger){ + Simulation sim; + if (!sim.run({}).completed){ + return "Expected the whole story through:" + joined(sim.lines); + } + logger.log("Steps the simulation does not play, by row:\n" + stub_report(sim.game.stubs().rows())); + for (const RowStubs& stubs : sim.game.stubs().rows()){ + const auto row = std::find_if(sim.rows.begin(), sim.rows.end(), [&](const StoryCheckpoint& data){ return data.id == stubs.row; }); + if (row == sim.rows.end()){ + return "Stubs for no row: " + stubs.row; + } + for (const StoryStep& step : row->steps){ + const Pokemon::StoryAction* action = sim.game.actions().find(step); + const bool stubbed = std::ranges::find(stubs.steps, step.name) != stubs.steps.end(); + if (action == nullptr || stubbed != action->needs_console){ + return std::format("{} {}: {}, but its action {} the console.", row->id, step.name, + stubbed ? "stubbed" : "played", action != nullptr && action->needs_console ? "needs" : "does not need"); + } + } + } + return true; +} + UnitTestResult test_start_and_end(){ Simulation sim; const Pokemon::SegmentReport report = sim.run({.from = "00.05", .to = "00.07"}); @@ -480,18 +332,6 @@ 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, Pokemon::story_arg>(step.args, "legs")); - } - const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "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. @@ -555,49 +395,6 @@ UnitTestResult test_cerulean_entry_short(){ return true; } -// Runs `step` of row `id` on `sim` as the program does: routes and legs -// by the sim's walker from `at`, where the table says the player stands, -// fighting a trainer who sees the player on the way; 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 row_step_on_sim(OverworldSim& sim, StoryPose& at, const StoryStep& step, const std::string& id){ - const std::string where = id + "/" + step.name + ": "; - const auto on = [&sim]{ return " On " + to_string(sim.state().position) + "."; }; - if (step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::ROUTE){ - 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 Direction direction = Pokemon::story_arg(step.args, "direction"); - const auto tap = [&sim, direction]{ - if (sim.state().facing != direction){ - sim.tap(direction); - } - sim.tap(direction); - }; - const auto seen = [&sim]{ - return sim.watch({SimWatcher::MESSAGE, SimWatcher::BATTLE_SCREEN}, TRAINER_LINE_WATCH).has_value(); - }; - const int tiles = step.action == 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(Pokemon::pose_of(*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 @@ -963,8 +760,59 @@ UnitTestResult test_out_of_bill_cottage(){ } +// Someone talks to the player before every step (StorySimKnobs:: +// dialog_before): cleared between steps, the whole story still passes; +// left up, as before the executor looked, a walk fails on it. +UnitTestResult test_dialog_before_every_step(){ + const auto always = [](const std::string&, const std::string&){ + return true; + }; + Simulation cleared({.dialog_before = always}); + if (!cleared.run({}).completed){ + return "Expected the story through, a dialog before every step cleared:" + joined(cleared.lines); + } + Simulation left({.dialog_before = always, .clear_interrupts = false}); + const bool completed = left.run({}).completed; + const auto stopped = [](const std::string& line){ + return line.find("is still up") != std::string::npos; + }; + if (completed || std::ranges::none_of(left.lines, stopped)){ + return "Expected a dialog left up to stop a walk:" + joined(left.lines); + } + return true; +} + +// Dialogs pop up at random before one step in five: how many whole runs +// pass with them cleared between steps, and with them left up. +UnitTestResult test_dialogs_at_random(Logger& logger){ + constexpr uint32_t SEEDS = 5; + size_t passes[2] = {0, 0}; + for (uint32_t seed = 1; seed <= SEEDS; seed++){ + for (bool clear : {false, true}){ + const auto rng = std::make_shared(seed); + Simulation sim({ + .dialog_before = [rng](const std::string&, const std::string&){ + return std::bernoulli_distribution(0.2)(*rng); + }, + .clear_interrupts = clear, + }); + passes[clear] += sim.run({}).completed ? 1 : 0; + } + } + logger.log(std::format( + "Dialogs before one step in five, {} seeds: {} passed left up, {} cleared between steps.", + SEEDS, passes[0], passes[1] + )); + if (passes[1] != SEEDS){ + return std::format("Expected every run through with the dialogs cleared, {} of {}.", passes[1], SEEDS); + } + return true; +} + + const AutoStorySimulationTestCase AUTO_STORY_SIMULATION_CASES[] = { {.input = {.name = "new game to Brock, in order, each start where the last save stood", .body = test_whole_story}, .expectation = {.description = "runs full story progression from new game through Brock gym"}}, + {.input = {.name = "the steps it stubs need the console", .body = nullptr, .logged = test_stubbed_steps_need_the_console}, .expectation = {.description = "stubs each needs-console step of the whole story and plays the rest"}}, {.input = {.name = "start and end checkpoints", .body = test_start_and_end}, .expectation = {.description = "executes segment bounded by start and end checkpoints"}}, {.input = {.name = "a failed walk reloads its checkpoint's save", .body = test_retry_from_save}, .expectation = {.description = "reloads checkpoint save state on simulated movement failure"}}, {.input = {.name = "a battle lost every time stops after 3 attempts", .body = test_gives_up_after_attempts}, .expectation = {.description = "aborts after three consecutive battle blackouts"}}, @@ -978,6 +826,8 @@ const AutoStorySimulationTestCase AUTO_STORY_SIMULATION_CASES[] = { {.input = {.name = "00.20 onto the grass out of Shane's sight, the leg west a tile short", .body = test_oddish_patch_west_short}, .expectation = {.description = "recovers when approaching grass patch with short western leg"}}, {.input = {.name = "the routes after pacing, from either of its tiles", .body = test_routes_after_pacing}, .expectation = {.description = "plans valid routes regardless of which pacing tile character ends on"}}, {.input = {.name = "a save off the start pose stops before any step", .body = test_save_off_start_pose}, .expectation = {.description = "fails the start check without walking or saving"}}, + {.input = {.name = "a dialog pops up before every step", .body = test_dialog_before_every_step}, .expectation = {.description = "cleared between steps, the story passes; left up, a walk fails on it"}}, + {.input = {.name = "dialogs pop up before one step in five, over 5 seeds", .body = nullptr, .logged = test_dialogs_at_random}, .expectation = {.description = "every run passes with them cleared"}}, }; } // namespace diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index 767ea8f311..63a23151fe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -4,6 +4,7 @@ * */ +#include #include "Common/Cpp/Exceptions.h" #include "PokemonFRLG_AutoStoryCapture.h" #include "PokemonFRLG_AutoStoryChoice.h" @@ -15,6 +16,7 @@ #include "PokemonFRLG_AutoStoryPcStorage.h" #include "PokemonFRLG_AutoStoryTeach.h" #include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryTrashCans.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -37,6 +39,10 @@ std::string_view story_action_name(StoryActionId id){ case StoryActionId::HEAL: return "heal"; case StoryActionId::SHOP: return "shop"; case StoryActionId::READY: return "ready"; + case StoryActionId::CLOSE_TRAINER_CARD: return "close_trainer_card"; + case StoryActionId::LEAVE_GIFT_SUMMARY: return "leave_gift_summary"; + case StoryActionId::CUT_TREE: return "cut_tree"; + case StoryActionId::TRASH_CANS: return "trash_cans"; case StoryActionId::GAME: return "game"; } throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown story action."); @@ -56,6 +62,10 @@ const std::vector& story_action_rows(){ {StoryStepKind::HEAL, "", StoryActionId::HEAL}, {StoryStepKind::SHOP, "", StoryActionId::SHOP}, {StoryStepKind::READY, "", StoryActionId::READY}, + {StoryStepKind::GAME, CLOSE_TRAINER_CARD, StoryActionId::CLOSE_TRAINER_CARD}, + {StoryStepKind::GAME, LEAVE_GIFT_SUMMARY, StoryActionId::LEAVE_GIFT_SUMMARY}, + {StoryStepKind::GAME, CUT_TREE_VARIANT, StoryActionId::CUT_TREE}, + {StoryStepKind::GAME, TRASH_CANS_VARIANT, StoryActionId::TRASH_CANS}, {StoryStepKind::GAME, "", StoryActionId::GAME}, }; return ROWS; @@ -131,6 +141,14 @@ Pokemon::StoryActionSpec grind_action_spec(){ }}; } +// GRIND_CHECK_ACTION's args: GRIND_ACTION's but the nurse. +Pokemon::StoryActionSpec grind_check_action_spec(){ + Pokemon::StoryActionSpec spec = grind_action_spec(); + spec.name = GRIND_CHECK_ACTION; + std::erase_if(spec.args, [](const Pokemon::StoryArgSpec& arg){ return arg.key == "nurse"; }); + return spec; +} + } // namespace std::span story_action_specs(){ @@ -156,14 +174,20 @@ std::span story_action_specs(){ run.name = "run"; specs.push_back(std::move(run)); } - Pokemon::StoryActionSpec trainer_line = *Pokemon::find_story_action(builtin, StoryStepKind::STEP, ""); - trainer_line.name = TRAINER_LINE_VARIANT; - specs.push_back(std::move(trainer_line)); + for (const std::string& name : {TRAINER_LINE_VARIANT, TRAINER_WAIT_VARIANT}){ + Pokemon::StoryActionSpec step = *Pokemon::find_story_action(builtin, StoryStepKind::STEP, ""); + step.name = name; + specs.push_back(std::move(step)); + } specs.push_back({.kind = StoryStepKind::GAME, .name = CLOSE_TRAINER_CARD, .args = {}}); specs.push_back({.kind = StoryStepKind::GAME, .name = LEAVE_GIFT_SUMMARY, .args = {}}); + specs.push_back({.kind = StoryStepKind::GAME, .name = CUT_TREE_VARIANT, .args = { + required_arg("direction", StoryArgType::DIRECTION, "the way to the tree, which the step then walks onto"), + }}); + specs.push_back({.kind = StoryStepKind::GAME, .name = TRASH_CANS_VARIANT, .args = {}}); for (Pokemon::StoryActionSpec spec : { pc_action_spec(), capture_action_spec(), fossil_action_spec(), level_action_spec(), - mart_action_spec(), teach_action_spec(), grind_action_spec(), + mart_action_spec(), teach_action_spec(), grind_action_spec(), grind_check_action_spec(), }){ specs.push_back(std::move(spec)); } @@ -181,9 +205,13 @@ Pokemon::StoryActionTable make_story_action_table(const StoryActionBinding& bind } table.add(row.kind, row.variant, std::move(action)); } - // FRLG's own GAME actions: the GAME row's action, with each one's args. + // FRLG's GAME actions without a row of their own: the GAME row's + // action, with each one's args. for (const Pokemon::StoryActionSpec& spec : story_action_specs()){ - if (spec.kind != StoryStepKind::GAME || spec.name.empty()){ + const bool has_row = std::ranges::any_of(story_action_rows(), [&](const StoryActionRow& row){ + return row.kind == spec.kind && row.variant == spec.name; + }); + if (spec.kind != StoryStepKind::GAME || spec.name.empty() || has_row){ continue; } Pokemon::StoryAction action = bind(StoryActionId::GAME); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h index bb902aadc8..1feb1136eb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h @@ -41,7 +41,20 @@ enum class StoryActionId{ HEAL, SHOP, READY, - // A GAME step: one only FRLG has. + // CLOSE_TRAINER_CARD: back from SID Helper (close_trainer_card()). + CLOSE_TRAINER_CARD, + // LEAVE_GIFT_SUMMARY: back from Gift RNG (leave_gift_summary()). + LEAVE_GIFT_SUMMARY, + // CUT_TREE_VARIANT: the tree ahead cut, and a step onto its tile. + CUT_TREE, + // TRASH_CANS_VARIANT: the search for Vermilion Gym's switches. + TRASH_CANS, + // Any other GAME step: a capture or a PC deposit or withdrawal + // (capture_step(), pc_step() in PokemonFRLG_AutoStoryCapture.h); a + // shiny met in a capture stops the program without reloading. A MART, + // TEACH, LEVEL, GRIND or fossil CHOICE + // (PokemonFRLG_AutoStoryAbilities.h); a GRIND heals by routing to its + // target, the nurse, and back. GAME, }; // "route", "game": the action's name in logs and test traces. @@ -60,10 +73,11 @@ const std::vector& story_action_rows(); // The actions FRLG's steps name, with the args each takes: the built-in // ones (Pokemon_BuiltinStoryActions.h), then a ROUTE and a LEGS named // "run" (RUN_VARIANT), which take the same args and run with B held, -// a STEP named "trainer_line" (TRAINER_LINE_VARIANT), which steps on -// until a trainer sees the player, then FRLG's GAME actions: closing the Trainer Card or the Gift RNG -// summary, a PC transfer, a capture, the fossil, a LEVEL check, a Mart, -// a TEACH and a GRIND, each with the args it declares. +// STEPs named "trainer_line" (TRAINER_LINE_VARIANT) and "trainer_wait" +// (TRAINER_WAIT_VARIANT), then FRLG's GAME actions: closing the Trainer +// Card or the Gift RNG summary, cutting a tree, the trash cans, a PC +// transfer, a capture, the fossil, a LEVEL check, a Mart, a TEACH and a +// GRIND, each with the args it declares. // A story file is read against these. std::span story_action_specs(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp index fbc9596dab..7892ea6f0b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp @@ -18,7 +18,9 @@ #include "Pokemon/AutoStory/Pokemon_StoryActions.h" #include "PokemonFRLG_AutoStoryStepInterrupts.h" #include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryTrashCans.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -36,6 +38,23 @@ const StoryStepKind ALL_KINDS[] = { StoryStepKind::SAVE, StoryStepKind::READY, StoryStepKind::GAME, }; +// The action StoryExecutor::game() ran for a GAME `step` before the table. +StoryActionId old_game_dispatch(const StoryStep& step){ + if (step.action == CLOSE_TRAINER_CARD){ + return StoryActionId::CLOSE_TRAINER_CARD; + } + if (step.action == LEAVE_GIFT_SUMMARY){ + return StoryActionId::LEAVE_GIFT_SUMMARY; + } + if (step.action == CUT_TREE_VARIANT){ + return StoryActionId::CUT_TREE; + } + if (step.action == TRASH_CANS_VARIANT){ + return StoryActionId::TRASH_CANS; + } + return StoryActionId::GAME; +} + // The action StoryExecutor ran for `step` before the table: the shared // per-kind dispatch (StoryStepExecutor::run()) into the kinds it // overrode. Nothing for the kinds it left to the shared executor. @@ -53,7 +72,7 @@ std::optional old_dispatch(const StoryStep& step){ case StoryStepKind::HEAL: return StoryActionId::HEAL; case StoryStepKind::SHOP: return StoryActionId::SHOP; case StoryStepKind::READY: return StoryActionId::READY; - case StoryStepKind::GAME: return StoryActionId::GAME; + case StoryStepKind::GAME: return old_game_dispatch(step); case StoryStepKind::TRAIN: case StoryStepKind::SAVE: return std::nullopt; @@ -113,6 +132,9 @@ std::string parity_error(FakeGame& game, const StoryStep& step){ } // Every kind, with no variant, an unknown one, and each one a row names. +// The table finds a row by the variant's first word, where game() compared +// the whole variant; the rows' variants are one word, as every authored +// step's is (test_parity_story_steps()). std::vector every_kind_and_variant(){ std::vector variants{"", "no_such_variant", "no_such_variant key=1"}; for (const StoryActionRow& row : story_action_rows()){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp index f6fe9b27cf..e61a81ab2a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp @@ -129,7 +129,9 @@ std::optional read_party_summary( if (read){ std::string moves; for (const SummaryMove& move : read->moves){ - moves += std::format("{}{} {}/{}", moves.empty() ? "" : ", ", move.move, move.pp, move.max_pp); + moves += std::format( + "{}{} {}/{}", moves.empty() ? "" : ", ", move.move.empty() ? "?" : move.move, move.pp, move.max_pp + ); } const std::string stats = read->stats ? std::format( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h index 9aeaf0fcb3..467da1a4f3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h @@ -4,9 +4,10 @@ * * FireRed from a new game to the Boulder Badge, the Running Shoes, Route * 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 + * Moon to Route 4 east of it, and on to Cerulean City, Misty, its rival, + * Nugget Bridge and Bill, then Route 6 to Vermilion City, the S.S. + * Anne's HM01 and Lt. Surge, as story checkpoints 00.01 to 00.25, 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. * * Each checkpoint is an authored JSON file in StoryData/ @@ -58,7 +59,7 @@ const std::vector>& autostory_checkpoint_jso // action args it doesn't take, or has notes for a step it doesn't have. StoryCheckpoint read_story_checkpoint_file(const JsonValue& value, std::string_view source); -// Checkpoints 00.01 to 00.16, in order: every file in StoryData/. With +// Checkpoints 00.01 to 00.25, in order: every file in StoryData/. 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, 00.12c, the Magikarp put in BOX 1, after it, 00.14b and @@ -74,6 +75,10 @@ void add_tests_AutoStory(UnitTestDatabase& database); void add_tests_AutoStoryRunPlan(UnitTestDatabase& database); // The table run end to end against a fake game (PokemonFRLG_AutoStorySimulation_Tests.cpp). void add_tests_AutoStorySimulation(UnitTestDatabase& database); +// Rows 00.21 and 00.22 on the overworld sim (PokemonFRLG_AutoStoryVermilion_Tests.cpp). +void add_tests_AutoStoryVermilion(UnitTestDatabase& database); +// Rows 00.23 to 00.25 on the overworld sim (PokemonFRLG_AutoStoryVermilionGym_Tests.cpp). +void add_tests_AutoStoryVermilionGym(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h index c73355d9d9..b89dbbdd8b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeach.h @@ -10,11 +10,12 @@ * "Teach which POKEMON?", each member ABLE or NOT ABLE. A on a member * that knows the move says so; one NOT ABLE: " and are not * compatible.". - * - " wants to learn the move ."; with fewer than four moves - * it learns. - * - With four: "However, already knows four moves.", "Should a - * move be deleted and replaced with ?" YES/NO. YES opens the - * moves page; A on a move forgets it and it learns. An HM move can't be + * - With fewer than four moves it learns, in the TM's scene ("Machine + * set!", " learned !"). + * - With four: " wants to learn the move .", "However, + * already knows four moves.", "Should a move be deleted and replaced + * with ?" YES/NO. YES opens the moves page; A on a move forgets + * it and it learns, in the same scene. An HM move can't be * forgotten (pokefirered: "HM moves can't be forgotten now.") and the * moves page shows again. B there, then "Stop trying to teach ?" * YES, leaves it unlearned. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp index 8bb1f3b329..a0685f67f7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp @@ -171,6 +171,7 @@ TeachPrompt ScreenTeachActions::member_answer(){ bool incompatible = false; bool texts = false; size_t prompts = 0; + size_t unplaced = 0; for (size_t c = 0; c < MAX_LOOKS; c++){ const TeachView view = m_screens.look(); switch (view.screen){ @@ -182,11 +183,18 @@ TeachPrompt ScreenTeachActions::member_answer(){ texts = true; press(TeachPress::A); break; + case TeachScreen::TM_SCENE: + return through_scene() ? TeachPrompt::LEARNED : TeachPrompt::FAILED; case TeachScreen::OTHER: // A tutor's party menu closes onto the overworld once learned. if (m_tutor && texts){ return TeachPrompt::LEARNED; } + // A TM's: the scene, not placed (the first look may be the + // party menu closing). + if (!m_tutor && ++unplaced > 1){ + return through_scene() ? TeachPrompt::LEARNED : TeachPrompt::FAILED; + } break; case TeachScreen::PARTY_YES_NO: return view.text == TeachText::STOP_QUESTION ? TeachPrompt::FAILED : TeachPrompt::DELETE_PROMPT; @@ -210,6 +218,38 @@ TeachPrompt ScreenTeachActions::member_answer(){ return TeachPrompt::FAILED; } +bool ScreenTeachActions::through_scene(){ + bool learned = false; + for (size_t c = 0; c < MAX_LOOKS; c++){ + const TeachView view = m_screens.look(); + switch (view.screen){ + case TeachScreen::TM_SCENE: + case TeachScreen::OTHER: + // A on every look, "learned" too: the forget's "Poof!" has + // read as "learned" (console B, 2026-11-03) and waits for A. + // The wobble and the real "learned" run on their own: an A + // then is lost, or opens the TM's menu once the TM CASE is + // back, which leave() closes. + learned |= view.text == TeachText::LEARNED; + press(TeachPress::A); + break; + case TeachScreen::TM_CASE: + case TeachScreen::ITEM_MENU: + case TeachScreen::BAG: + return true; + default: + m_logger.log(std::format("Teach: {} after the TM's scene: not learned.", teach_screen_name(view.screen)), COLOR_RED); + return false; + } + } + if (learned){ + m_logger.log("Teach: the TM CASE didn't show after \"learned\"; reading the moves will tell.", COLOR_ORANGE); + return true; + } + m_logger.log("Teach: the TM's scene didn't end.", COLOR_RED); + return false; +} + void ScreenTeachActions::answer_to_forget(const TeachView& view){ // YES to delete a move; NO to stop trying, back to the moves. if (view.text == TeachText::STOP_QUESTION){ @@ -254,10 +294,10 @@ ForgetEnd ScreenTeachActions::forget(size_t slot){ if (picked && m_tutor){ return ForgetEnd::LEARNED; } - // After the pick, its messages: B pages through them, once the - // moves page has closed (the first look). - if (picked && ++unplaced > 1){ - press(TeachPress::B); + // A TM's scene; one not placed once the moves page has closed + // (the first look). + if (picked && (view.screen == TeachScreen::TM_SCENE || ++unplaced > 1)){ + return through_scene() ? ForgetEnd::LEARNED : ForgetEnd::FAILED; } break; } @@ -300,6 +340,7 @@ void ScreenTeachActions::dump_screen(std::string_view label){ } bool ScreenTeachActions::leave(){ + bool scene_seen = false; for (size_t c = 0; c < MAX_LOOKS; c++){ const TeachView view = m_screens.look(); switch (view.screen){ @@ -307,7 +348,6 @@ bool ScreenTeachActions::leave(){ case TeachScreen::ITEM_MENU: case TeachScreen::TM_CASE: case TeachScreen::PARTY_PROMPT: - case TeachScreen::TM_SCENE: press(TeachPress::B); break; case TeachScreen::PARTY_TEXT: @@ -315,6 +355,16 @@ bool ScreenTeachActions::leave(){ case TeachScreen::KNOWN_MOVES: stop_teaching(); break; + case TeachScreen::TM_SCENE: + // B would cancel it: to its end, then out. Once: a scene + // that A didn't end is stuck. + if (scene_seen){ + m_logger.log("Teach: the TM's scene is still up.", COLOR_RED); + return false; + } + scene_seen = true; + through_scene(); + break; case TeachScreen::OTHER: return m_screens.to_overworld(); } @@ -402,6 +452,7 @@ TeachView ConsoleTeachScreens::read_view(const ImageViewRGB32& image, TeachScree case TeachScreen::PARTY_PROMPT: case TeachScreen::PARTY_TEXT: case TeachScreen::PARTY_YES_NO: + case TeachScreen::TM_SCENE: view.text = read_teach_text(logger, m_language, image); break; default: diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h index 686d5a5ba7..7ee8a1c5ce 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h @@ -13,16 +13,21 @@ * WATER PULSE x1", "No39 ROCK TOMB x1", CLOSE). * - A on a TM: USE/GIVE/EXIT, USE on top; A: the party menu, "Teach which * POKEMON?", each member ABLE or NOT ABLE, the cursor on the lead. - * - A on a member: " wants to learn the move ."; with room it - * learns. With four: "However, already knows four moves.", - * "Should a move be deleted and replaced with ?" YES/NO (YES on - * top), YES: "Which move should be forgotten?", then KNOWN MOVES with - * the four moves and the new one fifth, the red cursor on the first. A - * on a move forgets it: "1, 2 and... ... Poof!", " forgot .", - * "And... learned !", which the reader doesn't place (read - * "other"; B pages through them), then the TM CASE's list. B instead: "Stop trying to teach ?" - * YES/NO, YES: " did not learn the move ." and the TM CASE's - * list again, the TM kept. + * - A on a member with room: the TM's scene (pokefirered + * pokemon_special_anim.c), the member on pale blue diamonds: "Machine + * set!", which waits for A (B there cancels the teach), the disc's + * wobble, " learned !", then the TM CASE's list (console B, + * 00.23: HM01 to an Oddish with two free slots). With four: " + * wants to learn the move .", "However, already knows four + * moves.", "Should a move be deleted and replaced with ?" YES/NO + * (YES on top), YES: "Which move should be forgotten?", then KNOWN + * MOVES with the four moves and the new one fifth, the red cursor on + * the first. A on a move forgets it in the TM's scene: "1, 2 and... + * ... Poof!", " forgot .", "And...", each waiting for A, + * then "Machine set!" and the rest as with room. A pages through it + * all, until the TM CASE: "Poof!" has read as "learned". B on the + * moves instead: "Stop trying to teach ?" YES/NO, YES: " did not learn the move + * ." and the TM CASE's list again, the TM kept. * - From the TM CASE's list, B closes it to the bag, and B the bag. * - A move tutor (not seen on console B yet; pokefirered * move_tutors.inc): its lines and two YES/NOs in the overworld's @@ -128,6 +133,10 @@ class ScreenTeachActions : public TeachActions{ ItemOpen open_row(TeachScreen screen, std::string_view name); // After A on a member: what it showed. TeachPrompt member_answer(); + // In the TM's scene: A on each look, never B, until the TM CASE is + // back. True if it came back or "learned" showed (the moves + // read after decide); false if the party menu came back instead. + bool through_scene(); // On a YES/NO while forgetting: the answer that goes on to the moves. void answer_to_forget(const TeachView& view); void press(TeachPress press); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp index 72c6a651c6..cad2d6d3eb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp @@ -8,12 +8,20 @@ * tm03 from the TM Case": the console's steps had no readers and stopped * before the bag. * + * A TM or HM taught goes through the TM's scene (pokefirered + * pokemon_special_anim.c, Task_UseTM_NoForget / Task_ForgetMove, then + * Task_MachineSet): "Machine set!" waits for A and B cancels the teach; + * the wobble and " learned !" run on their own. Console B, + * 00.23 (2026-11-03): HM01 to an Oddish with two free slots stopped on + * "Machine set!", read as "other", and gave up. + * */ #include #include #include #include +#include #include #include #include @@ -57,6 +65,17 @@ enum class FakeScreen{ KNOWN_MOVES, // A tutor's last line in the overworld, after its party menu. TUTOR_TEXT, + // The TM's scene. + SCENE, +}; + +// A look at the TM's scene: what it shows, and whether it waits for A; +// the others pass with the look. +struct SceneStep{ + TeachText text = TeachText::UNKNOWN; + bool waits_for_a = false; + // The disc's wobble and zoom: no message box. + bool box = true; }; // The bag, TM CASE and party menu as console B showed them. @@ -80,8 +99,22 @@ struct FakeTeachGame{ FakeScreen after_texts = FakeScreen::OVERWORLD; // The messages after a move is forgotten ("1, 2 and... Poof!", "... // forgot TAIL WHIP.", "And... learned WATER PULSE!") read as "other", - // as on console B (2026-11-03). + // as on console B (2026-11-03): a tutor's over the party menu, a TM's + // whole scene. bool forget_texts_unread = false; + // The TM's scene left to show, and the move it teaches: into + // `scene_slot`, or a free slot. + std::deque scene = {}; + std::string scene_move = {}; + std::optional scene_slot = std::nullopt; + // The TM's scene reads as "other". + bool scene_unread = false; + // "1, 2, and... Poof!" reads as "learned", as on console B (TM28 to + // the Wartortle, 2026-11-03). + bool poof_reads_learned = false; + // A doesn't page the scene's boxes: it never ends. + bool scene_stuck = false; + size_t looks = 0; // The TM in use, by row. size_t tm = 0; std::vector presses = {}; @@ -127,10 +160,11 @@ std::string tm_move(const FakeTeachGame& game){ } void use_up(FakeTeachGame& game){ - if (game.tutoring){ + const std::string move = tm_move(game); + // An HM is kept. + if (game.tutoring || is_hm_move(move)){ return; } - const std::string move = tm_move(game); for (FakeTm& tm : game.tms){ if (tm.move == move && tm.count > 0){ tm.count--; @@ -139,17 +173,70 @@ void use_up(FakeTeachGame& game){ } } +// The TM's scene, after the forget's lines if any: "Machine set!", the +// wobble, " learned !", then the TM CASE. +void start_scene(FakeTeachGame& game, std::optional slot){ + game.scene.clear(); + // After a forget (pokefirered Task_ForgetMove): "1, 2, and... Poof!", + // " forgot .", "And...", each ending in \p: they wait for A. + if (slot){ + game.scene.push_back({}); + game.scene.push_back({ + .text = game.poof_reads_learned ? TeachText::LEARNED : TeachText::UNKNOWN, + .waits_for_a = true, + }); + game.scene.push_back({.waits_for_a = true}); + game.scene.push_back({.waits_for_a = true}); + } + game.scene.push_back({.text = TeachText::MACHINE_SET, .waits_for_a = true}); + game.scene.push_back({.box = false}); + game.scene.push_back({.box = false}); + game.scene.push_back({.text = TeachText::LEARNED}); + game.scene.push_back({.text = TeachText::LEARNED}); + game.scene_move = tm_move(game); + game.scene_slot = slot; + game.scene_unread |= slot && game.forget_texts_unread; + game.screen = FakeScreen::SCENE; +} + +// The scene's step passed: at its end the move is learned. +void next_scene_step(FakeTeachGame& game){ + game.scene.pop_front(); + if (!game.scene.empty()){ + return; + } + if (game.scene_slot){ + game.moves[*game.scene_slot] = game.scene_move; + }else{ + game.moves.push_back(game.scene_move); + } + use_up(game); + game.screen = FakeScreen::TM_CASE; + game.cursor = game.tm; +} + +void press_scene(FakeTeachGame& game, TeachPress press){ + if (press == TeachPress::B){ + game.error = "B cancelled the TM's scene"; + }else if (press == TeachPress::A && game.scene.front().waits_for_a && !game.scene_stuck){ + next_scene_step(game); + } +} + void choose_member(FakeTeachGame& game){ const std::string move = tm_move(game); if (!game.compatible.contains(move)){ show_texts(game, {TeachText::NOT_COMPATIBLE}, FakeScreen::PROMPT); return; } + if (game.moves.size() < MOVE_SLOTS && !game.tutoring){ + start_scene(game, std::nullopt); + return; + } if (game.moves.size() < MOVE_SLOTS){ game.moves.push_back(move); - use_up(game); game.cursor = 0; - show_texts(game, {TeachText::WANTS_TO_LEARN, TeachText::UNKNOWN}, after_party(game)); + show_texts(game, {TeachText::LEARNED}, after_party(game)); return; } show_texts(game, {TeachText::WANTS_TO_LEARN, TeachText::KNOWS_FOUR}, FakeScreen::DELETE_YES_NO); @@ -246,6 +333,10 @@ void press_known_moves(FakeTeachGame& game, TeachPress press){ if (is_hm_move(game.moves[game.cursor])){ return; } + if (!game.tutoring){ + start_scene(game, game.cursor); + return; + } game.moves[game.cursor] = tm_move(game); use_up(game); show_texts(game, {TeachText::UNKNOWN, TeachText::UNKNOWN, TeachText::UNKNOWN}, after_party(game)); @@ -271,6 +362,7 @@ void press_game(FakeTeachGame& game, TeachPress press){ case FakeScreen::DELETE_YES_NO: case FakeScreen::STOP_YES_NO: press_yes_no(game, press); return; case FakeScreen::KNOWN_MOVES: press_known_moves(game, press); return; + case FakeScreen::SCENE: press_scene(game, press); return; case FakeScreen::PROMPT: if (press == TeachPress::A){ choose_member(game); @@ -319,6 +411,13 @@ TeachView view_of(const FakeTeachGame& game){ return {.screen = TeachScreen::PARTY_YES_NO, .cursor = game.cursor, .text = TeachText::STOP_QUESTION}; case FakeScreen::KNOWN_MOVES: return {.screen = TeachScreen::KNOWN_MOVES, .cursor = game.cursor}; + case FakeScreen::SCENE:{ + const SceneStep& step = game.scene.front(); + if (game.scene_unread || !step.box){ + return {}; + } + return {.screen = TeachScreen::TM_SCENE, .text = step.text}; + } } return {}; } @@ -349,7 +448,14 @@ class FakeTeachScreens : public TeachScreens{ return true; } virtual TeachView look() override{ - return view_of(m_game); + if (++m_game.looks > 1000){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "more than 1000 looks"); + } + const TeachView view = view_of(m_game); + if (m_game.screen == FakeScreen::SCENE && !m_game.scene.front().waits_for_a){ + next_scene_step(m_game); + } + return view; } virtual void press(TeachPress press) override{ m_game.presses.emplace_back(teach_press_name(press)); @@ -396,9 +502,31 @@ void left_on_poke_balls(FakeTeachGame& game){ void three_moves(FakeTeachGame& game){ game.moves = {"bite", "bubble", "withdraw"}; } +void three_moves_scene_unread(FakeTeachGame& game){ + three_moves(game); + game.scene_unread = true; +} +// 00.23 on console B: HM01 to the Oddish (slot 2), ABSORB and SWEET +// SCENT. +void oddish_cut(FakeTeachGame& game){ + game.tms = {{"water-pulse", 1}, {"cut", 1}}; + game.moves = {"absorb", "sweet-scent"}; + game.compatible.insert("cut"); +} +// Next in the row: TM28 DIG over a move of the Wartortle's four. +void wartortle_dig(FakeTeachGame& game){ + game.tms = {{"water-pulse", 1}, {"dig", 1}}; + game.compatible.insert("dig"); +} void no_tm03(FakeTeachGame& game){ game.tms = {{"rock-tomb", 1}}; } +// Console B, 2026-11-03: the step stopped pressing on "Poof!" read as +// "learned", and waited 5 minutes. +void wartortle_dig_poof_learned(FakeTeachGame& game){ + wartortle_dig(game); + game.poof_reads_learned = true; +} void forget_texts_unread(FakeTeachGame& game){ game.forget_texts_unread = true; } @@ -458,6 +586,39 @@ std::vector screens_cases(){ }; } +// The TM's scene, with a free slot and after a forget, for a TM and an HM. +std::vector scene_screens_cases(){ + return { + { + .name = "a free slot, the TM's scene read as other", + .setup = three_moves_scene_unread, + .plan = {.item = "tm03", .move = "water-pulse", .member = 0}, + .moves = {"bite", "bubble", "withdraw", "water-pulse"}, + }, + { + .name = "console B 00.23: HM01 to the Oddish, two free slots", + .setup = oddish_cut, + .plan = {.item = "hm01", .move = "cut", .member = 1}, + .moves = {"absorb", "sweet-scent", "cut"}, + .tm03 = 1, + }, + { + .name = "TM28 DIG over WITHDRAW", + .setup = wartortle_dig, + .plan = {.item = "tm28", .move = "dig", .member = 0, .forget_move = "withdraw"}, + .moves = {"bite", "tail-whip", "bubble", "dig"}, + .tm03 = 1, + }, + { + .name = "console B: TM28 DIG over WITHDRAW, \"Poof!\" read as \"learned\"", + .setup = wartortle_dig_poof_learned, + .plan = {.item = "tm28", .move = "dig", .member = 0, .forget_move = "withdraw"}, + .moves = {"bite", "tail-whip", "bubble", "dig"}, + .tm03 = 1, + }, + }; +} + // Route 4's Mega Kick tutor: the TM03 still in the TM CASE after each. std::vector tutor_screens_cases(){ return { @@ -531,8 +692,32 @@ UnitTestResult check_screens_case(const ScreensCase& item){ return true; } +// A TM's scene that A doesn't page: the step gives up within a few +// scenes' looks, not one per leave() look. +UnitTestResult test_stuck_scene(){ + QuietLogger logger; + FakeTeachGame game; + wartortle_dig(game); + game.scene_stuck = true; + FakeTeachScreens screens(game); + ScreenTeachActions actions(logger, screens); + const MemberReader reader = [&game](size_t) -> std::optional{ + return MemberInfo{.species = "wartortle", .level = 22, .moves = game.moves}; + }; + const TeachPlan plan{.item = "tm28", .move = "dig", .member = 0, .forget_move = "withdraw"}; + const TeachResult result = run_teach(logger, actions, reader, plan); + if (result.end != TeachEnd::FAILED){ + return std::format("a stuck scene ended {} ({}).", teach_end_name(result.end), result.detail); + } + // The scene's looks: once in forget(), once in leave(). + if (game.looks > 150){ + return std::format("a stuck scene took {} looks.", game.looks); + } + return true; +} + UnitTestResult test_screens(){ - for (const std::vector& cases : {screens_cases(), tutor_screens_cases()}){ + for (const std::vector& cases : {screens_cases(), scene_screens_cases(), tutor_screens_cases()}){ for (const ScreensCase& item : cases){ const UnitTestResult result = check_screens_case(item); if (result.result != UnitTestResult::PASSED){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerLine.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerLine.h index 244178f9dc..a2d1511508 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerLine.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerLine.h @@ -37,6 +37,10 @@ std::optional step_until_seen(int max_tiles, const std::function& s // with no tiles to walk up (PokemonFRLG_OverworldRecoveryWalk.cpp). inline constexpr Milliseconds TRAINER_LINE_WATCH(2500); +// How long a step into the line of a trainer who looks around waits for +// them to turn to the player (TRAINER_WAIT_VARIANT). +inline constexpr Milliseconds TRAINER_WAIT_WATCH(30000); + // 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 @@ -45,12 +49,26 @@ inline const std::string TRAINER_LINE_VARIANT = "trainer_line"; // Maximum tiles to step into a trainer's line of sight. inline constexpr int TRAINER_LINE_TILES = 3; +// The variant of a STEP into the line of a trainer who looks around +// (MOVEMENT_TYPE_LOOK_AROUND): one tile, then a wait of up to +// TRAINER_WAIT_WATCH for the trainer to turn to the player. Indoors, where +// the player can't run, such a trainer turns a random way every 32 to 128 +// frames (pokefirered event_object_movement.c, MovementType_LookAround; +// it turns to the player only when the player runs), so they face the +// player within 30 s all but about 1 time in 500; and the game checks +// their sight every frame (ProcessPlayerFieldInput()), not only after a +// step. Stepped into from outside their sight onto the second tile of +// their line, the player is always seen there, and the trainer walks up +// one tile. +inline const std::string TRAINER_WAIT_VARIANT = "trainer_wait"; + // 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. +// unless `facing` is `direction`, each step watched `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 + Pokemon::Direction direction, std::optional facing, int max_tiles, + Milliseconds watch = TRAINER_LINE_WATCH ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCanLayout.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCanLayout.h new file mode 100644 index 0000000000..55bae87db6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCanLayout.h @@ -0,0 +1,63 @@ +/* AutoStory Trash Can Layout + * + * From: https://github.com/PokemonAutomation/ + * + * Where Vermilion Gym's fifteen trash cans stand, which are beside each + * other, and where the player stands to check one + * (PokemonFRLG_AutoStoryTrashCans.h has the search). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryTrashCanLayout_H +#define PokemonAutomation_PokemonFRLG_AutoStoryTrashCanLayout_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The GAME step that opens Vermilion Gym's door. +inline const std::string TRASH_CANS_VARIANT = "trash_cans"; + +// Total number of trash cans in Vermilion Gym. +inline constexpr int TRASH_CAN_COUNT = 15; + +// Can `can`'s tile (1-15). +Pokemon::TilePos trash_can_tile(int can); + +// The cans the second switch may be under when the first is under `can` +// (SetVermilionTrashCans()'s cases). +std::vector trash_can_neighbors(int can); + +// Where the player stands to check `can`, facing it: the row above it. +// Rows 9, 11 and 13 run the gym's width, clear of the trainers where +// their battles leave them (PokemonFRLG_AutoStoryTableVermilionGym.cpp). +struct TrashCanStand{ + Pokemon::TilePos tile; + Pokemon::Direction facing = Pokemon::Direction::SOUTH; +}; +// Position and facing to inspect a trash can. +TrashCanStand trash_can_stand(int can); + +// `maps` with Vermilion Gym's trainers where their battles in 00.23 leave +// them, beaten (PokemonFRLG_AutoStoryTableVermilionGym.cpp): Sailor +// Dwayne on (8, 14), Engineer Baily on (2, 12), Gentleman Tucker on +// (6, 8). The search plans its walks between the cans on these, not on +// the maps' tiles for them, which are free once they have walked up. +std::vector trash_can_maps(const std::vector& maps); + +// The order the search checks the cans: along row 10 east, row 12 west, +// row 14 east. +const std::vector& trash_can_order(); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.cpp new file mode 100644 index 0000000000..05fee29a88 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.cpp @@ -0,0 +1,154 @@ +/* AutoStory Trash Cans + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "PokemonFRLG_AutoStoryTrashCans.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::Direction; +using Pokemon::TilePos; + + +TilePos trash_can_tile(int can){ + return TilePos{1 + 2 * ((can - 1) % 5), 10 + 2 * ((can - 1) / 5)}; +} + +std::vector trash_can_neighbors(int can){ + const int column = (can - 1) % 5; + std::vector cans; + if (can > 5){ + cans.push_back(can - 5); + } + if (column < 4){ + cans.push_back(can + 1); + } + if (can <= 10){ + cans.push_back(can + 5); + } + if (column > 0){ + cans.push_back(can - 1); + } + return cans; +} + +TrashCanStand trash_can_stand(int can){ + const TilePos tile = trash_can_tile(can); + return TrashCanStand{TilePos{tile.x, tile.y - 1}, Direction::SOUTH}; +} + +const std::vector& trash_can_order(){ + static const std::vector ORDER{1, 2, 3, 4, 5, 10, 9, 8, 7, 6, 11, 12, 13, 14, 15}; + return ORDER; +} + +std::vector trash_can_maps(const std::vector& maps){ + struct Moved{ + std::string_view name; + TilePos tile; + }; + static constexpr Moved MOVED[] = { + {"sailor", {8, 14}}, + {"balding_man", {2, 12}}, + {"gentleman", {6, 8}}, + }; + std::vector moved = maps; + for (Pokemon::MapData& map : moved){ + if (map.name != "VermilionCity_Gym"){ + continue; + } + for (Pokemon::MapObject& object : map.objects){ + for (const Moved& trainer : MOVED){ + if (object.name == trainer.name){ + object.x = trainer.tile.x; + object.y = trainer.tile.y; + object.trainer.reset(); + } + } + } + } + return moved; +} + +std::string_view trash_can_end_name(TrashCanEnd end){ + switch (end){ + case TrashCanEnd::OPENED: return "opened"; + case TrashCanEnd::GAVE_UP: return "gave_up"; + case TrashCanEnd::FAILED: return "failed"; + } + return "?"; +} + + +namespace{ + +// The guess beside `first`: the next can in the search order, as the +// player is likely to walk that way anyway, else the first beside it. +int guess_beside(int first){ + const std::vector beside = trash_can_neighbors(first); + const std::vector& order = trash_can_order(); + const size_t at = std::find(order.begin(), order.end(), first) - order.begin(); + for (size_t c = 1; c < order.size(); c++){ + const int next = order[(at + c) % order.size()]; + if (std::find(beside.begin(), beside.end(), next) != beside.end()){ + return next; + } + } + return beside[0]; +} + +} // namespace + + +TrashCanResult run_trash_cans(Logger& logger, const CheckCan& check, size_t max_checks){ + TrashCanResult result; + const std::vector& order = trash_can_order(); + size_t next = 0; + std::optional first; + while (result.checks < max_checks){ + const int can = first ? guess_beside(*first) : order[next]; + const CanPages pages = check(can); + result.checks++; + result.last_can = can; + if (pages == CanPages::FAILED){ + logger.log(std::format("Trash cans: checking can {} failed.", can), COLOR_RED); + result.end = TrashCanEnd::FAILED; + return result; + } + if (!first){ + if (pages == CanPages::TWO){ + logger.log(std::format("Trash cans: the first switch is under can {}; the second may be under {} of the cans beside it.", can, trash_can_neighbors(can).size())); + first = can; + }else{ + next = (next + 1) % order.size(); + } + continue; + } + if (pages == CanPages::ONE){ + logger.log(std::format("Trash cans: the second switch is under can {}: the door is open, after {} checks and {} resets.", can, result.checks, result.resets)); + result.end = TrashCanEnd::OPENED; + return result; + } + // Reset: the new first switch is as likely under this can as any. + result.resets++; + logger.log(std::format("Trash cans: not under can {}; the locks reset ({}).", can, result.resets)); + first.reset(); + next = std::find(order.begin(), order.end(), can) - order.begin(); + } + logger.log(std::format("Trash cans: the door is still shut after {} checks.", result.checks), COLOR_RED); + result.end = TrashCanEnd::GAVE_UP; + return result; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.h new file mode 100644 index 0000000000..3a1bdad4d2 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.h @@ -0,0 +1,109 @@ +/* AutoStory Trash Cans + * + * From: https://github.com/PokemonAutomation/ + * + * Vermilion Gym's door switches (pokefirered data/maps/VermilionCity_Gym/ + * scripts.inc, src/field_specials.c SetVermilionTrashCans()). Fifteen + * cans stand in three rows of five, numbered 1-5 on row 10, 6-10 on row + * 12 and 11-15 on row 14, at x 1, 3, 5, 7, 9. Each time the player + * enters the gym the first switch goes under a can drawn at random, and + * the second under one of the cans beside it in the rows (left, right, + * above, below), each as likely. A can answers A from any side: + * + * - Before the first switch: "Nope! There's only trash here." (one page), + * or "Hey! There's a switch under the trash! Turn it on!" and "The first + * electric lock opened!" (two pages). + * - After it: "The second electric lock opened! The motorized door + * opened!" (one page): the beams across rows 6 and 7 go off for good + * (FLAG_FOUND_BOTH_VERMILION_GYM_SWITCHES). Or "Nope! There's only + * trash here." and "Hey! The electric locks were reset!" (two pages): + * both switches are drawn again, the first anywhere. The can that had + * the first switch counts as a wrong one. + * + * So in either state the number of pages tells the two answers apart, + * with no text read. Leaving the gym draws the switches again too; a + * battle doesn't (the first switch is a FLAG_TEMP, kept until the map + * changes). + * + * The search: the cans in a snake along the rows until one has two + * pages; then one guess beside it. A wrong guess draws both switches + * again, so the search goes on from the can the player stands at, which + * is as likely as any to have the new first switch. A guess is right + * 1 time in 2 to 4 (about 36% over the 15 cans), so the gym opens after + * about 3 rounds of about 9 cans; TRASH_CAN_MAX_CHECKS gives up after + * about 20 rounds (left 1 time in 10000). + * + * The decisions take their game step as a CheckCan, so they run in tests + * against a fake gym; on the console the step walks to the can + * and counts its pages (PokemonFRLG_AutoStoryEvents.cpp). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryTrashCans_H +#define PokemonAutomation_PokemonFRLG_AutoStoryTrashCans_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_AutoStoryTrashCanLayout.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Maximum number of trash can inspections before aborting. +inline constexpr size_t TRASH_CAN_MAX_CHECKS = 200; + +// What a can's message came to. +enum class CanPages{ + ONE, + TWO, + // The walk to the can or its message failed. + FAILED, +}; + +// The game step the search takes, injected so its decisions run in +// tests: from the overworld in the gym, to `can`'s stand, A on the can, +// its message to the overworld. +using CheckCan = std::function; + +// Termination reason for trash can search. +enum class TrashCanEnd{ + // The second lock opened. + OPENED, + // TRASH_CAN_MAX_CHECKS checks without it. + GAVE_UP, + FAILED, +}; +// String name for trash can search termination reason. +std::string_view trash_can_end_name(TrashCanEnd end); + +// Result summary of trash can search run. +struct TrashCanResult{ + TrashCanEnd end = TrashCanEnd::FAILED; + size_t checks = 0; + // Wrong guesses: the locks reset. + size_t resets = 0; + // The can checked last, where the player stands. + int last_can = 0; +}; + +// Searches the cans as above until the second lock opens, from the +// overworld in the gym with neither switch found since the player came +// in. +TrashCanResult run_trash_cans(Logger& logger, const CheckCan& check, size_t max_checks = TRASH_CAN_MAX_CHECKS); + +// Registers Vermilion Gym trash can puzzle unit tests. +void add_tests_AutoStoryTrashCans(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans_Tests.cpp new file mode 100644 index 0000000000..58122423af --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans_Tests.cpp @@ -0,0 +1,305 @@ +/* AutoStory Trash Cans Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The trash can search against a fake Vermilion Gym that draws its + * switches as SetVermilionTrashCans() does and answers each can with the + * pages its message has (PokemonFRLG_AutoStoryTrashCans.h). + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryTrashCans.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +struct AutoStoryTrashCansInput{ + std::string name; + std::function body; +}; + +struct AutoStoryTrashCansExpectation{ +}; + +struct AutoStoryTrashCansCase{ + AutoStoryTrashCansInput input; + AutoStoryTrashCansExpectation expectation; +}; + +class Test_AutoStoryTrashCans : public UnitTest{ +public: + explicit Test_AutoStoryTrashCans(AutoStoryTrashCansCase test_case) + : UnitTest("PokemonFRLG::AutoStoryTrashCans - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.body(); + } + +private: + AutoStoryTrashCansCase m_case; +}; + +using Switches = std::pair; + +// SetVermilionTrashCans()'s second switch for each first one, as its +// cases add to the first: 1 +1 or +5; 2-4 +1, +5 or -1; 5 +5 or -1; 6 -5, +// +1 or +5; 7-9 -5, +1, +5 or -1; 10 -5, +5 or -1; 11 -5 or +1; 12-14 -5, +// +1 or -1; 15 -5 or -1. +std::vector decomp_offsets(int first){ + switch (first){ + case 1: return {+1, +5}; + case 2: case 3: case 4: return {+1, +5, -1}; + case 5: return {+5, -1}; + case 6: return {-5, +1, +5}; + case 7: case 8: case 9: return {-5, +1, +5, -1}; + case 10: return {-5, +5, -1}; + case 11: return {-5, +1}; + case 12: case 13: case 14: return {-5, +1, -1}; + default: return {-5, -1}; + } +} + +Switches draw(std::mt19937& rng){ + const int first = 1 + static_cast(rng() % 15); + const std::vector offsets = decomp_offsets(first); + return {first, first + offsets[rng() % offsets.size()]}; +} + +// The gym's cans as its scripts answer them. +class FakeGym{ +public: + explicit FakeGym(std::function draw) + : m_draw(std::move(draw)) + , m_switches(m_draw()) + {} + + CanPages check(int can){ + checked.push_back(can); + if (can == fail_at){ + return CanPages::FAILED; + } + if (open){ + return CanPages::ONE; + } + if (!m_first_found){ + m_first_found = can == m_switches.first; + return m_first_found ? CanPages::TWO : CanPages::ONE; + } + if (can == m_switches.second){ + open = true; + return CanPages::ONE; + } + m_first_found = false; + m_switches = m_draw(); + return CanPages::TWO; + } + + std::vector checked; + bool open = false; + int fail_at = 0; + +private: + std::function m_draw; + Switches m_switches; + bool m_first_found = false; +}; + +// Draws `script` in order, then the game's draws. +std::function scripted(std::vector script, uint32_t seed = 1){ + auto rng = std::make_shared(seed); + auto next = std::make_shared(0); + return [script = std::move(script), rng, next]{ + return *next < script.size() ? script[(*next)++] : draw(*rng); + }; +} + +UnitTestResult test_cans_and_neighbors(){ + for (int can = 1; can <= TRASH_CAN_COUNT; can++){ + std::set expected; + for (int offset : decomp_offsets(can)){ + expected.insert(can + offset); + } + const std::vector beside = trash_can_neighbors(can); + if (std::set(beside.begin(), beside.end()) != expected){ + return std::format("Can {}: the cans beside it differ from SetVermilionTrashCans().", can); + } + // Beside: one tile apart on the map but for the can between. + const Pokemon::TilePos tile = trash_can_tile(can); + for (int other : beside){ + const Pokemon::TilePos there = trash_can_tile(other); + if (std::abs(there.x - tile.x) + std::abs(there.y - tile.y) != 2){ + return std::format("Cans {} and {} aren't two tiles apart.", can, other); + } + } + const TrashCanStand stand = trash_can_stand(can); + if (stand.tile.next(stand.facing) != tile){ + return std::format("Can {}'s stand doesn't face it.", can); + } + } + if (!(trash_can_tile(1) == Pokemon::TilePos{1, 10}) || !(trash_can_tile(15) == Pokemon::TilePos{9, 14})){ + return "Cans 1 and 15 aren't at (1, 10) and (9, 14), the gym's TrashCan1 and TrashCan15."; + } + std::vector order = trash_can_order(); + std::sort(order.begin(), order.end()); + for (int can = 1; can <= TRASH_CAN_COUNT; can++){ + if (order[can - 1] != can){ + return "The search order isn't every can once."; + } + } + return true; +} + +// The guess beside the first switch is right: the search ends there. +UnitTestResult test_right_guess(){ + QuietLogger logger; + FakeGym gym(scripted({{3, 4}})); + const TrashCanResult result = run_trash_cans(logger, [&](int can){ return gym.check(can); }); + const std::vector expected{1, 2, 3, 4}; + if (result.end != TrashCanEnd::OPENED || gym.checked != expected || result.resets != 0 || result.last_can != 4 || !gym.open){ + return std::format("Expected 1, 2, 3 then 4, open, got {} after {} checks.", trash_can_end_name(result.end), result.checks); + } + return true; +} + +// The guess is wrong: the locks reset and both switches are drawn again; +// the search goes on from the can the player stands at, finds the new +// first switch and guesses again. +UnitTestResult test_wrong_guess_resets(){ + QuietLogger logger; + // First under 3, second under 8: the guess, 4, is wrong. Then first + // under 4 (where the player stands), second under 5. + FakeGym gym(scripted({{3, 8}, {4, 5}})); + const TrashCanResult result = run_trash_cans(logger, [&](int can){ return gym.check(can); }); + const std::vector expected{1, 2, 3, 4, 4, 5}; + if (result.end != TrashCanEnd::OPENED || gym.checked != expected || result.resets != 1){ + std::string text; + for (int can : gym.checked){ + text += " " + std::to_string(can); + } + return std::format("Expected 1 2 3 4 4 5 with a reset, got{} ({}).", text, trash_can_end_name(result.end)); + } + // The new first switch further on: the search walks on from there. + FakeGym further(scripted({{3, 8}, {13, 14}})); + const TrashCanResult on = run_trash_cans(logger, [&](int can){ return further.check(can); }); + const std::vector walked{1, 2, 3, 4, 4, 5, 10, 9, 8, 7, 6, 11, 12, 13, 14}; + if (on.end != TrashCanEnd::OPENED || further.checked != walked){ + return "Expected the search to go on from can 4 to 13, then 14."; + } + return true; +} + +// Every first switch, with every second beside it: the door opens, the +// wrong guesses' draws as the game makes them. +UnitTestResult test_every_pair_opens(){ + QuietLogger logger; + uint32_t seed = 1; + for (int first = 1; first <= TRASH_CAN_COUNT; first++){ + for (int offset : decomp_offsets(first)){ + FakeGym gym(scripted({{first, first + offset}}, seed++)); + const TrashCanResult result = run_trash_cans(logger, [&](int can){ return gym.check(can); }); + if (result.end != TrashCanEnd::OPENED || !gym.open){ + return std::format("First {}, second {}: {} after {} checks.", first, first + offset, trash_can_end_name(result.end), result.checks); + } + } + } + return true; +} + +// 10000 gyms as the game draws them: the checks it takes, and how often +// TRASH_CAN_MAX_CHECKS isn't enough. +UnitTestResult test_many_gyms(){ + QuietLogger logger; + std::mt19937 rng(7); + size_t total = 0; + size_t gave_up = 0; + size_t most = 0; + constexpr size_t GYMS = 10000; + for (size_t c = 0; c < GYMS; c++){ + FakeGym gym([&rng]{ return draw(rng); }); + const TrashCanResult result = run_trash_cans(logger, [&](int can){ return gym.check(can); }); + gave_up += result.end != TrashCanEnd::OPENED; + total += result.checks; + most = std::max(most, result.checks); + } + const double mean = static_cast(total) / GYMS; + if (gave_up > 2 || mean < 15 || mean > 35){ + return std::format("Expected about 25 checks a gym and next to no give-ups, got {:.1f} checks, {} give-ups, at most {}.", mean, gave_up, most); + } + return true; +} + +UnitTestResult test_failed_check_stops(){ + QuietLogger logger; + FakeGym gym(scripted({{9, 14}})); + gym.fail_at = 3; + const TrashCanResult result = run_trash_cans(logger, [&](int can){ return gym.check(can); }); + if (result.end != TrashCanEnd::FAILED || result.checks != 3 || gym.checked.back() != 3){ + return "Expected the search to stop at the failed check of can 3."; + } + return true; +} + +} // namespace + + +const AutoStoryTrashCansCase AUTO_STORY_TRASH_CANS_CASES[] = { + { + .input = {"cans, the cans beside each and their stands match the gym", test_cans_and_neighbors}, + .expectation = {}, + }, + { + .input = {"a right guess opens the door", test_right_guess}, + .expectation = {}, + }, + { + .input = {"a wrong guess resets, the search goes on from there", test_wrong_guess_resets}, + .expectation = {}, + }, + { + .input = {"every first and second switch opens the door", test_every_pair_opens}, + .expectation = {}, + }, + { + .input = {"10000 gyms as the game draws them", test_many_gyms}, + .expectation = {}, + }, + { + .input = {"a failed check stops the search", test_failed_check_stops}, + .expectation = {}, + }, +}; + +void add_tests_AutoStoryTrashCans(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_TRASH_CANS_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVermilionGym_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVermilionGym_Tests.cpp new file mode 100644 index 0000000000..c73b72b976 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVermilionGym_Tests.cpp @@ -0,0 +1,463 @@ +/* AutoStory Vermilion Gym Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Rows 00.23 to 00.25 (StoryData/frlg-00.23..25.plan.json) on the + * overworld sim: the tree cut on the way in and out, the gym's three + * trainers fought where the table says, the trash can search walking + * between the cans clear of where the trainers stand after their battles + * (the switches found at once, and after a wrong can's reset), and Lt. + * Surge reached through the beams. And the sim's chance against Surge. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryGrind.h" +#include "PokemonFRLG_AutoStoryParty.h" +#include "PokemonFRLG_AutoStoryRowSim.h" +#include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryTrashCans.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class QuietLogger : public Logger{ +public: + using Logger::log; + virtual void log(const std::string&, Color) override{} +}; + +struct AutoStoryVermilionGymInput{ + std::string name; + std::function body; +}; + +struct AutoStoryVermilionGymExpectation{ +}; + +struct AutoStoryVermilionGymCase{ + AutoStoryVermilionGymInput input; + AutoStoryVermilionGymExpectation expectation; +}; + +class Test_AutoStoryVermilionGym : public UnitTest{ +public: + explicit Test_AutoStoryVermilionGym(AutoStoryVermilionGymCase test_case) + : UnitTest("PokemonFRLG::AutoStory - Simulation: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_case.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryVermilionGymCase m_case; +}; + +const std::string GYM = "VermilionCity_Gym"; +const std::string ROUTE6 = "Route6"; +const std::string VERMILION = "VermilionCity"; +const std::string VERMILION_CENTER = "VermilionCity_PokemonCenter_1F"; + +const StoryCheckpoint& checkpoint(std::string_view id){ + const std::vector& rows = story_checkpoints(); + const auto row = std::find_if(rows.begin(), rows.end(), [&](const StoryCheckpoint& data){ return data.id == id; }); + if (row == rows.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No checkpoint {}.", id)); + } + return *row; +} + +size_t step_index(const StoryCheckpoint& row, const std::string& name){ + const auto step = std::find_if(row.steps.begin(), row.steps.end(), [&](const StoryStep& data){ return data.name == name; }); + if (step == row.steps.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + row.id + "/" + name + "."); + } + return step - row.steps.begin(); +} + +std::string beaten_list(const OverworldSim& sim){ + std::string text; + for (const std::string& name : sim.state().trainers_beaten){ + text += " " + name; + } + return text.empty() ? " none" : text; +} + +MapData& map_named(std::vector& maps, const std::string& name){ + for (MapData& map : maps){ + if (map.name == name){ + return map; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No map " + name + "."); +} + +// `maps` with the trainers beaten that rows before 00.24 fought: Route +// 6's Jeff (00.21) and Vermilion Gym's three (00.23). +std::vector maps_after_gym(std::vector maps = story_maps()){ + for (MapObject& object : map_named(maps, GYM).objects){ + object.trainer.reset(); + } + for (MapObject& object : map_named(maps, ROUTE6).objects){ + if (object.name == "camper" && object.trainer){ + object.trainer.reset(); + } + } + return maps; +} + +// maps_after_gym() with Oak's aide on Vermilion City's (25, 7): Lt. +// Surge's win shows him (VermilionCity_Gym_EventScript_ShowOaksAide), +// and he stays until talked to (VermilionCity_EventScript_HideOaksAide). +std::vector maps_after_surge(){ + const std::vector all = overworld_maps(); + std::set flags = map_flag_set(all, "after_hall_of_fame"); + flags.merge(map_flag_set(all, "new_game")); + flags.erase("FLAG_HIDE_VERMILION_CITY_OAKS_AIDE"); + return maps_after_gym(overworld_maps(flags)); +} + +// The walk to `can`'s stand on `sim` as the trash can step plans it, on +// trash_can_maps(): ends there facing the can, or says why not. +std::string walk_to_stand(OverworldSim& sim, StoryPose& at, int can){ + static const std::vector MAPS = trash_can_maps(story_maps()); + const TrashCanStand stand = trash_can_stand(can); + const MapPosition start{at.map, at.tile}; + const std::optional> route = plan_overworld_route( + MAPS, start, RouteGoal{{GYM, stand.tile}, stand.facing}, story_route_costs(), at.facing + ); + if (!route){ + return std::format("no route from {} to can {}.", to_string(start), can); + } + if (!route->empty()){ + const RoutePlanning planning{.maps = &MAPS, .costs = story_route_costs(), .start = start, .label = "can"}; + if (const std::string failure = OverworldSimWalker(sim).run(*route, planning); !failure.empty()){ + return std::format("to can {}: ", can) + failure; + } + } + at = StoryPose{GYM, stand.tile, stand.facing}; + if (!(sim.state().position == MapPosition{GYM, stand.tile}) || sim.state().facing != stand.facing){ + return std::format("not at can {}'s stand facing it: on {}.", can, to_string(sim.state().position)); + } + if (!sim.state().violations.empty()){ + return std::format("to can {}: {}", can, sim.state().violations.back()); + } + return ""; +} + +// A step of a row on the sim: row_step_on_sim(), but Surge's battle, +// which a talk starts, leaves the player where the table says. The TEACH, +// the GRIND and the talks the sim hasn't got pass. +std::string gym_step_on_sim(OverworldSim& sim, StoryPose& at, const StoryStep& step, const std::string& id){ + if (step.kind == StoryStepKind::BATTLE && step.name == "lt_surge"){ + at = *story_pose(Pokemon::pose_of(*step.pose_after)); + return ""; + } + return row_step_on_sim(sim, at, step, id); +} + +using Switches = std::pair; + +// The gym's cans as its scripts answer them, each checked from its stand, +// walked to on the sim as the program plans it. +class SimGym{ +public: + SimGym(OverworldSim& sim, StoryPose& at, std::vector draws) + : m_sim(sim), m_at(at), m_draws(std::move(draws)) + { + next_draw(); + } + + CanPages check(int can){ + error = walk_to_stand(m_sim, m_at, can); + if (!error.empty()){ + return CanPages::FAILED; + } + if (open){ + return CanPages::ONE; + } + if (!m_first_found){ + m_first_found = can == m_switches.first; + return m_first_found ? CanPages::TWO : CanPages::ONE; + } + if (can == m_switches.second){ + open = true; + return CanPages::ONE; + } + m_first_found = false; + next_draw(); + return CanPages::TWO; + } + + std::string error; + bool open = false; + +private: + void next_draw(){ + // Past the script: one the search's guess finds. + m_switches = m_drawn < m_draws.size() ? m_draws[m_drawn++] : Switches{8, 7}; + } + + OverworldSim& m_sim; + StoryPose& m_at; + std::vector m_draws; + size_t m_drawn = 0; + Switches m_switches; + bool m_first_found = false; +}; + +// Row 00.23 from steps `first` to `last` (exclusive) on `sim`, the trash +// cans drawn as `draws` say. +std::string run_gym_steps(OverworldSim& sim, StoryPose& at, size_t first, size_t last, const std::vector& draws){ + const StoryCheckpoint& row = checkpoint("00.23"); + for (size_t c = first; c < last; c++){ + const StoryStep& step = row.steps[c]; + if (step.action == TRASH_CANS_VARIANT){ + QuietLogger logger; + SimGym gym(sim, at, draws); + const TrashCanResult result = run_trash_cans(logger, [&](int can){ return gym.check(can); }); + if (result.end != TrashCanEnd::OPENED || !gym.open){ + return "00.23/trash_cans: " + std::string(trash_can_end_name(result.end)) + " " + gym.error; + } + continue; + } + if (const std::string failure = gym_step_on_sim(sim, at, step, row.id); !failure.empty()){ + return failure; + } + } + return ""; +} + +// 00.23 on the sim from the nurse to the nurse: the tree cut, Dwayne, +// Baily and Tucker fought in that order where the table says and no one +// else, the cans searched, out past the tree grown back. The switches +// found at once (under 3 and 4), and after a wrong guess's reset (under +// 3 and 8, then 13 and 14). +UnitTestResult test_gym_row(){ + const StoryCheckpoint& row = checkpoint("00.23"); + for (const std::vector& draws : {std::vector{{3, 4}}, std::vector{{3, 8}, {13, 14}}}){ + StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + OverworldSim sim(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + if (const std::string failure = run_gym_steps(sim, at, 0, row.steps.size(), draws); !failure.empty()){ + return failure + " Beat" + beaten_list(sim) + "."; + } + const std::vector expected{"sailor", "balding_man", "gentleman"}; + if (sim.state().trainers_beaten != expected || !sim.state().violations.empty()){ + return "00.23: expected Dwayne, Baily and Tucker beaten and no violation; beat" + beaten_list(sim) + "."; + } + if (!(sim.state().position == MapPosition{VERMILION_CENTER, {7, 4}})){ + return "00.23: expected to end at Vermilion's nurse, not " + to_string(sim.state().position) + "."; + } + } + return true; +} + +// From where Tucker's battle leaves the player, with the three where +// their battles leave them: every can's stand reached from (5, 8) and from +// every other stand, and the way out to the nurse from every stand. +UnitTestResult test_cans_from_everywhere(){ + const StoryCheckpoint& row = checkpoint("00.23"); + StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + OverworldSim sim(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + const size_t cans = step_index(row, "trash_cans"); + if (const std::string failure = run_gym_steps(sim, at, 0, cans, {}); !failure.empty()){ + return failure; + } + for (int from = 1; from <= TRASH_CAN_COUNT; from++){ + OverworldSim there = sim; + StoryPose here = at; + if (const std::string failure = walk_to_stand(there, here, from); !failure.empty()){ + return "From Tucker's battle: " + failure; + } + for (int to = 1; to <= TRASH_CAN_COUNT; to++){ + OverworldSim walked = there; + StoryPose pose = here; + if (const std::string failure = walk_to_stand(walked, pose, to); !failure.empty()){ + return std::format("From can {}: ", from) + failure; + } + if (walked.state().trainers_beaten.size() != 3){ + return std::format("Can {} to can {}: a battle on the way.", from, to); + } + } + OverworldSim out = there; + if (const std::string failure = run_gym_steps(out, here, cans + 1, row.steps.size(), {}); !failure.empty()){ + return std::format("Out from can {}: ", from) + failure; + } + if (!(out.state().position == MapPosition{VERMILION_CENTER, {7, 4}}) || !out.state().violations.empty()){ + return std::format("Out from can {}: expected the nurse and no violation, on {}.", from, to_string(out.state().position)); + } + } + return true; +} + +// The tree shuts the gym's yard: no way from above it to the door. +UnitTestResult test_tree_shuts_the_yard(){ + const RouteGoal door{{GYM, {5, 19}}, std::nullopt}; + if (plan_overworld_route(story_maps(), MapPosition{VERMILION, {19, 23}}, door, story_route_costs(), Direction::SOUTH)){ + return "Planned a way into the gym past the uncut tree (19, 24)."; + } + if (!plan_overworld_route(story_maps(), MapPosition{VERMILION, {19, 24}}, door, story_route_costs(), Direction::SOUTH)){ + return "No way from the tree's tile to the gym."; + } + // The sim: no step onto the tree; cut, it's gone; a warp grows it back. + OverworldSim sim(story_maps(), MapPosition{VERMILION, {19, 23}}, Direction::SOUTH); + sim.tap(Direction::SOUTH); + if (!(sim.state().position == MapPosition{VERMILION, {19, 23}}) || !sim.cut_tree()){ + return "Expected the tree to stop the player, then be cut."; + } + sim.tap(Direction::SOUTH); + if (!(sim.state().position == MapPosition{VERMILION, {19, 24}})){ + return "Expected a step onto the cut tree's tile."; + } + return true; +} + +// 00.24 and 00.25 on the sim, the gym as 00.23 leaves it: to Route 6's +// grass round Isabelle's line and back, to below Surge through the beams, +// and from him back out past the tree to the nurse, meeting no one. +UnitTestResult test_to_surge_and_out(){ + for (std::string_view id : {"00.24", "00.25"}){ + const StoryCheckpoint& row = checkpoint(id); + StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + OverworldSim sim(maps_after_gym(), MapPosition{at.map, at.tile}, *at.facing); + for (const StoryStep& step : row.steps){ + if (const std::string failure = gym_step_on_sim(sim, at, step, row.id); !failure.empty()){ + return failure; + } + } + if (!sim.state().trainers_beaten.empty() || !sim.state().violations.empty()){ + return std::format("{}: a battle or a violation on the way.", id); + } + const MapPosition end = id == "00.24" ? MapPosition{GYM, {5, 3}} : MapPosition{VERMILION_CENTER, {7, 4}}; + if (!(sim.state().position == end)){ + return std::format("{}: ended on {}, not {}.", id, to_string(sim.state().position), to_string(end)); + } + } + const StoryPose next = *story_pose(Pokemon::pose_of(*checkpoint("00.25").start)); + if (!(next.tile == TilePos{5, 3}) || next.map != GYM){ + return "00.25 doesn't start where 00.24 ends."; + } + return true; +} + +// Console B, 00.25 (2026-11-03 18:17): the walk to the nurse went up +// column 27 to row 7 and west along it, into Oak's aide on (25, 7), there +// since Surge's win; the leg was taken as walked and the step into the +// Center's door went into a house's wall. 00.25 from Surge to the nurse +// with the aide there, meeting no one. +UnitTestResult test_out_past_oaks_aide(){ + const StoryCheckpoint& row = checkpoint("00.25"); + const std::vector maps = maps_after_surge(); + const MapData& city = *std::find_if(maps.begin(), maps.end(), [](const MapData& map){ return map.name == VERMILION; }); + if (object_at(city, {25, 7}) == nullptr){ + return "Expected Oak's aide on (25, 7) after Lt. Surge."; + } + StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + OverworldSim sim(maps, MapPosition{at.map, at.tile}, *at.facing); + for (const StoryStep& step : row.steps){ + if (const std::string failure = gym_step_on_sim(sim, at, step, row.id); !failure.empty()){ + return failure; + } + } + const MapPosition nurse{VERMILION_CENTER, {7, 4}}; + if (!sim.state().violations.empty() || !(sim.state().position == nurse)){ + return "Expected the nurse reached past Oak's aide; on " + to_string(sim.state().position) + (sim.state().violations.empty() ? "." : ", " + sim.state().violations.back()); + } + return true; +} + +// 00.24 with a lead at the grind's level already: the check in the Center +// comes first, and with its flag set the walk to Route 6's grass, the +// grind and the way back are skipped; the rest goes from the nurse to +// below Surge on the sim. Console B walked out and back at Lv29 +// (2026-11-03). +UnitTestResult test_lead_ready_skips_grind(){ + const StoryCheckpoint& row = checkpoint("00.24"); + const StoryStep& check = row.steps.front(); + if (check.action != GRIND_CHECK_ACTION || !grind_plan_of(check.args)){ + return "Expected 00.24 to start with the grind's check, not " + check.name + "."; + } + StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + OverworldSim sim(maps_after_gym(), MapPosition{at.map, at.tile}, *at.facing); + std::vector skipped; + for (const StoryStep& step : row.steps){ + if (step.skip_if == std::vector{check.name}){ + skipped.push_back(step.name); + continue; + } + if (const std::string failure = gym_step_on_sim(sim, at, step, row.id); !failure.empty()){ + return failure; + } + } + const std::vector expected{ + "route6_south_path", "round_isabelle_line", "grind_for_surge", "west_on_row_31", "down_to_jeff_row", "vermilion_nurse", "heal_vermilion", + }; + if (skipped != expected || !(sim.state().position == MapPosition{GYM, {5, 3}})){ + return std::format("Expected the trip to Route 6 skipped and below Surge reached; {} skipped, on {}.", skipped.size(), to_string(sim.state().position)); + } + return true; +} +} // namespace + + +const AutoStoryVermilionGymCase AUTO_STORY_VERMILION_GYM_CASES[] = { + { + .input = {"00.23 the tree shuts the gym's yard until cut", test_tree_shuts_the_yard}, + .expectation = {}, + }, + { + .input = {"00.23 Vermilion Gym: Dwayne, Baily and Tucker, the cans at once or after a reset", test_gym_row}, + .expectation = {}, + }, + { + .input = {"00.23 every can's stand from Tucker's tile and from every other, and out", test_cans_from_everywhere}, + .expectation = {}, + }, + { + .input = {"00.24 and 00.25 through the beams to Lt. Surge and out", test_to_surge_and_out}, + .expectation = {}, + }, + { + .input = {"00.25 out to the nurse past Oak's aide on (25, 7)", test_out_past_oaks_aide}, + .expectation = {}, + }, + { + .input = {"00.24 with the lead at its level already: no trip to Route 6", test_lead_ready_skips_grind}, + .expectation = {}, + }, +}; + +void add_tests_AutoStoryVermilionGym(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_VERMILION_GYM_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVermilion_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVermilion_Tests.cpp new file mode 100644 index 0000000000..61a889806c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVermilion_Tests.cpp @@ -0,0 +1,237 @@ +/* AutoStory Vermilion Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Rows 00.21 (Cerulean to Vermilion City) and 00.22 (the S.S. Anne) on + * the overworld sim: their walks reach their ends, and meet only the + * trainers the table fights. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRowSim.h" +#include "PokemonFRLG_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct AutoStoryVermilionInput{ + std::string name; + std::function body; +}; + +struct AutoStoryVermilionExpectation{ +}; + +struct AutoStoryVermilionCase{ + AutoStoryVermilionInput input; + AutoStoryVermilionExpectation expectation; +}; + +class Test_AutoStoryVermilion : public UnitTest{ +public: + explicit Test_AutoStoryVermilion(AutoStoryVermilionCase test_case) + : UnitTest("PokemonFRLG::AutoStory - Simulation: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_case.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryVermilionCase m_case; +}; + +const StoryCheckpoint* checkpoint(const std::string& id){ + const std::vector& rows = story_checkpoints(); + const auto row = std::find_if(rows.begin(), rows.end(), [&](const StoryCheckpoint& data){ return data.id == id; }); + return row == rows.end() ? nullptr : &*row; +} + +std::string beaten_list(const OverworldSim& sim){ + std::string text; + for (const std::string& name : sim.state().trainers_beaten){ + text += " " + name; + } + return text.empty() ? " none" : text; +} + +size_t step_index(const StoryCheckpoint& row, const std::string& name){ + const auto step = std::find_if(row.steps.begin(), row.steps.end(), [&](const StoryStep& data){ return data.name == name; }); + if (step == row.steps.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + row.id + "/" + name + "."); + } + return step - row.steps.begin(); +} + +// Runs row 00.21's steps from `first` to its end on `sim` from `at`, and +// checks that only Jeff ("camper") was fought and the walk ended at +// Vermilion's nurse. +std::string run_to_vermilion(OverworldSim& sim, StoryPose at, const StoryCheckpoint& row, size_t first){ + for (size_t c = first; c < row.steps.size(); c++){ + const std::string failure = row_step_on_sim(sim, at, row.steps[c], row.id); + if (!failure.empty()){ + return failure; + } + } + if (sim.state().trainers_beaten != std::vector{"camper"} || !sim.state().violations.empty()){ + return "00.21: expected Jeff alone beaten and no violation; beat" + beaten_list(sim) + "."; + } + if (!(sim.state().position == MapPosition{"VermilionCity_PokemonCenter_1F", {7, 4}})){ + return "00.21: expected to end at Vermilion's nurse, not " + to_string(sim.state().position) + "."; + } + return ""; +} + +// 00.21 on the sim, from Cerulean's Pokemon Center through the burgled +// house to (32, 7), west of the Rocket, meeting no one; his trigger and +// battle aren't the sim's, so from where his battle leaves the player: +// Route 5, the Underground Path and Route 6, down column 15 out of +// Keigo's and Elijah's lines, round Isabelle's row to Jeff, who is fought +// on the step onto (10, 33), and on to Vermilion's nurse. Then from the +// walk onto Route 6's column 15 ended a tile short, on column 16: the +// same. +UnitTestResult test_route6_jeff_only(){ + const StoryCheckpoint* row = checkpoint("00.21"); + if (row == nullptr){ + return "No checkpoint 00.21."; + } + StoryPose at = *story_pose(Pokemon::pose_of(*row->start)); + OverworldSim house(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + const size_t rocket = step_index(*row, "rocket_trigger"); + for (size_t c = 0; c < rocket; c++){ + if (const std::string failure = row_step_on_sim(house, at, row->steps[c], row->id); !failure.empty()){ + return failure; + } + } + if (!(house.state().position == MapPosition{"CeruleanCity", {32, 7}}) || !house.state().trainers_beaten.empty()){ + return std::format("00.21: expected to reach (32, 7) west of the Rocket, meeting no one, not {}.", to_string(house.state().position)); + } + const size_t battle = step_index(*row, "rocket_grunt"); + const StoryPose after_rocket = *story_pose(Pokemon::pose_of(*row->steps[battle].pose_after)); + OverworldSim whole(story_maps(), MapPosition{after_rocket.map, after_rocket.tile}, *after_rocket.facing); + if (const std::string failure = run_to_vermilion(whole, after_rocket, *row, battle + 1); !failure.empty()){ + return "From the Rocket: " + failure; + } + const size_t walk = step_index(*row, "route6_column15"); + const StoryPose column = *story_pose(Pokemon::pose_of(Pokemon::story_arg(row->steps[walk].args, "target"))); + OverworldSim sim(story_maps(), MapPosition{column.map, {column.tile.x + 1, column.tile.y}}, Direction::WEST); + if (const std::string failure = run_to_vermilion(sim, column, *row, walk + 1); !failure.empty()){ + return "A tile short: " + failure; + } + return true; +} + +// Whether `route` from `start` steps onto any of `tiles` of `map`. +bool steps_onto(const std::vector& route, MapPosition start, const std::string& map, const std::vector& tiles){ + for (const RouteStep& step : route){ + const std::vector passed = step.action == RouteAction::WALK ? leg_tiles(story_maps(), start, step) : std::vector{}; + for (size_t c = 1; c < passed.size(); c++){ + if (passed[c].map == map && std::find(tiles.begin(), tiles.end(), passed[c].point) != tiles.end()){ + return true; + } + } + start = step.end; + } + return false; +} + +// Where the table says the player stands after `step` from `at`. +StoryPose pose_after(const StoryPose& at, const StoryStep& step){ + if (step.pose_after){ + return *story_pose(Pokemon::pose_of(*step.pose_after)); + } + if (step.kind == StoryStepKind::STEP){ + return StoryPose{at.map, at.tile.next(Pokemon::story_arg(step.args, "direction")), Pokemon::story_arg(step.args, "direction")}; + } + return at; +} + +// 00.22's walks on the sim, each from where the table says it starts: to +// the harbor short of the ticket check, aboard and along 2F short of the +// rival's trigger row (30..32, 6), into the Captain's office behind him, +// back to 1F's door, and from the pier to the nurse. None meets a +// trainer: the ship's are in its cabins and on its deck. +UnitTestResult test_ss_anne_walks(){ + const StoryCheckpoint* row = checkpoint("00.22"); + if (row == nullptr){ + return "No checkpoint 00.22."; + } + StoryPose at = *story_pose(Pokemon::pose_of(*row->start)); + bool before_rival = true; + for (const StoryStep& step : row->steps){ + if (step.kind != StoryStepKind::ROUTE && step.kind != StoryStepKind::LEGS){ + before_rival &= step.kind != StoryStepKind::BATTLE; + at = pose_after(at, step); + continue; + } + const std::optional> route = walked_route(at, step); + if (!route || route->empty()){ + return "00.22/" + step.name + ": no route."; + } + const MapPosition start{at.map, at.tile}; + if (steps_onto(*route, start, "VermilionCity", {{22, 33}, {23, 33}}) + || (before_rival && steps_onto(*route, start, "SSAnne_2F_Corridor", {{30, 6}, {31, 6}, {32, 6}})) + ){ + return "00.22/" + step.name + ": crosses a trigger before its step."; + } + OverworldSim sim(story_maps(), start, *at.facing); + if (const std::string failure = row_step_on_sim(sim, at, step, row->id); !failure.empty()){ + return failure; + } + if (!(sim.state().position == MapPosition{at.map, at.tile})){ + return "00.22/" + step.name + ": ended on " + to_string(sim.state().position) + ", not " + to_string(MapPosition{at.map, at.tile}) + "."; + } + if (!sim.state().trainers_beaten.empty() || !sim.state().violations.empty()){ + return "00.22/" + step.name + ": a trainer's battle or a violation on the way."; + } + } + if (!(MapPosition{at.map, at.tile} == MapPosition{"VermilionCity_PokemonCenter_1F", {7, 4}})){ + return "00.22: expected to end at Vermilion's nurse."; + } + return true; +} + +} // namespace + + +const AutoStoryVermilionCase AUTO_STORY_VERMILION_CASES[] = { + { + .input = {"00.21 to Vermilion, only Jeff on Route 6, the walk onto column 15 whole or a tile short", test_route6_jeff_only}, + .expectation = {}, + }, + { + .input = {"00.22 the S.S. Anne's walks, short of the ticket check and the rival's trigger", test_ss_anne_walks}, + .expectation = {}, + }, +}; + +void add_tests_AutoStoryVermilion(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_VERMILION_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index 0f3f6a6db9..d0e430ce9b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -234,8 +234,8 @@ UnitTestResult check_checkpoint(const StoryCheckpoint& checkpoint, StoryPose& po UnitTestResult test_routes_and_chain(){ const std::vector& checkpoints = story_checkpoints(); - if (checkpoints.size() != 27 || checkpoints[0].start){ - return "Expected 27 checkpoints, the first from a new game."; + if (checkpoints.size() != 32 || checkpoints[0].start){ + return "Expected 32 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ @@ -386,11 +386,11 @@ bool looks_around(const MapObject& object){ } // The trainer on `map` who would see the player on `tile`, other than the -// `beaten`. Wanderers and those who look around are left out: no route -// can plan around one (see wanderer_stops() and held_past_lookers()). -const MapObject* trainer_seeing(const MapData& map, const TilePos& tile, const std::set& beaten){ +// `beaten`. Wanderers and those who look around are left out (no route can plan round one: wanderer_stops(), +// held_past_lookers()); with `lookers`, only those who look around, met by a wait (TRAINER_WAIT_VARIANT). +const MapObject* trainer_seeing(const MapData& map, const TilePos& tile, const std::set& beaten, bool lookers){ for (const MapObject& object : map.objects){ - if (object.trainer && !object.wander && !looks_around(object) && !beaten.contains(&object) && trainer_may_see(map, object, tile)){ + if (object.trainer && !object.wander && looks_around(object) == lookers && !beaten.contains(&object) && trainer_may_see(map, object, tile)){ return &object; } } @@ -411,7 +411,7 @@ TilePos step_end(const StoryPose& pose, const StoryStep& step, const std::set legs_walked(const StoryPose& pose, const StoryStep& step) const MapData* map = find_map_named(pose.map); const std::optional facing = pose.facing ? pose.facing : map ? wall_beside(*map, pose.tile) : std::nullopt; const StoryPose target = one_tile(Pokemon::story_arg(step.args, "target")); - route = plan_overworld_route(story_maps(), start, RouteGoal{{target.map, target.tile}, target.facing}, default_route_costs(), facing); + route = plan_overworld_route(story_maps(), start, RouteGoal{{target.map, target.tile}, target.facing}, story_route_costs(), facing); } return route ? *route : std::vector{}; } @@ -484,15 +484,15 @@ std::vector> wanderer_stops(const StoryPose& pose, co // the player's way, they walk up beside the leg, and the walker holds it // on to its wall after the battle. Or the leg is one tile: the trainer // sees the player when the step is done, on its end. Empty if so, else -// the leg that doesn't. -std::string held_past_lookers(const StoryPose& pose, const StoryStep& step){ +// the leg that doesn't. Trainers in `beaten` see no one. +std::string held_past_lookers(const StoryPose& pose, const StoryStep& step, const std::set& beaten){ MapPosition from{pose.map, pose.tile}; for (const RouteStep& leg : legs_walked(pose, step)){ const MapData* map = find_map_named(from.map); bool crosses = false; - for (const MapPosition& tile : leg.action == RouteAction::WALK ? leg_tiles(story_maps(), from, leg) : std::vector{}){ - for (const MapObject& object : map ? map->objects : std::vector{}){ - crosses |= looks_around(object) && trainer_may_see(*map, object, tile.point); + for (const MapPosition& tile : leg.action == RouteAction::WALK && map ? leg_tiles(story_maps(), from, leg) : std::vector{}){ + for (const MapObject& object : map->objects){ + crosses |= looks_around(object) && !beaten.contains(&object) && trainer_may_see(*map, object, tile.point); } } if (crosses && !leg.to_wall && leg.tiles != 1){ @@ -532,13 +532,19 @@ std::string tile_problem(const MapPosition& tile, const std::setto){ return "onto a warp to a map not loaded at " + to_string(tile); } - const MapObject* trainer = trainer_seeing(*map, tile.point, beaten); + const MapObject* trainer = trainer_seeing(*map, tile.point, beaten, false); if (trainer != nullptr){ return "in the line of the trainer at " + to_string(TilePos{trainer->x, trainer->y}) + " at " + to_string(tile); } return ""; } +// LEGS whose legs through grass end on walls or are one tile (Route 6). +bool grass_held(const StoryPose& pose, const StoryStep& step){ + const std::vector legs = legs_walked(pose, step); + return step.kind == StoryStepKind::LEGS && std::all_of(legs.begin(), legs.end(), [](const RouteStep& leg){ return !leg.wild || leg.to_wall || leg.tiles == 1; }); +} + // Moves `pose` past `step`, as check_checkpoint() does. UnitTestResult advance(StoryPose& pose, const StoryStep& step){ if (step.kind == StoryStepKind::ROUTE){ @@ -570,7 +576,7 @@ UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::set{}){ const StoryPose end = to_patch ? one_tile(Pokemon::story_arg(step.args, "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"))){ + if (const std::string problem = tile_problem(tile, beaten); !problem.empty() && !((patch || grass_held(pose, step)) && problem.starts_with("in the grass"))){ return where + problem; } } @@ -578,11 +584,11 @@ UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::set 0){ return where + "crosses a wandering trainer's sight where the walk can't tell where they'd stop the player."; } - if (const std::string problem = walks ? held_past_lookers(pose, step) : ""; !problem.empty()){ + if (const std::string problem = walks ? held_past_lookers(pose, step, beaten) : ""; !problem.empty()){ return where + problem; } const MapData* map = find_map_named(pose.map); - const MapObject* trainer = step.kind == StoryStepKind::STEP && map ? trainer_seeing(*map, step_end(pose, step, beaten), beaten) : nullptr; + const MapObject* trainer = step.kind == StoryStepKind::STEP && map ? trainer_seeing(*map, step_end(pose, step, beaten), beaten, step.action == TRAINER_WAIT_VARIANT) : nullptr; if (trainer != nullptr && (c + 1 == checkpoint.steps.size() || checkpoint.steps[c + 1].kind != StoryStepKind::BATTLE)){ return where + "steps into a trainer's line with no battle after it."; } @@ -597,9 +603,9 @@ 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, step_end(pose, steps[c], {}), {}) : nullptr; + const MapObject* trainer = steps[c].kind == StoryStepKind::STEP && map ? trainer_seeing(*map, step_end(pose, steps[c], {}), {}, false) : 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."; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.21.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.21.plan.json new file mode 100644 index 0000000000..39da1ef70b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.21.plan.json @@ -0,0 +1,103 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.21", + "title": "The Cerulean Rocket, Route 5, the Underground Path and Route 6 to Vermilion's Pokemon Center: Jeff", + "start": {"map": "CeruleanCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"}, + "events": [ + { + "id": "west_of_rocket", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "CeruleanCity", "tiles": [[32, 7]], "facing": "east"} + }, + "why": "through the burgled house and out of the hole in its back wall, west of the Rocket (33, 6)" + }, + { + "id": "rocket_trigger", + "kind": "step", + "args": { + "direction": "east" + }, + "why": "onto (33, 7), below the Rocket" + }, + { + "id": "rocket_grunt", + "kind": "battle", + "args": { + "trainer": "TRAINER_TEAM_ROCKET_GRUNT_5", + "foes": ["machop", "drowzee"] + }, + "declared_after": {"map": "CeruleanCity", "tiles": [[33, 7]], "facing": "north"}, + "why": "Machop and Drowzee, Lv17; TM28 Dig" + }, + { + "id": "route6_column15", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "Route6", "tiles": [[15, 14]]} + }, + "why": "round the yard and down Cerulean's east side, Route 5 into the Underground Path, through it onto Route 6, west to column 15" + }, + { + "id": "round_keigo_and_elijah", + "kind": "legs", + "action": "run", + "args": { + "legs": [{"direction": "south", "tiles": 19}, {"direction": "north", "tiles": 1}, {"direction": "north", "tiles": 1}, {"direction": "west", "tiles": 8}, {"direction": "south", "tiles": 2}, {"direction": "east", "tiles": 2}] + }, + "why": "down column 15 to the wall (15, 33); up to (15, 31), west to the wall (7, 31), down to the wall (7, 33), east to (9, 33)" + }, + { + "id": "jeff_line", + "kind": "step", + "action": "trainer_line", + "args": { + "direction": "east" + }, + "why": "onto (10, 33), in Jeff's line" + }, + { + "id": "camper_jeff", + "kind": "battle", + "args": { + "trainer": "TRAINER_CAMPER_JEFF", + "foes": ["spearow", "raticate"] + }, + "declared_after": {"map": "Route6", "tiles": [[10, 33]], "facing": "east"}, + "why": "Spearow and Raticate, Lv16; Jeff stops at (11, 33)" + }, + { + "id": "vermilion_nurse", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"} + }, + "why": "down Route 6's south path into Vermilion City, to the Pokemon Center" + }, + { + "id": "heal_vermilion", + "kind": "heal", + "why": "full HP" + } + ] + }, + "execution": { + "menu": "full", + "lead": "after_brock", + "notes": { + "checkpoint": [ + "Cerulean's only way south without Cut (CeruleanCity map.json, scripts.inc) is through the burgled house (30, 11), whose door the policeman leaves once the S.S. TICKET is had, out of the hole in its back wall into the yard (31, 8). The Rocket there (33, 6) stops the player on (33, 5) or (33, 7) (CeruleanCity_EventScript_GruntTrigger*): from (32, 7), the step east onto (33, 7) turns the player to him; Machop and Drowzee, Lv17, then TM28 Dig, and he is gone. Then east round the yard, down to the city's south edge by the path along its east side (39..40, 20..31), down Route 5's east side to the Underground Path's north house (31, 31), through its tunnel and out of the south house onto Route 6, below its door (19, 14).", + "Route 6: Bug Catcher Keigo (3, 16) faces east, sight 5, over the middle path (4..8, 16); Bug Catcher Elijah (20, 25) faces west, sight 3, over the east path (17..19, 25). The way goes down column 15, through the grass to the wall (15, 33), out of both lines; the open leg west to it, a tile short, leaves the player on column 16, out of them too.", + "Camper Ricky and Picnicker Nancy (12..13, 21) battle only when talked to.", + "Picnicker Isabelle (13, 32) and Camper Jeff (13, 33) face west, sight 3, over (10..12, 32) and (10..12, 33); the only way south, (10..12, 34), is from Jeff's row. Up to (15, 31), west to the wall (7, 31), down to the wall (7, 33), east: Jeff is fought on the step onto (10, 33) and walks up to (11, 33). Isabelle's row is kept off.", + "Then down into Vermilion City (offset 12) to its Pokemon Center." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.22.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.22.plan.json new file mode 100644 index 0000000000..172506f15d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.22.plan.json @@ -0,0 +1,164 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.22", + "title": "The S.S. Anne: the rival, HM01 Cut from the Captain, back to Vermilion's Pokemon Center", + "start": {"map": "VermilionCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"}, + "events": [ + { + "id": "above_ticket_check", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity", "tiles": [[23, 32]], "facing": "south"} + }, + "why": "out of the Center down to the harbor, above the ticket check (23, 33)" + }, + { + "id": "ticket_check", + "kind": "step", + "args": { + "direction": "south" + }, + "why": "onto (23, 33): \"Do you have a ticket?\"" + }, + { + "id": "show_ss_ticket", + "kind": "scene", + "declared_after": {"map": "VermilionCity", "tiles": [[23, 33]], "facing": "east"}, + "why": "the S.S. TICKET; the player turns to the sailor" + }, + { + "id": "aboard", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "SSAnne_1F_Corridor", "tiles": [[19, 2]], "facing": "south"} + }, + "why": "onto the pier, along the gangway and in by 1F's door, a step below it" + }, + { + "id": "past_the_cabins", + "kind": "legs", + "action": "run", + "args": { + "legs": [{"direction": "south", "tiles": 8}, {"direction": "north", "tiles": 1}, {"direction": "west", "tiles": 6}, {"direction": "north", "tiles": 1}] + }, + "why": "to the wall (19, 10), up a step, west to the worker (12, 9), up a step to (13, 8): off the cabins' mats on row 10" + }, + { + "id": "below_rival_trigger", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "SSAnne_2F_Corridor", "tiles": [[30, 7]], "facing": "north"} + }, + "why": "west along 1F, up the stairs (3, 8) and along 2F below the Captain's door" + }, + { + "id": "rival_trigger", + "kind": "step", + "args": { + "direction": "north" + }, + "why": "onto (30, 6): the rival comes out of the Captain's door" + }, + { + "id": "rival_ss_anne", + "kind": "battle", + "args": { + "trainer": "TRAINER_RIVAL_SS_ANNE_BULBASAUR", + "foes": ["pidgeotto", "raticate", "kadabra", "ivysaur"] + }, + "declared_after": {"map": "SSAnne_2F_Corridor", "tiles": [[30, 6]], "facing": "north"}, + "why": "Pidgeotto, Raticate, Kadabra and Ivysaur" + }, + { + "id": "behind_captain", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "SSAnne_CaptainsOffice", "tiles": [[5, 5]], "facing": "north"} + }, + "why": "into the Captain's office, behind the Captain (5, 4)" + }, + { + "id": "captain", + "kind": "talk", + "why": "\"Ooargh... I feel hideous... Urrp! Seasick...\"" + }, + { + "id": "hm01_cut", + "kind": "scene", + "declared_after": {"map": "SSAnne_CaptainsOffice", "tiles": [[5, 5]], "facing": "north"}, + "why": "the player rubs his back; HM01, and what Cut does" + }, + { + "id": "off_2f", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "SSAnne_1F_Corridor", "tiles": [[13, 8]]} + }, + "why": "back along 2F, down the stairs and east along 1F's row 8" + }, + { + "id": "round_the_sailor", + "kind": "legs", + "action": "run", + "args": { + "legs": [{"direction": "east", "tiles": 4}, {"direction": "south", "tiles": 1}, {"direction": "east", "tiles": 2}] + }, + "why": "to the sailor (18, 8), down a step, east to (19, 9): off the cabins' mats on row 10" + }, + { + "id": "below_ship_door", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "SSAnne_1F_Corridor", "tiles": [[19, 2]], "facing": "north"} + }, + "why": "up below the door to the gangway" + }, + { + "id": "off_the_ship", + "kind": "step", + "args": { + "direction": "north" + }, + "why": "out onto the gangway" + }, + { + "id": "ss_anne_sails", + "kind": "scene", + "declared_after": {"map": "VermilionCity", "tiles": [[23, 32]], "facing": "north"}, + "why": "the ship sails; the player is walked off the pier to (23, 32)" + }, + { + "id": "vermilion_nurse", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"} + }, + "why": "back to the Pokemon Center" + }, + { + "id": "heal_vermilion", + "kind": "heal", + "why": "full HP" + } + ] + }, + "execution": { + "menu": "full", + "lead": "after_brock", + "notes": { + "checkpoint": [ + "The S.S. Anne (VermilionCity, SSAnne_* scripts.inc). The step onto (23, 33) (VermilionCity_EventScript_CheckTicket) has the sailor (24, 33) ask for a ticket; the S.S. TICKET (00.18) is shown and the player turns east to him. Then onto the pier (23, 34), along the gangway, through 1F, by legs off its cabins' doormats on row 10, which planned routes cross, and up its stairs (3, 8) to 2F. The step onto (30, 6), below the Captain's door (30, 2) (SSAnne_2F_Corridor_EventScript_RivalTriggerLeft), brings the rival out and down to (30, 5); the player keeps facing north, and after the battle he walks round the player and off. For a player who took Squirtle: Pidgeotto Lv19, Raticate Lv16, Kadabra Lv18, Ivysaur Lv20. The ship's trainers are in its cabins and on its deck, off the way. The Captain (5, 4) faces up; talked to from (5, 5) he is rubbed on the back and gives HM01 (VAR_MAP_SCENE_VERMILION_CITY 1). Back out through 1F's door (19, 1): on the gangway the ship sails (SSAnne_Exterior_ExitSSAnne), the player is put on (23, 34) and walked up to (23, 32) (VermilionCity_EventScript_ExitSSAnne). Cut is taught later, to the Oddish." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.23.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.23.plan.json new file mode 100644 index 0000000000..0077160402 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.23.plan.json @@ -0,0 +1,199 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.23", + "title": "Vermilion Gym: Cut and Dig, the tree, Dwayne, Baily and Tucker, the trash cans", + "start": {"map": "VermilionCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"}, + "events": [ + { + "id": "teach_cut", + "kind": "game_action", + "action": "teach", + "args": { + "item": "hm01", + "move": "cut", + "slot": 2 + }, + "why": "HM01 Cut to the Oddish, second in the party, unless it knows it" + }, + { + "id": "teach_dig", + "kind": "game_action", + "action": "teach", + "args": { + "item": "tm28", + "move": "dig", + "slot": 1, + "forget": "withdraw" + }, + "why": "TM28 Dig in place of Withdraw, for Lt. Surge, unless the lead knows it or there is no TM28" + }, + { + "id": "above_gym_tree", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity", "tiles": [[19, 23]], "facing": "south"} + }, + "why": "out of the Center, south through the city to above the tree (19, 24)" + }, + { + "id": "cut_gym_tree", + "kind": "game_action", + "action": "cut_tree", + "args": { + "direction": "south" + }, + "declared_after": {"map": "VermilionCity", "tiles": [[19, 24]], "facing": "south"}, + "why": "the Oddish cuts the tree; a step onto its tile" + }, + { + "id": "gym_door", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity_Gym", "tiles": [[5, 19]], "facing": "north"} + }, + "why": "down into the yard and in by the gym's door (14, 25)" + }, + { + "id": "west_of_dwayne_line", + "kind": "legs", + "action": "run", + "args": { + "legs": [{"direction": "north", "tiles": 4}, {"direction": "east", "tiles": 2}] + }, + "why": "up column 5 to the can (5, 14), east to (7, 15): out of Dwayne's and Baily's sight" + }, + { + "id": "dwayne_sight", + "kind": "step", + "action": "trainer_wait", + "args": { + "direction": "east" + }, + "why": "onto (8, 15), two below Dwayne (8, 13): he turns to the player and walks up to (8, 14)" + }, + { + "id": "sailor_dwayne", + "kind": "battle", + "args": { + "trainer": "TRAINER_SAILOR_DWAYNE", + "foes": ["pikachu", "pikachu"] + }, + "declared_after": {"map": "VermilionCity_Gym", "tiles": [[8, 15]], "facing": "north"}, + "why": "two Pikachu, Lv21" + }, + { + "id": "east_of_baily_line", + "kind": "legs", + "action": "run", + "args": { + "legs": [{"direction": "west", "tiles": 4}, {"direction": "north", "tiles": 2}, {"direction": "west", "tiles": 1}] + }, + "why": "west along row 15 to (4, 15), up to (4, 13), west to (3, 13): out of Baily's sight" + }, + { + "id": "baily_sight", + "kind": "step", + "action": "trainer_wait", + "args": { + "direction": "west" + }, + "why": "onto (2, 13), two below Baily (2, 11): he turns to the player and walks up to (2, 12)" + }, + { + "id": "engineer_baily", + "kind": "battle", + "args": { + "trainer": "TRAINER_ENGINEER_BAILY", + "foes": ["voltorb", "magnemite"] + }, + "declared_after": {"map": "VermilionCity_Gym", "tiles": [[2, 13]], "facing": "north"}, + "why": "Voltorb and Magnemite, Lv21" + }, + { + "id": "below_tucker_line", + "kind": "legs", + "action": "run", + "args": { + "legs": [{"direction": "east", "tiles": 2}, {"direction": "north", "tiles": 4}, {"direction": "east", "tiles": 1}] + }, + "why": "east to (4, 13), up column 4 past Baily's row to (4, 9), east to (5, 9): below Tucker's line, not on it" + }, + { + "id": "tucker_line", + "kind": "step", + "action": "trainer_line", + "args": { + "direction": "north" + }, + "why": "onto (5, 8), in Tucker's line: he walks up to (6, 8)" + }, + { + "id": "gentleman_tucker", + "kind": "battle", + "args": { + "trainer": "TRAINER_GENTLEMAN_TUCKER", + "foes": ["pikachu"] + }, + "declared_after": {"map": "VermilionCity_Gym", "tiles": [[5, 8]], "facing": "east"}, + "why": "Pikachu, Lv23" + }, + { + "id": "trash_cans", + "kind": "game_action", + "action": "trash_cans", + "why": "the cans until both locks open; a wrong second can resets them" + }, + { + "id": "below_gym_tree", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity", "tiles": [[19, 25]], "facing": "north"} + }, + "why": "out of the gym, east to below the tree, grown back" + }, + { + "id": "cut_tree_out", + "kind": "game_action", + "action": "cut_tree", + "args": { + "direction": "north" + }, + "declared_after": {"map": "VermilionCity", "tiles": [[19, 24]], "facing": "north"}, + "why": "the tree again; a step onto its tile" + }, + { + "id": "vermilion_nurse", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"} + }, + "why": "north through the city to the Pokemon Center" + }, + { + "id": "heal_vermilion", + "kind": "heal", + "why": "full HP" + } + ] + }, + "execution": { + "menu": "full", + "lead": "after_brock", + "notes": { + "checkpoint": [ + "HM01 Cut, from the S.S. Anne (00.22), to the Oddish (00.20), second in the party: a wild Oddish of Lv12 to 14 knows 2 or 3 moves (Absorb, Sweet Scent, Poison Powder at 14), so it has room. TM28 Dig, from the Cerulean Rocket (00.21), to the lead in place of Withdraw: Ground, twice as strong on Lt. Surge's three, it is the lead's best move against him. Vermilion's tree (19, 24) (EventScript_CutTree) is the only way into the gym's yard, row 24 being walls but for it; the gym's door is (14, 25). In the gym, the trainers as below, then the trash cans until the door opens; out, the tree cut again from below, and back to the nurse.", + "The gym (VermilionCity_Gym map.json, scripts.inc), 11 x 20, entered on (5, 19): the cans on rows 10, 12 and 14 at x 1, 3, 5, 7, 9 (PokemonFRLG_AutoStoryTrashCans.h), the beams across rows 6 and 7 that the two switches turn off, Lt. Surge (5, 2) facing down above them. Its trainers, sight 3:", + "Sailor Dwayne (8, 13) and Engineer Baily (2, 11) look around (MOVEMENT_TYPE_LOOK_AROUND): between them they see across rows 11 and 13 and down columns 2 and 8, so no way from the door to the cans keeps out of their sight. Each is fought from the second tile of his line, stepped onto from beside it, out of sight, and waited on there until he turns to the player (\"trainer_wait\"): Dwayne from (8, 15), stepped onto from (7, 15), Baily from (2, 13), from (3, 13). Each walks up a tile, Dwayne to (8, 14), Baily to (2, 12), and stays there while the player is in the gym.", + "Gentleman Tucker (7, 8) faces west over (4..6, 8): fought on the step up from (5, 9) onto (5, 8); he walks up to (6, 8).", + "The cans' stands, on rows 9, 11 and 13 above each, are clear of where the three stand after their battles. Leaving the gym puts them back where the map has them, beaten, and grows the tree back." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.24.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.24.plan.json new file mode 100644 index 0000000000..577e9c68a8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.24.plan.json @@ -0,0 +1,133 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.24", + "title": "Route 6's grass until the lead is Lv31, then through the open beams to Lt. Surge", + "start": {"map": "VermilionCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"}, + "events": [ + { + "id": "ready_for_surge", + "kind": "game_action", + "action": "grind_check", + "args": { + "slot": 1, + "level": 31, + "encounters": 150, + "pace": "east", + "heal_every": 0 + }, + "why": "the lead as it is: at Lv31 already, no trip to Route 6" + }, + { + "id": "route6_south_path", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "Route6", "tiles": [[11, 34]], "facing": "north"} + }, + "skip_if": ["ready_for_surge"], + "why": "out of the Center, north out of the city onto Route 6's path, below Jeff's row" + }, + { + "id": "round_isabelle_line", + "kind": "legs", + "action": "run", + "args": { + "legs": [{"direction": "north", "tiles": 1}, {"direction": "west", "tiles": 4}, {"direction": "north", "tiles": 2}, {"direction": "east", "tiles": 5}, {"direction": "east", "tiles": 1}] + }, + "skip_if": ["ready_for_surge"], + "why": "onto Jeff's row (11, 33), west to the wall (7, 33), up to (7, 31), east along row 31 to (12, 31) and a step onto the grass, (13, 31): out of Isabelle's line" + }, + { + "id": "grind_for_surge", + "kind": "game_action", + "action": "grind", + "args": { + "slot": 1, + "level": 32, + "encounters": 150, + "pace": "east", + "heal_every": 0, + "nurse": {"map": "VermilionCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"} + }, + "skip_if": ["ready_for_surge"], + "why": "wild battles until the lead is Lv31, where it outspeeds Lt. Surge's Raichu (m73 lost at Lv29); the nurse when hurt or low on PP" + }, + { + "id": "west_on_row_31", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "Route6", "tiles": [[7, 31]]} + }, + "skip_if": ["ready_for_surge"], + "why": "west along row 31, out of the grass, to the wall (7, 31)" + }, + { + "id": "down_to_jeff_row", + "kind": "legs", + "action": "run", + "args": { + "legs": [{"direction": "south", "tiles": 2}, {"direction": "east", "tiles": 4}] + }, + "skip_if": ["ready_for_surge"], + "why": "down to the wall (7, 33), east along Jeff's row to (11, 33): out of Isabelle's line" + }, + { + "id": "vermilion_nurse", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"} + }, + "skip_if": ["ready_for_surge"], + "why": "south into the city to the Pokemon Center" + }, + { + "id": "heal_vermilion", + "kind": "heal", + "skip_if": ["ready_for_surge"], + "why": "full HP" + }, + { + "id": "above_gym_tree", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity", "tiles": [[19, 23]], "facing": "south"} + }, + "why": "out of the Center, south through the city to above the tree (19, 24)" + }, + { + "id": "cut_gym_tree", + "kind": "game_action", + "action": "cut_tree", + "args": { + "direction": "south" + }, + "declared_after": {"map": "VermilionCity", "tiles": [[19, 24]], "facing": "south"}, + "why": "the tree; a step onto its tile" + }, + { + "id": "below_lt_surge", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity_Gym", "tiles": [[5, 3]], "facing": "north"} + }, + "why": "into the gym, up round the cans and through the beams, off, to below Surge (5, 2)" + } + ] + }, + "execution": { + "menu": "full", + "lead": "after_brock", + "notes": { + "checkpoint": [ + "Wild battles on Route 6 until the lead is Lv31: at Lv29 with Dig, console B's lead (m73) lost to Lt. Surge's Raichu, which it outspeeds at Lv31. The grass nearest the city is Route 6's south patch (13..16, 30..33); Picnicker Isabelle (13, 32) faces west over (10..12, 32), on the way north from the city, so the walk goes along Jeff's row 33 (he is beaten) to the wall (7, 33), up to row 31 and east along it onto the patch's west edge, (13, 31), above Isabelle, out of her line. Back to the nurse the same way. All that is skipped when the lead, read in the Center, is Lv31 already. Then the tree, the gym, whose trainers stand where the map has them, beaten, and whose beams stay off (FLAG_FOUND_BOTH_VERMILION_GYM_SWITCHES): up column 5 to below Lt. Surge, and saved there." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.25.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.25.plan.json new file mode 100644 index 0000000000..7d72d919f0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.25.plan.json @@ -0,0 +1,78 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.25", + "title": "Vermilion Gym: Lt. Surge, the THUNDERBADGE, then the Center", + "start": {"map": "VermilionCity_Gym", "tiles": [[5, 3]], "facing": "north"}, + "events": [ + { + "id": "challenge_lt_surge", + "kind": "talk", + "why": "\"Hey, kid! What do you think you're doing here?\"" + }, + { + "id": "lt_surge", + "kind": "battle", + "args": { + "trainer": "TRAINER_LEADER_LT_SURGE", + "foes": ["voltorb", "pikachu", "raichu"] + }, + "declared_after": {"map": "VermilionCity_Gym", "tiles": [[5, 3]], "facing": "north"}, + "why": "Voltorb, Pikachu and Raichu; THUNDERBADGE and TM34" + }, + { + "id": "below_gym_tree", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity", "tiles": [[19, 25]], "facing": "north"} + }, + "why": "down through the beams, out of the gym, east to below the tree, grown back" + }, + { + "id": "cut_tree_out", + "kind": "game_action", + "action": "cut_tree", + "args": { + "direction": "north" + }, + "declared_after": {"map": "VermilionCity", "tiles": [[19, 24]], "facing": "north"}, + "why": "the tree; a step onto its tile" + }, + { + "id": "below_oaks_aide", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity", "tiles": [[14, 10]]} + }, + "why": "north through the city and west along row 10 to the water, (14, 10): off Oak's aide's row 7" + }, + { + "id": "vermilion_nurse", + "kind": "route", + "action": "run", + "args": { + "target": {"map": "VermilionCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"} + }, + "why": "up to the Pokemon Center" + }, + { + "id": "heal_vermilion", + "kind": "heal", + "why": "full HP" + } + ] + }, + "execution": { + "menu": "full", + "lead": "after_brock", + "notes": { + "checkpoint": [ + "Lt. Surge (5, 2), talked to from below, from the save in front of him: Voltorb Lv21, Pikachu Lv18 and Raichu Lv24, Shock Wave and Thunder Wave, a Super Potion and a Full Heal (sParty_LeaderLtSurge); then the THUNDERBADGE and TM34, read to the overworld with the battle's text. Out, the tree, and the nurse. Surge's win also puts Oak's aide on Vermilion City's (25, 7) (VermilionCity_Gym_EventScript_ShowOaksAide), where he stays until talked to; the story's maps don't have him. The way to the nurse along row 7 runs into him (console B, 2026-11-03: the leg west stopped beside him and the step into the Center's door went into a house), so it goes along row 10 to the water instead, clear of him, and up column 14 from there." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 9adb3d2ab5..a4b35185f2 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2114,6 +2114,9 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSimStubs.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngReturns.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRunPlan_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -2152,6 +2155,12 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTeachScreens_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCanLayout.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrashCans_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVermilion_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryVermilionGym_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStatusBadge.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerLine.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTrainerMessage.h