From 6d5f2ce9dd868f61f2265768f75791e122f3406f Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 23:19:04 -0800 Subject: [PATCH] FRLG: an overworld sim, and the walker's console failures as its tests The walker's failures on console B could only be checked again on the console. OverworldSim models FireRed's overworld a whole tile at a time on the maps the planner uses: the player moves while the D-pad is held, hops ledges the way they face, takes warps with a fade, reads signs walked into moving north or south, and is seen by trainers along their sight. Wild battles start on the grass steps a test chooses, with their flashes seen or missed. Each shows a screen at a time after its step's press, which the walker's watchers see or miss as on the console. OverworldSimWalker is the console side of run_route() (RouteCalls) on the sim, step for step as walk_overworld_route_with_recovery() does it, with the walker's real leg bookkeeping (Pokemon::walk_leg_with()), timings and detection delays. The rules console failures added are switches, so each test also turns its rule off and checks the sim fails the old way. Tests replay nine failures from 2026-11-01: the fade and the black below the forest's north gate read as battles, the START menu left open, a battle at the end of a leg walked into, a late battle stopping an open leg, a trainer's battle fled, a hold over a ledge, a short leg then a sign, Camper Liam on the way out of Pewter Gym, and the walk out of Viridian Mart from the clerk's scene. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Overworld/PokemonFRLG_OverworldSim.cpp | 688 ++++++++++++++++++ .../Overworld/PokemonFRLG_OverworldSim.h | 301 ++++++++ .../PokemonFRLG_OverworldSim_Tests.cpp | 422 +++++++++++ .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + SerialPrograms/cmake/SourceFiles.cmake | 3 + 5 files changed, 1416 insertions(+) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp new file mode 100644 index 0000000000..3e0f4f75f6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -0,0 +1,688 @@ +/* Overworld Sim + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon/Navigation/Pokemon_LegWalker.h" +#include "PokemonFRLG_OverworldReanchor.h" +#include "PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_OverworldSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; + + +const char* sim_screen_name(SimScreen screen){ + switch (screen){ + case SimScreen::OVERWORLD: + return "the overworld"; + case SimScreen::MESSAGE: + return "a message"; + case SimScreen::START_MENU: + return "the START menu"; + case SimScreen::BATTLE_FLASH: + return "a battle's flashes"; + case SimScreen::BATTLE: + return "a battle"; + case SimScreen::FADE: + return "a warp's fade"; + } + return "?"; +} + + +namespace{ + +// A short press: TURN_TAP and TURN_SETTLE. +constexpr Milliseconds TAP_TIME(340); +// The story's battle loop takes a battle that doesn't show in this long +// for none. +constexpr Milliseconds NO_BATTLE_WAIT(15000); +constexpr Milliseconds BATTLE_TIME(10000); +constexpr Milliseconds MESSAGE_CLOSE(1000); +// 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; + +int find_map(const std::vector& maps, const std::string& name){ + for (size_t c = 0; c < maps.size(); c++){ + if (maps[c].name == name){ + return (int)c; + } + } + return -1; +} + +// The way a ledge on `tile` hops the player, if it is one. +std::optional ledge_direction(TileKind tile){ + switch (tile){ + case TileKind::LEDGE_NORTH: + return Direction::NORTH; + case TileKind::LEDGE_SOUTH: + return Direction::SOUTH; + case TileKind::LEDGE_WEST: + return Direction::WEST; + case TileKind::LEDGE_EAST: + return Direction::EAST; + default: + return std::nullopt; + } +} + +// The tile next to `player` a trainer standing on `box` walks up to. +TilePos trainer_stop(const Pokemon::TileBox& box, const TilePos& player){ + if (box.x0 <= player.x && player.x <= box.x1){ + return TilePos{player.x, box.y0 > player.y ? player.y + 1 : player.y - 1}; + } + return TilePos{box.x0 > player.x ? player.x + 1 : player.x - 1, player.y}; +} + +} + + +OverworldSim::OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script) + : m_maps(std::move(maps)) + , m_script(std::move(script)) + , m_map(find_map(m_maps, start.map)) +{ + if (m_map < 0){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Sim: start on a map that isn't loaded: " + start.map); + } + m_player = PlayerState{start.point, elevation_at(map(), start.point), false}; + m_state.facing = facing; + m_state.screen = m_script.start_menu_open ? SimScreen::START_MENU : SimScreen::OVERWORLD; + update_view(); +} + + +void OverworldSim::note(const std::string& line){ + m_state.log.push_back(std::format("[Sim {} ms] {}", m_now.count(), line)); +} +void OverworldSim::violation(const std::string& line){ + note("violation: " + line); + m_state.violations.push_back(line); +} + +void OverworldSim::update_view(){ + m_state.position = MapPosition{map().name, m_player.position}; + m_state.black_below = map().connections.empty() && map().tiles.height <= SMALL_ROOM_ROWS + && m_player.position.y >= map().tiles.height - BLACK_BELOW_ROWS; +} + +void OverworldSim::schedule(Milliseconds at, SimScreen screen, bool unfreeze){ + const Pending pending{at, screen, unfreeze}; + const auto iter = std::upper_bound( + m_pending.begin(), m_pending.end(), pending, + [](const Pending& a, const Pending& b){ return a.at < b.at; } + ); + m_pending.insert(iter, pending); +} + +void OverworldSim::advance_to(Milliseconds time){ + while (!m_pending.empty() && m_pending.front().at <= time){ + m_state.screen = m_pending.front().screen; + m_frozen = m_frozen && !m_pending.front().unfreeze; + m_pending.erase(m_pending.begin()); + } + m_now = std::max(m_now, time); +} + + +bool OverworldSim::sees(SimWatcher watcher, SimScreen screen) const{ + switch (watcher){ + case SimWatcher::FLASH: + return screen == SimScreen::BATTLE_FLASH || screen == SimScreen::FADE; + case SimWatcher::BATTLE_SCREEN: + return screen == SimScreen::BATTLE; + case SimWatcher::BATTLE_TEXT_BOX: + return screen == SimScreen::BATTLE || (screen == SimScreen::OVERWORLD && m_state.black_below); + case SimWatcher::MESSAGE: + return screen == SimScreen::MESSAGE; + case SimWatcher::FADE: + return screen == SimScreen::FADE; + } + return false; +} + +std::optional OverworldSim::first_seen(SimWatcher watcher, Milliseconds from, Milliseconds to) const{ + if (sees(watcher, m_state.screen)){ + return from; + } + for (const Pending& pending : m_pending){ + if (pending.at > to){ + break; + } + if (pending.at > from && sees(watcher, pending.screen)){ + return pending.at; + } + } + return std::nullopt; +} + +std::optional OverworldSim::watch_until(const std::vector& watchers, Milliseconds from, Milliseconds to){ + advance_to(from); + std::optional seen; + std::optional when; + for (size_t c = 0; c < watchers.size(); c++){ + const std::optional at = first_seen(watchers[c], from, to); + if (at && (!when || *at < *when)){ + when = at; + seen = SimSeen{c, *at - from}; + } + } + advance_to(when.value_or(to)); + return seen; +} + + +std::optional OverworldSim::take_warp(int map_index, const TilePos& tile) const{ + const MapWarp* warp = warp_at(m_maps[map_index], tile); + if (warp == nullptr || !warp->to){ + return std::nullopt; + } + const int destination = find_map(m_maps, warp->to->map); + if (destination < 0){ + return std::nullopt; + } + const MapData& to = m_maps[destination]; + const auto arrival = to.points.find(warp->to->point); + if (arrival == to.points.end()){ + return std::nullopt; + } + TilePos position = arrival->second; + const bool walked_out = walks_out_on_arrival(to, position); + if (walked_out){ + position = position.next(Direction::SOUTH); + } + return Step{destination, PlayerState{position, elevation_at(to, position), false}, true, walked_out, false}; +} + +std::optional OverworldSim::cross_edge(Direction direction) const{ + for (const MapConnection& connection : map().connections){ + const int destination = connection.side == direction ? find_map(m_maps, connection.to_map) : -1; + if (destination < 0){ + continue; + } + const MapData& to = m_maps[destination]; + const TilePos here = m_player.position; + TilePos point{here.x - connection.offset, here.y - connection.offset}; + switch (direction){ + case Direction::NORTH: point.y = to.tiles.height - 1; break; + case Direction::SOUTH: point.y = 0; break; + case Direction::WEST: point.x = to.tiles.width - 1; break; + case Direction::EAST: point.x = 0; break; + } + const StepKind kind = classify_step_onto(map(), m_player, direction, to, point); + if (kind != StepKind::WALK){ + return std::nullopt; + } + return Step{destination, after_step_onto(map(), m_player, to, point, kind), false, false, false}; + } + return std::nullopt; +} + +// Pressing `direction` once, as the planner's press() reads the game, and +// also hopping a ledge the way it faces. +std::optional OverworldSim::press(Direction direction) const{ + const TilePos here = m_player.position; + if (exit_mat(map(), here) == direction){ + return take_warp(m_map, here); + } + const TilePos ahead = here.next(direction); + if (direction == Direction::NORTH && is_door(map(), ahead)){ + return take_warp(m_map, ahead); + } + if (!in_bounds(map(), ahead)){ + return cross_edge(direction); + } + if (ledge_direction(tile_at(map(), ahead)) == direction){ + const TilePos landed = ahead.next(direction); + return Step{m_map, PlayerState{landed, elevation_at(map(), landed), false}, false, false, true}; + } + const StepKind kind = classify_step(map(), m_player, direction); + if (kind != StepKind::WALK){ + return std::nullopt; + } + const Step step{m_map, after_step_onto(map(), m_player, map(), ahead, kind), false, false, false}; + if (warps_on_step(map(), ahead)){ + return take_warp(m_map, ahead); + } + return step; +} + + +// A trainer on the player's map who sees them now walks up and speaks. +bool OverworldSim::trainer_sees(Milliseconds pressed){ + std::vector& objects = m_maps[m_map].objects; + for (size_t c = 0; c < objects.size(); c++){ + MapObject& trainer = objects[c]; + if (!trainer.trainer || !trainer_may_see(map(), trainer, m_player.position)){ + continue; + } + const Pokemon::TileBox box = trainer.wander.value_or(Pokemon::TileBox{trainer.x, trainer.y, trainer.x, trainer.y}); + const TilePos stop = trainer_stop(box, m_player.position); + const int approach = std::abs(stop.x - trainer.x) + std::abs(stop.y - trainer.y); + trainer.x = stop.x; + trainer.y = stop.y; + trainer.wander.reset(); + // The player turns to face the trainer. + for (Direction direction : {Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST}){ + m_state.facing = m_player.position.next(direction) == stop ? direction : m_state.facing; + } + m_trainer_speaking = c; + m_frozen = true; + schedule(pressed + m_script.timing.tile * (1 + approach) + m_script.timing.trainer_notice, SimScreen::MESSAGE, false); + note(std::format("{} on {} sees the player, walks up {} tile(s) to {}.", trainer.name, map().name, approach, to_string(stop))); + return true; + } + return false; +} + +// The player has taken `step`, pressed at `pressed`. Returns whether the +// game stopped them there: a warp, a wild battle, a trainer. +bool OverworldSim::after_step(const Step& step, Milliseconds pressed){ + const SimTiming& timing = m_script.timing; + m_map = step.map; + m_player = step.player; + m_state.steps++; + update_view(); + if (step.warped){ + m_state.warps++; + m_frozen = true; + schedule(pressed + timing.tile, SimScreen::FADE, false); + schedule(pressed + timing.tile + timing.fade, SimScreen::OVERWORLD, true); + note("warped to " + to_string(m_state.position) + "."); + return true; + } + return wild_battle(pressed) || trainer_sees(pressed); +} + +// A wild battle the script starts on this step onto tall grass. +bool OverworldSim::wild_battle(Milliseconds pressed){ + if (!is_tall_grass(map(), m_player.position)){ + return false; + } + m_grass_steps++; + for (const SimEncounter& encounter : m_script.encounters){ + if (encounter.grass_step != m_grass_steps){ + continue; + } + m_frozen = true; + m_battle_pending = true; + if (!encounter.seen_late){ + schedule(pressed + m_script.timing.flash, SimScreen::BATTLE_FLASH, false); + } + schedule(pressed + m_script.timing.battle_screen, SimScreen::BATTLE, false); + note(std::format("a wild battle on {}{}.", to_string(m_state.position), encounter.seen_late ? " (flashes missed)" : "")); + return true; + } + return false; +} + +// Blocked holding `direction` at `pressed`: a sign walked into moving north +// or south shows its message. +void OverworldSim::bump(Direction direction, Milliseconds pressed){ + const TilePos ahead = m_player.position.next(direction); + const bool sign = tile_at(map(), ahead) == TileKind::SIGN + && (direction == Direction::NORTH || direction == Direction::SOUTH); + if (!sign){ + return; + } + m_state.signs_read++; + m_frozen = true; + schedule(pressed + m_script.timing.message, SimScreen::MESSAGE, false); + note("reads the sign on " + to_string(ahead) + "."); +} + +// The steps a hold of `duration` takes, `short_by` fewer. +void OverworldSim::walk_hold(Direction direction, Milliseconds duration, int short_by){ + const Milliseconds tile = m_script.timing.tile; + const Milliseconds end = m_now + duration; + Milliseconds pressed = m_now; + if (m_state.facing != direction){ + // Holding through a turn lost a tile on the console. + m_state.facing = direction; + pressed += tile; + } + int left = (int)((end - pressed + tile - 1ms) / tile) - short_by; + for (; left > 0 && pressed < end; left--){ + const std::optional step = press(direction); + if (!step){ + bump(direction, pressed); + return; + } + if (step->walked_out){ + m_state.facing = Direction::SOUTH; + } + if (after_step(*step, pressed)){ + return; + } + pressed += step->ledge ? tile * 2 : tile; + } +} + +// A hold the game doesn't move the player for. +void OverworldSim::stuck_hold(Direction direction){ + if (m_state.screen == SimScreen::START_MENU){ + note(std::string("the D-pad moves the START menu's cursor (") + direction_name(direction) + ")."); + }else if (m_battle_pending){ + violation(std::string("the D-pad held ") + direction_name(direction) + " into a battle."); + }else{ + note(std::string("the D-pad held ") + direction_name(direction) + " under " + sim_screen_name(m_state.screen) + "."); + } +} + + +std::optional OverworldSim::hold( + Direction direction, Milliseconds duration, Milliseconds release, Milliseconds watch, + const std::vector& watchers +){ + const Milliseconds start = m_now; + m_holds++; + if (m_state.screen != SimScreen::OVERWORLD || m_frozen){ + stuck_hold(direction); + }else{ + const auto short_hold = m_script.short_holds.find(m_holds); + walk_hold(direction, duration, short_hold == m_script.short_holds.end() ? 0 : short_hold->second); + } + return watch_until(watchers, start, start + std::max(duration + release, watch)); +} + +void OverworldSim::tap(Direction direction){ + if (m_state.screen != SimScreen::OVERWORLD || m_frozen){ + stuck_hold(direction); + }else if (m_state.facing != direction){ + m_state.facing = direction; + }else{ + walk_hold(direction, m_script.timing.tile / 2, 0); + } + advance_to(m_now + TAP_TIME); +} + +std::optional OverworldSim::watch(const std::vector& watchers, Milliseconds duration){ + return watch_until(watchers, m_now, m_now + duration); +} + +SimBattleEnd OverworldSim::handle_battle(SimBattleChoice choice){ + if (!m_battle_pending){ + violation("fought a battle that isn't there, on " + std::string(sim_screen_name(m_state.screen)) + "."); + advance_to(m_now + NO_BATTLE_WAIT); + return SimBattleEnd::NO_BATTLE; + } + while (m_state.screen != SimScreen::BATTLE && !m_pending.empty()){ + advance_to(m_pending.front().at); + } + if (m_trainer && choice == SimBattleChoice::RUN){ + violation("ran from a trainer's battle."); + advance_to(m_now + BATTLE_TIME); + return SimBattleEnd::CANT_RUN; + } + advance_to(m_now + BATTLE_TIME); + m_state.screen = SimScreen::OVERWORLD; + m_frozen = false; + m_battle_pending = false; + if (m_trainer){ + MapObject& trainer = m_maps[m_map].objects[*m_trainer]; + trainer.trainer.reset(); + m_state.trainers_beaten.push_back(trainer.name); + m_trainer.reset(); + } + note(std::string(choice == SimBattleChoice::RUN ? "ran from" : "won") + " the battle."); + return SimBattleEnd::ENDED; +} + +bool OverworldSim::close_message(){ + if (m_state.screen != SimScreen::MESSAGE){ + return false; + } + advance_to(m_now + MESSAGE_CLOSE); + m_state.screen = SimScreen::OVERWORLD; + if (!m_trainer_speaking){ + m_frozen = false; + return false; + } + m_trainer = m_trainer_speaking; + m_trainer_speaking.reset(); + m_battle_pending = true; + schedule(m_now + m_script.timing.trainer_battle, SimScreen::BATTLE, false); + note("the trainer's battle starts."); + return true; +} + + + +// +// OverworldSimWalker +// + +namespace{ + +using namespace OverworldWalkSteps; + +// As the console's watch for a trainer (PokemonFRLG_OverworldRecoveryWalk.cpp). +constexpr Milliseconds TRAINER_NOTICE(1500); +constexpr Milliseconds TRAINER_SPEAKS(1000); +// The console's wait for a warp's fade (wait_out_warp()). +constexpr Milliseconds WARP_TIMEOUT(8000); + +// The detection delay of the walker's interrupt `index` in `interrupts`. +Milliseconds delay_of(const OverworldInterrupts& interrupts, size_t index){ + return interrupts[index]->detection_delay(); +} + +} + + +OverworldSimWalker::OverworldSimWalker(OverworldSim& sim, SimWalkerRules rules) + : m_sim(sim) + , m_rules(rules) +{ + // The walker's own interrupts, in its order: battles first. + const OverworldInterruptSet& walker = default_overworld_interrupts(); + m_wild = { + {"a wild battle", SimWatcher::FLASH, delay_of(walker.wild, 0), true}, + {"a wild battle (seen late)", SimWatcher::BATTLE_SCREEN, delay_of(walker.wild, 1), true}, + {"a message", SimWatcher::MESSAGE, delay_of(walker.wild, 2), false}, + }; + m_other = { + {"a message", SimWatcher::MESSAGE, delay_of(walker.other, 0), false}, + }; +} + +void OverworldSimWalker::fail(const std::string& message){ + m_log.push_back("FAILED: " + message); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, message); +} + +const std::vector& OverworldSimWalker::interrupts(const RouteStep& step) const{ + return step.wild ? m_wild : m_other; +} + +std::vector OverworldSimWalker::watchers(const std::vector& interrupts) const{ + std::vector ret; + for (const Interrupt& interrupt : interrupts){ + const bool old_battle_screen = interrupt.watcher == SimWatcher::BATTLE_SCREEN && !m_rules.battle_needs_hp_box; + ret.push_back(old_battle_screen ? SimWatcher::BATTLE_TEXT_BOX : interrupt.watcher); + } + return ret; +} + +// The story's interrupts: a battle is run from (a trainer's can't be), a +// message closed and a trainer's battle after it fought. +void OverworldSimWalker::clear(const Interrupt& interrupt){ + if (interrupt.battle){ + if (m_sim.handle_battle(SimBattleChoice::RUN) == SimBattleEnd::CANT_RUN){ + fail("Failed to flee the battle: it is a trainer's."); + } + return; + } + if (m_sim.close_message() && m_rules.fight_trainer_after_message){ + m_sim.handle_battle(SimBattleChoice::FIGHT); + } +} + +// Pokemon::clear_late_interrupts(). +size_t OverworldSimWalker::clear_late(const std::vector& interrupts, Milliseconds watch, size_t max){ + for (size_t count = 0; ; count++){ + const std::optional seen = m_sim.watch(watchers(interrupts), watch); + if (!seen){ + return count; + } + if (count >= max){ + fail(std::format("Interrupted {} times in a row after a leg.", count)); + } + m_log.push_back("Leg: " + interrupts[seen->watcher].name + " at the end of the leg."); + clear(interrupts[seen->watcher]); + } +} + +void OverworldSimWalker::check_overworld(const RouteStep& step){ + const SimScreen screen = m_sim.state().screen; + if (m_rules.check_overworld && (screen == SimScreen::START_MENU || screen == SimScreen::MESSAGE)){ + fail(std::string("walk_overworld_route(): ") + sim_screen_name(screen) + " is open, before: " + to_string(step)); + } +} + +std::optional OverworldSimWalker::hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts){ + return m_sim.hold(step.direction, hold, STEP_RELEASE, hold + STEP_RELEASE + m_rules.watch_past_hold, watchers(interrupts)); +} + +// wait_out_warp(), then check_warp_was_no_battle(). +void OverworldSimWalker::after_warp(const RouteStep& step, int warps_before){ + if (m_sim.state().warps == warps_before){ + m_sim.watch({}, WARP_TIMEOUT); + fail("walk_overworld_route(): no fade in and out after walking onto the warp to " + step.end.map + "."); + } + m_sim.watch({SimWatcher::FADE}, WARP_TIMEOUT); + m_sim.watch({}, AFTER_WARP); + if (m_sim.watch(watchers({m_wild[1]}), AFTER_WARP_BATTLE_WATCH - AFTER_WARP)){ + m_sim.handle_battle(SimBattleChoice::RUN); + fail("walk_overworld_route(): a wild battle, not the warp to " + step.end.map + ": the player is off the route."); + } +} + +std::optional OverworldSimWalker::walk_step(const RouteStep& step, std::optional facing){ + if (step.action == RouteAction::FACE){ + m_sim.tap(step.direction); + return std::nullopt; + } + if (step.action != RouteAction::WALK){ + fail("Sim: Surf isn't modelled."); + } + if (facing != step.direction){ + m_sim.tap(step.direction); + } + const int warps_before = m_sim.state().warps; + const std::vector& ints = interrupts(step); + Pokemon::LegSpec leg; + leg.direction = step.direction; + leg.tiles = step.tiles; + leg.to_wall = step.to_wall; + leg.tile_time = TILE_TIME; + leg.stop_on_interrupt = !step.to_wall; + leg.stop_if_blocked = step.to_wall && m_rules.stop_if_blocked; + Pokemon::LegCalls calls; + calls.hold_watching = [&](Milliseconds hold) -> std::optional{ + const std::optional seen = hold_watching(step, hold, ints); + return seen ? std::optional(Pokemon::HoldOutcome{seen->watcher, seen->elapsed}) : std::nullopt; + }; + calls.clear = [&](size_t index){ clear(ints[index]); }; + calls.detection_delay = [&](size_t index){ return ints[index].delay; }; + calls.name = [&](size_t index){ return ints[index].name; }; + calls.log = [&](const std::string& message){ m_log.push_back("Leg: " + message); }; + calls.fail = [&](const std::string& message){ fail(message); }; + const Pokemon::LegResult result = Pokemon::walk_leg_with(leg, calls, MAX_INTERRUPTIONS_PER_LEG); + if (result.stopped){ + return walked_near(step, result.tiles, TILE_TIME); + } + if (step.warps){ + after_warp(step, warps_before); + } + return std::nullopt; +} + +// walk_and_watch(), after clear_open_message() and check_overworld(). +StepOutcome OverworldSimWalker::walk(const RouteStep& step, std::optional facing){ + if (m_sim.state().screen == SimScreen::MESSAGE){ + m_log.push_back("Route: a message is open before " + to_string(step) + "; handing it to the leg's interrupts."); + clear_late(interrupts(step), OPEN_MESSAGE_WATCH, 1); + } + check_overworld(step); + if (const std::optional walked = walk_step(step, facing)){ + return StepOutcome{.end = StepEnd::STOPPED, .walked = walked}; + } + if (step.action == RouteAction::FACE){ + return StepOutcome{}; + } + const size_t late = clear_late(interrupts(step), step.wild ? m_rules.after_wild_leg_watch : AFTER_LEG_WATCH, MAX_INTERRUPTIONS_PER_LEG); + const bool done = late == 0 || step.warps || step.action != RouteAction::WALK; + return StepOutcome{.end = done ? StepEnd::DONE : StepEnd::LATE, .walked = std::nullopt}; +} + +void OverworldSimWalker::hold_to_warp(const RouteStep& step){ + std::vector fade_first{SimWatcher::FADE}; + for (const SimWatcher watcher : watchers(m_other)){ + fade_first.push_back(watcher); + } + const int warps_before = m_sim.state().warps; + for (size_t count = 0; count <= MAX_INTERRUPTIONS_PER_LEG; count++){ + m_sim.tap(step.direction); + const Milliseconds hold = TILE_TIME * (step.tiles + 2); + const std::optional seen = m_sim.hold(step.direction, hold, STEP_RELEASE, hold + STEP_RELEASE, fade_first); + if (seen && seen->watcher == 0){ + after_warp(step, warps_before); + return; + } + if (!seen){ + break; + } + clear(m_other[seen->watcher - 1]); + } + fail("walk_overworld_route(): no fade holding on toward the warp to " + step.end.map + "."); +} + +StepEnd OverworldSimWalker::watch_for_trainer(const RouteStep& step, int approach_tiles){ + const Milliseconds watch = TRAINER_NOTICE + TILE_TIME * approach_tiles + TRAINER_SPEAKS; + return clear_late(interrupts(step), watch, MAX_INTERRUPTIONS_PER_LEG) == 0 ? StepEnd::DONE : StepEnd::LATE; +} + +bool OverworldSimWalker::moved_past_wall(const RouteStep& step){ + const MapPosition before = m_sim.state().position; + m_sim.tap(step.direction); + return !(m_sim.state().position == before); +} + +RouteCalls OverworldSimWalker::calls(){ + RouteCalls calls; + calls.walk = [this](const RouteStep& step, std::optional facing){ return walk(step, facing); }; + calls.hold_to_warp = [this](const RouteStep& step){ hold_to_warp(step); }; + calls.log = [this](const std::string& message){ m_log.push_back(message); }; + calls.fail = [this](const std::string& message){ fail(message); }; + calls.moved_past_wall = [this](const RouteStep& step){ return moved_past_wall(step); }; + calls.watch_for_trainer = [this](const RouteStep& step, int approach_tiles){ return watch_for_trainer(step, approach_tiles); }; + return calls; +} + +std::string OverworldSimWalker::run(const std::vector& route, const RoutePlanning& planning){ + try{ + run_route(route, m_sim.state().facing, &planning, calls()); + }catch (OperationFailedException& e){ + return e.message(); + } + return ""; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h new file mode 100644 index 0000000000..b4b7aa3626 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -0,0 +1,301 @@ +/* Overworld Sim + * + * From: https://github.com/PokemonAutomation/ + * + * A whole-tile model of FireRed's overworld, for running the walker + * (run_route(), Pokemon::walk_leg_with()) without a console. The player + * moves a tile per 16 frames while the D-pad is held, by the maps' step + * rules (classify_step()), and also hops ledges the way they face, takes + * warps with a fade, reads signs walked into moving north or south, and is + * seen by trainers along their sight. Wild battles start on the steps a + * test chooses. Each of these shows a screen at a time after the step's + * press, which the walker's watchers see or miss as the console's do. + * + * Every console failure of the walker becomes a test here (red first). + * OverworldSimWalker is the console side of run_route() (RouteCalls) on + * the sim, step for step as walk_overworld_route_with_recovery() does it, + * with the walker's rules as switches, so a test can show a failure with + * the rule that was missing and its absence with the rule. + * + * Not modelled: Surf, bikes, running, HP and status. Wandering people + * stand on their tile. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldSim_H +#define PokemonAutomation_PokemonFRLG_OverworldSim_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldRecovery.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldWalk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What the screen shows, as the walker's detectors see it. +enum class SimScreen{ + OVERWORLD, + MESSAGE, // a white message box: a sign, a trainer + START_MENU, + BATTLE_FLASH, // a wild battle's opening flashes + BATTLE, // a battle's text box with the HP boxes + FADE, // a warp's fade out and in +}; +const char* sim_screen_name(SimScreen screen); + +// What the walker watches the screen with. +enum class SimWatcher{ + FLASH, // BattleFlashWatcher: a battle's flashes, and a warp's fade + BATTLE_SCREEN, // BattleScreenWatcher: the battle menu or an HP box + // BattleDialogDetector, which the walker used before BattleScreenWatcher: + // the battle text box alone, which black below a small room passes for. + BATTLE_TEXT_BOX, + MESSAGE, // WhiteDialogWatcher + FADE, // BlackScreenWatcher: a warp's fade +}; + +// A wild battle on the player's `grass_step`th step onto tall grass (from +// 1). Seen late: its flashes are missed, and only the battle screen shows. +struct SimEncounter{ + int grass_step = 1; + bool seen_late = false; +}; + +// How long after a step's press each thing shows. The walker's own +// detection delays (OverworldInterrupt::detection_delay()) are its guesses +// at these. +struct SimTiming{ + Milliseconds tile{267}; + Milliseconds flash{300}; + Milliseconds battle_screen{3700}; + Milliseconds message{400}; + Milliseconds fade{1000}; // from the step's end to the new map + Milliseconds trainer_notice{1000}; // "!" over the trainer, before they walk up + Milliseconds trainer_battle{2000}; // after the trainer's message closes +}; + +// What a test sets up beyond the maps. +struct SimScript{ + std::vector encounters; + // The START menu is open at the start: the D-pad moves its cursor. + bool start_menu_open = false; + // The hold numbered by the key (from 1) stops this many tiles short, + // with nothing on screen (the forest drift, console B, 2026-11-01). + std::map short_holds; + SimTiming timing; +}; + +// The player and the screen, and what went wrong that the game would show. +struct SimState{ + MapPosition position; + Direction facing = Direction::SOUTH; + SimScreen screen = SimScreen::OVERWORLD; + // Whether black shows below the map: the player stands near the bottom + // of a map with nothing joined to it (a small room or a gate). + bool black_below = false; + int steps = 0; + int warps = 0; + int signs_read = 0; + std::vector trainers_beaten; + // Things the walker did that the game wouldn't let pass: D-pad holds + // under a battle, a trainer's battle fled, a battle fought that wasn't + // there. + std::vector violations; + std::vector log; +}; + +// A watcher that fired: which (an index into the watchers asked for), and +// how long after the hold or watch started. +struct SimSeen{ + size_t watcher = 0; + Milliseconds elapsed{0}; +}; + +// How the walker handles the battle on screen. +enum class SimBattleChoice{ + RUN, + FIGHT, +}; +enum class SimBattleEnd{ + ENDED, + CANT_RUN, // a trainer's battle: "No! There's no running from a TRAINER battle!" + NO_BATTLE, // there was none, on screen or about to show +}; + +class OverworldSim{ +public: + OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script = {}); + + const SimState& state() const{ return m_state; } + + // Holds `direction` for `duration` then lets go for `release`, while + // `watchers` watch until `watch` (at least the hold and release) from + // the start. Returns the first that saw its screen, as run_until(). + std::optional hold( + Direction direction, Milliseconds duration, Milliseconds release, Milliseconds watch, + const std::vector& watchers + ); + + // A short press of `direction`: turns the player, or steps if they + // already face that way. + void tap(Direction direction); + + // Watches `watchers` for `duration`, as wait_until(). + std::optional watch(const std::vector& watchers, Milliseconds duration); + + // Runs from or fights the battle on screen, back to the overworld. A + // trainer's battle can't be run from; a battle that isn't there is + // waited out (the story's battle loop gives up after 15 s). + SimBattleEnd handle_battle(SimBattleChoice choice); + + // Closes the message on screen with B. Returns whether a trainer's + // battle follows it. + bool close_message(); + +private: + // A screen that shows at `at`; `unfreeze`: the player can move again. + struct Pending{ + Milliseconds at; + SimScreen screen; + bool unfreeze; + }; + // Where one press of the D-pad takes the player. + struct Step{ + int map = 0; + PlayerState player; + bool warped = false; + bool walked_out = false; // the warp ended with the game walking the player a tile south + bool ledge = false; + }; + + void advance_to(Milliseconds time); + void schedule(Milliseconds at, SimScreen screen, bool unfreeze); + bool sees(SimWatcher watcher, SimScreen screen) const; + std::optional first_seen(SimWatcher watcher, Milliseconds from, Milliseconds to) const; + std::optional watch_until(const std::vector& watchers, Milliseconds from, Milliseconds to); + void walk_hold(Direction direction, Milliseconds duration, int short_by); + void stuck_hold(Direction direction); + void bump(Direction direction, Milliseconds pressed); + std::optional press(Direction direction) const; + std::optional take_warp(int map_index, const TilePos& tile) const; + std::optional cross_edge(Direction direction) const; + bool after_step(const Step& step, Milliseconds pressed); + bool wild_battle(Milliseconds pressed); + bool trainer_sees(Milliseconds pressed); + void update_view(); + void note(const std::string& line); + void violation(const std::string& line); + const MapData& map() const{ return m_maps[m_map]; } + + std::vector m_maps; + SimScript m_script; + int m_map = 0; + PlayerState m_player; + Milliseconds m_now{0}; + std::vector m_pending; // in time order + // The game has stopped the player: a battle, a message, a warp. + bool m_frozen = false; + // A battle is on screen or about to show. + bool m_battle_pending = false; + // The trainer (an object of the player's map) whose message is up or + // about to show, and whose battle follows it. + std::optional m_trainer_speaking; + // The trainer whose battle is on screen or about to show. + std::optional m_trainer; + int m_grass_steps = 0; + int m_holds = 0; + SimState m_state; +}; + + +// The walker's rules that console failures added, each on unless a test +// turns it off to show the failure it fixed. +struct SimWalkerRules{ + // Fail before a step unless the overworld is up (START menu left open, + // console B, 2026-11-01, Viridian Forest). + bool check_overworld = true; + // A battle needs an HP box or the battle menu: black below a small room + // isn't one (console B, 2026-11-01, Viridian Forest's north gate). + bool battle_needs_hp_box = true; + // A trainer's battle after their message is fought, not taken for a + // wild one and run from (console B, 2026-11-01, Viridian Forest). + bool fight_trainer_after_message = true; + // How long the walker watches after a leg through grass for a battle + // whose flashes it missed. It watched 500 ms, and walked the next leg + // into the battle (console B, 2026-11-01, Route 1, run 7 and r14). + Milliseconds after_wild_leg_watch = OverworldWalkSteps::AFTER_WILD_LEG_WATCH; + // A leg to a wall held again after an interrupt stops when it is + // interrupted again right away: by a sign it is held into. Without it + // the walker read the sign 6 times (console B, 2026-11-01, r16). + bool stop_if_blocked = true; + // How long a hold's watch goes on past the hold and its release. 0 as + // now; the tile-at-a-time build watched each step for 900 ms, and saw + // the warp's fade on the step onto the forest's north gate as a battle. + Milliseconds watch_past_hold{0}; +}; + +// The console side of run_route() on an OverworldSim, as +// walk_overworld_route_with_recovery() does it, with the story's +// interrupts: a wild battle (flashes, or seen late) is fought or run from, +// a message is closed and a trainer's battle after it fought. +class OverworldSimWalker{ +public: + OverworldSimWalker(OverworldSim& sim, SimWalkerRules rules = {}); + + // RouteCalls whose `fail` throws OperationFailedException, as the + // console's does. + RouteCalls calls(); + + // run_route() from the sim's facing, planned with `planning`. Returns + // the failure's message, or empty if the route was walked. + std::string run(const std::vector& route, const RoutePlanning& planning); + + const std::vector& log() const{ return m_log; } + +private: + // One of the story's interrupts (story_interrupts()), with the + // walker's detection delay for it. + struct Interrupt{ + std::string name; + SimWatcher watcher; + Milliseconds delay; + bool battle; + }; + StepOutcome walk(const RouteStep& step, std::optional facing); + std::optional walk_step(const RouteStep& step, std::optional facing); + void after_warp(const RouteStep& step, int warps_before); + std::optional hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts); + size_t clear_late(const std::vector& interrupts, Milliseconds watch, size_t max); + void clear(const Interrupt& interrupt); + void hold_to_warp(const RouteStep& step); + StepEnd watch_for_trainer(const RouteStep& step, int approach_tiles); + bool moved_past_wall(const RouteStep& step); + void check_overworld(const RouteStep& step); + const std::vector& interrupts(const RouteStep& step) const; + std::vector watchers(const std::vector& interrupts) const; + [[noreturn]] void fail(const std::string& message); + + OverworldSim& m_sim; + SimWalkerRules m_rules; + std::vector m_wild; + std::vector m_other; + std::vector m_log; +}; + + +void add_tests_OverworldSim(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp new file mode 100644 index 0000000000..0c3b955630 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -0,0 +1,422 @@ +/* Overworld Sim Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The walker's console failures (console B, 2026-11-01 and 02; + * ~/FRLGLab/notes/newgame-firered-console-B.md) replayed on the sim: each + * test walks the route that failed, the way it failed, and checks the + * walker now gets the player there, or stops without claiming it did. + * Where a walker rule fixed the failure, the test also turns the rule off + * and checks the sim fails the old way, so the sim is known to reproduce + * it. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class Test_OverworldSim : public UnitTest{ +public: + Test_OverworldSim(std::string name, std::function body) + : UnitTest("PokemonFRLG::OverworldSim - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +const std::vector& maps(){ + static const std::vector MAPS = overworld_maps(); + return MAPS; +} + +MapPosition at(const char* map, int x, int y){ + return MapPosition{map, {x, y}}; +} + +// Where a warp to point `point` of `map` puts the player: there, or a tile +// south when the game walks them out of a door. +MapPosition arrival(const char* map, const char* point){ + const TilePos tile = map_point(maps(), map, point); + for (const MapData& data : maps()){ + if (data.name == map && walks_out_on_arrival(data, tile)){ + return MapPosition{map, tile.next(Direction::SOUTH)}; + } + } + return MapPosition{map, tile}; +} + +RouteStep leg(Direction direction, int tiles, MapPosition end, bool to_wall){ + RouteStep step; + step.direction = direction; + step.tiles = tiles; + step.to_wall = to_wall; + step.facing_after = direction; + step.end = std::move(end); + return step; +} + +// A walk on the sim: the route from `start` (planned to `goal` if not +// given), what the sim starts with, and the walker's rules. +struct SimCase{ + MapPosition start = {}; + Direction facing = Direction::NORTH; + MapPosition goal = {}; + SimScript script = {}; + SimWalkerRules rules = {}; + std::optional> route = std::nullopt; + WallCheck wall_check = WallCheck::TAP; +}; + +struct SimRun{ + std::vector route; + std::string failure; + SimState state; + std::vector log; +}; + +std::vector planned(const SimCase& c){ + if (c.route){ + return *c.route; + } + const std::optional> route = plan_overworld_route( + maps(), c.start, RouteGoal{c.goal, std::nullopt}, default_route_costs(), c.facing + ); + if (!route){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No route from " + to_string(c.start) + " to " + to_string(c.goal) + "."); + } + return *route; +} + +SimRun run_case(const SimCase& c){ + SimRun run; + run.route = planned(c); + OverworldSim sim(maps(), c.start, c.facing, c.script); + OverworldSimWalker walker(sim, c.rules); + const RoutePlanning planning{.maps = &maps(), .costs = default_route_costs(), .start = c.start, .label = "Sim", .wall_check = c.wall_check}; + run.failure = walker.run(run.route, planning); + run.state = sim.state(); + run.log = walker.log(); + run.log.insert(run.log.end(), sim.state().log.begin(), sim.state().log.end()); + return run; +} + +std::string describe(const std::vector& route){ + std::string text; + for (const RouteStep& step : route){ + text += "\n " + to_string(step); + } + return text; +} + +std::string describe(const SimRun& run){ + std::string text = std::format( + "\n ended at {}, facing {}, on {}; failure: \"{}\"", + to_string(run.state.position), direction_name(run.state.facing), sim_screen_name(run.state.screen), run.failure + ); + for (const std::string& violation : run.state.violations){ + text += "\n violation: " + violation; + } + text += "\n route:" + describe(run.route) + "\n log:"; + for (const std::string& line : run.log){ + text += "\n " + line; + } + return text; +} + +// The walk returned with the player at `goal`, and the game let it all pass. +bool arrived(const SimRun& run, const MapPosition& goal){ + return run.failure.empty() && run.state.position == goal && run.state.violations.empty(); +} + +// The walk stopped with `failure`, without claiming to be anywhere. +bool stopped_with(const SimRun& run, const std::string& failure){ + return run.failure.find(failure) != std::string::npos; +} + +bool on_grass(const MapPosition& tile){ + for (const MapData& map : maps()){ + if (map.name == tile.map){ + return is_tall_grass(map, tile.point); + } + } + return false; +} + +// The grass steps a walk of `route` from `start` takes before step `index` +// (from 0), and on it. +struct GrassSteps{ + int before = 0; + int on = 0; +}; +GrassSteps grass_steps(const MapPosition& start, const std::vector& route, size_t index){ + GrassSteps steps; + MapPosition from = start; + for (size_t c = 0; c <= index && c < route.size(); c++){ + const std::vector tiles = leg_tiles(maps(), from, route[c]); + for (size_t t = 1; t < tiles.size(); t++){ + (c < index ? steps.before : steps.on) += on_grass(tiles[t]) ? 1 : 0; + } + from = route[c].end; + } + return steps; +} + +bool open_wild_walk(const RouteStep& step){ + return step.action == RouteAction::WALK && step.wild && !step.warps && !step.to_wall; +} + +// The first open WALK of `route` through grass that ends on grass. +std::optional leg_ending_on_grass(const std::vector& route){ + for (size_t c = 0; c < route.size(); c++){ + if (open_wild_walk(route[c]) && on_grass(route[c].end)){ + return c; + } + } + return std::nullopt; +} + +// The longest open WALK of `route` through grass. +std::optional longest_wild_leg(const std::vector& route){ + std::optional found; + for (size_t c = 0; c < route.size(); c++){ + if (open_wild_walk(route[c]) && (!found || route[c].tiles > route[*found].tiles)){ + found = c; + } + } + return found; +} + + +// cp0007 m6f and r15 (console B, 2026-11-01): out of Viridian Forest +// through its north gate. The leg through the grass ends on the gate's +// warp. Two rules keep it from failing on screens that aren't battles: +// the hold isn't watched past its release, which the warp's fade comes +// after (the tile-at-a-time build watched each step 900 ms, took the fade +// for a battle's flashes, and tried to flee in the gate); and a battle +// needs an HP box (black below the gate's mat read as a battle's text +// box, and the story fought it for 10 minutes). +UnitTestResult test_forest_north_gate(){ + SimCase c{.start = at("ViridianForest", 5, 20), .facing = Direction::NORTH, .goal = at("Route2_ViridianForest_NorthEntrance", 7, 9)}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal) || now.state.warps != 1){ + return "Expected the gate reached:" + describe(now); + } + SimCase watched_past = c; + watched_past.rules.watch_past_hold = Milliseconds(900); + const SimRun fade = run_case(watched_past); + if (arrived(fade, c.goal)){ + return "Expected the fade taken for a battle when the hold is watched 900 ms past its end:" + describe(fade); + } + SimCase text_box = c; + text_box.rules.battle_needs_hp_box = false; + const SimRun black = run_case(text_box); + if (arrived(black, c.goal)){ + return "Expected the black below the gate's mat taken for a battle without an HP box:" + describe(black); + } + return true; +} + +// cp0007-zy (console B, 2026-11-01): with the START menu still open, three +// legs to walls in Viridian Forest "walked" without the player moving. +// The walker now stops before the first. +UnitTestResult test_start_menu_open(){ + SimCase c{.start = at("ViridianForest", 42, 44), .facing = Direction::NORTH, .goal = at("ViridianForest", 39, 25)}; + c.script.start_menu_open = true; + const SimRun now = run_case(c); + if (!stopped_with(now, "the START menu is open") || now.state.steps != 0){ + return "Expected a stop before the first leg:" + describe(now); + } + SimCase unchecked = c; + unchecked.rules.check_overworld = false; + const SimRun old = run_case(unchecked); + if (!old.failure.empty() || !(old.state.position == c.start)){ + return "Expected the walk to claim the route done without moving, with the check off:" + describe(old); + } + return true; +} + +// Route 1 (console B, 2026-11-01, run 7 and r14): a battle on a leg's last +// grass step whose flashes are missed shows only after the leg. The walker +// watches long enough after a leg through grass to see it and run before +// the next leg; watching 500 ms, it walked the next leg into the battle. +UnitTestResult test_battle_at_end_of_leg(){ + SimCase c{.start = at("PalletTown", 12, 1), .facing = Direction::NORTH, .goal = at("ViridianCity", 26, 27)}; + const std::vector route = planned(c); + const std::optional wild = leg_ending_on_grass(route); + if (!wild){ + return "Expected an open leg ending on Route 1's grass:" + describe(route); + } + const GrassSteps steps = grass_steps(c.start, route, *wild); + c.script.encounters = {{.grass_step = steps.before + steps.on, .seen_late = true}}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal)){ + return "Expected the battle run from, then the route walked:" + describe(now); + } + SimCase short_watch = c; + short_watch.rules.after_wild_leg_watch = Milliseconds(500); + const SimRun old = run_case(short_watch); + if (old.state.violations.empty()){ + return "Expected the next leg held into the battle when watching 500 ms:" + describe(old); + } + return true; +} + +// r16 and r17 (console B, 2026-11-01), Route 1 to Oak's Lab: a battle seen +// only late stops an open leg through grass part-way. The walker works out +// from the timing which tiles the player may be on, finds them again at +// walls, and walks on to the lab's door. +UnitTestResult test_late_battle_mid_leg(){ + SimCase c{.start = at("ViridianCity_Mart", 4, 3), .facing = Direction::WEST, .goal = at("PalletTown_ProfessorOaksLab", 6, 11)}; + const std::vector route = planned(c); + const std::optional open = longest_wild_leg(route); + if (!open || route[*open].tiles < 16){ + return "Expected an open leg through Route 1's grass of 16 tiles or more:" + describe(route); + } + const GrassSteps steps = grass_steps(c.start, route, *open); + c.script.encounters = {{.grass_step = steps.before + 1, .seen_late = true}}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal)){ + return "Expected the player found again and the lab reached:" + describe(now); + } + return true; +} + +// cp0007 m6f (console B, 2026-11-01), Viridian Forest: a Bug Catcher sees +// the player, speaks, and their battle starts. It is fought; the walker +// tried to flee it, 5 times, when it closed the message as any other. +UnitTestResult test_trainer_not_fled(){ + SimCase c{.start = at("ViridianForest", 42, 49), .facing = Direction::NORTH, .goal = at("ViridianForest", 41, 40)}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal) || now.state.trainers_beaten.empty()){ + return "Expected the Bug Catcher fought and the route walked:" + describe(now); + } + SimCase old_message = c; + old_message.rules.fight_trainer_after_message = false; + const SimRun old = run_case(old_message); + if (old.state.violations.empty()){ + return "Expected the trainer's battle run from, or walked into, without the rule:" + describe(old); + } + return true; +} + +// cp0007-r..t (console B, 2026-11-01), Viridian City: "south 2 (to wall)" +// from the Pokemon Center held into a ledge and hopped it, to (26, 31). +// The planner no longer holds into ledges; the old leg still hops one. +UnitTestResult test_no_hold_over_ledge(){ + const SimCase c{.start = at("ViridianCity", 26, 27), .facing = Direction::SOUTH, .goal = at("ViridianCity", 26, 29)}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal)){ + return "Expected the route to stop above the ledge:" + describe(now); + } + SimCase old_leg = c; + old_leg.route = std::vector{leg(Direction::SOUTH, 2, c.goal, true)}; + old_leg.wall_check = WallCheck::SKIP; // the tap after it came later + const SimRun old = run_case(old_leg); + if (!(old.state.position == at("ViridianCity", 26, 31))){ + return "Expected the old leg to hop the ledge to (26, 31):" + describe(old); + } + return true; +} + +// r16 (console B, 2026-11-01), Viridian Forest: an open leg west ended 2 +// tiles short with nothing on screen, and the next leg, south to a wall, +// was held into the TRAINER TIPS sign on (9, 29) six times. The walker now +// stops at the second read, as off the route; it can't yet tell the leg +// ended short (follow-up). +UnitTestResult test_short_leg_then_sign(){ + SimCase c{.start = at("ViridianForest", 13, 28), .facing = Direction::WEST, .goal = at("ViridianForest", 7, 33)}; + c.route = std::vector{ + leg(Direction::WEST, 6, at("ViridianForest", 7, 28), false), + leg(Direction::SOUTH, 5, c.goal, true), + }; + c.script.short_holds[1] = 2; + const SimRun now = run_case(c); + if (!stopped_with(now, "interrupted right away, again") || now.state.signs_read > 2){ + return "Expected a stop at the sign's second read:" + describe(now); + } + SimCase unbounded = c; + unbounded.rules.stop_if_blocked = false; + const SimRun old = run_case(unbounded); + if (!stopped_with(old, "Interrupted 6 times") || old.state.signs_read != 6){ + return "Expected the sign read 6 times without the rule:" + describe(old); + } + return true; +} + +// r18 (console B, 2026-11-01), Pewter Gym: after Brock, Camper Liam sees +// the player on the walk south to the door, walks up and battles. The +// route holds on south to the door's mat; finding the player again at +// walls failed there, since the gym's trainers block every hold. +UnitTestResult test_trainer_on_way_out(){ + const SimCase c{.start = at("PewterCity_Gym", 6, 6), .facing = Direction::NORTH, .goal = arrival("PewterCity", "warp_2")}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal) || now.state.trainers_beaten != std::vector{"camper"}){ + return "Expected Liam fought and the gym left:" + describe(now); + } + return true; +} + +// cp0006-a (console B, 2026-11-01), Viridian Mart: the clerk's scene ends +// with the player on (4, 3), the story's start for the walk out. From the +// tile beside it the walk misses the only exit mat, (4, 7), and stops on +// no fade rather than going on as if outside. +UnitTestResult test_mart_exit(){ + const SimCase c{.start = at("ViridianCity_Mart", 4, 3), .facing = Direction::WEST, .goal = arrival("ViridianCity", "warp_4")}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal)){ + return "Expected the Mart left by its mat:" + describe(now); + } + SimCase wrong = c; + wrong.route = planned(c); + wrong.start = at("ViridianCity_Mart", 5, 3); + const SimRun off = run_case(wrong); + if (!stopped_with(off, "no fade") || off.state.warps != 0){ + return "Expected a stop on no fade from (5, 3):" + describe(off); + } + return true; +} + +} + + +void add_tests_OverworldSim(UnitTestDatabase& database){ + database.add("the forest's north gate: no fade or black read as a battle", test_forest_north_gate); + database.add("the START menu left open", test_start_menu_open); + database.add("a battle at the end of a leg", test_battle_at_end_of_leg); + database.add("a late battle stops an open leg", test_late_battle_mid_leg); + database.add("a trainer's battle is fought, not fled", test_trainer_not_fled); + database.add("no hold over a ledge", test_no_hold_over_ledge); + database.add("a short leg, then a sign", test_short_leg_then_sign); + database.add("a trainer on the way out of Pewter Gym", test_trainer_on_way_out); + database.add("out of Viridian Mart from the clerk's scene", test_mart_exit); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index ce5f8865ac..e4a03db650 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -37,6 +37,7 @@ #include "Overworld/PokemonFRLG_OverworldReanchor.h" #include "Overworld/PokemonFRLG_OverworldRecovery.h" #include "Overworld/PokemonFRLG_OverworldRoute.h" +#include "Overworld/PokemonFRLG_OverworldSim.h" #include "Overworld/PokemonFRLG_OverworldWalk.h" #include "Overworld/PokemonFRLG_PlayerFacingReader.h" #include "Programs/PokemonFRLG_NamingScreenKeyboard.h" @@ -731,6 +732,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_OverworldWalk(database); add_tests_OverworldReanchor(database); add_tests_OverworldRecovery(database); + add_tests_OverworldSim(database); add_tests_PlayerFacingReader(database); add_tests_AutoStory(database); add_tests_AutoStorySimulation(database); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a094132814..5f07a24c47 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1822,6 +1822,9 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery_Tests.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp