From e153b53b7afda1880a9a7c2aa3a3a7b28ffc378a Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 10 Nov 2026 15:04:40 -0800 Subject: [PATCH] FRLG AutoStory: battles, party and the trimmed battle data The story's battle flow and party tracking, copied from #213's tip: the console actions battles use, the battle loop and its decisions, the party's moves and PP, the summary reader, and the battle data cut to types, damage flags and PP. A battle's foes come from its plan; with no plan move, the damaging move with the best type multiplier against them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- SerialPrograms/CMakeLists.txt | 2 + .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../Programs/AutoStory/BattleData/moves.json | 356 +++++++ .../AutoStory/BattleData/species.json | 388 +++++++ .../AutoStory/BattleData/type_chart.json | 112 ++ .../PokemonFRLG_AutoStoryActions.cpp | 846 +++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryActions.h | 85 ++ .../AutoStory/PokemonFRLG_AutoStoryBattle.cpp | 976 ++++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryBattle.h | 113 ++ .../PokemonFRLG_AutoStoryBattleData.cpp | 173 ++++ .../PokemonFRLG_AutoStoryBattleData.h | 68 ++ .../PokemonFRLG_AutoStoryBattleData_Tests.cpp | 224 ++++ .../PokemonFRLG_AutoStoryBattleDecisions.cpp | 360 +++++++ .../PokemonFRLG_AutoStoryBattleDecisions.h | 194 ++++ .../PokemonFRLG_AutoStoryBattleRisk.h | 43 + .../PokemonFRLG_AutoStoryBattleTurns.h | 92 ++ .../AutoStory/PokemonFRLG_AutoStoryIntro.h | 71 ++ .../PokemonFRLG_AutoStoryItemsPocket.h | 68 ++ .../PokemonFRLG_AutoStoryItems_Tests.cpp | 341 ++++++ .../AutoStory/PokemonFRLG_AutoStoryLevelUps.h | 56 + .../AutoStory/PokemonFRLG_AutoStoryMoveData.h | 60 ++ .../PokemonFRLG_AutoStoryNewMembers.h | 55 + .../AutoStory/PokemonFRLG_AutoStoryParty.cpp | 422 ++++++++ .../AutoStory/PokemonFRLG_AutoStoryParty.h | 74 ++ .../PokemonFRLG_AutoStoryPartyMember.h | 75 ++ .../PokemonFRLG_AutoStoryParty_Tests.cpp | 901 ++++++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryPresses.h | 66 ++ .../AutoStory/PokemonFRLG_AutoStorySave.h | 91 ++ .../PokemonFRLG_AutoStoryStartMenu.h | 66 ++ .../AutoStory/PokemonFRLG_AutoStoryStats.h | 34 + .../PokemonFRLG_AutoStorySummary.cpp | 153 +++ .../AutoStory/PokemonFRLG_AutoStorySummary.h | 57 + .../AutoStory/PokemonFRLG_AutoStorySupplies.h | 107 ++ SerialPrograms/cmake/SourceFiles.cmake | 28 + devtools/maps/RESOURCE_MAPS.md | 6 +- 35 files changed, 6764 insertions(+), 1 deletion(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/moves.json create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/species.json create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/type_chart.json create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleRisk.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleTurns.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLevelUps.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMoveData.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryNewMembers.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyMember.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStats.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index 01d3bb2bca..4f343321ce 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -231,6 +231,8 @@ include(cmake/PokesimMapResources.cmake) pa_frlg_map_resources(FRLG_MAP_RESOURCES) pa_embed_text_files(SerialProgramsLib "${FRLG_MAP_RESOURCES}" VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h PokemonAutomation::NintendoSwitch::PokemonFRLG overworld_map_json) +pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData + VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h PokemonAutomation::NintendoSwitch::PokemonFRLG autostory_battle_json) # Create binary target diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 961badd4e6..42e3411280 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -42,6 +42,7 @@ #include "Overworld/PokemonFRLG_OverworldWalk.h" #include "Overworld/PokemonFRLG_PlayerFacingReader.h" #include "PokemonFRLG_Navigation.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h" #include "Tests/TestUtils.h" #include "PokemonFRLG_Tests.h" @@ -323,6 +324,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_OverworldReanchor(database); add_tests_OverworldRecovery(database); add_tests_PlayerFacingReader(database); + add_tests_AutoStoryItems(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/moves.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/moves.json new file mode 100644 index 0000000000..6927368ca1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/moves.json @@ -0,0 +1,356 @@ +{ +"pound": ["normal", 1, 35], +"karate-chop": ["fighting", 1, 25], +"double-slap": ["normal", 1, 10], +"comet-punch": ["normal", 1, 15], +"mega-punch": ["normal", 1, 20], +"pay-day": ["normal", 1, 20], +"fire-punch": ["fire", 1, 15], +"ice-punch": ["ice", 1, 15], +"thunder-punch": ["electric", 1, 15], +"scratch": ["normal", 1, 35], +"vise-grip": ["normal", 1, 30], +"guillotine": ["normal", 1, 5], +"razor-wind": ["normal", 1, 10], +"swords-dance": ["normal", 0, 30], +"cut": ["normal", 1, 30], +"gust": ["flying", 1, 35], +"wing-attack": ["flying", 1, 35], +"whirlwind": ["normal", 0, 20], +"fly": ["flying", 1, 15], +"bind": ["normal", 1, 20], +"slam": ["normal", 1, 20], +"vine-whip": ["grass", 1, 10], +"stomp": ["normal", 1, 20], +"double-kick": ["fighting", 1, 30], +"mega-kick": ["normal", 1, 5], +"jump-kick": ["fighting", 1, 25], +"rolling-kick": ["fighting", 1, 15], +"sand-attack": ["ground", 0, 15], +"headbutt": ["normal", 1, 15], +"horn-attack": ["normal", 1, 25], +"fury-attack": ["normal", 1, 20], +"horn-drill": ["normal", 1, 5], +"tackle": ["normal", 1, 35], +"body-slam": ["normal", 1, 15], +"wrap": ["normal", 1, 20], +"take-down": ["normal", 1, 20], +"thrash": ["normal", 1, 20], +"double-edge": ["normal", 1, 15], +"tail-whip": ["normal", 0, 30], +"poison-sting": ["poison", 1, 35], +"twineedle": ["bug", 1, 20], +"pin-missile": ["bug", 1, 20], +"leer": ["normal", 0, 30], +"bite": ["dark", 1, 25], +"growl": ["normal", 0, 40], +"roar": ["normal", 0, 20], +"sing": ["normal", 0, 15], +"supersonic": ["normal", 0, 20], +"sonic-boom": ["normal", 1, 20], +"disable": ["normal", 0, 20], +"acid": ["poison", 1, 30], +"ember": ["fire", 1, 25], +"flamethrower": ["fire", 1, 15], +"mist": ["ice", 0, 30], +"water-gun": ["water", 1, 25], +"hydro-pump": ["water", 1, 5], +"surf": ["water", 1, 15], +"ice-beam": ["ice", 1, 10], +"blizzard": ["ice", 1, 5], +"psybeam": ["psychic", 1, 20], +"bubble-beam": ["water", 1, 20], +"aurora-beam": ["ice", 1, 20], +"hyper-beam": ["normal", 1, 5], +"peck": ["flying", 1, 35], +"drill-peck": ["flying", 1, 20], +"submission": ["fighting", 1, 25], +"low-kick": ["fighting", 1, 20], +"counter": ["fighting", 1, 20], +"seismic-toss": ["fighting", 1, 20], +"strength": ["normal", 1, 15], +"absorb": ["grass", 1, 20], +"mega-drain": ["grass", 1, 10], +"leech-seed": ["grass", 0, 10], +"growth": ["normal", 0, 40], +"razor-leaf": ["grass", 1, 25], +"solar-beam": ["grass", 1, 10], +"poison-powder": ["poison", 0, 35], +"stun-spore": ["grass", 0, 30], +"sleep-powder": ["grass", 0, 15], +"petal-dance": ["grass", 1, 20], +"string-shot": ["bug", 0, 40], +"dragon-rage": ["dragon", 1, 10], +"fire-spin": ["fire", 1, 15], +"thunder-shock": ["electric", 1, 30], +"thunderbolt": ["electric", 1, 15], +"thunder-wave": ["electric", 0, 20], +"thunder": ["electric", 1, 10], +"rock-throw": ["rock", 1, 15], +"earthquake": ["ground", 1, 10], +"fissure": ["ground", 1, 5], +"dig": ["ground", 1, 10], +"toxic": ["poison", 0, 10], +"confusion": ["psychic", 1, 25], +"psychic": ["psychic", 1, 10], +"hypnosis": ["psychic", 0, 20], +"meditate": ["psychic", 0, 40], +"agility": ["psychic", 0, 30], +"quick-attack": ["normal", 1, 30], +"rage": ["normal", 1, 20], +"teleport": ["psychic", 0, 20], +"night-shade": ["ghost", 1, 15], +"mimic": ["normal", 0, 10], +"screech": ["normal", 0, 40], +"double-team": ["normal", 0, 15], +"recover": ["normal", 0, 20], +"harden": ["normal", 0, 30], +"minimize": ["normal", 0, 20], +"smokescreen": ["normal", 0, 20], +"confuse-ray": ["ghost", 0, 10], +"withdraw": ["water", 0, 40], +"defense-curl": ["normal", 0, 40], +"barrier": ["psychic", 0, 30], +"light-screen": ["psychic", 0, 30], +"haze": ["ice", 0, 30], +"reflect": ["psychic", 0, 20], +"focus-energy": ["normal", 0, 30], +"bide": ["normal", 1, 10], +"metronome": ["normal", 0, 10], +"mirror-move": ["flying", 0, 20], +"self-destruct": ["normal", 1, 5], +"egg-bomb": ["normal", 1, 10], +"lick": ["ghost", 1, 30], +"smog": ["poison", 1, 20], +"sludge": ["poison", 1, 20], +"bone-club": ["ground", 1, 20], +"fire-blast": ["fire", 1, 5], +"waterfall": ["water", 1, 15], +"clamp": ["water", 1, 10], +"swift": ["normal", 1, 20], +"skull-bash": ["normal", 1, 15], +"spike-cannon": ["normal", 1, 15], +"constrict": ["normal", 1, 35], +"amnesia": ["psychic", 0, 20], +"kinesis": ["psychic", 0, 15], +"soft-boiled": ["normal", 0, 10], +"high-jump-kick": ["fighting", 1, 20], +"glare": ["normal", 0, 30], +"dream-eater": ["psychic", 1, 15], +"poison-gas": ["poison", 0, 40], +"barrage": ["normal", 1, 20], +"leech-life": ["bug", 1, 15], +"lovely-kiss": ["normal", 0, 10], +"sky-attack": ["flying", 1, 5], +"transform": ["normal", 0, 10], +"bubble": ["water", 1, 30], +"dizzy-punch": ["normal", 1, 10], +"spore": ["grass", 0, 15], +"flash": ["normal", 0, 20], +"psywave": ["psychic", 1, 15], +"splash": ["normal", 0, 40], +"acid-armor": ["poison", 0, 40], +"crabhammer": ["water", 1, 10], +"explosion": ["normal", 1, 5], +"fury-swipes": ["normal", 1, 15], +"bonemerang": ["ground", 1, 10], +"rest": ["psychic", 0, 10], +"rock-slide": ["rock", 1, 10], +"hyper-fang": ["normal", 1, 15], +"sharpen": ["normal", 0, 30], +"conversion": ["normal", 0, 30], +"tri-attack": ["normal", 1, 10], +"super-fang": ["normal", 1, 10], +"slash": ["normal", 1, 20], +"substitute": ["normal", 0, 10], +"struggle": ["normal", 1, 1], +"sketch": ["normal", 0, 1], +"triple-kick": ["fighting", 1, 10], +"thief": ["dark", 1, 10], +"spider-web": ["bug", 0, 10], +"mind-reader": ["normal", 0, 5], +"nightmare": ["ghost", 0, 15], +"flame-wheel": ["fire", 1, 25], +"snore": ["normal", 1, 15], +"curse": ["mystery", 0, 10], +"flail": ["normal", 1, 15], +"conversion-2": ["normal", 0, 30], +"aeroblast": ["flying", 1, 5], +"cotton-spore": ["grass", 0, 40], +"reversal": ["fighting", 1, 15], +"spite": ["ghost", 0, 10], +"powder-snow": ["ice", 1, 25], +"protect": ["normal", 0, 10], +"mach-punch": ["fighting", 1, 30], +"scary-face": ["normal", 0, 10], +"feint-attack": ["dark", 1, 20], +"sweet-kiss": ["normal", 0, 10], +"belly-drum": ["normal", 0, 10], +"sludge-bomb": ["poison", 1, 10], +"mud-slap": ["ground", 1, 10], +"octazooka": ["water", 1, 10], +"spikes": ["ground", 0, 20], +"zap-cannon": ["electric", 1, 5], +"foresight": ["normal", 0, 40], +"destiny-bond": ["ghost", 0, 5], +"perish-song": ["normal", 0, 5], +"icy-wind": ["ice", 1, 15], +"detect": ["fighting", 0, 5], +"bone-rush": ["ground", 1, 10], +"lock-on": ["normal", 0, 5], +"outrage": ["dragon", 1, 15], +"sandstorm": ["rock", 0, 10], +"giga-drain": ["grass", 1, 5], +"endure": ["normal", 0, 10], +"charm": ["normal", 0, 20], +"rollout": ["rock", 1, 20], +"false-swipe": ["normal", 1, 40], +"swagger": ["normal", 0, 15], +"milk-drink": ["normal", 0, 10], +"spark": ["electric", 1, 20], +"fury-cutter": ["bug", 1, 20], +"steel-wing": ["steel", 1, 25], +"mean-look": ["normal", 0, 5], +"attract": ["normal", 0, 15], +"sleep-talk": ["normal", 0, 10], +"heal-bell": ["normal", 0, 5], +"return": ["normal", 1, 20], +"present": ["normal", 1, 15], +"frustration": ["normal", 1, 20], +"safeguard": ["normal", 0, 25], +"pain-split": ["normal", 0, 20], +"sacred-fire": ["fire", 1, 5], +"magnitude": ["ground", 1, 30], +"dynamic-punch": ["fighting", 1, 5], +"megahorn": ["bug", 1, 10], +"dragon-breath": ["dragon", 1, 20], +"baton-pass": ["normal", 0, 40], +"encore": ["normal", 0, 5], +"pursuit": ["dark", 1, 20], +"rapid-spin": ["normal", 1, 40], +"sweet-scent": ["normal", 0, 20], +"iron-tail": ["steel", 1, 15], +"metal-claw": ["steel", 1, 35], +"vital-throw": ["fighting", 1, 10], +"morning-sun": ["normal", 0, 5], +"synthesis": ["grass", 0, 5], +"moonlight": ["normal", 0, 5], +"hidden-power": ["normal", 1, 15], +"cross-chop": ["fighting", 1, 5], +"twister": ["dragon", 1, 20], +"rain-dance": ["water", 0, 5], +"sunny-day": ["fire", 0, 5], +"crunch": ["dark", 1, 15], +"mirror-coat": ["psychic", 1, 20], +"psych-up": ["normal", 0, 10], +"extreme-speed": ["normal", 1, 5], +"ancient-power": ["rock", 1, 5], +"shadow-ball": ["ghost", 1, 15], +"future-sight": ["psychic", 1, 15], +"rock-smash": ["fighting", 1, 15], +"whirlpool": ["water", 1, 15], +"beat-up": ["dark", 1, 10], +"fake-out": ["normal", 1, 10], +"uproar": ["normal", 1, 10], +"stockpile": ["normal", 0, 10], +"spit-up": ["normal", 1, 10], +"swallow": ["normal", 0, 10], +"heat-wave": ["fire", 1, 10], +"hail": ["ice", 0, 10], +"torment": ["dark", 0, 15], +"flatter": ["dark", 0, 15], +"will-o-wisp": ["fire", 0, 15], +"memento": ["dark", 0, 10], +"facade": ["normal", 1, 20], +"focus-punch": ["fighting", 1, 20], +"smelling-salts": ["normal", 1, 10], +"follow-me": ["normal", 0, 20], +"nature-power": ["normal", 0, 20], +"charge": ["electric", 0, 20], +"taunt": ["dark", 0, 20], +"helping-hand": ["normal", 0, 20], +"trick": ["psychic", 0, 10], +"role-play": ["psychic", 0, 10], +"wish": ["normal", 0, 10], +"assist": ["normal", 0, 20], +"ingrain": ["grass", 0, 20], +"superpower": ["fighting", 1, 5], +"magic-coat": ["psychic", 0, 15], +"recycle": ["normal", 0, 10], +"revenge": ["fighting", 1, 10], +"brick-break": ["fighting", 1, 15], +"yawn": ["normal", 0, 10], +"knock-off": ["dark", 1, 20], +"endeavor": ["normal", 1, 5], +"eruption": ["fire", 1, 5], +"skill-swap": ["psychic", 0, 10], +"imprison": ["psychic", 0, 10], +"refresh": ["normal", 0, 20], +"grudge": ["ghost", 0, 5], +"snatch": ["dark", 0, 10], +"secret-power": ["normal", 1, 20], +"dive": ["water", 1, 10], +"arm-thrust": ["fighting", 1, 20], +"camouflage": ["normal", 0, 20], +"tail-glow": ["bug", 0, 20], +"luster-purge": ["psychic", 1, 5], +"mist-ball": ["psychic", 1, 5], +"feather-dance": ["flying", 0, 15], +"teeter-dance": ["normal", 0, 20], +"blaze-kick": ["fire", 1, 10], +"mud-sport": ["ground", 0, 15], +"ice-ball": ["ice", 1, 20], +"needle-arm": ["grass", 1, 15], +"slack-off": ["normal", 0, 10], +"hyper-voice": ["normal", 1, 10], +"poison-fang": ["poison", 1, 15], +"crush-claw": ["normal", 1, 10], +"blast-burn": ["fire", 1, 5], +"hydro-cannon": ["water", 1, 5], +"meteor-mash": ["steel", 1, 10], +"astonish": ["ghost", 1, 15], +"weather-ball": ["normal", 1, 10], +"aromatherapy": ["grass", 0, 5], +"fake-tears": ["dark", 0, 20], +"air-cutter": ["flying", 1, 25], +"overheat": ["fire", 1, 5], +"odor-sleuth": ["normal", 0, 40], +"rock-tomb": ["rock", 1, 10], +"silver-wind": ["bug", 1, 5], +"metal-sound": ["steel", 0, 40], +"grass-whistle": ["grass", 0, 15], +"tickle": ["normal", 0, 20], +"cosmic-power": ["psychic", 0, 20], +"water-spout": ["water", 1, 5], +"signal-beam": ["bug", 1, 15], +"shadow-punch": ["ghost", 1, 20], +"extrasensory": ["psychic", 1, 30], +"sky-uppercut": ["fighting", 1, 15], +"sand-tomb": ["ground", 1, 15], +"sheer-cold": ["ice", 1, 5], +"muddy-water": ["water", 1, 10], +"bullet-seed": ["grass", 1, 30], +"aerial-ace": ["flying", 1, 20], +"icicle-spear": ["ice", 1, 30], +"iron-defense": ["steel", 0, 15], +"block": ["normal", 0, 5], +"howl": ["normal", 0, 40], +"dragon-claw": ["dragon", 1, 15], +"frenzy-plant": ["grass", 1, 5], +"bulk-up": ["fighting", 0, 20], +"bounce": ["flying", 1, 5], +"mud-shot": ["ground", 1, 15], +"poison-tail": ["poison", 1, 25], +"covet": ["normal", 1, 40], +"volt-tackle": ["electric", 1, 15], +"magical-leaf": ["grass", 1, 20], +"water-sport": ["water", 0, 15], +"calm-mind": ["psychic", 0, 20], +"leaf-blade": ["grass", 1, 15], +"dragon-dance": ["dragon", 0, 20], +"rock-blast": ["rock", 1, 10], +"shock-wave": ["electric", 1, 20], +"water-pulse": ["water", 1, 20], +"doom-desire": ["steel", 1, 5], +"psycho-boost": ["psychic", 1, 5] +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/species.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/species.json new file mode 100644 index 0000000000..1c1b8866aa --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/species.json @@ -0,0 +1,388 @@ +{ +"bulbasaur": ["grass", "poison"], +"ivysaur": ["grass", "poison"], +"venusaur": ["grass", "poison"], +"charmander": ["fire", "fire"], +"charmeleon": ["fire", "fire"], +"charizard": ["fire", "flying"], +"squirtle": ["water", "water"], +"wartortle": ["water", "water"], +"blastoise": ["water", "water"], +"caterpie": ["bug", "bug"], +"metapod": ["bug", "bug"], +"butterfree": ["bug", "flying"], +"weedle": ["bug", "poison"], +"kakuna": ["bug", "poison"], +"beedrill": ["bug", "poison"], +"pidgey": ["normal", "flying"], +"pidgeotto": ["normal", "flying"], +"pidgeot": ["normal", "flying"], +"rattata": ["normal", "normal"], +"raticate": ["normal", "normal"], +"spearow": ["normal", "flying"], +"fearow": ["normal", "flying"], +"ekans": ["poison", "poison"], +"arbok": ["poison", "poison"], +"pikachu": ["electric", "electric"], +"raichu": ["electric", "electric"], +"sandshrew": ["ground", "ground"], +"sandslash": ["ground", "ground"], +"nidoran-f": ["poison", "poison"], +"nidorina": ["poison", "poison"], +"nidoqueen": ["poison", "ground"], +"nidoran-m": ["poison", "poison"], +"nidorino": ["poison", "poison"], +"nidoking": ["poison", "ground"], +"clefairy": ["normal", "normal"], +"clefable": ["normal", "normal"], +"vulpix": ["fire", "fire"], +"ninetales": ["fire", "fire"], +"jigglypuff": ["normal", "normal"], +"wigglytuff": ["normal", "normal"], +"zubat": ["poison", "flying"], +"golbat": ["poison", "flying"], +"oddish": ["grass", "poison"], +"gloom": ["grass", "poison"], +"vileplume": ["grass", "poison"], +"paras": ["bug", "grass"], +"parasect": ["bug", "grass"], +"venonat": ["bug", "poison"], +"venomoth": ["bug", "poison"], +"diglett": ["ground", "ground"], +"dugtrio": ["ground", "ground"], +"meowth": ["normal", "normal"], +"persian": ["normal", "normal"], +"psyduck": ["water", "water"], +"golduck": ["water", "water"], +"mankey": ["fighting", "fighting"], +"primeape": ["fighting", "fighting"], +"growlithe": ["fire", "fire"], +"arcanine": ["fire", "fire"], +"poliwag": ["water", "water"], +"poliwhirl": ["water", "water"], +"poliwrath": ["water", "fighting"], +"abra": ["psychic", "psychic"], +"kadabra": ["psychic", "psychic"], +"alakazam": ["psychic", "psychic"], +"machop": ["fighting", "fighting"], +"machoke": ["fighting", "fighting"], +"machamp": ["fighting", "fighting"], +"bellsprout": ["grass", "poison"], +"weepinbell": ["grass", "poison"], +"victreebel": ["grass", "poison"], +"tentacool": ["water", "poison"], +"tentacruel": ["water", "poison"], +"geodude": ["rock", "ground"], +"graveler": ["rock", "ground"], +"golem": ["rock", "ground"], +"ponyta": ["fire", "fire"], +"rapidash": ["fire", "fire"], +"slowpoke": ["water", "psychic"], +"slowbro": ["water", "psychic"], +"magnemite": ["electric", "steel"], +"magneton": ["electric", "steel"], +"farfetch-d": ["normal", "flying"], +"doduo": ["normal", "flying"], +"dodrio": ["normal", "flying"], +"seel": ["water", "water"], +"dewgong": ["water", "ice"], +"grimer": ["poison", "poison"], +"muk": ["poison", "poison"], +"shellder": ["water", "water"], +"cloyster": ["water", "ice"], +"gastly": ["ghost", "poison"], +"haunter": ["ghost", "poison"], +"gengar": ["ghost", "poison"], +"onix": ["rock", "ground"], +"drowzee": ["psychic", "psychic"], +"hypno": ["psychic", "psychic"], +"krabby": ["water", "water"], +"kingler": ["water", "water"], +"voltorb": ["electric", "electric"], +"electrode": ["electric", "electric"], +"exeggcute": ["grass", "psychic"], +"exeggutor": ["grass", "psychic"], +"cubone": ["ground", "ground"], +"marowak": ["ground", "ground"], +"hitmonlee": ["fighting", "fighting"], +"hitmonchan": ["fighting", "fighting"], +"lickitung": ["normal", "normal"], +"koffing": ["poison", "poison"], +"weezing": ["poison", "poison"], +"rhyhorn": ["ground", "rock"], +"rhydon": ["ground", "rock"], +"chansey": ["normal", "normal"], +"tangela": ["grass", "grass"], +"kangaskhan": ["normal", "normal"], +"horsea": ["water", "water"], +"seadra": ["water", "water"], +"goldeen": ["water", "water"], +"seaking": ["water", "water"], +"staryu": ["water", "water"], +"starmie": ["water", "psychic"], +"mr-mime": ["psychic", "psychic"], +"scyther": ["bug", "flying"], +"jynx": ["ice", "psychic"], +"electabuzz": ["electric", "electric"], +"magmar": ["fire", "fire"], +"pinsir": ["bug", "bug"], +"tauros": ["normal", "normal"], +"magikarp": ["water", "water"], +"gyarados": ["water", "flying"], +"lapras": ["water", "ice"], +"ditto": ["normal", "normal"], +"eevee": ["normal", "normal"], +"vaporeon": ["water", "water"], +"jolteon": ["electric", "electric"], +"flareon": ["fire", "fire"], +"porygon": ["normal", "normal"], +"omanyte": ["rock", "water"], +"omastar": ["rock", "water"], +"kabuto": ["rock", "water"], +"kabutops": ["rock", "water"], +"aerodactyl": ["rock", "flying"], +"snorlax": ["normal", "normal"], +"articuno": ["ice", "flying"], +"zapdos": ["electric", "flying"], +"moltres": ["fire", "flying"], +"dratini": ["dragon", "dragon"], +"dragonair": ["dragon", "dragon"], +"dragonite": ["dragon", "flying"], +"mewtwo": ["psychic", "psychic"], +"mew": ["psychic", "psychic"], +"chikorita": ["grass", "grass"], +"bayleef": ["grass", "grass"], +"meganium": ["grass", "grass"], +"cyndaquil": ["fire", "fire"], +"quilava": ["fire", "fire"], +"typhlosion": ["fire", "fire"], +"totodile": ["water", "water"], +"croconaw": ["water", "water"], +"feraligatr": ["water", "water"], +"sentret": ["normal", "normal"], +"furret": ["normal", "normal"], +"hoothoot": ["normal", "flying"], +"noctowl": ["normal", "flying"], +"ledyba": ["bug", "flying"], +"ledian": ["bug", "flying"], +"spinarak": ["bug", "poison"], +"ariados": ["bug", "poison"], +"crobat": ["poison", "flying"], +"chinchou": ["water", "electric"], +"lanturn": ["water", "electric"], +"pichu": ["electric", "electric"], +"cleffa": ["normal", "normal"], +"igglybuff": ["normal", "normal"], +"togepi": ["normal", "normal"], +"togetic": ["normal", "flying"], +"natu": ["psychic", "flying"], +"xatu": ["psychic", "flying"], +"mareep": ["electric", "electric"], +"flaaffy": ["electric", "electric"], +"ampharos": ["electric", "electric"], +"bellossom": ["grass", "grass"], +"marill": ["water", "water"], +"azumarill": ["water", "water"], +"sudowoodo": ["rock", "rock"], +"politoed": ["water", "water"], +"hoppip": ["grass", "flying"], +"skiploom": ["grass", "flying"], +"jumpluff": ["grass", "flying"], +"aipom": ["normal", "normal"], +"sunkern": ["grass", "grass"], +"sunflora": ["grass", "grass"], +"yanma": ["bug", "flying"], +"wooper": ["water", "ground"], +"quagsire": ["water", "ground"], +"espeon": ["psychic", "psychic"], +"umbreon": ["dark", "dark"], +"murkrow": ["dark", "flying"], +"slowking": ["water", "psychic"], +"misdreavus": ["ghost", "ghost"], +"unown": ["psychic", "psychic"], +"wobbuffet": ["psychic", "psychic"], +"girafarig": ["normal", "psychic"], +"pineco": ["bug", "bug"], +"forretress": ["bug", "steel"], +"dunsparce": ["normal", "normal"], +"gligar": ["ground", "flying"], +"steelix": ["steel", "ground"], +"snubbull": ["normal", "normal"], +"granbull": ["normal", "normal"], +"qwilfish": ["water", "poison"], +"scizor": ["bug", "steel"], +"shuckle": ["bug", "rock"], +"heracross": ["bug", "fighting"], +"sneasel": ["dark", "ice"], +"teddiursa": ["normal", "normal"], +"ursaring": ["normal", "normal"], +"slugma": ["fire", "fire"], +"magcargo": ["fire", "rock"], +"swinub": ["ice", "ground"], +"piloswine": ["ice", "ground"], +"corsola": ["water", "rock"], +"remoraid": ["water", "water"], +"octillery": ["water", "water"], +"delibird": ["ice", "flying"], +"mantine": ["water", "flying"], +"skarmory": ["steel", "flying"], +"houndour": ["dark", "fire"], +"houndoom": ["dark", "fire"], +"kingdra": ["water", "dragon"], +"phanpy": ["ground", "ground"], +"donphan": ["ground", "ground"], +"porygon2": ["normal", "normal"], +"stantler": ["normal", "normal"], +"smeargle": ["normal", "normal"], +"tyrogue": ["fighting", "fighting"], +"hitmontop": ["fighting", "fighting"], +"smoochum": ["ice", "psychic"], +"elekid": ["electric", "electric"], +"magby": ["fire", "fire"], +"miltank": ["normal", "normal"], +"blissey": ["normal", "normal"], +"raikou": ["electric", "electric"], +"entei": ["fire", "fire"], +"suicune": ["water", "water"], +"larvitar": ["rock", "ground"], +"pupitar": ["rock", "ground"], +"tyranitar": ["rock", "dark"], +"lugia": ["psychic", "flying"], +"ho-oh": ["fire", "flying"], +"celebi": ["psychic", "grass"], +"treecko": ["grass", "grass"], +"grovyle": ["grass", "grass"], +"sceptile": ["grass", "grass"], +"torchic": ["fire", "fire"], +"combusken": ["fire", "fighting"], +"blaziken": ["fire", "fighting"], +"mudkip": ["water", "water"], +"marshtomp": ["water", "ground"], +"swampert": ["water", "ground"], +"poochyena": ["dark", "dark"], +"mightyena": ["dark", "dark"], +"zigzagoon": ["normal", "normal"], +"linoone": ["normal", "normal"], +"wurmple": ["bug", "bug"], +"silcoon": ["bug", "bug"], +"beautifly": ["bug", "flying"], +"cascoon": ["bug", "bug"], +"dustox": ["bug", "poison"], +"lotad": ["water", "grass"], +"lombre": ["water", "grass"], +"ludicolo": ["water", "grass"], +"seedot": ["grass", "grass"], +"nuzleaf": ["grass", "dark"], +"shiftry": ["grass", "dark"], +"nincada": ["bug", "ground"], +"ninjask": ["bug", "flying"], +"shedinja": ["bug", "ghost"], +"taillow": ["normal", "flying"], +"swellow": ["normal", "flying"], +"shroomish": ["grass", "grass"], +"breloom": ["grass", "fighting"], +"spinda": ["normal", "normal"], +"wingull": ["water", "flying"], +"pelipper": ["water", "flying"], +"surskit": ["bug", "water"], +"masquerain": ["bug", "flying"], +"wailmer": ["water", "water"], +"wailord": ["water", "water"], +"skitty": ["normal", "normal"], +"delcatty": ["normal", "normal"], +"kecleon": ["normal", "normal"], +"baltoy": ["ground", "psychic"], +"claydol": ["ground", "psychic"], +"nosepass": ["rock", "rock"], +"torkoal": ["fire", "fire"], +"sableye": ["dark", "ghost"], +"barboach": ["water", "ground"], +"whiscash": ["water", "ground"], +"luvdisc": ["water", "water"], +"corphish": ["water", "water"], +"crawdaunt": ["water", "dark"], +"feebas": ["water", "water"], +"milotic": ["water", "water"], +"carvanha": ["water", "dark"], +"sharpedo": ["water", "dark"], +"trapinch": ["ground", "ground"], +"vibrava": ["ground", "dragon"], +"flygon": ["ground", "dragon"], +"makuhita": ["fighting", "fighting"], +"hariyama": ["fighting", "fighting"], +"electrike": ["electric", "electric"], +"manectric": ["electric", "electric"], +"numel": ["fire", "ground"], +"camerupt": ["fire", "ground"], +"spheal": ["ice", "water"], +"sealeo": ["ice", "water"], +"walrein": ["ice", "water"], +"cacnea": ["grass", "grass"], +"cacturne": ["grass", "dark"], +"snorunt": ["ice", "ice"], +"glalie": ["ice", "ice"], +"lunatone": ["rock", "psychic"], +"solrock": ["rock", "psychic"], +"azurill": ["normal", "normal"], +"spoink": ["psychic", "psychic"], +"grumpig": ["psychic", "psychic"], +"plusle": ["electric", "electric"], +"minun": ["electric", "electric"], +"mawile": ["steel", "steel"], +"meditite": ["fighting", "psychic"], +"medicham": ["fighting", "psychic"], +"swablu": ["normal", "flying"], +"altaria": ["dragon", "flying"], +"wynaut": ["psychic", "psychic"], +"duskull": ["ghost", "ghost"], +"dusclops": ["ghost", "ghost"], +"roselia": ["grass", "poison"], +"slakoth": ["normal", "normal"], +"vigoroth": ["normal", "normal"], +"slaking": ["normal", "normal"], +"gulpin": ["poison", "poison"], +"swalot": ["poison", "poison"], +"tropius": ["grass", "flying"], +"whismur": ["normal", "normal"], +"loudred": ["normal", "normal"], +"exploud": ["normal", "normal"], +"clamperl": ["water", "water"], +"huntail": ["water", "water"], +"gorebyss": ["water", "water"], +"absol": ["dark", "dark"], +"shuppet": ["ghost", "ghost"], +"banette": ["ghost", "ghost"], +"seviper": ["poison", "poison"], +"zangoose": ["normal", "normal"], +"relicanth": ["water", "rock"], +"aron": ["steel", "rock"], +"lairon": ["steel", "rock"], +"aggron": ["steel", "rock"], +"castform": ["normal", "normal"], +"volbeat": ["bug", "bug"], +"illumise": ["bug", "bug"], +"lileep": ["rock", "grass"], +"cradily": ["rock", "grass"], +"anorith": ["rock", "bug"], +"armaldo": ["rock", "bug"], +"ralts": ["psychic", "psychic"], +"kirlia": ["psychic", "psychic"], +"gardevoir": ["psychic", "psychic"], +"bagon": ["dragon", "dragon"], +"shelgon": ["dragon", "dragon"], +"salamence": ["dragon", "flying"], +"beldum": ["steel", "psychic"], +"metang": ["steel", "psychic"], +"metagross": ["steel", "psychic"], +"regirock": ["rock", "rock"], +"regice": ["ice", "ice"], +"registeel": ["steel", "steel"], +"kyogre": ["water", "water"], +"groudon": ["ground", "ground"], +"rayquaza": ["dragon", "flying"], +"latias": ["dragon", "psychic"], +"latios": ["dragon", "psychic"], +"jirachi": ["steel", "psychic"], +"deoxys": ["psychic", "psychic"], +"chimecho": ["psychic", "psychic"] +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/type_chart.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/type_chart.json new file mode 100644 index 0000000000..555a4f323d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData/type_chart.json @@ -0,0 +1,112 @@ +[ +["normal", "rock", 5], +["normal", "steel", 5], +["fire", "fire", 5], +["fire", "water", 5], +["fire", "grass", 20], +["fire", "ice", 20], +["fire", "bug", 20], +["fire", "rock", 5], +["fire", "dragon", 5], +["fire", "steel", 20], +["water", "fire", 20], +["water", "water", 5], +["water", "grass", 5], +["water", "ground", 20], +["water", "rock", 20], +["water", "dragon", 5], +["electric", "water", 20], +["electric", "electric", 5], +["electric", "grass", 5], +["electric", "ground", 0], +["electric", "flying", 20], +["electric", "dragon", 5], +["grass", "fire", 5], +["grass", "water", 20], +["grass", "grass", 5], +["grass", "poison", 5], +["grass", "ground", 20], +["grass", "flying", 5], +["grass", "bug", 5], +["grass", "rock", 20], +["grass", "dragon", 5], +["grass", "steel", 5], +["ice", "water", 5], +["ice", "grass", 20], +["ice", "ice", 5], +["ice", "ground", 20], +["ice", "flying", 20], +["ice", "dragon", 20], +["ice", "steel", 5], +["ice", "fire", 5], +["fighting", "normal", 20], +["fighting", "ice", 20], +["fighting", "poison", 5], +["fighting", "flying", 5], +["fighting", "psychic", 5], +["fighting", "bug", 5], +["fighting", "rock", 20], +["fighting", "dark", 20], +["fighting", "steel", 20], +["poison", "grass", 20], +["poison", "poison", 5], +["poison", "ground", 5], +["poison", "rock", 5], +["poison", "ghost", 5], +["poison", "steel", 0], +["ground", "fire", 20], +["ground", "electric", 20], +["ground", "grass", 5], +["ground", "poison", 20], +["ground", "flying", 0], +["ground", "bug", 5], +["ground", "rock", 20], +["ground", "steel", 20], +["flying", "electric", 5], +["flying", "grass", 20], +["flying", "fighting", 20], +["flying", "bug", 20], +["flying", "rock", 5], +["flying", "steel", 5], +["psychic", "fighting", 20], +["psychic", "poison", 20], +["psychic", "psychic", 5], +["psychic", "dark", 0], +["psychic", "steel", 5], +["bug", "fire", 5], +["bug", "grass", 20], +["bug", "fighting", 5], +["bug", "poison", 5], +["bug", "flying", 5], +["bug", "psychic", 20], +["bug", "ghost", 5], +["bug", "dark", 20], +["bug", "steel", 5], +["rock", "fire", 20], +["rock", "ice", 20], +["rock", "fighting", 5], +["rock", "ground", 5], +["rock", "flying", 20], +["rock", "bug", 20], +["rock", "steel", 5], +["ghost", "normal", 0], +["ghost", "psychic", 20], +["ghost", "dark", 5], +["ghost", "steel", 5], +["ghost", "ghost", 20], +["dragon", "dragon", 20], +["dragon", "steel", 5], +["dark", "fighting", 5], +["dark", "psychic", 20], +["dark", "ghost", 20], +["dark", "dark", 5], +["dark", "steel", 5], +["steel", "fire", 5], +["steel", "water", 5], +["steel", "electric", 5], +["steel", "ice", 20], +["steel", "rock", 20], +["steel", "steel", 5], +["normal", "ghost", 0], +["fighting", "ghost", 0] +] diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp new file mode 100644 index 0000000000..74d8f117b1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -0,0 +1,846 @@ +/* AutoStory Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_NamingScreenDetector.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_OptionMenuReader.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_StartMenuDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_SelectionArrowDetector.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.h" +#include "PokemonFRLG_AutoStoryActions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; +using Pokemon::Direction; + + +namespace{ + +constexpr Milliseconds POLL = 300ms; +// Text without an arrow or a prompt this long: press anyway, for a last +// line that waits without an arrow (Oak's "Here, come with me!"). +constexpr Milliseconds TEXT_STILL = 4000ms; +// In the intro: A this often on a message box; how long with no box +// before checking for the bedroom; and before pressing A on a screen +// nothing reads. +constexpr Milliseconds INTRO_A_EVERY = 1500ms; +constexpr Milliseconds INTRO_QUIET = 3000ms; +constexpr Milliseconds INTRO_STUCK = 15000ms; +constexpr Milliseconds INTRO_TIMEOUT = 600000ms; +// "Wait about 8 s" after YES at the nurse (console B, 2026-11-01): 1.5 s +// between presses did not heal. +constexpr Milliseconds HEAL_TIME = 8000ms; +// FRLG takes a tap this short as a turn, without a step. +constexpr Milliseconds TURN_TAP = 40ms; +constexpr Milliseconds TURN_SETTLE = 300ms; + +DpadPosition dpad(Direction direction){ + switch (direction){ + case Direction::NORTH: + return DPAD_UP; + case Direction::EAST: + return DPAD_RIGHT; + case Direction::SOUTH: + return DPAD_DOWN; + case Direction::WEST: + return DPAD_LEFT; + } + return DPAD_NONE; +} + +void press(ProControllerContext& context, Button button, Milliseconds after = 340ms){ + pbf_press_button(context, button, 160ms, after); +} + +void tap(ProControllerContext& context, DpadPosition position, Milliseconds after = 400ms){ + pbf_press_dpad(context, position, 160ms, after); +} + + + +bool wait_for_yes_no(ConsoleHandle& console, ProControllerContext& context, Milliseconds timeout){ + SelectionArrowWatcher yes(COLOR_RED, &console.overlay(), SelectionArrowPositionConfirmationMenu::YES); + context.wait_for_all_requests(); + return wait_until(console, context, timeout, {yes}) >= 0; +} + +// The START menu row the arrow is on, from the top, as the closest of the +// first `rows` rows. Nothing if no arrow shows. +std::optional start_cursor_row(ConsoleHandle& console, ProControllerContext& context, int rows){ + SelectionArrowWatcher arrow(COLOR_RED, &console.overlay(), MENU_ARROW_BOX); + context.wait_for_all_requests(); + if (wait_until(console, context, 2000ms, {arrow}) < 0){ + return std::nullopt; + } + const double arrow_y = arrow.last_detected().y + arrow.last_detected().height / 2; + int current = 0; + double closest = std::numeric_limits::max(); + for (int c = 0; c < rows; c++){ + const ImageFloatBox box = SelectionArrowDetector::arrow_box_for_position(static_cast(c)); + const double distance = std::abs(arrow_y - (box.y + box.height / 2)); + if (distance < closest){ + closest = distance; + current = c; + } + } + return current; +} + +// The START menu's cursor onto `row`, read from the arrow. As +// move_cursor_to_position(), for a menu of any length. +bool move_start_cursor(ConsoleHandle& console, ProControllerContext& context, int rows, int row){ + const std::optional current = start_cursor_row(console, context, rows); + if (!current){ + return false; + } + console.log(std::format("START menu: cursor on row {}, moving to row {}.", *current + 1, row + 1)); + const int down = (row - *current + rows) % rows; + const int up = (*current - row + rows) % rows; + for (int c = 0; c < std::min(down, up); c++){ + tap(context, down <= up ? DPAD_DOWN : DPAD_UP); + } + context.wait_for_all_requests(); + return true; +} + +// The START menu's cursor onto SAVE, in a menu of any length: up past the +// top wraps to EXIT, the last row, whose place gives the length; SAVE is +// two above it. +bool move_start_cursor_to_save(ConsoleHandle& console, ProControllerContext& context){ + const int most = start_menu_rows(StartMenu::FULL); + const std::optional current = start_cursor_row(console, context, most); + if (!current){ + return false; + } + for (int c = 0; c <= *current; c++){ + tap(context, DPAD_UP); + } + const std::optional last = start_cursor_row(console, context, most); + if (!last){ + return false; + } + console.log(std::format("START menu: {} rows, moving to SAVE.", *last + 1)); + tap(context, DPAD_UP); + tap(context, DPAD_UP); + context.wait_for_all_requests(); + return true; +} + +void open_start_menu_row(ConsoleHandle& console, ProControllerContext& context, StartMenu menu, int row){ + open_start_menu(console, context); + if (!move_start_cursor(console, context, start_menu_rows(menu), row)){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "START menu: no cursor.", console + ); + } + press(context, BUTTON_A, 1500ms); +} + + +// The new game's intro, from the title screen. Everything but the names +// is advanced with A, which never hurts there (BOY is the default, YES to +// "So your name is ...?" and "Er, was it GREEN?"); B is never pressed +// outside the keyboard, since in the intro it goes back to the controls +// pages (console B, 2026-11-01). The controls pages read as a message box +// without an arrow, and the arrow at the end of Oak's lines may be missed, +// so a message box gets A every 1.5 s whatever it shows. The player's name +// is asked on the keyboard straight away: B deletes whatever a stray A +// typed and START jumps to OK, which confirms the empty name as the +// default. The rival's is asked on a list with NEW NAME first, where A +// would open the keyboard: the cursor goes to the first preset name (the +// game's default rival, GREEN in FireRed, RED in LeafGreen) and A picks +// it, then YES confirms it (pokefirered oak_speech.c). If the keyboard +// opens anyway, the list was missed, and the empty name is confirmed +// there instead, which also names the rival GREEN. +class NewGameIntro{ +public: + NewGameIntro(ConsoleHandle& console, ProControllerContext& context) + : m_console(console) + , m_context(context) + {} + + void run(){ + press_a_until_dialog(); + const WallClock deadline = current_time() + INTRO_TIMEOUT; + m_last_dialog = current_time(); + m_last_press = m_last_dialog; + while (current_time() < deadline){ + if (step()){ + m_console.log("New game: the bedroom."); + return; + } + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "play_new_game_intro(): still in the intro after 10 minutes.", m_console + ); + } + +private: + // The title, then the controls pages, which A turns, up to a message box. + void press_a_until_dialog(){ + WhiteDialogWatcher dialog(COLOR_RED); + m_context.wait_for_all_requests(); + const int ret = run_until( + m_console, m_context, + [](ProControllerContext& context){ + for (int c = 0; c < 80; c++){ + pbf_press_button(context, BUTTON_A, 160ms, 1340ms); + } + }, + {dialog} + ); + if (ret < 0){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "play_new_game_intro(): no message after the title screen.", m_console + ); + } + } + + // True once the bedroom shows. + bool step(){ + m_context.wait_for_all_requests(); + const WallClock now = current_time(); + VideoSnapshot screen = m_console.video().snapshot(); + if (!screen){ + pbf_wait(m_context, POLL); + return false; + } + if (names(screen)){ + m_last_dialog = current_time(); + m_last_press = m_last_dialog; + return false; + } + if (yes_no_cursor(screen) || WhiteDialogDetector(COLOR_RED).detect(screen)){ + m_dialog_seen = true; + m_last_dialog = now; + if (now - m_last_press >= INTRO_A_EVERY){ + press(m_context, BUTTON_A, 200ms); + m_last_press = now; + }else{ + pbf_wait(m_context, POLL); + } + return false; + } + return quiet(screen, now); + } + + // True if a keyboard or the rival's name list showed and was handled. + bool names(const ImageViewRGB32& screen){ + IntroNameScreen shown = IntroNameScreen::OTHER; + std::optional list_row; + if (NamingScreenDetector(COLOR_RED).detect(screen)){ + shown = IntroNameScreen::KEYBOARD; + }else if (m_keyboards_seen > 0){ + // The list shows over a message box: look for it before the A + // every 1.5 s, which would open the keyboard. + list_row = rival_name_list_cursor(screen); + shown = list_row ? IntroNameScreen::RIVAL_LIST : IntroNameScreen::OTHER; + } + switch (intro_name_step(shown, m_keyboards_seen, m_presets_picked)){ + case IntroNameStep::PLAYER_KEYBOARD: + m_keyboards_seen++; + enter_empty_name(); + return true; + case IntroNameStep::RIVAL_KEYBOARD: + m_keyboards_seen++; + m_console.log("New game: the rival's keyboard opened, so the name list was missed.", COLOR_ORANGE); + enter_empty_name(); + return true; + case IntroNameStep::RIVAL_PRESET: + pick_rival_preset(*list_row); + return true; + case IntroNameStep::NONE: + return false; + } + return false; + } + + // Row 1 is the first preset name. The cursor is read again before A, so + // a dropped press is made up on the next look. + void pick_rival_preset(int row){ + if (row != 1){ + m_console.log(std::format("New game: the rival's name list, cursor on row {}, moving to the first preset name.", row)); + const DpadPosition direction = row < 1 ? DPAD_DOWN : DPAD_UP; + for (int c = 0; c < std::abs(row - 1); c++){ + tap(m_context, direction, 300ms); + } + m_context.wait_for_all_requests(); + return; + } + m_console.log("New game: the rival's name list, picking the first preset name."); + press(m_context, BUTTON_A, 2000ms); + m_context.wait_for_all_requests(); + m_presets_picked++; + } + + // No message box and no keyboard: a fade, a pause in the speech, or + // the bedroom. + bool quiet(const ImageViewRGB32& screen, WallClock now){ + const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); + if (is_black(game) || !m_dialog_seen || now - m_last_dialog < INTRO_QUIET){ + pbf_wait(m_context, POLL); + return false; + } + // START does nothing in the intro. + if (overworld_shows(m_console, m_context)){ + return true; + } + // A screen still waiting for A that none of the detectors knows. + if (now - m_last_press > INTRO_STUCK){ + m_console.log("New game: nothing known on screen, pressing A."); + press(m_context, BUTTON_A, 200ms); + m_last_press = current_time(); + } + return false; + } + + void enter_empty_name(){ + m_console.log("New game: the keyboard, confirming an empty name."); + for (int c = 0; c < 8; c++){ + press(m_context, BUTTON_B, 340ms); + } + press(m_context, BUTTON_PLUS, 500ms); + press(m_context, BUTTON_A, 2000ms); + m_context.wait_for_all_requests(); + } + + ConsoleHandle& m_console; + ProControllerContext& m_context; + WallClock m_last_dialog; + WallClock m_last_press; + bool m_dialog_seen = false; + size_t m_keyboards_seen = 0; + size_t m_presets_picked = 0; +}; + +} // namespace + + +IntroNameStep intro_name_step(IntroNameScreen screen, size_t keyboards_seen, size_t presets_picked){ + switch (screen){ + case IntroNameScreen::KEYBOARD: + return keyboards_seen == 0 ? IntroNameStep::PLAYER_KEYBOARD : IntroNameStep::RIVAL_KEYBOARD; + case IntroNameScreen::RIVAL_LIST: + // The list only comes after the player's keyboard. + return keyboards_seen > 0 && presets_picked < RIVAL_PRESET_TRIES ? IntroNameStep::RIVAL_PRESET : IntroNameStep::NONE; + case IntroNameScreen::OTHER: + return IntroNameStep::NONE; + } + return IntroNameStep::NONE; +} + + +int start_menu_rows(StartMenu menu){ + switch (menu){ + case StartMenu::BEFORE_POKEMON: + return 5; + case StartMenu::BEFORE_POKEDEX: + return 6; + case StartMenu::FULL: + return 7; + } + return 7; +} +int start_menu_save_row(StartMenu menu){ + return start_menu_rows(menu) - 3; +} +int start_menu_option_row(StartMenu menu){ + return start_menu_rows(menu) - 2; +} + + +std::optional yes_no_cursor(const ImageViewRGB32& screen){ + // The box's white right of NO (x 196-212, y 92-102 on the 240x160 + // screen). Without it the arrow alone matches the dark edge of a rock + // on Route 3 at (36, 8), right where YES's arrow shows. + const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); + if (!is_white(extract_box_reference(game, ImageFloatBox(196.0 / 240, 92.0 / 160, 16.0 / 240, 10.0 / 160)))){ + return std::nullopt; + } + if (SelectionArrowDetector(COLOR_RED, nullptr, SelectionArrowPositionConfirmationMenu::YES).detect(screen)){ + return true; + } + if (SelectionArrowDetector(COLOR_RED, nullptr, SelectionArrowPositionConfirmationMenu::NO).detect(screen)){ + return false; + } + return std::nullopt; +} + +std::optional rival_name_list_cursor(const ImageViewRGB32& screen){ + // On the 240x160 screen: the list's window spans x 16-112, y 16-96, and + // this box (x 64-100, y 36-46) is white there, right of the names and + // below NEW NAME. A YES/NO box's right frame runs through it. + const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); + if (!is_white(extract_box_reference(game, ImageFloatBox(0.267, 0.225, 0.15, 0.0625)))){ + return std::nullopt; + } + for (int row = 0; row < 5; row++){ + // The START menu's arrow box (window at x 176, y 8; the box starts + // 1.4 px left and 0.4 px below), moved to the list's cursor at + // x 16, y 17 + 16 * row. + const ImageFloatBox box(14.6 / 240, (17.4 + 16 * row) / 160, 0.0369231, 0.0778846); + if (SelectionArrowDetector(COLOR_RED, nullptr, box).detect(screen)){ + return row; + } + } + return std::nullopt; +} + +bool overworld_shows(ConsoleHandle& console, ProControllerContext& context){ + press(context, BUTTON_PLUS, 1200ms); + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (!screen || !StartMenuDetector(COLOR_RED).detect(screen)){ + return false; + } + press(context, BUTTON_B, 600ms); + context.wait_for_all_requests(); + return true; +} + +namespace{ +bool yes_no_shows(ConsoleHandle& console){ + VideoSnapshot screen = console.video().snapshot(); + return screen && yes_no_cursor(screen).has_value(); +} +} // namespace + +TextEnd advance_text(ConsoleHandle& console, ProControllerContext& context, Milliseconds timeout, bool stop_at_battle){ + const WallClock deadline = current_time() + timeout; + // A YES/NO here is a move to learn: "Delete a move to make room?" NO, + // then, right after, "Stop learning?" YES. B to "Stop learning?" goes + // back to the first, for good (console B, 2026-11-01). + std::optional last_no; + while (current_time() < deadline){ + BattleScreenWatcher battle(COLOR_RED); + BattleMenuWatcher battle_menu(COLOR_RED); + SelectionArrowWatcher yes(COLOR_RED, &console.overlay(), SelectionArrowPositionConfirmationMenu::YES); + SelectionArrowWatcher no(COLOR_RED, &console.overlay(), SelectionArrowPositionConfirmationMenu::NO); + BattleLearnDialogWatcher learn(COLOR_RED); + context.wait_for_all_requests(); + int ret = run_until( + console, context, + [](ProControllerContext& context){ + for (int c = 0; c < 5; c++){ + pbf_press_button(context, BUTTON_B, 160ms, 340ms); + } + }, + {battle, battle_menu, yes, no, learn} + ); + // The arrow watchers alone match scenery (a rock's edge on Route 3), + // so a YES/NO also needs its box. + if ((ret == 2 || ret == 3) && !yes_no_shows(console)){ + ret = -1; + } + if (ret >= 2){ + const bool stop_learning = last_no && current_time() - *last_no < 10000ms; + console.log(stop_learning ? "Text: YES/NO, YES (stop learning)." : "Text: YES/NO, NO."); + press(context, stop_learning ? BUTTON_A : BUTTON_B, 1500ms); + last_no = stop_learning ? std::nullopt : std::optional(current_time()); + continue; + } + if (ret >= 0 && stop_at_battle){ + return TextEnd::BATTLE; + } + if (ret < 0 && overworld_shows(console, context)){ + return TextEnd::OVERWORLD; + } + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format("advance_text(): the overworld didn't come back within {} s.", timeout.count() / 1000), + console + ); +} + +void mash_until_overworld(ConsoleHandle& console, ProControllerContext& context, Milliseconds timeout){ + advance_text(console, context, timeout, false); +} + +void answer_yes_no(ConsoleHandle& console, ProControllerContext& context, bool yes, Button advance, Milliseconds timeout){ + const WallClock deadline = current_time() + timeout; + WallClock last_press = current_time(); + while (current_time() < deadline){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + const std::optional on_yes = screen ? yes_no_cursor(screen) : std::nullopt; + if (on_yes){ + console.log(yes ? "Answering YES." : "Answering NO."); + if (yes && !*on_yes){ + tap(context, DPAD_UP); + } + press(context, yes ? BUTTON_A : BUTTON_B, 800ms); + context.wait_for_all_requests(); + return; + } + const WallClock now = current_time(); + if ((screen && AdvanceWhiteDialogDetector(COLOR_RED).detect(screen)) || now - last_press > TEXT_STILL){ + press(context, advance, 300ms); + last_press = now; + } + pbf_wait(context, POLL); + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "answer_yes_no(): no YES/NO.", console + ); +} + +void step_once(ProControllerContext& context, Direction direction, std::optional facing){ + if (facing != direction){ + pbf_press_dpad(context, dpad(direction), TURN_TAP, TURN_SETTLE); + } + // A step, once started, finishes on its own. + pbf_press_dpad(context, dpad(direction), 120ms, 500ms); + context.wait_for_all_requests(); +} + +void face_wall(ProControllerContext& context, Direction direction){ + pbf_press_dpad(context, dpad(direction), TURN_TAP, TURN_SETTLE); + context.wait_for_all_requests(); +} + +SaveAction SaveDialog::next(SaveScreen screen){ + if (screen != SaveScreen::NOTHING){ + m_nothing_seen = 0; + } + switch (screen){ + case SaveScreen::YES_NO: + m_paged_since_yes = false; + return SaveAction::ANSWER_YES; + case SaveScreen::PAGED_TEXT: + m_paged_since_yes = true; + return SaveAction::NEXT_PAGE; + case SaveScreen::TEXT: + return SaveAction::WAIT; + case SaveScreen::START_MENU: + return SaveAction::FAIL_CANCELLED; + case SaveScreen::NOTHING: + // Twice in a row: not the frame between two boxes. + if (++m_nothing_seen < 2){ + return SaveAction::WAIT; + } + return m_paged_since_yes ? SaveAction::FAIL_ERROR : SaveAction::CHECK_OVERWORLD; + } + return SaveAction::WAIT; +} + +namespace{ + +// The four WARNING pages over another game's save, at the new game's text +// speed, the save itself and its 60-frame pause, with room to spare. +constexpr Milliseconds SAVE_TIMEOUT = 30000ms; + +SaveScreen read_save_screen(const ImageViewRGB32& screen){ + if (yes_no_cursor(screen)){ + return SaveScreen::YES_NO; + } + // Before the message boxes: the menu can show a help box under it. + if (StartMenuDetector(COLOR_RED).detect(screen)){ + return SaveScreen::START_MENU; + } + if (AdvanceWhiteDialogDetector(COLOR_RED).detect(screen)){ + return SaveScreen::PAGED_TEXT; + } + if (WhiteDialogDetector(COLOR_RED).detect(screen)){ + return SaveScreen::TEXT; + } + return SaveScreen::NOTHING; +} + +// From the save card's first YES/NO to the overworld, as SaveDialog says. +void run_save_dialog(ConsoleHandle& console, ProControllerContext& context){ + SaveDialog dialog; + const WallClock deadline = current_time() + SAVE_TIMEOUT; + while (current_time() < deadline){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (!screen){ + pbf_wait(context, POLL); + continue; + } + switch (dialog.next(read_save_screen(screen))){ + case SaveAction::WAIT: + pbf_wait(context, POLL); + break; + case SaveAction::ANSWER_YES: + // The overwrite over another game's save starts on NO. + if (yes_no_cursor(screen) == false){ + tap(context, DPAD_UP); + } + console.log("Save: YES."); + press(context, BUTTON_A, 1000ms); + break; + case SaveAction::NEXT_PAGE: + press(context, BUTTON_A, 500ms); + break; + case SaveAction::CHECK_OVERWORLD: + if (overworld_shows(console, context)){ + console.log("Saved."); + return; + } + break; + case SaveAction::FAIL_CANCELLED: + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "save_game(): the START menu came back: the save was cancelled.", console + ); + case SaveAction::FAIL_ERROR: + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "save_game(): a message after the last YES: the save failed.", console + ); + } + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format("save_game(): not back on the overworld {} s after saving.", SAVE_TIMEOUT.count() / 1000), + console + ); +} + +} // namespace + +void save_game(ConsoleHandle& console, ProControllerContext& context, StartMenu menu){ + console.log("Saving the game."); + open_start_menu_row(console, context, menu, start_menu_save_row(menu)); + // The save card and "Would you like to save the game?" + if (!wait_for_yes_no(console, context, 5000ms)){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "save_game(): no YES/NO to save.", console + ); + } + context.wait_for_all_requests(); + dump_debug_image(console, "AutoStory/save", "save-card", console.video().snapshot()); + run_save_dialog(console, context); +} + +std::string read_save_place(ConsoleHandle& console, ProControllerContext& context, Language language){ + open_start_menu(console, context); + if (!move_start_cursor_to_save(console, context)){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "START menu: no cursor.", console + ); + } + press(context, BUTTON_A, 1500ms); + std::string place; + if (wait_for_yes_no(console, context, 5000ms)){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + place = screen ? read_save_card_location(console, language, screen) : ""; + dump_debug_image(console, "AutoStory/save", "card-" + (place.empty() ? std::string("unread") : place), screen); + } + // NO, then out of the menu. + press(context, BUTTON_B, 1000ms); + mash_until_overworld(console, context, 20000ms); + return place; +} + +std::optional option_right_presses( + const std::vector& values, const std::string& current, const std::string& target +){ + const auto from = std::find(values.begin(), values.end(), current); + const auto to = std::find(values.begin(), values.end(), target); + if (from == values.end() || to == values.end()){ + return std::nullopt; + } + const size_t count = values.size(); + return (static_cast(to - values.begin()) + count - static_cast(from - values.begin())) % count; +} + +static void options_shot(ConsoleHandle& console, ProControllerContext& context, const std::string& label){ + context.wait_for_all_requests(); + dump_debug_image(console, "AutoStory/options", label, console.video().snapshot()); +} + +// The item's value, read up to 3 times while the menu may still be fading +// in or redrawing; empty if never read. +static std::string read_option( + ConsoleHandle& console, ProControllerContext& context, OptionMenuItem item, Language language +){ + for (size_t attempt = 0; attempt < 3; attempt++){ + if (attempt > 0){ + pbf_wait(context, 500ms); + } + context.wait_for_all_requests(); + const VideoSnapshot screen = console.video().snapshot(); + const std::string value = screen ? read_option_value(console, language, screen, item) : ""; + if (!value.empty()){ + return value; + } + } + return ""; +} + +// With the cursor on the item's row: RIGHT until it shows `target`. +static void set_option( + ConsoleHandle& console, ProControllerContext& context, + OptionMenuItem item, const std::string& target, Language language +){ + const std::string_view name = option_menu_name(item); + const std::string current = read_option(console, context, item, language); + const std::optional presses = option_right_presses(option_menu_values(item), current, target); + if (!presses){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format("set_options(): can't read {} (read \"{}\", language {}).", name, current, language_data(language).name), + console + ); + } + console.log(std::format("Options: {} is {}, {} RIGHT to {}.", name, current, *presses, target)); + for (size_t i = 0; i < *presses; i++){ + tap(context, DPAD_RIGHT); + } + const std::string now = read_option(console, context, item, language); + if (now != target){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format("set_options(): {} reads \"{}\" after {} RIGHT from {}, not {}.", name, now, *presses, current, target), + console + ); + } +} + +void set_options(ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language){ + console.log("Options: text speed FAST, battle scene OFF, battle style SET."); + open_start_menu_row(console, context, menu, start_menu_option_row(menu)); + options_shot(console, context, "before"); + struct Target{ + OptionMenuItem item; + std::string_view value; + }; + // In row order. The cursor opens on TEXT SPEED (option_menu.c: + // cursorPos = 0) and DOWN moves it a row. Were it on another row, the + // presses would change that row instead, and the read after them fails. + const Target targets[] = { + {.item = OptionMenuItem::TEXT_SPEED, .value = "fast"}, + {.item = OptionMenuItem::BATTLE_SCENE, .value = "off"}, + {.item = OptionMenuItem::BATTLE_STYLE, .value = "set"}, + }; + size_t cursor = 0; + for (const Target& target : targets){ + for (; cursor < option_menu_row(target.item); cursor++){ + tap(context, DPAD_DOWN); + } + set_option(console, context, target.item, std::string(target.value), language); + } + options_shot(console, context, "after"); + press(context, BUTTON_B, 1500ms); + mash_until_overworld(console, context, 20000ms); +} + +void heal_at_center(ConsoleHandle& console, ProControllerContext& context){ + console.log("Healing at the Pokemon Center."); + // The nurse's YES/NO isn't seen by the selection detector (console B, + // 2026-11-01); YES is the default, so A after her lines is YES. + // "Welcome ... We heal your POKEMON ... Shall we heal?" is 3 lines. + press(context, BUTTON_A, 1500ms); + press(context, BUTTON_A, 1500ms); + press(context, BUTTON_A, 2500ms); + press(context, BUTTON_A, 1000ms); + pbf_wait(context, HEAL_TIME); + mash_until_overworld(console, context, 30000ms); +} + +// A picture of the Mart screen for the run's record: the list with the +// cursor, the quantity, the bag after. +static void mart_shot(ConsoleHandle& console, ProControllerContext& context, const std::string& label){ + context.wait_for_all_requests(); + dump_debug_image(console, "AutoStory/mart", label, console.video().snapshot()); +} + +int mart_cursor_moves(int cursor, int row){ + return row - cursor; +} + +// THOROUGH: the item on the cursor's row is `order.item`. +static void check_mart_row(ConsoleHandle& console, ProControllerContext& context, const MartOrder& order, Language language){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + const std::string item = screen ? read_item_list_name(console, language, screen, order.row) : ""; + if (item == order.item){ + console.log(std::format("Mart: row {} is {}.", order.row + 1, item)); + return; + } + if (item.empty()){ + console.log(std::format("Mart: couldn't read row {}, expected {}; buying anyway.", order.row + 1, order.item), COLOR_ORANGE); + dump_debug_image(console, "AutoStory/mart", std::format("row{}-unread", order.row + 1), screen); + return; + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format("buy_items(): row {} is {}, not {}.", order.row + 1, item, order.item), + console + ); +} + +void buy_items( + ConsoleHandle& console, ProControllerContext& context, + const std::vector& orders, Pokemon::StoryCheckLevel checks, Language language +){ + // "May I help you?" with BUY on top, then the list, cursor on its top. + press(context, BUTTON_A, 2000ms); + press(context, BUTTON_A, 2000ms); + // After a purchase the cursor stays on the item bought (run on console B, + // 2026-11-01: rows {1, 2, 3} counted from the top each time bought + // Parlyz Heals instead of Antidotes, and the third order hit CANCEL). + int cursor = 0; + for (const MartOrder& order : orders){ + console.log(std::format("Mart: buying {} of row {} (cursor on row {}).", order.quantity, order.row + 1, cursor + 1)); + const int moves = mart_cursor_moves(cursor, order.row); + for (int c = 0; c < std::abs(moves); c++){ + tap(context, moves > 0 ? DPAD_DOWN : DPAD_UP, 300ms); + } + cursor = order.row; + mart_shot(console, context, std::format("row{}-list", order.row + 1)); + if (checks_screen(checks)){ + check_mart_row(console, context, order, language); + } + // "How many?" drops presses while its text prints. + press(context, BUTTON_A, 2500ms); + for (int c = 1; c < order.quantity; c++){ + tap(context, DPAD_UP, 340ms); + } + mart_shot(console, context, std::format("row{}-quantity", order.row + 1)); + // "That will be..." YES/NO, YES, "Here you are!"; the cursor stays + // on the row. + press(context, BUTTON_A, 3500ms); + press(context, BUTTON_A, 2000ms); + press(context, BUTTON_A, 1500ms); + mart_shot(console, context, std::format("row{}-bought", order.row + 1)); + } + press(context, BUTTON_B, 1500ms); + press(context, BUTTON_B, 1500ms); + mash_until_overworld(console, context, 20000ms); +} + +void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context){ + console.log("New game: from the title screen."); + NewGameIntro(console, context).run(); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h new file mode 100644 index 0000000000..17f73ead43 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h @@ -0,0 +1,85 @@ +/* AutoStory Actions + * + * From: https://github.com/PokemonAutomation/ + * + * The console steps the FRLG story is made of, as a by-hand run from a new + * game to Brock found them (console B, 2026-11-01): reading text to its end, + * YES/NO prompts, saving from the START menu, the nurse, the Viridian Mart, + * and the new game's intro. Story text is advanced with B, which never + * starts a talk; the overworld is back once START opens the menu, which it + * doesn't while a scene runs. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryActions_H +#define PokemonAutomation_PokemonFRLG_AutoStoryActions_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonFRLG_AutoStorySave.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// RIGHT presses that turn an option showing `current` into `target`. +// RIGHT steps through `values` and wraps from the last to the first +// (pokefirered option_menu.c OptionMenu_ProcessInput). Nothing if either +// isn't one of `values`. +std::optional option_right_presses( + const std::vector& values, const std::string& current, const std::string& target +); + +// From the overworld: OPTION, text speed FAST, battle scene OFF (no move +// animations), battle style SET (no "Will you switch?" between a +// trainer's Pokemon). Returns to the overworld. A new game keeps the +// options of the save it replaces, so each value is read and stepped to +// its target, then read again; one that can't be read, as in a language +// the reader has no names for, or that isn't the target after the +// presses, fails with a screenshot and leaves the menu open. +void set_options(ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language); + +// Facing the nurse: A, YES, the heal, and the text to its end. +void heal_at_center(ConsoleHandle& console, ProControllerContext& context); + +// One line of a Mart's BUY list: the row (from 0) and how many. +struct MartOrder{ + int row = 0; + int quantity = 1; + // The item's slug for the check (see read_item_list_name()). + std::string_view item = ""; +}; + +// Down (positive) or up (negative) presses to move a Mart list's cursor +// from `cursor` to `row`. After a purchase the cursor stays on its row. +int mart_cursor_moves(int cursor, int row); + +// Facing a Mart clerk: BUY each order, then out to the overworld. +// THOROUGH: each row's item is read before buying; one that reads as +// another item fails with a screenshot, one that can't be read is only +// logged. +// `language` is the game's: in one the reader has no names for, rows are +// bought by position only. +void buy_items( + ConsoleHandle& console, ProControllerContext& context, + const std::vector& orders, Pokemon::StoryCheckLevel checks, Language language +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp new file mode 100644 index 0000000000..f119e6c6a6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -0,0 +1,976 @@ +/* AutoStory Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleFlashWatcher.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleHpBarReader.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattlePokemonDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMenuDetector.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattleData.h" +#include "PokemonFRLG_AutoStoryBattleDecisions.h" +#include "PokemonFRLG_AutoStoryBattle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; + + +namespace{ + +constexpr Milliseconds POLL = 300ms; +constexpr Milliseconds BATTLE_TIMEOUT = 600000ms; +// To see the battle at all, from its first flash. +constexpr Milliseconds BATTLE_START_TIMEOUT = 20000ms; +// No battle screen for this long: check for the overworld with START. +constexpr Milliseconds BATTLE_GONE = 2000ms; +// A battle screen with neither an arrow nor a menu for this long: B, for +// a prompt the detectors miss. +constexpr Milliseconds STUCK = 8000ms; +// Seen this many polls in a row: the starter fainted. +constexpr int FAINT_POLLS = 3; +// No battle menu for this long: A and B in turn, for a prompt nothing reads. +// Only near battle screens: A on the overworld after a gym leader's speech +// would talk to them again. +constexpr Milliseconds NO_MENU = 60000ms; +constexpr Milliseconds NO_MENU_NEAR = 10000ms; +// No battle screen yet and no turn taken: whether the overworld is back +// is checked by START this often (a trainer's battle that never started, +// console B, 2026-11-01: 10 minutes of B on the overworld). +constexpr Milliseconds OVERWORLD_CHECK = 3000ms; +// No battle menu or HP box this long after a battle was seen: there was +// none (console B, 2026-11-01, Viridian Forest's north gate mat). +constexpr Milliseconds NOT_A_BATTLE = 15000ms; +// An evolution's animation, with no presses: as long as exit_wild_battle() +// (PokemonFRLG_Navigation.cpp) waits for one. +constexpr Milliseconds EVOLUTION = 20000ms; +// Text and the move learn prompts after a battle, on the overworld. +constexpr Milliseconds AFTER_BATTLE_TEXT = 60000ms; +// The move list to fade in after "Delete a move?", and its cursor to move. +constexpr Milliseconds MOVE_LIST_TIMEOUT = 5000ms; + +// In the player's box, as a fraction of the 240x160 screen: the status +// badge left of the HP numbers. The box bobs by a pixel; this keeps a +// pixel inside. +const ImageFloatBox STATUS_BADGE_BOX(146.0 / 240, 99.0 / 160, 12.0 / 240, 4.0 / 160); + +StatusCondition read_status_badge(const ImageViewRGB32& badge){ + const ImageStats stats = image_stats(badge); + const double r = stats.average.r; + const double g = stats.average.g; + const double b = stats.average.b; + const double off_white = std::abs(r - 255) + std::abs(g - 255) + std::abs(b - 217); + if (off_white < 60){ + return StatusCondition::NONE; + } + if (r > 200 && g < 200 && b > 180){ + return StatusCondition::POISON; + } + // Not measured yet: PAR's badge is taken to be the yellow one. + if (r > 180 && g > 150 && b < 140){ + return StatusCondition::PARALYSIS; + } + return StatusCondition::OTHER; +} + + +enum class BattleScreen{ + // Keep in step with screen_name(). + MENU, // "What will do?" with FIGHT/BAG/POKEMON/RUN + LEARN, // a YES/NO about a move to learn + ADVANCE, // battle text waiting for a button + OTHER, // the battle, busy + NONE, // no battle on screen +}; + +std::string_view screen_name(BattleScreen screen){ + switch (screen){ + case BattleScreen::MENU: + return "battle menu"; + case BattleScreen::LEARN: + return "move prompt"; + case BattleScreen::ADVANCE: + return "battle text with arrow"; + case BattleScreen::OTHER: + return "battle text box"; + case BattleScreen::NONE: + return "no battle screen"; + } + return "?"; +} + +// Until `confirmed`, the battle text box alone counts for nothing: it also +// reads on the black below a small indoor map. +BattleScreen read_battle_screen(const ImageViewRGB32& screen, bool confirmed){ + if (BattleMenuDetector(COLOR_RED).detect(screen)){ + return BattleScreen::MENU; + } + if (BattleLearnDialogDetector(COLOR_RED).detect(screen)){ + return BattleScreen::LEARN; + } + if (!confirmed && !BattleScreenDetector(COLOR_RED).detect(screen)){ + return BattleScreen::NONE; + } + if (AdvanceBattleDialogDetector(COLOR_RED).detect(screen)){ + return BattleScreen::ADVANCE; + } + if (BattleDialogDetector(COLOR_RED).detect(screen)){ + return BattleScreen::OTHER; + } + return BattleScreen::NONE; +} + +BattleTextScreen read_text_screen(const ImageViewRGB32& screen){ + return BattleTextScreen{ + .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(), + }; +} + +// The player's Pokemon gone while the opponent's is still there. +bool starter_fainted(const ImageViewRGB32& screen){ + return !BattlePokemonDetector(COLOR_RED).detect(screen) && BattleOpponentDetector(COLOR_RED).detect(screen); +} + +void tap(ProControllerContext& context, DpadPosition position){ + pbf_press_dpad(context, position, 160ms, 240ms); +} + +// In the bag, with the cursor on `row`: whether that row is `item`. FAST +// doesn't look. A row that can't be read (as in a language the reader has +// no names for) is taken by its position; only another item's name stops it. +bool bag_row_is( + ConsoleHandle& console, ProControllerContext& context, + int row, const std::string& item, Pokemon::StoryCheckLevel checks, Language language +){ + if (!checks_screen(checks)){ + return true; + } + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + const std::string read = screen ? read_item_list_name(console, language, screen, row) : ""; + if (read == item){ + return true; + } + if (read.empty()){ + console.log(std::format("Bag: row {} unread, taking it as the {} by its position.", row + 1, item), COLOR_ORANGE); + return true; + } + console.log(std::format("Bag: row {} reads \"{}\", not {}: not using it.", row + 1, read, item), COLOR_RED); + dump_debug_image(console, "AutoStory/bag", std::format("row{}-not-{}", row + 1, item), screen); + return false; +} + +// 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. +bool use_item( + ConsoleHandle& console, ProControllerContext& context, + int row, const std::string& item, Pokemon::StoryCheckLevel checks, Language language +){ + console.log(std::format("Battle: using the {} in row {} of the Items pocket.", item, row + 1)); + tap(context, DPAD_LEFT); + tap(context, DPAD_UP); + tap(context, DPAD_RIGHT); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); + for (int c = 0; c < 2; c++){ + pbf_press_dpad(context, DPAD_LEFT, 160ms, 500ms); + } + for (int c = 0; c < 12; c++){ + pbf_press_dpad(context, DPAD_UP, 100ms, 150ms); + } + for (int c = 0; c < row; c++){ + tap(context, DPAD_DOWN); + } + if (!bag_row_is(console, context, row, item, checks, language)){ + pbf_press_button(context, BUTTON_B, 160ms, 1500ms); + return false; + } + // The item, USE, then the starter in the party list. + pbf_press_button(context, BUTTON_A, 160ms, 800ms); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + return true; +} + +// RUN, bottom right of the battle menu. +void run_away(ProControllerContext& context){ + tap(context, DPAD_LEFT); + tap(context, DPAD_UP); + tap(context, DPAD_RIGHT); + tap(context, DPAD_DOWN); + 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. +void use_move(ProControllerContext& context, size_t slot){ + tap(context, DPAD_LEFT); + tap(context, DPAD_UP); + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + tap(context, DPAD_LEFT); + tap(context, DPAD_UP); + if (slot % 2 == 1){ + tap(context, DPAD_RIGHT); + } + if (slot >= 2){ + tap(context, DPAD_DOWN); + } + pbf_press_button(context, BUTTON_A, 160ms, 500ms); +} + +// The move list's cursor row once it shows, and, if `before` is given, once +// it has left that row: up to `timeout`. +std::optional read_move_list_cursor( + ConsoleHandle& console, ProControllerContext& context, + std::optional before, Milliseconds timeout +){ + const WallClock deadline = current_time() + timeout; + while (true){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + const std::optional cursor = screen ? read_summary_move_cursor(screen) : std::nullopt; + if (cursor && cursor != before){ + return cursor; + } + if (current_time() >= deadline){ + return std::nullopt; + } + pbf_wait(context, POLL); + } +} + +// After YES to "Delete a move?": the move list fades in with its cursor on +// the top move (pret pokemon_summary_screen.c); A on a move forgets it, +// B would go back to "Stop learning?". The cursor is read before A and +// after each press: DOWNs sent while the list faded in were lost, and A +// forgot the top move, Tackle, for Water Gun instead of Bubble (console B, +// 2026-11-02). Done in one go, so the loop's B presses can't land on the +// list. A list whose cursor never shows gets the presses by time, as +// before; a cursor that can't be brought to `slot` fails the battle. +// YES, then `slot` on the move list. False, with nothing more pressed, if no move list showed. +bool forget_move(ConsoleHandle& console, ProControllerContext& context, size_t slot){ + pbf_press_button(context, BUTTON_A, 160ms, 0ms); + std::optional cursor = read_move_list_cursor(console, context, std::nullopt, MOVE_LIST_TIMEOUT); + if (!cursor){ + console.log("Battle: no move list after YES; the moves stay as they were.", COLOR_ORANGE); + return false; + } + for (size_t presses = 0; *cursor != slot; presses++){ + if (presses >= 2 * SUMMARY_MOVE_ROWS){ + break; + } + const size_t from = *cursor; + pbf_press_dpad(context, from < slot ? DPAD_DOWN : DPAD_UP, 160ms, 0ms); + cursor = read_move_list_cursor(console, context, from, MOVE_LIST_TIMEOUT); + if (!cursor){ + break; + } + } + if (cursor != slot){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format("forget_move(): the cursor didn't reach move {} on the move list.", slot + 1), + console + ); + } + pbf_press_button(context, BUTTON_A, 160ms, 2000ms); + 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; +} + +void send_member(ProControllerContext& context, size_t slot){ + for (size_t c = 0; c < slot; c++){ + pbf_press_dpad(context, DPAD_DOWN, 160ms, 400ms); + } + pbf_press_button(context, BUTTON_A, 160ms, 800ms); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); +} + + +class BattleLoop{ +public: + BattleLoop( + ConsoleHandle& console, ProControllerContext& context, + Supplies& supplies, BattleKind kind, Pokemon::StoryCheckLevel checks, Language language + ) + : m_console(console) + , m_context(context) + , m_supplies(supplies) + , m_decisions(supplies, kind) + , m_evolution(supplies.lead) + , m_kind(kind) + , m_checks(checks) + , m_language(language) + , m_start(current_time()) + , m_last_battle(m_start) + , m_last_press(m_start) + , m_last_menu(m_start) + , m_last_overworld_check(m_start) + {} + + BattleEnd run(){ + m_console.log( + m_kind == BattleKind::TRAINER ? "Battle: fighting a trainer." : + m_kind == BattleKind::WILD_FIGHT ? "Battle: fighting a wild Pokemon." : "Battle: running from a wild Pokemon." + ); + bool over = false; + while (!over){ + over = step(); + } + m_console.log(std::format( + "Battle: over after {} turns{}.", m_decisions.turns(), m_decisions.lost() ? ", the starter fainted" : "" + )); + return m_decisions.lost() ? BattleEnd::LOST : BattleEnd::WON; + } + +private: + // One look at the screen and what it asks for. True once the battle is over. + bool step(){ + m_context.wait_for_all_requests(); + const WallClock now = current_time(); + check_time(now); + VideoSnapshot screen = m_console.video().snapshot(); + if (!screen){ + pbf_wait(m_context, POLL); + return false; + } + if (!m_confirmed && BattleScreenDetector(COLOR_RED).detect(screen)){ + m_console.log("Battle: the battle menu or an HP box shows."); + m_confirmed = true; + } + if (!m_confirmed && now - m_start > NOT_A_BATTLE){ + m_console.log("Battle: no battle menu or HP box in 15 s: not a battle.", COLOR_ORANGE); + return true; + } + if (between_turns(screen, now)){ + return false; + } + if (battle_gone(screen, now)){ + return true; + } + const BattleScreen seen = read_battle_screen(screen, m_confirmed); + if (seen != m_last_seen){ + m_console.log(std::format("Battle: {} (turn {}).", screen_name(seen), m_decisions.turns())); + m_last_seen = seen; + } + if (seen == BattleScreen::MENU){ + m_last_menu = now; + m_move_chosen = false; + }else if (now - m_last_menu > NO_MENU && now - m_last_battle < NO_MENU_NEAR && now - m_last_press > 1500ms){ + // Something waits that none of the battle screens knows. + return press_blind(now); + } + if (seen == BattleScreen::NONE){ + m_refusal.no_battle_screen(); + return no_battle_screen(screen, now); + } + m_seen_battle = true; + m_last_battle = now; + read_hp(screen); + watch_for_faint(screen); + act(seen, screen, now); + return false; + } + + // The screens between the turns that need more than B: "no PP left", + // the party list once the lead fainted, and an evolution after the + // battle. True if one was handled. + bool between_turns(const ImageViewRGB32& screen, WallClock now){ + if (!m_confirmed){ + return false; + } + if (m_move_chosen && 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; + m_refusal = MoveRefusalWatch(); + pbf_press_button(m_context, BUTTON_B, 160ms, 800ms); + pbf_press_button(m_context, BUTTON_B, 160ms, 800ms); + m_last_press = now; + return true; + } + if (m_decisions.lost() && PartyMenuDetector(COLOR_RED).detect(screen)){ + send_next_member(now); + return true; + } + if (m_evolution.holds(read_text_screen(screen))){ + wait_out_evolution(); + return true; + } + return false; + } + + // The party list after the lead fainted: the next member allowed in, or + // a stop with only protected members left. + void send_next_member(WallClock now){ + const std::optional slot = m_decisions.next_member_slot(); + if (!slot){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::NO_ERROR_REPORT, + "fight_battle(): the starter fainted and only protected members are left; not sending one.", + m_console + ); + } + m_console.log(std::format("Battle: the lead fainted; sending party slot {}.", *slot + 1), COLOR_ORANGE); + send_member(m_context, *slot); + m_last_press = now; + } + + // Nothing pressed while the screen may be an evolution, up to EVOLUTION. + void wait_out_evolution(){ + const WallClock start = current_time(); + bool holds = true; + while (holds && current_time() - start < EVOLUTION){ + pbf_wait(m_context, POLL); + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_console.video().snapshot(); + holds = !screen || m_evolution.holds(read_text_screen(screen)); + } + const WallClock end = current_time(); + const Milliseconds held = std::chrono::duration_cast(end - start); + if (held >= 2000ms){ + m_console.log(std::format("Battle: no B for {} s, for an evolution.", held.count() / 1000)); + } + m_evolution.held(held, m_decisions.lost()); + m_last_press = end; + m_last_battle = end; + } + + // True once START opens the menu, after no battle menu, HP box or + // YES/NO for a while: whatever the text box reads, the battle is over. + bool battle_gone(const ImageViewRGB32& screen, WallClock now){ + const BattleSeen seen = BattleMenuDetector(COLOR_RED).detect(screen) ? BattleSeen::MENU + : battle_shows(screen) ? BattleSeen::BATTLE : BattleSeen::NONE; + m_end.seen(seen, now); + if (!m_end.check_overworld(now)){ + return false; + } + m_last_overworld_check = now; + return overworld_shows(m_console, m_context); + } + + // A or B, in turn. True once they have gone on too long: the walk, + // which finds the player again, takes over. + bool press_blind(WallClock now){ + if (m_end.pressed_blind(now)){ + m_console.log("Battle: no battle menu after pressing A and B; leaving the rest to the walk.", COLOR_RED); + return true; + } + m_console.log(std::format("Battle: no battle menu for {} s, pressing {}.", + std::chrono::duration_cast(now - m_last_menu).count(), m_press_a ? "A" : "B")); + pbf_press_button(m_context, m_press_a ? BUTTON_A : BUTTON_B, 160ms, 200ms); + m_press_a = !m_press_a; + m_last_press = now; + return false; + } + + // True once the battle is over: only when START opens the menu. The + // battle screens are gone during the opening slide-in (console B: "over + // after 0 turns" at the rival) and under a move prompt's YES/NO (console + // B, 2026-11-01, Viridian Forest: called over, then stuck at "Stop + // learning?"). + bool no_battle_screen(const ImageViewRGB32& screen, WallClock now){ + if (!m_seen_battle){ + pbf_wait(m_context, POLL); + return false; + } + if (m_decisions.turns() > 0 && yes_no_cursor(screen)){ + answer_prompt(screen, now); + return false; + } + if (now - m_last_battle > BATTLE_GONE && now - m_last_overworld_check > OVERWORLD_CHECK){ + m_last_overworld_check = now; + if (overworld_shows(m_console, m_context)){ + return true; + } + } + // Oak's white text box in the rival's battle reads as no battle screen: + // B moves it on, and B does nothing on the overworld once the battle is over. + if (now - m_last_press > 1500ms){ + pbf_press_button(m_context, BUTTON_B, 160ms, 200ms); + m_last_press = now; + return false; + } + pbf_wait(m_context, POLL); + return false; + } + + void check_time(WallClock now){ + if (!m_seen_battle && now - m_start > BATTLE_START_TIMEOUT){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "fight_battle(): no battle on screen.", m_console + ); + } + if (now - m_start > BATTLE_TIMEOUT){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "fight_battle(): the battle took over 10 minutes.", m_console + ); + } + } + + void act(BattleScreen seen, const ImageViewRGB32& screen, WallClock now){ + switch (seen){ + case BattleScreen::MENU: + take_turn(screen); + m_last_press = now; + return; + case BattleScreen::LEARN: + if (m_decisions.turns() == 0){ + // The prompts come after a turn; before one it is a misread. + break; + } + answer_prompt(screen, now); + return; + case BattleScreen::ADVANCE: + pbf_press_button(m_context, BUTTON_B, 160ms, 200ms); + m_last_press = now; + return; + default: + break; + } + if (now - m_last_press > STUCK){ + pbf_press_button(m_context, BUTTON_B, 160ms, 200ms); + m_last_press = now; + } + pbf_wait(m_context, POLL); + } + + // The HP bar whenever the starter's box shows, so the last reading + // includes the battle's last hit. Not once another member is out. + void read_hp(const ImageViewRGB32& screen){ + if (m_decisions.lost() || !BattlePokemonDetector(COLOR_RED).detect(screen)){ + return; + } + const PartyStatus status = read_party_status(screen); + if (status.hp_seen){ + m_supplies.hurt = status.hp_red || status.hp_yellow; + m_supplies.hp_red = status.hp_red; + m_supplies.hp_fill = status.hp_fill; + } + m_supplies.status = status.status; + } + + void answer_prompt(const ImageViewRGB32& screen, WallClock now){ + dump_debug_image(m_console, "AutoStory/battle", std::format("turn{}-yes-no", m_decisions.turns()), screen); + const PromptAnswer answer = m_decisions.prompt(starter_fainted(screen)); + if (answer.forget_slot){ + m_console.log(std::format("Battle: learning the new move over move {}.", *answer.forget_slot + 1)); + if (forget_move(m_console, m_context, *answer.forget_slot) && answer.learned){ + m_supplies.lead = *answer.learned; + } + }else{ + m_console.log(std::format("Battle: answering {} to a YES/NO.", answer.answer == YesNo::YES ? "YES" : "NO")); + pbf_press_button(m_context, answer.answer == YesNo::YES ? BUTTON_A : BUTTON_B, 160ms, 1500ms); + } + m_last_press = now; + } + + void take_turn(const ImageViewRGB32& screen){ + m_faint_polls = 0; + if (m_kind != BattleKind::TRAINER && m_decisions.turns() == 0){ + m_supplies.wild_foes = read_wild_foes(m_console.logger(), m_language, screen); + } + if (m_kind == BattleKind::TRAINER && !m_supplies.foes.empty()){ + m_supplies.foe_out = read_trainer_foe(m_console.logger(), m_language, screen, m_supplies.foes); + } + if (m_refusal.refused(current_time())){ + m_console.log("Battle: the move list came back without a turn (Disable?); choosing another move.", COLOR_ORANGE); + m_decisions.turn_done(TurnChoice::MOVE, TurnResult::REFUSED); + } + const PartyStatus status = read_party_status(screen); + const TurnAction action = m_decisions.turn(status); + m_evolution.turn_taken(action.choice); + m_console.log(std::format( + "Battle: turn {}, HP {} ({:.0f}% of the bar), {}, {} Potions, {} Antidotes, {} Parlyz Heals.", + m_decisions.turns(), status.hp_red ? "red" : status.hp_yellow ? "yellow" : "green", 100 * status.hp_fill, + status_name(status.status), m_supplies.potions, m_supplies.antidotes, m_supplies.parlyz_heals + )); + dump_debug_image(m_console, "AutoStory/battle", std::format("turn{}-menu", m_decisions.turns()), screen); + switch (action.choice){ + case TurnChoice::RUN: + m_console.log("Battle: RUN."); + run_away(m_context); + return; + case TurnChoice::POTION: + m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, item_row(m_supplies, "potion"), "potion", m_checks, m_language))); + return; + case TurnChoice::ANTIDOTE: + m_decisions.turn_done(action.choice, item_result(use_item(m_console, m_context, item_row(m_supplies, "antidote"), "antidote", m_checks, m_language))); + return; + case TurnChoice::MOVE: + m_console.log(std::format("Battle: move {}.", action.slot + 1)); + m_refusal.move_chosen(current_time()); + use_move(m_context, action.slot); + m_move_chosen = true; + return; + } + } + + void watch_for_faint(const ImageViewRGB32& screen){ + if (m_decisions.turns() == 0 || m_decisions.lost()){ + return; + } + m_faint_polls = starter_fainted(screen) ? m_faint_polls + 1 : 0; + if (m_faint_polls >= FAINT_POLLS){ + m_console.log("Battle: the starter fainted.", COLOR_RED); + m_decisions.lead_fainted(); + } + } + + ConsoleHandle& m_console; + ProControllerContext& m_context; + Supplies& m_supplies; + BattleDecisions m_decisions; + EvolutionHold m_evolution; + BattleEndWatch m_end; + MoveRefusalWatch m_refusal; + const BattleKind m_kind; + const Pokemon::StoryCheckLevel m_checks; + const Language m_language; + const WallClock m_start; + WallClock m_last_battle; + WallClock m_last_press; + WallClock m_last_menu; + WallClock m_last_overworld_check; + BattleScreen m_last_seen = BattleScreen::NONE; + bool m_seen_battle = false; + bool m_confirmed = false; + bool m_press_a = true; + // A move was chosen and no battle menu has shown since. + bool m_move_chosen = false; + int m_faint_polls = 0; +}; + + +// From the overworld: the bag open on the Items pocket, cursor on its top. +void open_items_pocket(ConsoleHandle& console, ProControllerContext& context){ + open_bag_from_overworld(console, context); + // The bag ignores presses while it slides in. + pbf_wait(context, 1000ms); + for (int c = 0; c < 3; c++){ + pbf_press_dpad(context, DPAD_LEFT, 100ms, 500ms); + } + for (int c = 0; c < 20; c++){ + pbf_press_dpad(context, DPAD_UP, 100ms, 100ms); + } +} + +// From the overworld: `item`, in `row` (from 0) of the Items pocket, on +// the starter. Returns whether it was used (THOROUGH reads the row first). +// Not run on the console yet. +bool use_item_on_overworld( + ConsoleHandle& console, ProControllerContext& context, + int row, const std::string& item, Pokemon::StoryCheckLevel checks, Language language +){ + console.log(std::format("Story: using a {} from the bag (Items pocket, row {}).", item, row + 1)); + open_items_pocket(console, context); + for (int c = 0; c < row; c++){ + pbf_press_dpad(context, DPAD_DOWN, 100ms, 300ms); + } + if (!bag_row_is(console, context, row, item, checks, language)){ + mash_until_overworld(console, context, AFTER_BATTLE_TEXT); + return false; + } + // The item, USE, the starter, then its message. + pbf_press_button(context, BUTTON_A, 160ms, 800ms); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); + pbf_press_button(context, BUTTON_A, 160ms, 2500ms); + pbf_press_button(context, BUTTON_B, 160ms, 1500ms); + mash_until_overworld(console, context, AFTER_BATTLE_TEXT); + return true; +} + +void fail_on_blackout(ConsoleHandle& console, BattleEnd end){ + if (end == BattleEnd::LOST){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::NO_ERROR_REPORT, "Story: blackout: the starter fainted in a battle on the way.", console + ); + } +} + + +// A wild battle, seen by its flashes or, when they were missed, by "Wild +// appeared!". +class StoryWildBattle : public OverworldInterrupt{ +public: + StoryWildBattle(Supplies& supplies, bool fight, bool late, Pokemon::StoryCheckLevel checks, Language language) + : m_supplies(supplies) + , m_checks(checks) + , m_language(language) + , m_fight(fight) + , m_late(late) + {} + virtual std::string name() const override{ + return m_late ? "a wild battle (seen late)" : "a wild battle"; + } + virtual std::unique_ptr make_watcher() const override{ + if (m_late){ + return std::make_unique(COLOR_RED); + } + return std::make_unique(COLOR_RED); + } + // As the walker's own wild battle interrupts. + virtual Milliseconds detection_delay() const override{ + return m_late ? 2000ms : 300ms; + } + // Run from or fought by the battle loop, which returns only once START + // opens on the overworld, so nothing of the battle is left before the + // next leg. + virtual void clear(ConsoleHandle& console, ProControllerContext& context) const override{ + const BattleKind kind = m_fight ? BattleKind::WILD_FIGHT : BattleKind::WILD_RUN; + fail_on_blackout(console, fight_battle(console, context, m_supplies, kind, m_checks, m_language)); + recover_after_battle(console, context, m_supplies, m_checks, m_language); + } + +private: + Supplies& m_supplies; + const Pokemon::StoryCheckLevel m_checks; + const Language m_language; + const bool m_fight; + const bool m_late; +}; + +// A message: read to its end, then a trainer's battle if one starts. +class StoryMessage : public OverworldInterrupt{ +public: + StoryMessage(Supplies& supplies, Pokemon::StoryCheckLevel checks, Language language) + : m_supplies(supplies) + , m_checks(checks) + , m_language(language) + {} + virtual std::string name() const override{ + return "a message"; + } + virtual std::unique_ptr make_watcher() const override{ + return std::make_unique(COLOR_RED); + } + virtual Milliseconds detection_delay() const override{ + return 400ms; + } + virtual void clear(ConsoleHandle& console, ProControllerContext& context) const override{ + if (advance_text(console, context, AFTER_BATTLE_TEXT, true) == TextEnd::OVERWORLD){ + return; + } + console.log("Story: a trainer's battle after a message on the overworld."); + fail_on_blackout(console, fight_battle(console, context, m_supplies, BattleKind::TRAINER, m_checks, m_language)); + mash_until_overworld(console, context, AFTER_BATTLE_TEXT); + recover_after_battle(console, context, m_supplies, m_checks, m_language); + } + +private: + Supplies& m_supplies; + const Pokemon::StoryCheckLevel m_checks; + const Language m_language; +}; + +} // namespace + + +std::string_view status_name(StatusCondition status){ + switch (status){ + case StatusCondition::NONE: + return "no status"; + case StatusCondition::POISON: + return "PSN"; + case StatusCondition::PARALYSIS: + return "PAR"; + case StatusCondition::OTHER: + return "a status"; + } + return "?"; +} + +PartyStatus read_party_status(const ImageViewRGB32& screen){ + const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); + const HpBarReading bar = read_player_hp_bar(game); + PartyStatus status; + status.hp_seen = bar.seen; + status.hp_yellow = bar.seen && bar.color == HpBarColor::YELLOW; + status.hp_red = bar.seen && bar.color == HpBarColor::RED; + status.hp_fill = bar.fill; + status.status = read_status_badge(extract_box_reference(game, STATUS_BADGE_BOX)); + return status; +} + +bool battle_shows(const ImageViewRGB32& screen){ + const BattleTextScreen text = read_text_screen(screen); + return text.hp_box || text.yes_no; +} + +// The count the story keeps for `item`, or null for an item it doesn't count. +static int* count_slot(Supplies& supplies, const std::string& item){ + if (item == "potion"){ + return &supplies.potions; + } + if (item == "antidote"){ + return &supplies.antidotes; + } + if (item == "parlyz-heal"){ + return &supplies.parlyz_heals; + } + return nullptr; +} + +int item_count(const Supplies& supplies, const std::string& item){ + if (item == "potion"){ + return supplies.potions; + } + if (item == "antidote"){ + return supplies.antidotes; + } + if (item == "parlyz-heal"){ + return supplies.parlyz_heals; + } + return 0; +} + +// Whether the story keeps a count for `item`. +static bool counted(const std::string& item){ + Supplies probe; + return count_slot(probe, item) != nullptr; +} + +int item_row(const Supplies& supplies, const std::string& item){ + int row = 0; + for (const std::string& slot : supplies.pocket){ + if (counted(slot) && item_count(supplies, slot) <= 0){ + continue; + } + if (slot == item){ + return row; + } + row++; + } + return -1; +} + +std::vector set_from_bag(Supplies& supplies, const std::vector& rows){ + const Supplies before = supplies; + supplies.potions = 0; + supplies.antidotes = 0; + supplies.parlyz_heals = 0; + supplies.pocket.clear(); + std::vector unread; + for (const BagRow& row : rows){ + supplies.pocket.push_back(row.item); + int* slot = count_slot(supplies, row.item); + if (slot == nullptr){ + continue; + } + if (row.count > 0){ + *slot = row.count; + continue; + } + // Taking an unread count for none left the starter unhealed at + // 9 HP until it fainted (console B, 2026-11-02). + *slot = std::max(item_count(before, row.item), 1); + unread.push_back(row.item); + } + return unread; +} + +std::vector set_from_loaded_bag(Supplies& supplies, Supplies& saved, const std::vector& rows){ + if (rows.empty()){ + return {}; + } + std::vector unread = set_from_bag(supplies, rows); + saved.potions = supplies.potions; + saved.antidotes = supplies.antidotes; + saved.parlyz_heals = supplies.parlyz_heals; + saved.pocket = supplies.pocket; + return unread; +} + +std::vector read_items_pocket(ConsoleHandle& console, ProControllerContext& context, Language language){ + open_items_pocket(console, context); + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + dump_debug_image(console, "AutoStory/bag", "items-pocket", screen); + std::vector rows = screen ? read_bag_pocket(console, language, screen) : std::vector{}; + std::string text; + for (const BagRow& row : rows){ + text += std::format(" {} x{};", row.item, row.count); + } + console.log("Bag: Items pocket:" + (text.empty() ? std::string(" nothing read.") : text)); + mash_until_overworld(console, context, AFTER_BATTLE_TEXT); + return rows; +} + +void recover_after_battle( + ConsoleHandle& console, ProControllerContext& context, + Supplies& supplies, Pokemon::StoryCheckLevel checks, Language language +){ + if (supplies.status == StatusCondition::POISON && supplies.antidotes > 0){ + if (use_item_on_overworld(console, context, item_row(supplies, "antidote"), "antidote", checks, language)){ + supplies.antidotes--; + supplies.status = StatusCondition::NONE; + } + }else if (supplies.status == StatusCondition::PARALYSIS && supplies.parlyz_heals > 0){ + if (use_item_on_overworld(console, context, item_row(supplies, "parlyz-heal"), "parlyz-heal", checks, language)){ + supplies.parlyz_heals--; + supplies.status = StatusCondition::NONE; + } + } + // One Potion (20 HP) takes a starter of these levels (about 30 HP) + // from red to green; the bar can't be read again on the overworld. + if (supplies.hurt && supplies.potions > 0){ + if (use_item_on_overworld(console, context, item_row(supplies, "potion"), "potion", checks, language)){ + supplies.potions--; + supplies.hurt = false; + supplies.hp_red = false; + supplies.hp_fill = 1.0; + } + } +} + +BattleEnd fight_battle( + ConsoleHandle& console, ProControllerContext& context, + Supplies& supplies, BattleKind kind, Pokemon::StoryCheckLevel checks, Language language +){ + return BattleLoop(console, context, supplies, kind, checks, language).run(); +} + +OverworldInterruptSet story_interrupts(Supplies& supplies, bool fight_wild, Pokemon::StoryCheckLevel checks, Language language){ + // Battles first: their screens are checked before the message box's. + OverworldInterruptSet ret; + ret.wild.emplace_back(std::make_unique(supplies, fight_wild, false, checks, language)); + ret.wild.emplace_back(std::make_unique(supplies, fight_wild, true, checks, language)); + ret.wild.emplace_back(std::make_unique(supplies, checks, language)); + ret.other.emplace_back(std::make_unique(supplies, checks, language)); + return ret; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h new file mode 100644 index 0000000000..cd651c25f5 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h @@ -0,0 +1,113 @@ +/* AutoStory Battle + * + * From: https://github.com/PokemonAutomation/ + * + * The battle loop of the FRLG story, the starter leading, as the by-hand + * run to Brock played it (console B, 2026-11-01): at each turn the cursor + * is put back on FIGHT and the move list's top left, since the game + * remembers both, then onto the move BattleDecisions picks. A Potion is + * used when the HP bar turns yellow or red, an Antidote (once a battle) + * when the status reads PSN at two turns in a row; after the battle, PSN + * and PAR are cured from the bag. Move prompts, an evolution after the + * battle and a fainted lead are as PokemonFRLG_AutoStoryBattleDecisions.h + * says. + * + * Also the overworld interrupts the story walks routes with: wild battles + * run from (or fought, for EXP), and messages, after which a trainer's + * battle is fought instead of stopping the route. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryBattle_H +#define PokemonAutomation_PokemonFRLG_AutoStoryBattle_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattleData.h" +#include "PokemonFRLG_AutoStoryParty.h" +#include "PokemonFRLG_AutoStoryItemsPocket.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// Type of battle engagement strategy. +enum class BattleKind{ + WILD_RUN, // RUN, or fight after a few "Can't escape!" + WILD_FIGHT, // fight for EXP with green HP, no status and 2 Potions, else RUN + TRAINER, +}; + +// Terminal state of a battle encounter. +enum class BattleEnd{ + WON, + // The starter fainted: a blackout, or a wild battle run from (or won) + // by the next member, except in the lab's rival battle, which the + // story goes on from. + LOST, +}; + + + +// What the HP bar (read_player_hp_bar()) and the status badge of the +// player's Pokemon show, on a battle screen with its box. The badge's +// place measured on console B's captures (2026-11-01): off-white +// (255, 255, 217) with no status, (228, 168, 212) for PSN. +struct PartyStatus{ + bool hp_seen = false; + bool hp_yellow = false; + bool hp_red = false; + // The HP bar's filled share of its width, 0 to 1, for the log. + double hp_fill = 0; + StatusCondition status = StatusCondition::NONE; +}; +// Reads current party health and status from battle screen. +PartyStatus read_party_status(const ImageViewRGB32& screen); + +// Whether `screen` shows a battle, for the battle loop's end: the battle +// menu, an HP box or a YES/NO. Not the text box alone, which also reads on +// the black below a small room or a dark cave's corridor. +bool battle_shows(const ImageViewRGB32& screen); + +// From anywhere in a battle (or its opening), plays it to the end as +// `kind` says, using `supplies` as needed. Returns once START opens the +// menu on the overworld: text after the battle (a gym leader's speech) is +// read with B on the way. After 30 s of A and B for a screen nothing reads, +// returns anyway, for the walk to find the player. Throws +// OperationFailedException if it runs over 10 minutes. +// THOROUGH: an item's name is read in the bag before it is used, and a +// different one isn't used. +BattleEnd fight_battle( + ConsoleHandle& console, ProControllerContext& context, + Supplies& supplies, BattleKind kind, Pokemon::StoryCheckLevel checks, Language language +); + + + +// The interrupts for walking story routes. Wild battles are run from, or +// fought if `fight_wild`. A message is advanced until the overworld is +// back; a battle that starts after it (a trainer who saw the player) is +// fought. A battle lost (a blackout) throws OperationFailedException. +OverworldInterruptSet story_interrupts(Supplies& supplies, bool fight_wild, Pokemon::StoryCheckLevel checks, Language language); + + +// Registers AutoStory item usage unit tests. +void add_tests_AutoStoryItems(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.cpp new file mode 100644 index 0000000000..fda6bae066 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.cpp @@ -0,0 +1,173 @@ +/* AutoStory Battle Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_WildEncounterReader.h" +#include "PokemonFRLG_AutoStoryBattleData.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +using JsonTable = std::map>; + +const JsonValue& file_json(std::string_view name){ + static const JsonTable FILES = []{ + JsonTable files; + for (const auto& [file, text] : autostory_battle_json()){ + files.emplace(file, parse_json(text)); + } + return files; + }(); + const auto it = FILES.find(name); + if (it == FILES.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("BattleData/{}.json is not built into the program.", name)); + } + return it->second; +} + +PokemonType type_of(const JsonValue& value){ + return Pokemon::POKEMON_TYPE_SLUGS().get_enum(value.to_string_throw(), PokemonType::NONE); +} + +uint8_t byte_of(const JsonValue& value){ + return static_cast(std::clamp(value.to_integer_throw(), 0, 255)); +} + +template +using Table = std::map>; + +// [type, damaging (0 or 1), pp] +const Table& moves(){ + static const Table MOVES = []{ + Table moves; + for (const auto& [name, value] : file_json("moves").to_object_throw()){ + const JsonArray& entry = value.to_array_throw(); + moves.emplace(name, MoveData{ + .type = type_of(entry[0]), .damaging = entry[1].to_integer_throw() != 0, .pp = byte_of(entry[2]), + }); + } + return moves; + }(); + return MOVES; +} + +// [type, type] +const Table& species(){ + static const Table SPECIES = []{ + Table species; + for (const auto& [name, value] : file_json("species").to_object_throw()){ + const JsonArray& entry = value.to_array_throw(); + species.emplace(name, SpeciesData{.first = type_of(entry[0]), .second = type_of(entry[1])}); + } + return species; + }(); + return SPECIES; +} + +bool starts_with_any(std::string_view text, std::initializer_list prefixes){ + return std::ranges::any_of(prefixes, [text](std::string_view prefix){ + return text.starts_with(prefix); + }); +} + +} // namespace + + +const MoveData* move_data(std::string_view move){ + const auto it = moves().find(move); + return it == moves().end() ? nullptr : &it->second; +} + +const SpeciesData* species_data(std::string_view name){ + const auto it = species().find(name); + return it == species().end() ? nullptr : &it->second; +} + +const std::set& battle_species(){ + static const std::set NAMES = []{ + std::set names; + for (const auto& item : species()){ + names.insert(item.first); + } + return names; + }(); + return NAMES; +} + +std::vector wild_foes(std::string_view species){ + if (species_data(species) == nullptr){ + return {}; + } + return {std::string(species)}; +} + +std::vector read_wild_foes(Logger& logger, Language language, const ImageViewRGB32& screen){ + if (language == Language::None){ + return {}; + } + const std::string species = WildEncounterReader().read_encounter(logger, language, screen, battle_species()).name; + std::vector foes = wild_foes(species); + logger.log(foes.empty() + ? "Battle: the wild Pokemon wasn't read; attacks in the plan's order." + : std::format("Battle: a wild {}; attacks are chosen against it.", species) + ); + return foes; +} + +size_t type_effectiveness(PokemonType attack, PokemonType defend){ + static const std::map, size_t> CHART = []{ + std::map, size_t> chart; + for (const JsonValue& value : file_json("type_chart").to_array_throw()){ + const JsonArray& entry = value.to_array_throw(); + chart[{type_of(entry[0]), type_of(entry[1])}] = static_cast(entry[2].to_integer_throw()); + } + return chart; + }(); + const auto it = CHART.find({attack, defend}); + return it == CHART.end() ? 10 : it->second; +} + +std::string read_trainer_foe(Logger& logger, Language language, const ImageViewRGB32& screen, const std::vector& party){ + if (language == Language::None || party.empty()){ + return ""; + } + const std::set species(party.begin(), party.end()); + std::string read = WildEncounterReader().read_encounter(logger, language, screen, species).name; + if (!species.contains(read)){ + read.clear(); + } + logger.log(read.empty() ? "Battle: the trainer's Pokemon wasn't read." : std::format("Battle: the trainer's {} is out.", read)); + return read; +} + +std::string_view battle_risk_name(BattleRisk risk){ + return risk == BattleRisk::HIGH ? "high" : "low"; +} + +BattleRisk default_battle_risk(std::string_view trainer){ + const bool big = starts_with_any(trainer, { + "TRAINER_RIVAL_", "TRAINER_CHAMPION_", "TRAINER_LEADER_", "TRAINER_ELITE_FOUR_", "TRAINER_BOSS_", "TRAINER_TEAM_ROCKET_ADMIN", + }); + return big ? BattleRisk::HIGH : BattleRisk::LOW; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h new file mode 100644 index 0000000000..5b67ace4d7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h @@ -0,0 +1,68 @@ +/* AutoStory Battle Data + * + * From: https://github.com/PokemonAutomation/ + * + * The game's data the story's attacks are chosen from when the plan has + * none, built into the program from BattleData/: the type chart, each + * species' types, and each move's type, whether it does damage and its + * PP. A battle's foes come from its step in the checkpoint's plan. + * + * Names are the program's slugs ("water-gun", "mr-mime"). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryBattleData_H +#define PokemonAutomation_PokemonFRLG_AutoStoryBattleData_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Language.h" +#include "PokemonFRLG_AutoStoryBattleRisk.h" +#include "PokemonFRLG_AutoStoryMoveData.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// Every species, for reading a wild Pokemon's name. +const std::set& battle_species(); + +// The foes of a wild battle whose Pokemon was read as `species`: it, or +// none when it wasn't read ("") or the data doesn't have it. +std::vector wild_foes(std::string_view species); + +// The foes of the wild battle on `screen`, a battle menu: the Pokemon its +// HP box names (WildEncounterReader, among battle_species()), as +// wild_foes() takes it. Logs what it read. +std::vector read_wild_foes(Logger& logger, Language language, const ImageViewRGB32& screen); + +// The Pokemon a trainer's battle shows on `screen`, a battle menu: the +// name its HP box shows (WildEncounterReader), among `party`'s species. +// Empty if not read. Logs what it read. +std::string read_trainer_foe(Logger& logger, Language language, const ImageViewRGB32& screen, const std::vector& party); + + + +// (name, JSON text) of each file in BattleData/, sorted by name. +// Generated at build time (SerialPrograms/cmake/EmbedTextFiles.cmake). +const std::vector>& autostory_battle_json(); + + +// Registers AutoStory battle data unit tests. +void add_tests_AutoStoryBattleData(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData_Tests.cpp new file mode 100644 index 0000000000..1f689f35d0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData_Tests.cpp @@ -0,0 +1,224 @@ +/* AutoStory Battle Data Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The battle data, and the attacks chosen against trainers' parties and wild Pokemon from it. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryBattleData.h" +#include "PokemonFRLG_AutoStoryBattleDecisions.h" +#include "PokemonFRLG_AutoStoryParty.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct AutoStoryBattleDataInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct AutoStoryBattleDataExpectation{ + std::string_view description; +}; + +struct AutoStoryBattleDataTestCase{ + AutoStoryBattleDataInput input; + AutoStoryBattleDataExpectation expectation; +}; + +class Test_AutoStoryBattleData : public UnitTest{ +public: + explicit Test_AutoStoryBattleData(AutoStoryBattleDataTestCase scenario) + : UnitTest(std::format("PokemonFRLG::AutoStoryBattleData - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + } + } + +private: + AutoStoryBattleDataTestCase m_scenario; +}; + +const PartyStatus GREEN{.hp_seen = true, .hp_yellow = false, .hp_red = false, .status = StatusCondition::NONE}; + +// The story's Wartortle once Bite is in: Tackle, Bite, Water Gun, Withdraw. +constexpr size_t BITE = 1; +constexpr size_t WATER_GUN = BOTTOM_LEFT_MOVE; + +std::string slot_name(std::optional slot){ + return slot ? std::to_string(*slot) : "none"; +} + +// The slot a wild battle's first turn attacks with, against `species` as +// read off the screen. +size_t wild_turn(const PartyMember& lead, std::string_view species){ + Supplies supplies; + supplies.lead = lead; + supplies.potions = 5; + supplies.wild_foes = wild_foes(species); + BattleDecisions wild(supplies, BattleKind::WILD_FIGHT); + return wild.turn(GREEN).slot; +} + + +// Spot checks against pret: the type chart, Bite, Growl and species' +// types. +UnitTestResult test_data(){ + if (type_effectiveness(PokemonType::WATER, PokemonType::FIRE) != 20 + || type_effectiveness(PokemonType::DARK, PokemonType::PSYCHIC) != 20 + || type_effectiveness(PokemonType::NORMAL, PokemonType::GHOST) != 0 + || type_effectiveness(PokemonType::WATER, PokemonType::NORMAL) != 10 + ){ + return "Expected Water 2x on Fire, Dark 2x on Psychic, Normal 0x on Ghost, Water 1x on Normal."; + } + const MoveData* bite = move_data("bite"); + if (bite == nullptr || !bite->damaging || bite->type != PokemonType::DARK || bite->pp != 25){ + return "Expected Bite: damaging, Dark, 25 PP."; + } + const MoveData* growl = move_data("growl"); + if (growl == nullptr || growl->damaging || growl->pp != 40){ + return "Expected Growl: no damage, 40 PP."; + } + const SpeciesData* starmie = species_data("starmie"); + if (starmie == nullptr || starmie->first != PokemonType::WATER || starmie->second != PokemonType::PSYCHIC){ + return "Expected Starmie: Water, Psychic."; + } + if (battle_species().size() != 386 || species_data("farfetch-d") == nullptr || species_data("missingno") != nullptr){ + return std::format("Expected the 386 species by the program's slugs, got {}.", battle_species().size()); + } + return true; +} + +// Mt. Moon: Super Nerd Miguel's Grimer (Poison) takes Water Gun, with or +// without Bite known: Water Gun and Bite both hit his party 1x, and the +// tie goes to the plan's Water Gun. +UnitTestResult test_miguel_grimer(){ + const std::vector miguel{"grimer", "voltorb", "koffing"}; + const std::vector leads{grown_to(new_member("squirtle", 5), 17), grown_to(new_member("squirtle", 5), 20)}; + for (const PartyMember& lead : leads){ + for (const std::vector& foes : {std::vector{"grimer"}, miguel}){ + const std::optional slot = attack_slot_against(lead, foes); + if (slot != WATER_GUN){ + return std::format("{} against {} foes: expected Water Gun, got slot {}.", lead.species, foes.size(), slot_name(slot)); + } + } + } + return true; +} + +// Bite where it hits better than Water Gun: on a Psychic or Ghost foe +// (2x), and on one that resists Water, where Bite's 1x beats Water Gun's +// 0.5x. Against a wild Pokemon as read, and a trainer's party. +UnitTestResult test_bite_wins(){ + const PartyMember wartortle = grown_to(new_member("squirtle", 5), 20); + for (std::string_view foe : {"abra", "starmie", "gastly", "staryu", "oddish", "dratini"}){ + const size_t slot = wild_turn(wartortle, foe); + if (slot != BITE){ + return std::format("A wild {}: expected Bite, got slot {}.", foe, slot); + } + } + for (std::string_view foe : {"geodude", "pidgey", "rattata"}){ + const size_t slot = wild_turn(wartortle, foe); + if (slot != WATER_GUN){ + return std::format("A wild {}: expected Water Gun, got slot {}.", foe, slot); + } + } + if (attack_slot_against(wartortle, {"staryu", "starmie"}) != BITE){ + return "Expected Bite against Misty's party."; + } + return true; +} + +// The default risks: the rival and gym leaders HIGH, route trainers, +// grunts and a battle that names no trainer LOW. +UnitTestResult test_risks(){ + const std::vector> cases = { + {"TRAINER_RIVAL_CERULEAN_BULBASAUR", BattleRisk::HIGH}, + {"TRAINER_LEADER_MISTY", BattleRisk::HIGH}, + {"TRAINER_LEADER_BROCK", BattleRisk::HIGH}, + {"TRAINER_LASS_ALI", BattleRisk::LOW}, + {"TRAINER_TEAM_ROCKET_GRUNT", BattleRisk::LOW}, + {"", BattleRisk::LOW}, + }; + for (const auto& [trainer, risk] : cases){ + if (default_battle_risk(trainer) != risk){ + return std::format("\"{}\": expected {}.", trainer, battle_risk_name(risk)); + } + } + return true; +} + +// A wild Pokemon that wasn't read, or a name the data doesn't have, gets +// the plan's order: Water Gun first. +UnitTestResult test_wild_fallback(){ + const PartyMember wartortle = grown_to(new_member("squirtle", 5), 20); + for (std::string_view read : {"", "missingno"}){ + if (!wild_foes(read).empty()){ + return std::format("Expected no foes for \"{}\".", read); + } + const size_t slot = wild_turn(wartortle, read); + if (slot != WATER_GUN || attack_slot(wartortle) != WATER_GUN){ + return std::format("A wild \"{}\": expected the plan's Water Gun, got slot {}.", read, slot); + } + } + return true; +} + +const AutoStoryBattleDataTestCase AUTO_STORY_BATTLE_DATA_CASES[] = { + { + .input = {.name = "type chart, moves and species from pret", .body = test_data}, + .expectation = {.description = "validates decompiled type charts, moves, and species"}, + }, + { + .input = {.name = "Miguel's Grimer: Water Gun", .body = test_miguel_grimer}, + .expectation = {.description = "verifies move matchup choice against Miguel Grimer"}, + }, + { + .input = {.name = "Bite on Psychic, Ghost and Water-resistant foes", .body = test_bite_wins}, + .expectation = {.description = "verifies move matchup prioritization for Bite"}, + }, + { + .input = {.name = "a wild Pokemon not read: the plan's order", .body = test_wild_fallback}, + .expectation = {.description = "falls back to default move preference when unread"}, + }, + { + .input = {.name = "battle risks by trainer", .body = test_risks}, + .expectation = {.description = "rival and gym leaders HIGH, route trainers and grunts LOW"}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryBattleData(UnitTestDatabase& database){ + for (const auto& scenario : AUTO_STORY_BATTLE_DATA_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp new file mode 100644 index 0000000000..5b60553788 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp @@ -0,0 +1,360 @@ +/* AutoStory Battle Decisions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonFRLG_AutoStoryBattleDecisions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +constexpr size_t PARTY_SLOTS = 6; +// A wild Pokemon is fought (WILD_FIGHT) only with green HP and this many +// Potions left; otherwise it is run from. +constexpr int MIN_POTIONS_TO_FIGHT = 2; +// RUN this many times ("Can't escape!") before fighting instead. +constexpr int RUN_TRIES = 4; +// PSN read at this many turns in a row before an Antidote. +constexpr int PSN_READS = 2; +// An evolution screen held this long was an evolution, not a text box +// between two others. +constexpr Milliseconds EVOLUTION_SEEN = std::chrono::milliseconds(5000); +// Nothing pressed for at most this long in all in a battle: an evolution +// and the next member's, with room to spare. +constexpr Milliseconds EVOLUTION_HOLDS = std::chrono::milliseconds(45000); +// No battle menu, HP box or YES/NO for this long: START, to see whether +// the overworld is back. Longer than a turn's text between two HP boxes. +constexpr Milliseconds BATTLE_GONE = std::chrono::milliseconds(3000); +// START at most this often: each look takes over a second. +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); +// 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; +// The battle menu back this soon after a move was chosen, with the move +// list between: the move wasn't used. +constexpr Milliseconds REFUSED_WITHIN = std::chrono::milliseconds(7000); +// Below this much PP left in the lead's attacks, the nurse before a fight +// that needs them: about a trainer's worth of turns. +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 HP a Potion heals (pret src/data/items.h). +constexpr double POTION_HP = 20; + +// A trainer's battle: the plan's attack, else the best type matchup +// (attack_slot_against()) against the foe out as read at the battle +// menu, else against the whole party its plan lists. +std::optional trainer_attack_slot(const PartyMember& usable, const Supplies& supplies){ + if (!supplies.foe_out.empty()){ + return attack_slot_against(usable, std::vector{supplies.foe_out}); + } + return attack_slot_against(usable, supplies.foes); +} + +// A Potion this turn: whenever the bar isn't green, unless the last hit +// took a Potion's worth or more (`seen_hit`, 0 if not seen). +bool wants_potion(const PartyStatus& status, double seen_hit){ + return (status.hp_red || status.hp_yellow) && seen_hit < POTION_HP; +} + +// The lead's HP from the bar's share, if it showed and POKEMON SKILLS was +// read for its species. +std::optional lead_hp(const Supplies& supplies, const PartyStatus& status){ + if (!status.hp_seen || !supplies.lead.stats){ + return std::nullopt; + } + return status.hp_fill * supplies.lead.stats->hp; +} + +} // namespace + + +void healed_by_nurse(Supplies& supplies){ + supplies.hurt = false; + supplies.hp_red = false; + supplies.hp_fill = 1.0; + supplies.status = StatusCondition::NONE; + restore_pp(supplies.lead); +} + +bool attacks_low_on_pp(const Supplies& supplies){ + return attack_slot(supplies.lead).has_value() && attack_pp(supplies.lead) < LOW_ATTACK_PP; +} + +bool nurse_before_battle(const Supplies& supplies){ + return supplies.hurt || supplies.status != StatusCondition::NONE || attacks_low_on_pp(supplies); +} + + +BattleDecisions::BattleDecisions(Supplies& supplies, BattleKind kind) + : m_supplies(supplies) + , m_kind(kind) +{} + +TurnAction BattleDecisions::turn(const PartyStatus& status){ + m_turns++; + m_move_prompts = 0; + m_before_forget.reset(); + count_down_refused(); + m_last_move_slot.reset(); + if (!m_lost){ + return lead_turn(status); + } + // The next member is out: it runs from a wild Pokemon for as long as + // it takes, and against a trainer uses its first move. + if (m_kind != BattleKind::TRAINER){ + return TurnAction{.choice = TurnChoice::RUN}; + } + return TurnAction{.choice = TurnChoice::MOVE, .slot = TOP_LEFT_MOVE}; +} + +TurnAction BattleDecisions::lead_turn(const PartyStatus& status){ + const bool hurt = status.hp_red || status.hp_yellow; + m_supplies.hurt = hurt; + if (status.hp_seen){ + m_supplies.hp_fill = status.hp_fill; + } + m_supplies.status = status.status; + m_psn_reads = status.status == StatusCondition::POISON ? m_psn_reads + 1 : 0; + // A wild Pokemon is fought for EXP only at full strength: fighting + // every one in Viridian Forest used up all 4 Potions and then the + // starter (console B, 2026-11-01). With a status, it is run from too. + const bool weak = hurt || status.status != StatusCondition::NONE || m_supplies.potions < MIN_POTIONS_TO_FIGHT; + const bool run = m_kind == BattleKind::WILD_RUN || (m_kind == BattleKind::WILD_FIGHT && weak); + if (run && m_run_tries < RUN_TRIES){ + m_run_tries++; + return TurnAction{.choice = TurnChoice::RUN}; + } + see_hit(status); + if (!m_items_off && m_supplies.potions > 0 && wants_potion(status, m_seen_hit)){ + return TurnAction{.choice = TurnChoice::POTION}; + } + if (!m_items_off && m_psn_reads >= PSN_READS && !m_antidote_used && m_supplies.antidotes > 0){ + m_antidote_used = true; + return TurnAction{.choice = TurnChoice::ANTIDOTE}; + } + return move_turn(); +} + +void BattleDecisions::see_hit(const PartyStatus& status){ + if (m_supplies.foe_out != m_hit_by){ + m_seen_hit = 0; + m_hit_by = m_supplies.foe_out; + } + const std::optional hp = lead_hp(m_supplies, status); + if (hp && m_last_hp){ + const double taken = *m_last_hp + (m_healed ? POTION_HP : 0) - *hp; + if (taken > 0){ + m_seen_hit = taken; + } + } + m_last_hp = hp; + m_healed = false; +} + +// The plan's attack with PP left, or against known foes (a trainer's +// party, the wild Pokemon read), the best type matchup. While the story doesn't know +// all four moves, the bottom left one (Bubble from Lv7), which the cursor +// can't reach while that slot is empty, so before Bubble it stays on +// Tackle. +TurnAction BattleDecisions::move_turn(){ + PartyMember usable = m_supplies.lead; + for (const auto& refused : m_refused){ + if (refused.first < usable.moves.size()){ + usable.moves[refused.first].pp = 0; + } + } + const std::optional slot = m_kind == BattleKind::TRAINER + ? trainer_attack_slot(usable, m_supplies) + : attack_slot_against(usable, m_supplies.wild_foes); + if (!slot){ + return TurnAction{.choice = TurnChoice::MOVE, .slot = BOTTOM_LEFT_MOVE}; + } + spend_pp(m_supplies.lead, *slot); + m_last_move_slot = slot; + return TurnAction{.choice = TurnChoice::MOVE, .slot = *slot}; +} + +void BattleDecisions::count_down_refused(){ + for (auto it = m_refused.begin(); it != m_refused.end();){ + it = --it->second <= 0 ? m_refused.erase(it) : std::next(it); + } +} + +void BattleDecisions::move_refused(){ + if (!m_last_move_slot){ + return; + } + const size_t slot = *m_last_move_slot; + if (slot < m_supplies.lead.moves.size()){ + m_supplies.lead.moves[slot].pp++; + } + // One more: the next turn() counts down the one that didn't happen. + m_refused[slot] = DISABLE_TURNS + 1; + m_last_move_slot.reset(); +} + +void BattleDecisions::turn_done(TurnChoice choice, TurnResult result){ + if (result == TurnResult::REFUSED){ + move_refused(); + return; + } + const bool done = result == TurnResult::DONE; + if (!done && choice == TurnChoice::MOVE){ + if (m_last_move_slot){ + no_pp_left(m_supplies.lead, *m_last_move_slot); + } + return; + } + if (!done){ + m_items_off = true; + return; + } + switch (choice){ + case TurnChoice::POTION: + m_healed = true; + m_supplies.potions--; + m_supplies.hurt = false; + m_supplies.hp_red = false; + return; + case TurnChoice::ANTIDOTE: + m_supplies.antidotes--; + return; + case TurnChoice::RUN: + case TurnChoice::MOVE: + return; + } +} + +PromptAnswer BattleDecisions::prompt(bool lead_box_gone){ + if (lead_box_gone){ + lead_fainted(); + // NO tries to run; if that fails, the party list opens. + return PromptAnswer{.answer = m_kind == BattleKind::TRAINER ? YesNo::YES : YesNo::NO}; + } + m_move_prompts++; + if (m_before_forget){ + // A YES/NO right after the move list: it closed with no move + // forgotten, and this is "Stop learning ?" (console B, + // 2026-11-03, Miguel's battle). The lead keeps its moves. + m_supplies.lead = std::move(*m_before_forget); + m_before_forget.reset(); + return PromptAnswer{.answer = YesNo::YES}; + } + if (m_move_prompts > MOVE_PROMPTS){ + // More than the move prompts can be: YES ends either one, as + // "Delete a move?" opens the move list, which the loop's B closes. + return PromptAnswer{.answer = YesNo::YES}; + } + if (m_declined_delete){ + // "Stop learning ?" YES; NO would ask "Delete a move?" again. + m_declined_delete = false; + return PromptAnswer{.answer = YesNo::YES}; + } + PartyMember learning = m_supplies.lead; + const LearnDecision decision = learn_move(learning); + if (decision.forget_slot){ + m_before_forget = m_supplies.lead; + return PromptAnswer{.answer = YesNo::YES, .forget_slot = decision.forget_slot, .learned = std::move(learning)}; + } + m_supplies.lead = std::move(learning); + m_declined_delete = true; + return PromptAnswer{.answer = YesNo::NO}; +} + +std::optional BattleDecisions::next_member_slot(){ + lead_fainted(); + // A slot sent before and still offered was empty or fainted: the next. + for (size_t slot = 1; slot < PARTY_SLOTS; slot++){ + const bool kept = std::ranges::find(m_supplies.protected_slots, slot) != m_supplies.protected_slots.end(); + if (!kept && !m_sent.contains(slot)){ + m_sent.insert(slot); + return slot; + } + } + return std::nullopt; +} + +void BattleDecisions::lead_fainted(){ + m_lost = true; +} + +EvolutionHold::EvolutionHold(PartyMember& lead) + : m_lead(lead) +{} + +void EvolutionHold::turn_taken(TurnChoice choice){ + m_attacked = choice == TurnChoice::MOVE; +} + +bool EvolutionHold::holds(const BattleTextScreen& screen) const{ + return m_attacked && m_held < EVOLUTION_HOLDS && screen.text_box && !screen.hp_box && !screen.arrow && !screen.yes_no; +} + +void EvolutionHold::held(Milliseconds held, bool lead_fainted){ + m_held += held; + // Only the lead fights, so only it evolves; once a battle. + if (held < EVOLUTION_SEEN || m_evolved || lead_fainted){ + return; + } + m_evolved = true; + evolve(m_lead); +} + +void BattleEndWatch::seen(BattleSeen what, WallClock now){ + if (what != BattleSeen::NONE){ + m_last_battle = now; + } + if (what == BattleSeen::MENU){ + m_blind_since.reset(); + } +} + +bool BattleEndWatch::check_overworld(WallClock now){ + if (!m_last_battle || now - *m_last_battle < BATTLE_GONE){ + return false; + } + if (m_last_check && now - *m_last_check < OVERWORLD_CHECK){ + return false; + } + m_last_check = now; + return true; +} + +void MoveRefusalWatch::move_chosen(WallClock now){ + m_chosen = now; + m_list_back = false; +} + +void MoveRefusalWatch::no_battle_screen(){ + m_list_back = m_chosen.has_value(); +} + +bool MoveRefusalWatch::refused(WallClock now){ + const bool refused = m_chosen && m_list_back && now - *m_chosen < REFUSED_WITHIN; + m_chosen.reset(); + m_list_back = false; + return refused; +} + +bool BattleEndWatch::pressed_blind(WallClock now){ + if (!m_blind_since){ + m_blind_since = now; + } + return now - *m_blind_since >= BLIND_PRESSES; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h new file mode 100644 index 0000000000..2d4c0730ff --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h @@ -0,0 +1,194 @@ +/* AutoStory Battle Decisions + * + * From: https://github.com/PokemonAutomation/ + * + * What the story's battle loop chooses at each screen, apart from reading + * the screens and pressing the buttons, so the choices run in tests: + * each turn's action, the YES/NO prompts (a move to learn, "Use next + * POKEMON?"), when not to press B for an evolution, and the lead's PP. + * + * The party is the lead (the starter) and members that don't fight: the + * lead is never switched out. If it faints, a wild battle is run from + * ("Use next POKEMON?" NO); a trainer's, or a failed run, sends the next + * member not in Supplies::protected_slots, which only runs or uses its + * first move; with only protected ones left, the program stops instead. + * The battle counts as lost either way. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryBattleDecisions_H +#define PokemonAutomation_PokemonFRLG_AutoStoryBattleDecisions_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryParty.h" +#include "PokemonFRLG_AutoStoryBattleTurns.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// State machine deciding turn choices and prompt answers in battles. +class BattleDecisions{ +public: + BattleDecisions(Supplies& supplies, BattleKind kind); + + // At the battle menu, with the player's box as read. + TurnAction turn(const PartyStatus& status); + // What came of what turn() chose. + void turn_done(TurnChoice choice, TurnResult result); + + // 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). + PromptAnswer prompt(bool lead_box_gone); + + // The party list opened with the lead fainted: the slot to send in, + // or none if every member left is protected. + std::optional next_member_slot(); + + // The lead's box gone for good: it fainted. + void lead_fainted(); + bool lost() const{ return m_lost; } + + size_t turns() const{ return m_turns; } + +private: + TurnAction lead_turn(const PartyStatus& status); + TurnAction move_turn(); + // The HP the lead lost since the last turn, from the bar. + void see_hit(const PartyStatus& status); + void count_down_refused(); + void move_refused(); + + Supplies& m_supplies; + const BattleKind m_kind; + size_t m_turns = 0; + int m_run_tries = 0; + int m_psn_reads = 0; + bool m_antidote_used = false; + // An item read as another in the bag: none is used again this battle. + bool m_items_off = false; + bool m_lost = false; + // NO was answered to "Delete a move?": "Stop learning?" comes next. + bool m_declined_delete = false; + // The move prompts since the last turn. + int m_move_prompts = 0; + // YES was answered to "Delete a move?": the lead as it was before. + // A YES/NO before the next turn means nothing was forgotten. + std::optional m_before_forget; + std::optional m_last_move_slot; + // The lead's HP at the last turn, from the bar, and whether a Potion + // was used on it since. + std::optional m_last_hp; + bool m_healed = false; + // The HP the last hit seen took, from the foe out `m_hit_by`; 0 if none + // was seen. + double m_seen_hit = 0; + std::string m_hit_by; + // The slots the game turned down, and the turns until they are tried again. + std::map m_refused; + // The members sent in after the lead fainted. + std::set m_sent; +}; + + +// No B while an evolution may be on screen: any B cancels it (pret +// evolution_scene.c; console B, 2026-11-02: Squirtle stayed Lv16 after the +// battle loop's B presses). +class EvolutionHold{ +public: + explicit EvolutionHold(PartyMember& lead); + + // The loop took a turn: only one that attacked can end the battle in a + // win, and so in an evolution. + void turn_taken(TurnChoice choice); + // Whether `screen` may be an evolution: after a turn that attacked (not + // after RUN: console B, 2026-11-03, a minute without B after "Got away + // safely!"), the text box with no HP box and no arrow or YES/NO, as + // "What? is evolving!" shows through the animation. Nothing + // is pressed while it shows, for at most EVOLUTION_HOLDS in all in a + // battle, in case it is something else. + bool holds(const BattleTextScreen& screen) const; + // Such a screen showed for `held` with nothing pressed: long enough, + // and the lead evolved (unless it had fainted). + void held(Milliseconds held, bool lead_fainted); + +private: + PartyMember& m_lead; + bool m_attacked = false; + bool m_evolved = false; + Milliseconds m_held = Milliseconds::zero(); +}; + + +// What the battle loop saw of the battle at a poll. +enum class BattleSeen{ + NONE, + BATTLE, // as battle_shows() reads it + MENU, // the battle menu +}; + +// When the battle loop presses START to see whether the overworld is +// back, and when it gives up pressing A and B for a screen nothing reads. +// The battle counts as on screen by its menu, an HP box or a YES/NO only: +// its text box alone also reads on the black below a dark cave's corridor +// (console B, 2026-11-03, Mt. Moon B2F: after "Got away safely!" the loop +// took the cave for the battle and pressed A and B for 9 minutes). +class BattleEndWatch{ +public: + // What the loop read at `now`. + void seen(BattleSeen what, WallClock now); + // Whether to press START at `now`: a battle was seen, and none since + // for BATTLE_GONE. At most every OVERWORLD_CHECK. + bool check_overworld(WallClock now); + // A or B was pressed blind at `now`. True once that has gone on for + // BLIND_PRESSES with no battle menu: the loop stops, and the walker, + // which finds the player again, goes on. + bool pressed_blind(WallClock now); + +private: + std::optional m_last_battle; + std::optional m_last_check; + std::optional m_blind_since; +}; + + +// Whether the game turned down the move chosen, at the battle menu after +// it: the move list came back (no battle screen reads on it) and the menu +// followed sooner than any turn (console B, 2026-11-03: 5.7 s from the +// choice for a disabled move, 8.3 s and up for a turn). +class MoveRefusalWatch{ +public: + void move_chosen(WallClock now); + // 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. + bool refused(WallClock now); + +private: + std::optional m_chosen; + bool m_list_back = false; +}; + + +// Registers AutoStory party management unit tests. +void add_tests_AutoStoryParty(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleRisk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleRisk.h new file mode 100644 index 0000000000..a71b3e6c12 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleRisk.h @@ -0,0 +1,43 @@ +/* AutoStory Battle Risk + * + * From: https://github.com/PokemonAutomation/ + * + * How carefully a story battle is fought, by the trainer its plan names. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryBattleRisk_H +#define PokemonAutomation_PokemonFRLG_AutoStoryBattleRisk_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// How carefully a battle step is fought. +enum class BattleRisk{ + // The plan's attacks, else the best type matchup against the foe out. + LOW, + // The battles the simulation's plan is for (the rival, gym leaders, + // bosses); fought as LOW until the checkpoint carries a plan. + HIGH, +}; + +// String representation of battle risk level. +std::string_view battle_risk_name(BattleRisk risk); + +// A trainer's risk by its kind, from pret's constant the battle step's +// plan names ("TRAINER_LEADER_BROCK"): HIGH for the rival, gym leaders, +// bosses (Giovanni, the Rocket admins), the Elite Four and the Champion; +// LOW for the rest and for a battle that names no trainer. +BattleRisk default_battle_risk(std::string_view trainer); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleTurns.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleTurns.h new file mode 100644 index 0000000000..4de3040e02 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleTurns.h @@ -0,0 +1,92 @@ +/* AutoStory Battle Turns + * + * From: https://github.com/PokemonAutomation/ + * + * What the battle loop decides each turn and at each prompt: the turn's + * choice and what came of it, and the answer to a YES/NO. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryBattleTurns_H +#define PokemonAutomation_PokemonFRLG_AutoStoryBattleTurns_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryParty.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// High-level action chosen for a battle turn. +enum class TurnChoice{ + RUN, + POTION, + ANTIDOTE, + MOVE, +}; + +// Decided battle action including slot or item index. +struct TurnAction{ + TurnChoice choice = TurnChoice::MOVE; + // For MOVE, the move list's slot. + size_t slot = BOTTOM_LEFT_MOVE; +}; + +// What came of a TurnAction. +enum class TurnResult{ + DONE, + // An item not used (another item in its row), or a move the game said + // has no PP left. + NOT_DONE, + // The game turned the move down although it has PP left: a foe's + // Disable (console B, 2026-11-03, Mt. Moon: Miguel's Grimer disabled + // Water Gun, and the loop chose it 17 more times while no turn passed). + // Its PP comes back, and it isn't chosen for as long as Disable can + // last (pret: 2 to 5 turns). + REFUSED, +}; + +// Binary prompt decision. +enum class YesNo{ + YES, + NO, +}; + +// A battle screen as the loop reads it, for the evolution check. +struct BattleTextScreen{ + // The battle's text box. + bool text_box = false; + // The battle menu or an HP box. + bool hp_box = false; + // The text waits for a button. + bool arrow = false; + // A YES/NO box. + bool yes_no = false; +}; + +// Answer to an in-battle prompt dialogue. +struct PromptAnswer{ + YesNo answer = YesNo::NO; + // After YES to "Delete a move?": the slot to forget on the move list + // that opens, its cursor on the top move. + std::optional forget_slot = {}; + // With forget_slot: the lead once the move is learned, to keep only if + // the move list opened (console B, 2026-11-03: a YES/NO read where no + // move list followed was taken as Bite over Tail Whip, and the loop + // later chose Tail Whip for Bite). + std::optional learned = {}; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h new file mode 100644 index 0000000000..735cc17aa6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h @@ -0,0 +1,71 @@ +/* AutoStory Intro + * + * From: https://github.com/PokemonAutomation/ + * + * The new game's intro: what it asks about the names, and the intro + * played from the title screen to the bedroom. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryIntro_H +#define PokemonAutomation_PokemonFRLG_AutoStoryIntro_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonFRLG_AutoStoryPresses.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The arrow's row on Oak's list of rival names (NEW NAME, then four preset +// names), if the list shows. In pokefirered's oak_speech.c the list is a +// 12x10-tile window at tile (2, 2), rows 16 px apart, the cursor starting +// on NEW NAME. The intro's YES/NO boxes open in the same corner but are +// 6x4 tiles: the list is told from them by its white past their frame. +std::optional rival_name_list_cursor(const ImageViewRGB32& screen); + +// What shows in the new game's intro, as far as the names go. +enum class IntroNameScreen{ + OTHER, + KEYBOARD, + RIVAL_LIST, +}; +// What the new game's intro does about the names. The player's name is +// asked on a keyboard, always first; the rival's on the name list, where +// the first preset name is picked, as SID Helper does. A keyboard after +// the player's is the rival's, opened because the list was missed. +enum class IntroNameStep{ + NONE, + PLAYER_KEYBOARD, + RIVAL_PRESET, + RIVAL_KEYBOARD, +}; +// A preset picked returns to the list only after NO on "Er, was it ...?", +// so after this many picks A opens the keyboard instead. +constexpr size_t RIVAL_PRESET_TRIES = 3; +// Determines the next input step in character/rival naming sequence. +IntroNameStep intro_name_step(IntroNameScreen screen, size_t keyboards_seen, size_t presets_picked); +// From the title screen of a game with no save, to the bedroom: the +// controls pages, Oak's speech, BOY, the default name for the player (an +// empty name confirmed) and the rival's first preset name. Returns on the +// overworld. +void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.h new file mode 100644 index 0000000000..d61e0daf35 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.h @@ -0,0 +1,68 @@ +/* AutoStory Items Pocket + * + * From: https://github.com/PokemonAutomation/ + * + * The Items pocket as the story counts it: rows and counts, read from + * the bag, and the items used after a battle. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryItemsPocket_H +#define PokemonAutomation_PokemonFRLG_AutoStoryItemsPocket_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattleData.h" +#include "PokemonFRLG_AutoStoryParty.h" +#include "PokemonFRLG_AutoStorySupplies.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// How many of `item` (a slug) the bag holds, as far as known. +int item_count(const Supplies& supplies, const std::string& item); + +// The row (from 0) of `item` in the Items pocket, or -1 if none is left. +// Items the story doesn't count, such as a MOON STONE, take rows too. +int item_row(const Supplies& supplies, const std::string& item); + +// Sets the counts and the pocket's order from the Items pocket as read. +// A row whose count couldn't be read still holds at least one: it keeps +// the count known before (the order bought), or 1. Returns those rows' +// items, for the log. +std::vector set_from_bag(Supplies& supplies, const std::vector& rows); + +// After a save is loaded: the Items pocket as read, taken into `supplies` +// and `saved` (what a reload restores) in place of the row's counts, as +// set_from_bag() does. With nothing read both keep the row's. Returns the +// items whose count couldn't be read. +std::vector set_from_loaded_bag(Supplies& supplies, Supplies& saved, const std::vector& rows); + +// From the overworld: opens the Items pocket, reads it, and closes the +// bag again. Empty if nothing could be read. +std::vector read_items_pocket(ConsoleHandle& console, ProControllerContext& context, Language language); +// From the overworld, after a battle: an Antidote for PSN, a Parlyz Heal +// for PAR, then a Potion if the HP bar wasn't green, each if one is left. +// The bag's inputs are not checked on the console yet. +void recover_after_battle( + ConsoleHandle& console, ProControllerContext& context, + Supplies& supplies, Pokemon::StoryCheckLevel checks, Language language +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp new file mode 100644 index 0000000000..36c50ea066 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp @@ -0,0 +1,341 @@ +/* AutoStory Items Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The Mart cursor's moves, and the bag's rows as the story counts them. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Language.h" +#include "Tests/ImageUnitTest.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryBattleDecisions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct AutoStoryItemsInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct AutoStoryItemsExpectation{ + std::string_view description; +}; + +struct AutoStoryItemsTestCase{ + AutoStoryItemsInput input; + AutoStoryItemsExpectation expectation; +}; + +class Test_AutoStoryItems : public UnitTest{ +public: + explicit Test_AutoStoryItems(AutoStoryItemsTestCase scenario) + : UnitTest("PokemonFRLG::AutoStoryItems - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_scenario.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryItemsTestCase m_scenario; +}; + + +// The orders the story gives the Viridian Mart: rows 1, 2, 3 in turn. The +// cursor stays on the row bought, so each is one row down from the last. +UnitTestResult test_mart_cursor(Logger&){ + if (mart_cursor_moves(0, 1) != 1 || mart_cursor_moves(1, 2) != 1 || mart_cursor_moves(2, 3) != 1){ + return "Expected one press down between the story's orders."; + } + if (mart_cursor_moves(3, 1) != -2 || mart_cursor_moves(2, 2) != 0){ + return "Expected presses up to a row above, none to the same row."; + } + int cursor = 0; + std::vector bought; + for (int row : {1, 2, 3}){ + cursor += mart_cursor_moves(cursor, row); + bought.push_back(cursor); + } + if (bought != std::vector{1, 2, 3}){ + return "The cursor didn't land on rows 1, 2, 3."; + } + return true; +} + +// Rows skip items with none left; the order read from the bag replaces +// the order bought. +UnitTestResult test_pocket_rows(Logger&){ + Supplies supplies; + supplies.potions = 5; + supplies.antidotes = 3; + supplies.parlyz_heals = 1; + if (item_row(supplies, "potion") != 0 || item_row(supplies, "antidote") != 1 || item_row(supplies, "parlyz-heal") != 2){ + return "Wrong rows for the order bought."; + } + supplies.potions = 0; + if (item_row(supplies, "potion") != -1 || item_row(supplies, "antidote") != 0){ + return "An item with none left still takes a row."; + } + set_from_bag(supplies, {{"potion", 4}, {"parlyz-heal", 3}}); + if (supplies.potions != 4 || supplies.antidotes != 0 || supplies.parlyz_heals != 3){ + return "Counts not taken from the bag."; + } + if (item_row(supplies, "parlyz-heal") != 1 || item_row(supplies, "antidote") != -1){ + return "Rows not taken from the bag."; + } + return true; +} + +// #211: a row loaded from a save counted no Potions, so its wild battles +// were all run from. The counts come from the bag as read, both for the +// run and for a reload; with nothing read, the row's are kept. +UnitTestResult test_loaded_bag(Logger&){ + Supplies row; + Supplies saved = row; + const std::vector unread = set_from_loaded_bag(row, saved, {{"potion", 4}, {"antidote", 2}}); + if (row.potions != 4 || saved.potions != 4 || row.antidotes != 2 || saved.antidotes != 2 || !unread.empty()){ + return std::format( + "Expected 4 Potions and 2 Antidotes from the bag, now and for a reload; got {} and {}, {} and {}.", + row.potions, saved.potions, row.antidotes, saved.antidotes + ); + } + if (item_row(saved, "antidote") != 1){ + return "Expected the reload's pocket order from the bag."; + } + + Supplies known; + known.potions = 2; + Supplies known_saved = known; + set_from_loaded_bag(known, known_saved, {}); + if (known.potions != 2 || known_saved.potions != 2){ + return "Expected the row's 2 Potions kept with nothing read."; + } + return true; +} + +// A count the bag reader couldn't read (-1) is never taken for none: the +// row still holds some, so it keeps the count bought, or 1 with none +// known, and the battle's checks (a count above 0, a row) still use it. +UnitTestResult test_unread_counts(Logger&){ + Supplies bought; + bought.potions = 5; + bought.antidotes = 3; + bought.parlyz_heals = 1; + const std::vector rows{{"potion", -1}, {"antidote", -1}, {"parlyz-heal", 1}}; + const std::vector unread = set_from_bag(bought, rows); + if (unread != std::vector{"potion", "antidote"}){ + return "Expected the Potion and Antidote counts reported unread."; + } + if (bought.potions != 5 || bought.antidotes != 3 || bought.parlyz_heals != 1){ + return std::format( + "Expected 5 Potions, 3 Antidotes, 1 Parlyz Heal kept from the order, got {}, {}, {}.", + bought.potions, bought.antidotes, bought.parlyz_heals + ); + } + + Supplies unknown; + unknown.potions = 0; + unknown.antidotes = 0; + unknown.parlyz_heals = 0; + set_from_bag(unknown, rows); + if (item_count(unknown, "potion") <= 0 || item_count(unknown, "antidote") <= 0){ + return std::format( + "Expected unread counts with none known to count as some, got {} Potions, {} Antidotes.", + unknown.potions, unknown.antidotes + ); + } + if (item_row(unknown, "potion") != 0 || item_row(unknown, "antidote") != 1 || item_row(unknown, "parlyz-heal") != 2){ + return std::format( + "Expected rows 0, 1, 2 with unread counts, got {}, {}, {}.", + item_row(unknown, "potion"), item_row(unknown, "antidote"), item_row(unknown, "parlyz-heal") + ); + } + return true; +} + +// Console B, 2026-11-03: a save from Mt. Moon has a MOON STONE above the +// PARLYZ HEAL and 15 POTIONs. An item the story doesn't count still takes +// its row, so the battle knows all 15 Potions and finds them in row 2. +UnitTestResult test_loaded_bag_other_items(Logger&){ + Supplies row; + row.potions = 0; + row.parlyz_heals = 0; + Supplies saved = row; + set_from_loaded_bag(row, saved, {{"", 1}, {"parlyz-heal", 1}, {"potion", 15}}); + if (row.potions != 15 || saved.potions != 15 || row.parlyz_heals != 1){ + return std::format( + "Expected 15 Potions and 1 Parlyz Heal from the bag, now and for a reload; got {}, {} and {}.", + row.potions, saved.potions, row.parlyz_heals + ); + } + if (item_row(row, "parlyz-heal") != 1 || item_row(row, "potion") != 2 || item_row(saved, "potion") != 2){ + return std::format( + "Expected the Parlyz Heal in row 1 and the Potions in row 2 below the Moon Stone, got {} and {}.", + item_row(row, "parlyz-heal"), item_row(row, "potion") + ); + } + return true; +} + +// The pocket's rows as read: an unread name keeps its row, so the rows +// below it are still read; the rows end at CANCEL, or at the last name read. +UnitTestResult test_pocket_rows_unread(Logger&){ + const std::vector rows = pocket_rows({{"", 1}, {"parlyz-heal", 1}, {"potion", 15}, {"cancel", -1}, {"", -1}}); + if (rows.size() != 3 || !rows[0].item.empty() || rows[2].item != "potion" || rows[2].count != 15){ + return std::format("Expected 3 rows, the Potions' last with 15, got {}.", rows.size()); + } + if (pocket_rows({{"potion", 3}, {"", -1}, {"", -1}}).size() != 1){ + return "Expected the unread rows after the last name dropped."; + } + if (!pocket_rows({{"", 1}, {"", 2}}).empty()){ + return "Expected nothing with no name read."; + } + return true; +} + +// In a language the reader has no names for, nothing is read, so the +// checks fall back to positions instead of failing. +UnitTestResult test_unread_language(Logger& logger){ + const ImageRGB32 screen(1920, 1080); + if (!read_item_list_name(logger, Language::Japanese, screen, 0).empty()){ + return "Read an item name in Japanese."; + } + if (!read_bag_pocket(logger, Language::Japanese, screen).empty()){ + return "Read bag rows in Japanese."; + } + if (!read_save_card_location(logger, Language::Japanese, screen).empty()){ + return "Read a save card's place in Japanese."; + } + return true; +} + + +// battle_shows(), the battle loop's look at whether the battle is still on +// screen, on console B's captures. +class Test_BattleShows : public ImageUnitTest{ +public: + Test_BattleShows(const std::string& image, bool expected) + : ImageUnitTest("PokemonFRLG::AutoStoryBattle - " + image, {image}) + , m_expected(expected) + {} + + virtual UnitTestResult run_on_images( + Logger& logger, CancellableScope& scope, + const std::vector& images + ) const override{ + return battle_shows(images[0]) == m_expected; + } + +private: + bool m_expected; +}; + +// read_party_status() on console B's captures: the bar's color, and its +// colored share within a pixel of the 48-pixel bar of `hp` / `max_hp`. +// Console B, 2026-11-03, before Miguel: 17/55 HP read as 15% of the bar, +// then 2% with the box a pixel lower. +class Test_PartyHp : public ImageUnitTest{ +public: + Test_PartyHp(const std::string& image, std::string_view color, int hp, int max_hp) + : ImageUnitTest("PokemonFRLG::AutoStoryBattle - " + image, {image}) + , m_color(color) + , m_share(double(hp) / max_hp) + {} + + virtual UnitTestResult run_on_images( + Logger& logger, CancellableScope& scope, + const std::vector& images + ) const override{ + const PartyStatus status = read_party_status(images[0]); + const std::string_view color = !status.hp_seen ? "none" : status.hp_red ? "red" : status.hp_yellow ? "yellow" : "green"; + if (color != m_color){ + return std::format("Expected an HP bar read as {}, got {}.", m_color, color); + } + if (std::abs(status.hp_fill - m_share) > 1.0 / 48){ + return std::format("Expected {:.0f}% of the bar, got {:.0f}%.", 100 * m_share, 100 * status.hp_fill); + } + return true; + } + +private: + std::string_view m_color; + double m_share; +}; + + +const AutoStoryItemsTestCase AUTO_STORY_ITEMS_CASES[] = { + { + .input = {.name = "Mart cursor stays on the row bought", .body = test_mart_cursor}, + .expectation = {.description = "verifies mart cursor remains on purchased item index"}, + }, + { + .input = {.name = "Items pocket rows", .body = test_pocket_rows}, + .expectation = {.description = "parses item pocket rows from visual representation"}, + }, + { + .input = {.name = "a loaded save's counts come from the bag", .body = test_loaded_bag}, + .expectation = {.description = "initializes bag counts when loading saved state"}, + }, + { + .input = {.name = "an item the story doesn't count keeps its row", .body = test_loaded_bag_other_items}, + .expectation = {.description = "preserves row indexing for uncounted items"}, + }, + { + .input = {.name = "an unread item name keeps its row", .body = test_pocket_rows_unread}, + .expectation = {.description = "preserves placeholder row when item name is unread"}, + }, + { + .input = {.name = "unread bag counts count as some", .body = test_unread_counts}, + .expectation = {.description = "treats unread quantities as holding at least one"}, + }, + { + .input = {.name = "no item names read in a language without them", .body = test_unread_language}, + .expectation = {.description = "handles unsupported languages gracefully"}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryItems(UnitTestDatabase& database){ + for (const auto& scenario : AUTO_STORY_ITEMS_CASES){ + database.add(scenario); + } + // "Wild CHANSEY appeared!" with its HP box, and Mt. Moon B2F's corridor + // after "Got away safely!", whose black lower half reads as the battle's + // text box (console B, 2026-11-03: 9 minutes of A and B there). + database.add("PokemonFRLG/WildEncounterReader/eng_chansey.jpg", true); + database.add("PokemonFRLG/AutoStoryBattle/MtMoonB2F_AfterRun_False.png", false); + database.add("PokemonFRLG/AutoStoryBattle/MtMoon1F_HpGreen_Full.png", "green", 45, 45); + database.add("PokemonFRLG/AutoStoryBattle/MtMoon1F_HpGreen_27of45.png", "green", 27, 45); + database.add("PokemonFRLG/AutoStoryBattle/MtMoonB2F_HpYellow_17of55.png", "yellow", 17, 55); + database.add("PokemonFRLG/AutoStoryBattle/MtMoonB2F_HpYellow_17of55_BarLow.png", "yellow", 17, 55); + // The battle's choices, registered here to keep add_tests() within its size. + add_tests_AutoStoryParty(database); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLevelUps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLevelUps.h new file mode 100644 index 0000000000..e157d1f414 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLevelUps.h @@ -0,0 +1,56 @@ +/* AutoStory Level Ups + * + * From: https://github.com/PokemonAutomation/ + * + * What a level up brings: an evolution by level, and the answer to + * "Delete a move to make room for ...?". + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryLevelUps_H +#define PokemonAutomation_PokemonFRLG_AutoStoryLevelUps_H + +#include +#include +#include +#include +#include +#include +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.h" +#include "PokemonFRLG_AutoStoryStats.h" +#include "PokemonFRLG_AutoStoryPartyMember.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The species `species` evolves into by level, and at which level. +struct LevelEvolution{ + std::string_view into; + uint8_t level = 0; +}; +// Level-up evolution target if species evolves by level. +std::optional level_evolution(std::string_view species); +// The answer to "Delete a move to make room for ?". +struct LearnDecision{ + // The move offered, if the table knows which one it is. + std::optional move = {}; + // The slot to forget for it, or none to keep the moves as they are. + std::optional forget_slot = {}; +}; + +// At "Delete a move to make room for ...?": takes in the moves learned +// into free slots since the last prompt, decides on the move offered, and +// leaves `member` as that answer will. +LearnDecision learn_move(PartyMember& member); + +// The lead evolved: its species becomes what it evolves into. +void evolve(PartyMember& member); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMoveData.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMoveData.h new file mode 100644 index 0000000000..e9723e3d4c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMoveData.h @@ -0,0 +1,60 @@ +/* AutoStory Move Data + * + * From: https://github.com/PokemonAutomation/ + * + * What the story needs of moves, species and the type chart to choose an + * attack when the plan has none: each move's type, whether it does damage + * and its PP; each species' types (BattleData/moves.json, species.json, + * type_chart.json, from pret/pokefirered). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryMoveData_H +#define PokemonAutomation_PokemonFRLG_AutoStoryMoveData_H + +#include +#include +#include +#include "Pokemon/Pokemon_Types.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// The type enum, from the shared Pokemon code. +using Pokemon::PokemonType; + +// A move, as far as choosing an attack and tracking PP needs it. +struct MoveData{ + // NONE for Curse's "???". + PokemonType type = PokemonType::NONE; + // It does damage: any power, including moves whose damage doesn't + // come from their power (Flail, Dragon Rage). + bool damaging = false; + // Full PP. + uint8_t pp = 0; +}; + +// A species' types; the same type twice for a species with one. +struct SpeciesData{ + PokemonType first = PokemonType::NONE; + PokemonType second = PokemonType::NONE; +}; + +// None for a move the data doesn't have. +const MoveData* move_data(std::string_view move); + +// None for a species the data doesn't have. +const SpeciesData* species_data(std::string_view species); + +// How well `attack` hits `defend`, in tenths: 20 is 2x, 5 is 0.5x. +size_t type_effectiveness(PokemonType attack, PokemonType defend); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryNewMembers.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryNewMembers.h new file mode 100644 index 0000000000..0afbbafe9a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryNewMembers.h @@ -0,0 +1,55 @@ +/* AutoStory New Members + * + * From: https://github.com/PokemonAutomation/ + * + * A party member as the game gives it, as the story grows it, or as its + * summary shows it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryNewMembers_H +#define PokemonAutomation_PokemonFRLG_AutoStoryNewMembers_H + +#include +#include +#include +#include +#include +#include +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.h" +#include "PokemonFRLG_AutoStoryStats.h" +#include "PokemonFRLG_AutoStoryLevelUps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// As the game gives `species` at `level` (a starter, a gift): its last four +// level-up moves up to `level`, at full PP. +PartyMember new_member(std::string_view species, uint8_t level); + +// The member as the story plays it up to `level`: each level-up move is +// learned into a free slot or answered as learn_move() says, and it +// evolves at its level. For the rows that start after a part of the story. +PartyMember grown_to(PartyMember member, uint8_t level); + +// Squirtle as the story leaves it after Brock (Lv13, Water Gun offered). +PartyMember story_lead_after_brock(); + +// `species` at `level` with `moves` as its summary shows them, in slot +// order, and its `stats` if POKEMON SKILLS was read. A PP that wasn't +// read is taken as half the move's full PP: the game draws the PP in +// color from half down (pokefirered pokemon_summary_screen.c), which the +// reader may not read. +PartyMember member_from_summary( + std::string_view species, uint8_t level, const std::vector& moves, + const std::optional& stats = std::nullopt +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp new file mode 100644 index 0000000000..204411b5f8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp @@ -0,0 +1,422 @@ +/* AutoStory Party + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonFRLG_AutoStoryMoveData.h" +#include "PokemonFRLG_AutoStoryParty.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct LevelUpMove{ + std::string_view species; + uint8_t level = 0; + std::string_view move; +}; + +// pret/pokefirered src/data/pokemon/level_up_learnsets.h, the lines the +// story's party comes from. +constexpr LevelUpMove LEVEL_UP_MOVES[] = { + {.species = "squirtle", .level = 1, .move = "tackle"}, + {.species = "squirtle", .level = 4, .move = "tail-whip"}, + {.species = "squirtle", .level = 7, .move = "bubble"}, + {.species = "squirtle", .level = 10, .move = "withdraw"}, + {.species = "squirtle", .level = 13, .move = "water-gun"}, + {.species = "squirtle", .level = 18, .move = "bite"}, + {.species = "squirtle", .level = 23, .move = "rapid-spin"}, + {.species = "squirtle", .level = 28, .move = "protect"}, + {.species = "squirtle", .level = 33, .move = "rain-dance"}, + {.species = "squirtle", .level = 40, .move = "skull-bash"}, + {.species = "squirtle", .level = 47, .move = "hydro-pump"}, + {.species = "wartortle", .level = 1, .move = "tackle"}, + {.species = "wartortle", .level = 1, .move = "tail-whip"}, + {.species = "wartortle", .level = 1, .move = "bubble"}, + {.species = "wartortle", .level = 4, .move = "tail-whip"}, + {.species = "wartortle", .level = 7, .move = "bubble"}, + {.species = "wartortle", .level = 10, .move = "withdraw"}, + {.species = "wartortle", .level = 13, .move = "water-gun"}, + {.species = "wartortle", .level = 19, .move = "bite"}, + {.species = "wartortle", .level = 25, .move = "rapid-spin"}, + {.species = "wartortle", .level = 31, .move = "protect"}, + {.species = "wartortle", .level = 37, .move = "rain-dance"}, + {.species = "wartortle", .level = 45, .move = "skull-bash"}, + {.species = "wartortle", .level = 53, .move = "hydro-pump"}, + {.species = "blastoise", .level = 1, .move = "tackle"}, + {.species = "blastoise", .level = 1, .move = "tail-whip"}, + {.species = "blastoise", .level = 1, .move = "bubble"}, + {.species = "blastoise", .level = 1, .move = "withdraw"}, + {.species = "blastoise", .level = 4, .move = "tail-whip"}, + {.species = "blastoise", .level = 7, .move = "bubble"}, + {.species = "blastoise", .level = 10, .move = "withdraw"}, + {.species = "blastoise", .level = 13, .move = "water-gun"}, + {.species = "blastoise", .level = 19, .move = "bite"}, + {.species = "blastoise", .level = 25, .move = "rapid-spin"}, + {.species = "blastoise", .level = 31, .move = "protect"}, + {.species = "blastoise", .level = 42, .move = "rain-dance"}, + {.species = "blastoise", .level = 55, .move = "skull-bash"}, + {.species = "blastoise", .level = 68, .move = "hydro-pump"}, + {.species = "magikarp", .level = 1, .move = "splash"}, + {.species = "magikarp", .level = 15, .move = "tackle"}, + {.species = "magikarp", .level = 30, .move = "flail"}, + {.species = "gyarados", .level = 1, .move = "thrash"}, + {.species = "gyarados", .level = 20, .move = "bite"}, + {.species = "gyarados", .level = 25, .move = "dragon-rage"}, + {.species = "gyarados", .level = 30, .move = "leer"}, + {.species = "gyarados", .level = 35, .move = "twister"}, + {.species = "gyarados", .level = 40, .move = "hydro-pump"}, + {.species = "gyarados", .level = 45, .move = "rain-dance"}, + {.species = "gyarados", .level = 50, .move = "dragon-dance"}, + {.species = "gyarados", .level = 55, .move = "hyper-beam"}, +}; + +struct Evolution{ + std::string_view species; + LevelEvolution evolution; +}; + +// pret/pokefirered src/data/pokemon/evolution.h. +constexpr Evolution EVOLUTIONS[] = { + {.species = "squirtle", .evolution = {.into = "wartortle", .level = 16}}, + {.species = "wartortle", .evolution = {.into = "blastoise", .level = 36}}, + {.species = "magikarp", .evolution = {.into = "gyarados", .level = 20}}, +}; + +// The story's plan per line (named by its first species): a level-up move +// it learns over a full move list, and the move whose slot it takes. Any +// other move offered over four is declined. Squirtle's is the speedrun's: +// Water Gun where Bubble was (so the attack stays bottom left), Bite over +// Tail Whip. TM moves are not level-up prompts and are not here. +struct LearnRule{ + std::string_view line; + std::string_view move; + std::string_view replaces; +}; +constexpr LearnRule LEARN_RULES[] = { + {.line = "squirtle", .move = "water-gun", .replaces = "bubble"}, + {.line = "squirtle", .move = "bite", .replaces = "tail-whip"}, + // A save whose Water Gun took another slot may have no Tail Whip. + {.line = "squirtle", .move = "bite", .replaces = "withdraw"}, + {.line = "magikarp", .move = "twister", .replaces = "splash"}, +}; + +// The attacks per line, the one used first at the top. Past these, the +// strongest damaging move with PP left. +struct Attack{ + std::string_view line; + std::string_view move; +}; +constexpr Attack ATTACKS[] = { + {.line = "squirtle", .move = "water-gun"}, + {.line = "squirtle", .move = "bite"}, + {.line = "squirtle", .move = "bubble"}, + {.line = "squirtle", .move = "tackle"}, + {.line = "magikarp", .move = "bite"}, + {.line = "magikarp", .move = "twister"}, + {.line = "magikarp", .move = "tackle"}, +}; + + +// The first species of `species`'s line. +std::string_view line_of(std::string_view species){ + for (const Evolution& evolution : EVOLUTIONS){ + if (evolution.evolution.into == species){ + return line_of(evolution.species); + } + } + return species; +} + +bool knows(const PartyMember& member, std::string_view move){ + return std::ranges::any_of(member.moves, [move](const KnownMove& known){ + return known.move == move; + }); +} + +std::optional slot_of(const PartyMember& member, std::string_view move){ + for (size_t slot = 0; slot < member.moves.size(); slot++){ + if (member.moves[slot].move == move){ + return slot; + } + } + return std::nullopt; +} + +// The next level-up move past `moves_through_level` that it doesn't know. +const LevelUpMove* next_move(const PartyMember& member){ + for (const LevelUpMove& entry : LEVEL_UP_MOVES){ + if (entry.species == member.species && entry.level > member.moves_through_level && !knows(member, entry.move)){ + return &entry; + } + } + return nullptr; +} + +KnownMove at_full_pp(std::string_view move){ + return KnownMove{.move = std::string(move), .pp = max_pp(move)}; +} + +// The slot the plan gives `move`, over a full move list: the first of +// its rules' moves the member knows. +std::optional forget_slot_for(const PartyMember& member, std::string_view move){ + const std::string_view line = line_of(member.species); + for (const LearnRule& rule : LEARN_RULES){ + if (rule.line != line || rule.move != move){ + continue; + } + if (const std::optional slot = slot_of(member, rule.replaces)){ + return slot; + } + } + return std::nullopt; +} + +// Learns, or answers the prompt for, each of its moves at exactly `level`. +void take_level(PartyMember& member, uint8_t level){ + for (const LevelUpMove& entry : LEVEL_UP_MOVES){ + if (entry.species != member.species || entry.level != level || knows(member, entry.move)){ + continue; + } + if (member.moves.size() < MAX_MOVES){ + member.moves.emplace_back(at_full_pp(entry.move)); + }else if (std::optional slot = forget_slot_for(member, entry.move)){ + member.moves[*slot] = at_full_pp(entry.move); + } + } + member.moves_through_level = level; +} + +// How well `move` hits `defender`, in tenths: 40 is 4x, 5 is 0.5x. +size_t effectiveness(const MoveData& move, const SpeciesData& defender){ + size_t tenths = type_effectiveness(move.type, defender.first); + if (defender.second != defender.first){ + tenths = tenths * type_effectiveness(move.type, defender.second) / 10; + } + return tenths; +} + +// `move`'s type multiplier, in tenths, summed over `foes`; 0 for a move +// that does no damage. Each foe must be in species_data(). +size_t matchup(std::string_view move, const std::vector& foes){ + const MoveData* data = move_data(move); + if (data == nullptr || !data->damaging){ + return 0; + } + size_t total = 0; + for (const std::string& foe : foes){ + total += effectiveness(*data, *species_data(foe)); + } + return total; +} + +// The member's slots in the plan's order: its line's attacks first, as +// ATTACKS lists them, then the rest in slot order. +std::vector attack_order(const PartyMember& member){ + std::vector order; + const std::string_view line = line_of(member.species); + for (const Attack& attack : ATTACKS){ + const std::optional slot = attack.line == line ? slot_of(member, attack.move) : std::nullopt; + if (slot && std::ranges::find(order, *slot) == order.end()){ + order.push_back(*slot); + } + } + for (size_t slot = 0; slot < member.moves.size(); slot++){ + if (std::ranges::find(order, slot) == order.end()){ + order.push_back(slot); + } + } + return order; +} + +} // namespace + + +std::optional level_evolution(std::string_view species){ + for (const Evolution& evolution : EVOLUTIONS){ + if (evolution.species == species){ + return evolution.evolution; + } + } + return std::nullopt; +} + +uint8_t max_pp(std::string_view move){ + const MoveData* data = move_data(move); + return data == nullptr ? 0 : data->pp; +} + +bool does_damage(std::string_view move){ + const MoveData* data = move_data(move); + return data != nullptr && data->damaging; +} + +PartyMember new_member(std::string_view species, uint8_t level){ + PartyMember member{ + .species = std::string(species), .moves = {}, .moves_through_level = level, .moves_read = false, + .level = 0, .stats = std::nullopt, + }; + for (const LevelUpMove& entry : LEVEL_UP_MOVES){ + if (entry.species != species || entry.level > level || knows(member, entry.move)){ + continue; + } + if (member.moves.size() == MAX_MOVES){ + member.moves.erase(member.moves.begin()); + } + member.moves.emplace_back(at_full_pp(entry.move)); + } + return member; +} + +PartyMember grown_to(PartyMember member, uint8_t level){ + for (uint8_t at = static_cast(member.moves_through_level + 1); at <= level; at++){ + take_level(member, at); + const std::optional evolution = level_evolution(member.species); + if (evolution && evolution->level <= at){ + evolve(member); + // The new species learns its moves of the level it evolved at. + take_level(member, at); + } + } + return member; +} + +PartyMember story_lead_after_brock(){ + return grown_to(new_member("squirtle", 5), 13); +} + +uint8_t battle_level(const PartyMember& member){ + return std::max(member.level, member.moves_through_level); +} + +PartyMember member_from_summary( + std::string_view species, uint8_t level, const std::vector& moves, + const std::optional& stats +){ + PartyMember member{ + .species = std::string(species), .moves = {}, .moves_through_level = level, .moves_read = true, + .level = level, .stats = stats, + }; + for (const SummaryMove& read : moves){ + const uint8_t full = max_pp(read.move); + const uint8_t pp = read.pp >= 0 ? static_cast(std::min(read.pp, 255)) : static_cast(full / 2); + member.moves.emplace_back(KnownMove{.move = read.move, .pp = pp}); + } + return member; +} + +LearnDecision learn_move(PartyMember& member){ + while (member.moves.size() < MAX_MOVES){ + const LevelUpMove* learned = next_move(member); + if (learned == nullptr){ + break; + } + member.moves.emplace_back(at_full_pp(learned->move)); + member.moves_through_level = learned->level; + } + const LevelUpMove* offered = next_move(member); + if (offered == nullptr){ + return LearnDecision{}; + } + member.moves_through_level = offered->level; + LearnDecision decision{.move = std::string(offered->move), .forget_slot = forget_slot_for(member, offered->move)}; + if (decision.forget_slot){ + member.moves[*decision.forget_slot] = at_full_pp(offered->move); + } + return decision; +} + +void evolve(PartyMember& member){ + if (const std::optional evolution = level_evolution(member.species)){ + member.species = std::string(evolution->into); + member.stats.reset(); + } +} + +std::optional attack_slot(const PartyMember& member){ + if (member.moves.size() < MAX_MOVES && !member.moves_read){ + return std::nullopt; + } + const std::string_view line = line_of(member.species); + for (const Attack& attack : ATTACKS){ + if (attack.line != line){ + continue; + } + const std::optional slot = slot_of(member, attack.move); + if (slot && member.moves[*slot].pp > 0){ + return slot; + } + } + for (size_t slot = 0; slot < member.moves.size(); slot++){ + if (does_damage(member.moves[slot].move) && member.moves[slot].pp > 0){ + return slot; + } + } + for (size_t slot = 0; slot < member.moves.size(); slot++){ + if (member.moves[slot].pp > 0){ + return slot; + } + } + return TOP_LEFT_MOVE; +} + +std::optional attack_slot_against(const PartyMember& member, const std::vector& foes){ + const std::optional plan = attack_slot(member); + std::vector known; + std::ranges::copy_if(foes, std::back_inserter(known), [](const std::string& foe){ + return species_data(foe) != nullptr; + }); + if (known.empty() || !plan){ + return plan; + } + std::optional best; + size_t best_matchup = 0; + for (size_t slot : attack_order(member)){ + const size_t tenths = matchup(member.moves[slot].move, known); + if (member.moves[slot].pp > 0 && tenths > best_matchup){ + best = slot; + best_matchup = tenths; + } + } + return best ? best : plan; +} + +size_t attack_pp(const PartyMember& member){ + size_t pp = 0; + for (const KnownMove& known : member.moves){ + if (does_damage(known.move)){ + pp += known.pp; + } + } + return pp; +} + +void spend_pp(PartyMember& member, size_t slot){ + if (slot < member.moves.size() && member.moves[slot].pp > 0){ + member.moves[slot].pp--; + } +} + +void no_pp_left(PartyMember& member, size_t slot){ + if (slot < member.moves.size()){ + member.moves[slot].pp = 0; + } +} + +void restore_pp(PartyMember& member){ + for (KnownMove& known : member.moves){ + known.pp = max_pp(known.move); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h new file mode 100644 index 0000000000..9c0a85a982 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h @@ -0,0 +1,74 @@ +/* AutoStory Party + * + * From: https://github.com/PokemonAutomation/ + * + * The lead's moves as the story knows them, and the data its choices come + * from: level-up moves and evolutions (pret/pokefirered + * src/data/pokemon/level_up_learnsets.h, evolution.h), which new move + * takes which old one's slot, and which moves the lead attacks with + * first. Moves' PP, power and type, species' types and trainers' parties + * are the generated battle data (PokemonFRLG_AutoStoryBattleData.h). + * + * The story starts from the moves read off the lead's summary when a run + * loads a save (member_from_summary()), else from the moves a checkpoint's + * row says the lead has, and follows the game: a move learned into a free + * slot shows no prompt, so at the next "Delete a move?" the moves due + * before it are taken as learned. Which move is offered is the next + * level-up move after the last one, so the level isn't needed. + * + * Attacks are picked by name and PP, never by slot: a save's moves can sit + * in other slots than the plan's (console B, 2026-11-02: Water Gun took + * Tackle's slot, not Bubble's). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryParty_H +#define PokemonAutomation_PokemonFRLG_AutoStoryParty_H + +#include +#include +#include +#include +#include +#include +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.h" +#include "PokemonFRLG_AutoStoryStats.h" +#include "PokemonFRLG_AutoStoryNewMembers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// The slot to attack with: the first of the plan's attacks for its line +// that it knows with PP left, else its first damaging move with PP left, +// else any move with PP left, else the top left (Struggle). None while the +// story doesn't know all its moves (fewer than four, not read). +std::optional attack_slot(const PartyMember& member); + +// The slot to attack `foes` with, any of them as likely to be out: the +// damaging move with PP left whose type multiplier, summed over the foes, +// is best; ties go to the plan's attacks, then slot order. A foe the data +// doesn't have is left out; with none left, or while the story doesn't +// know all the lead's moves, attack_slot() itself. +std::optional attack_slot_against(const PartyMember& member, const std::vector& foes); + +// The PP left in the damaging moves it knows. +size_t attack_pp(const PartyMember& member); + +// One use of the move in `slot`. +void spend_pp(PartyMember& member, size_t slot); + +// The game said the move in `slot` has no PP left. +void no_pp_left(PartyMember& member, size_t slot); + +// The nurse heals: every move back to full PP. +void restore_pp(PartyMember& member); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyMember.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyMember.h new file mode 100644 index 0000000000..20e9bc5c15 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyMember.h @@ -0,0 +1,75 @@ +/* AutoStory Party Member + * + * From: https://github.com/PokemonAutomation/ + * + * A party member as the story knows it: species, level, moves and their + * PP, and the moves' full PP and power. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryPartyMember_H +#define PokemonAutomation_PokemonFRLG_AutoStoryPartyMember_H + +#include +#include +#include +#include +#include +#include +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.h" +#include "PokemonFRLG_AutoStoryStats.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The move slots, in the order of the battle's move list and the summary. +inline constexpr size_t TOP_LEFT_MOVE = 0; +// Move slot index for bottom-left move. +inline constexpr size_t BOTTOM_LEFT_MOVE = 2; +// Maximum number of moves a Pokemon can know. +inline constexpr size_t MAX_MOVES = 4; + +// A move the lead knows, by slug ("water-gun"), and the PP the story +// counts left. +struct KnownMove{ + std::string move; + uint8_t pp = 0; +}; + +// Party member Pokemon status and learned moves. +struct PartyMember{ + std::string species; + // In slot order. Fewer than four while moves learned into free slots + // haven't been taken in yet (see the top of this file). + std::vector moves; + // The level of the last level-up move offered to it, learned or not. + uint8_t moves_through_level = 0; + // The moves were read off its summary: they are all it knows, even + // fewer than four. + bool moves_read = false; + // Its level as its summary showed it, 0 if not read. Level-ups since + // aren't seen: battle_level() takes the higher of this and + // moves_through_level. + uint8_t level = {}; + // Its stats as POKEMON SKILLS showed them at `level`, as this + // species; none if not read, or once it evolves. + std::optional stats = {}; +}; + +// The level the story takes for `member`: its level, or the level its +// moves were grown through if that is higher. +uint8_t battle_level(const PartyMember& member); +// A move's full PP; 0 for a move the table doesn't have. +uint8_t max_pp(std::string_view move); + +// The move does damage; false for one the table doesn't have. +bool does_damage(std::string_view move); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp new file mode 100644 index 0000000000..cf77964002 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp @@ -0,0 +1,901 @@ +/* AutoStory Party Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The lead's moves as the story tracks them, and the battle loop's choices + * (BattleDecisions) against scripted screens: move prompts, a fainted lead, + * PP, and no B while an evolution may be on screen. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryBattleData.h" +#include "PokemonFRLG_AutoStoryBattleDecisions.h" +#include "PokemonFRLG_AutoStoryParty.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; + + +namespace{ + +struct AutoStoryPartyInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct AutoStoryPartyExpectation{ + std::string_view description; +}; + +struct AutoStoryPartyTestCase{ + AutoStoryPartyInput input; + AutoStoryPartyExpectation expectation; +}; + +class Test_AutoStoryParty : public UnitTest{ +public: + explicit Test_AutoStoryParty(AutoStoryPartyTestCase scenario) + : UnitTest("PokemonFRLG::AutoStoryParty - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_scenario.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryPartyTestCase m_scenario; +}; + + +std::vector move_names(const PartyMember& member){ + std::vector names; + for (const KnownMove& known : member.moves){ + names.push_back(known.move); + } + return names; +} + +std::string joined(const std::vector& names){ + std::string text; + for (const std::string& name : names){ + text += (text.empty() ? "" : ", ") + name; + } + return "[" + text + "]"; +} + +PartyMember with_moves(std::string species, std::vector moves, uint8_t through){ + PartyMember member{.species = std::move(species), .moves = {}, .moves_through_level = through, .moves_read = false}; + for (std::string& move : moves){ + const uint8_t pp = max_pp(move); + member.moves.emplace_back(KnownMove{.move = std::move(move), .pp = pp}); + } + return member; +} + +const PartyStatus GREEN{.hp_seen = true, .hp_yellow = false, .hp_red = false, .status = StatusCondition::NONE}; + + +// The moves the game gives, and the story's plan played to a level. +UnitTestResult test_movesets(Logger&){ + struct Case{ + std::string name; + PartyMember member; + std::string species; + std::vector moves; + }; + const std::vector cases{ + {.name = "new game Squirtle", .member = new_member("squirtle", 5), .species = "squirtle", .moves = {"tackle", "tail-whip"}}, + {.name = "Squirtle after Brock", .member = story_lead_after_brock(), .species = "squirtle", .moves = {"tackle", "tail-whip", "water-gun", "withdraw"}}, + {.name = "Squirtle to Lv20", .member = grown_to(new_member("squirtle", 5), 20), .species = "wartortle", .moves = {"tackle", "bite", "water-gun", "withdraw"}}, + {.name = "Magikarp to Lv25", .member = grown_to(new_member("magikarp", 5), 25), .species = "gyarados", .moves = {"splash", "tackle", "bite", "dragon-rage"}}, + }; + for (const Case& c : cases){ + if (c.member.species != c.species || move_names(c.member) != c.moves){ + return std::format( + "{}: expected {} {}, got {} {}.", + c.name, c.species, joined(c.moves), c.member.species, joined(move_names(c.member)) + ); + } + } + return true; +} + +// "Delete a move?": the move offered is the next level-up move, after the +// moves learned into free slots, and the plan says which slot it takes. +UnitTestResult test_learn_prompts(Logger&){ + struct Case{ + std::string name; + PartyMember member; + std::string offered; + std::optional forget_slot; + std::vector after; + }; + const std::vector cases{ + { + .name = "first prompt of a new game", + .member = new_member("squirtle", 5), + .offered = "water-gun", .forget_slot = BOTTOM_LEFT_MOVE, + .after = {"tackle", "tail-whip", "water-gun", "withdraw"}, + }, + { + .name = "Bite after Brock", + .member = story_lead_after_brock(), + .offered = "bite", .forget_slot = 1, + .after = {"tackle", "bite", "water-gun", "withdraw"}, + }, + { + // The lab's save from before the story learned moves. + .name = "Bite with Bubble kept", + .member = with_moves("squirtle", {"tackle", "tail-whip", "bubble", "withdraw"}, 13), + .offered = "bite", .forget_slot = 1, + .after = {"tackle", "bite", "bubble", "withdraw"}, + }, + { + .name = "Wartortle declines Rapid Spin", + .member = with_moves("wartortle", {"tackle", "bite", "water-gun", "withdraw"}, 19), + .offered = "rapid-spin", .forget_slot = std::nullopt, + .after = {"tackle", "bite", "water-gun", "withdraw"}, + }, + }; + for (Case c : cases){ + const LearnDecision decision = learn_move(c.member); + if (decision.move != c.offered || decision.forget_slot != c.forget_slot || move_names(c.member) != c.after){ + return std::format( + "{}: expected {} over slot {}, leaving {}; got {} over slot {}, leaving {}.", + c.name, c.offered, c.forget_slot ? std::to_string(*c.forget_slot) : "none", joined(c.after), + decision.move.value_or("nothing"), decision.forget_slot ? std::to_string(*decision.forget_slot) : "none", + joined(move_names(c.member)) + ); + } + } + return true; +} + +// NO to "Delete a move?" is followed by YES to "Stop learning?" (B there +// asks "Delete a move?" again, console B 2026-11-01); a move the plan +// wants is YES with the slot to forget. +UnitTestResult test_prompt_answers(Logger&){ + Supplies supplies; + supplies.lead = with_moves("wartortle", {"tackle", "bite", "water-gun", "withdraw"}, 19); + BattleDecisions decline(supplies, BattleKind::TRAINER); + decline.turn(GREEN); + const PromptAnswer first = decline.prompt(false); + const PromptAnswer second = decline.prompt(false); + if (first.answer != YesNo::NO || first.forget_slot || second.answer != YesNo::YES || second.forget_slot){ + return "Expected NO to \"Delete a move?\", then YES to \"Stop learning?\"."; + } + + Supplies learning; + learning.lead = story_lead_after_brock(); + BattleDecisions learn(learning, BattleKind::WILD_FIGHT); + learn.turn(GREEN); + const PromptAnswer answer = learn.prompt(false); + if (answer.answer != YesNo::YES || answer.forget_slot != std::optional(1)){ + return "Expected YES and Tail Whip's slot (1) for Bite."; + } + return true; +} + +// The lead fainted: a wild battle is run from, and a member sent only +// runs; in a trainer's, the next member is sent and uses its first move. +// Protected members are never sent: with only those left there is no +// slot, and the loop stops. Either way the +// battle is lost, and no item goes to the fainted lead. +UnitTestResult test_fainted_lead(Logger&){ + Supplies protected_party; + protected_party.protected_slots = {1, 2, 3, 4, 5}; + BattleDecisions only_protected(protected_party, BattleKind::WILD_FIGHT); + only_protected.turn(GREEN); + if (only_protected.prompt(true).answer != YesNo::NO || !only_protected.lost()){ + return "Expected NO to \"Use next POKEMON?\" in a wild battle, and the battle lost."; + } + if (only_protected.next_member_slot()){ + return "Expected no member sent with every member after the lead protected."; + } + + // Slot 1 protected, the rest not. + Supplies wild_supplies; + wild_supplies.potions = 3; + wild_supplies.protected_slots = {1}; + BattleDecisions wild(wild_supplies, BattleKind::WILD_FIGHT); + wild.turn(GREEN); + wild.prompt(true); + if (wild.next_member_slot() != std::optional(2) || wild.next_member_slot() != std::optional(3)){ + return "Expected slot 2 past the protected slot 1, then slot 3 if 2 couldn't go."; + } + const PartyStatus red{.hp_seen = true, .hp_yellow = false, .hp_red = true, .status = StatusCondition::NONE}; + for (int c = 0; c < 10; c++){ + if (wild.turn(red).choice != TurnChoice::RUN){ + return std::format("Expected the next member to run at turn {}, not fight or use an item.", c + 1); + } + } + + Supplies trainer_supplies; + BattleDecisions trainer(trainer_supplies, BattleKind::TRAINER); + trainer.turn(GREEN); + if (trainer.next_member_slot() != std::optional(1) || !trainer.lost()){ + return "Expected the member after the lead sent in a trainer's battle, and the battle lost."; + } + const TurnAction action = trainer.turn(GREEN); + if (action.choice != TurnChoice::MOVE || action.slot != TOP_LEFT_MOVE){ + return "Expected the next member to use its first move against a trainer."; + } + return true; +} + +// Water Gun until its 25 PP are gone, then Tackle; a "no PP left" moves +// on at once; the nurse restores all. Before the story knows four moves, +// the bottom left slot, as before. +UnitTestResult test_pp(Logger&){ + Supplies supplies; + supplies.lead = story_lead_after_brock(); + BattleDecisions decisions(supplies, BattleKind::TRAINER); + for (int c = 0; c < 25; c++){ + const TurnAction action = decisions.turn(GREEN); + if (action.choice != TurnChoice::MOVE || action.slot != BOTTOM_LEFT_MOVE){ + return std::format("Expected Water Gun (slot 2) at turn {}.", c + 1); + } + } + if (decisions.turn(GREEN).slot != TOP_LEFT_MOVE || attacks_low_on_pp(supplies)){ + return "Expected Tackle once Water Gun is out of PP, with its 34 PP not low."; + } + for (int c = 0; c < 30; c++){ + decisions.turn(GREEN); + } + if (!attacks_low_on_pp(supplies)){ + return "Expected the attacks low on PP with 4 Tackles left."; + } + healed_by_nurse(supplies); + if (supplies.lead.moves[BOTTOM_LEFT_MOVE].pp != 25 || attacks_low_on_pp(supplies)){ + return "Expected the nurse to restore Water Gun's 25 PP."; + } + + BattleDecisions out(supplies, BattleKind::TRAINER); + out.turn(GREEN); + out.turn_done(TurnChoice::MOVE, TurnResult::NOT_DONE); + if (out.turn(GREEN).slot != TOP_LEFT_MOVE){ + return "Expected Tackle after the game said Water Gun has no PP left."; + } + + Supplies new_game; + BattleDecisions unknown(new_game, BattleKind::TRAINER); + if (unknown.turn(GREEN).slot != BOTTOM_LEFT_MOVE){ + return "Expected the bottom left slot while the moves aren't all known."; + } + return true; +} + +// Regression: the save console B left after Route 3 (2026-11-02) has +// Squirtle Lv16 with WATER GUN where TACKLE was and BUBBLE kept, as its +// summary shows. From the moves read, the battle uses Water Gun from the +// top left, then Bubble; never a Tackle it doesn't know, nor Bubble's slot +// for Water Gun. +UnitTestResult test_moves_from_summary(Logger&){ + const std::vector read{ + {.move = "water-gun", .pp = 25, .max_pp = 25}, + {.move = "tail-whip", .pp = 30, .max_pp = 30}, + {.move = "bubble", .pp = 30, .max_pp = 30}, + {.move = "withdraw", .pp = 40, .max_pp = 40}, + }; + Supplies supplies; + supplies.lead = member_from_summary("squirtle", 16, read); + if (attack_pp(supplies.lead) != 55){ + return std::format("Expected 55 PP in Water Gun and Bubble, got {}.", attack_pp(supplies.lead)); + } + BattleDecisions decisions(supplies, BattleKind::TRAINER); + struct Turns{ + size_t count; + size_t slot; + std::string move; + }; + const std::vector plan{ + {.count = 25, .slot = TOP_LEFT_MOVE, .move = "Water Gun"}, + {.count = 30, .slot = BOTTOM_LEFT_MOVE, .move = "Bubble"}, + // No damaging move left: a move with PP, so the turn isn't lost to "no PP left". + {.count = 1, .slot = 1, .move = "Tail Whip"}, + }; + size_t turn = 0; + for (const Turns& turns : plan){ + for (size_t c = 0; c < turns.count; c++){ + turn++; + const TurnAction action = decisions.turn(GREEN); + if (action.choice != TurnChoice::MOVE || action.slot != turns.slot){ + return std::format("Expected {} (slot {}) at turn {}, got slot {}.", turns.move, turns.slot, turn, action.slot); + } + } + } + + // Bite at Lv18 takes Tail Whip's slot, as the plan says. + PartyMember lead = member_from_summary("squirtle", 16, read); + const LearnDecision bite = learn_move(lead); + if (bite.move != std::optional("bite") || bite.forget_slot != std::optional(1)){ + return "Expected Bite offered over Tail Whip (slot 1) after the moves read."; + } + return true; +} + +// Moves read off a summary: all it knows even when fewer than four, a PP +// not read taken as half the full PP (the game colors it from half down), +// and the first damaging move once the plan's attacks are gone. +UnitTestResult test_summary_members(Logger&){ + struct Case{ + std::string name; + PartyMember member; + std::optional slot; + size_t pp; + }; + const std::vector cases{ + { + .name = "three moves read", + .member = member_from_summary("squirtle", 9, { + {.move = "tackle", .pp = 35, .max_pp = 35}, {.move = "tail-whip", .pp = 30, .max_pp = 30}, + {.move = "bubble", .pp = 30, .max_pp = 30}, + }), + .slot = 2, .pp = 65, + }, + { + .name = "Water Gun's PP not read", + .member = member_from_summary("squirtle", 16, { + {.move = "water-gun", .pp = -1, .max_pp = -1}, {.move = "tail-whip", .pp = 30, .max_pp = 30}, + {.move = "bubble", .pp = 30, .max_pp = 30}, {.move = "withdraw", .pp = 40, .max_pp = 40}, + }), + .slot = 0, .pp = 42, + }, + { + .name = "none of the plan's attacks", + .member = member_from_summary("wartortle", 40, { + {.move = "tail-whip", .pp = 30, .max_pp = 30}, {.move = "rapid-spin", .pp = 40, .max_pp = 40}, + {.move = "skull-bash", .pp = 15, .max_pp = 15}, {.move = "withdraw", .pp = 40, .max_pp = 40}, + }), + .slot = 1, .pp = 55, + }, + { + .name = "four moves not read, fewer known", + .member = with_moves("squirtle", {"tackle", "tail-whip", "bubble"}, 7), + .slot = std::nullopt, .pp = 65, + }, + }; + for (const Case& c : cases){ + const std::optional slot = attack_slot(c.member); + if (slot != c.slot || attack_pp(c.member) != c.pp){ + return std::format( + "{}: expected slot {} and {} PP in attacks, got slot {} and {}.", + c.name, c.slot ? std::to_string(*c.slot) : "none", c.pp, + slot ? std::to_string(*slot) : "none", attack_pp(c.member) + ); + } + } + return true; +} + + +// #211: Bite, not Water Gun, against the trainers whose parties resist +// Water Gun: the Cerulean rival's Bulbasaur, and Misty's Staryu and +// Starmie (Water, Psychic: Bite does twice). Once Bite is out of PP, +// Tackle (1x) over the resisted Water Gun (0.5x); and the battle loop +// picks Bite against a known party, +// but not in a wild battle, which has its own foes (BattleData tests). +UnitTestResult test_attack_by_matchup(Logger&){ + PartyMember wartortle = grown_to(new_member("squirtle", 5), 20); + const std::vector bulbasaur{"bulbasaur"}; + const std::optional bite = 1; + const std::optional water_gun = BOTTOM_LEFT_MOVE; + if (move_names(wartortle) != std::vector{"tackle", "bite", "water-gun", "withdraw"}){ + return std::format("Expected Wartortle Lv20 with Tackle, Bite, Water Gun, Withdraw, got {}.", joined(move_names(wartortle))); + } + struct Case{ + std::string name; + std::vector foes; + }; + const std::vector cases{ + {.name = "the rival's Bulbasaur", .foes = bulbasaur}, + {.name = "the Cerulean rival's party", .foes = {"pidgeotto", "abra", "rattata", "bulbasaur"}}, + {.name = "Misty's party", .foes = {"staryu", "starmie"}}, + }; + for (const Case& c : cases){ + const std::optional slot = attack_slot_against(wartortle, c.foes); + if (slot != bite){ + return std::format("{} ({}): expected Bite (slot 1), got slot {}.", c.name, joined(c.foes), slot ? std::to_string(*slot) : "none"); + } + } + PartyMember no_bite = wartortle; + no_bite.moves[1].pp = 0; + if (attack_slot_against(no_bite, bulbasaur) != TOP_LEFT_MOVE || attack_slot_against(no_bite, {"pidgeotto"}) != water_gun){ + return "Expected Tackle against Bulbasaur once Bite is out of PP, and Water Gun against Pidgeotto."; + } + + Supplies supplies; + supplies.lead = wartortle; + supplies.foes = bulbasaur; + BattleDecisions trainer(supplies, BattleKind::TRAINER); + if (trainer.turn(GREEN).slot != *bite || supplies.lead.moves[1].pp != 24){ + return "Expected the trainer battle's turn to use Bite against Bulbasaur, spending its PP."; + } + BattleDecisions wild(supplies, BattleKind::WILD_FIGHT); + supplies.potions = 5; + if (wild.turn(GREEN).slot != *water_gun){ + return "Expected a wild battle with nothing read to keep the plan's order (Water Gun), whatever foes are set."; + } + return true; +} + +// A species the data doesn't have, and no foes at all, get the plan's +// order: Water Gun first. +UnitTestResult test_attack_unknown_foe(Logger&){ + const PartyMember wartortle = grown_to(new_member("squirtle", 5), 20); + const std::vector> unknown{{}, {"missingno"}}; + for (const std::vector& foes : unknown){ + if (attack_slot_against(wartortle, foes) != attack_slot(wartortle) || attack_slot(wartortle) != BOTTOM_LEFT_MOVE){ + return std::format("Expected the plan's order (Water Gun) against {}.", joined(foes)); + } + } + return true; +} + +// Bite is learned when offered (Wartortle Lv19, pret's +// sWartortleLevelUpLearnset) over Tail Whip, else over Withdraw; never +// over Water Gun. +UnitTestResult test_bite_learned(Logger&){ + struct Case{ + std::string name; + std::vector moves; + size_t forget; + }; + const std::vector cases{ + {.name = "with Tail Whip", .moves = {"tackle", "tail-whip", "water-gun", "withdraw"}, .forget = 1}, + {.name = "Water Gun over Tackle, no Tail Whip", .moves = {"water-gun", "bubble", "tackle", "withdraw"}, .forget = 3}, + }; + for (const Case& c : cases){ + PartyMember member = with_moves("wartortle", c.moves, 18); + const LearnDecision decision = learn_move(member); + if (decision.move != "bite" || decision.forget_slot != c.forget){ + return std::format( + "{}: expected Bite over slot {}, got {} over slot {}.", c.name, c.forget, + decision.move.value_or("nothing"), decision.forget_slot ? std::to_string(*decision.forget_slot) : "none" + ); + } + } + return true; +} + + +// A fake evolution scene: B pressed while it shows "is evolving!" cancels +// the evolution, as in the game. +struct FakeEvolution{ + std::vector frames; + size_t evolving_from = 0; + size_t evolving_to = 0; +}; + +// Plays `scene` against the loop's rule (B at any screen it doesn't hold +// for): whether the evolution went through. +bool evolves_against_loop(const FakeEvolution& scene, const EvolutionHold& hold){ + bool cancelled = false; + for (size_t frame = 0; frame < scene.frames.size(); frame++){ + const bool pressed_b = !hold.holds(scene.frames[frame]); + if (pressed_b && frame >= scene.evolving_from && frame < scene.evolving_to){ + cancelled = true; + } + } + return !cancelled; +} + +// Regression: Squirtle stayed Lv16 on console B (2026-11-02), the B +// presses after the battle cancelling its evolution. No B while "What? +// SQUIRTLE is evolving!" shows; B again for the arrow after it. +UnitTestResult test_no_b_during_evolution(Logger&){ + const BattleTextScreen in_battle{.text_box = true, .hp_box = true, .arrow = false, .yes_no = false}; + const BattleTextScreen evolving{.text_box = true, .hp_box = false, .arrow = false, .yes_no = false}; + const BattleTextScreen congratulations{.text_box = true, .hp_box = false, .arrow = true, .yes_no = false}; + const BattleTextScreen learn_prompt{.text_box = true, .hp_box = false, .arrow = false, .yes_no = true}; + FakeEvolution scene; + scene.frames = {in_battle, in_battle, congratulations}; + scene.frames.insert(scene.frames.begin() + 2, 40, evolving); + scene.evolving_from = 2; + scene.evolving_to = 42; + + PartyMember lead = with_moves("squirtle", {"tackle", "tail-whip", "bubble", "withdraw"}, 13); + EvolutionHold hold(lead); + hold.turn_taken(TurnChoice::MOVE); + if (!evolves_against_loop(scene, hold)){ + return "B was pressed during \"is evolving!\": the evolution would be cancelled."; + } + if (hold.holds(congratulations) || hold.holds(learn_prompt)){ + return "Expected B (or the prompt's answer) for the text with an arrow and the YES/NO after the evolution."; + } + + hold.held(1s, false); + if (lead.species != "squirtle"){ + return "A text box held for 1 s was taken for an evolution."; + } + hold.held(15s, false); + if (lead.species != "wartortle"){ + return "Expected Squirtle to be Wartortle after 15 s of its evolution screen, got " + lead.species + "."; + } + hold.held(40s, false); + if (hold.holds(evolving)){ + return "Expected no more holding once a battle's holds reach their cap."; + } + + PartyMember other = new_member("squirtle", 5); + EvolutionHold before_turn(other); + if (before_turn.holds(evolving)){ + return "Held before the first turn, where Oak's text box needs B."; + } + return true; +} + +// A poll of the battle loop: what it read, at `ms` from the start. +struct LoopPoll{ + int ms; + BattleTextScreen screen; + bool menu = false; +}; + +// Regression: console B, 2026-11-03, Mt. Moon B2F: RUN, "Got away +// safely!", then the cave corridor, whose black lower half reads as the +// battle's text box with no HP box. The loop held B for an evolution for +// a minute, then pressed A and B for 9 minutes. After RUN nothing is held, +// and START looks for the overworld within seconds of the last HP box. +UnitTestResult test_run_then_overworld(Logger&){ + const BattleTextScreen menu_screen{.text_box = true, .hp_box = true, .arrow = false, .yes_no = false}; + const BattleTextScreen got_away{.text_box = true, .hp_box = true, .arrow = true, .yes_no = false}; + const BattleTextScreen dark_cave{.text_box = true, .hp_box = false, .arrow = false, .yes_no = false}; + std::vector polls{{.ms = 0, .screen = menu_screen, .menu = true}}; + for (int ms = 300; ms <= 1500; ms += 300){ + polls.push_back({.ms = ms, .screen = got_away}); + } + for (int ms = 1800; ms <= 60000; ms += 300){ + polls.push_back({.ms = ms, .screen = dark_cave}); + } + + Supplies supplies; + BattleDecisions decisions(supplies, BattleKind::WILD_RUN); + EvolutionHold hold(supplies.lead); + BattleEndWatch watch; + const WallClock start = current_time(); + const TurnChoice choice = decisions.turn(PartyStatus{.hp_seen = true}).choice; + if (choice != TurnChoice::RUN){ + return "Expected RUN from a wild Pokemon."; + } + hold.turn_taken(choice); + for (const LoopPoll& poll : polls){ + const WallClock now = start + std::chrono::milliseconds(poll.ms); + if (hold.holds(poll.screen)){ + return std::format("Held B for an evolution at {} ms, after RUN.", poll.ms); + } + const bool battle = poll.screen.hp_box || poll.screen.yes_no; + watch.seen(poll.menu ? BattleSeen::MENU : battle ? BattleSeen::BATTLE : BattleSeen::NONE, now); + if (watch.check_overworld(now)){ + // The last HP box at 1.5 s; START within the next 3.5 s. + if (poll.ms > 5000){ + return std::format("START first looked for the overworld at {} ms.", poll.ms); + } + return true; + } + } + return "START never looked for the overworld in the dark cave."; +} + +// START only once the battle is gone for a while, and then not at every +// poll; A and B blind for at most 30 s since the last battle menu. +UnitTestResult test_end_watch_timing(Logger&){ + const WallClock start = current_time(); + const auto at = [&](int ms){ return start + std::chrono::milliseconds(ms); }; + BattleEndWatch watch; + if (watch.check_overworld(at(10000))){ + return "Looked for the overworld before any battle screen showed."; + } + for (int ms = 0; ms <= 20000; ms += 300){ + watch.seen(BattleSeen::BATTLE, at(ms)); + if (watch.check_overworld(at(ms))){ + return std::format("Looked for the overworld at {} ms with an HP box on screen.", ms); + } + } + int checks = 0; + for (int ms = 20100; ms <= 32000; ms += 300){ + watch.seen(BattleSeen::NONE, at(ms)); + checks += watch.check_overworld(at(ms)) ? 1 : 0; + } + if (checks < 2 || checks > 4){ + return std::format("Expected START every 3 s for 12 s without the battle, got {} looks.", checks); + } + for (int ms = 0; ms < 30000; ms += 1500){ + if (watch.pressed_blind(at(40000 + ms))){ + return std::format("Gave up pressing blind after {} ms.", ms); + } + } + if (!watch.pressed_blind(at(70000))){ + return "Expected to give up after 30 s of blind presses."; + } + watch.seen(BattleSeen::MENU, at(71000)); + if (watch.pressed_blind(at(72000))){ + return "Expected the battle menu to start the blind presses' time over."; + } + return true; +} + + +} // namespace + + +// The lead console B took into Super Nerd Miguel's battle (2026-11-03, +// Mt. Moon B2F), as its summary read before the run. +PartyMember squirtle_before_miguel(){ + return member_from_summary("squirtle", 16, { + {.move = "water-gun", .pp = 25, .max_pp = 25}, + {.move = "tail-whip", .pp = 30, .max_pp = 30}, + {.move = "bubble", .pp = 30, .max_pp = 30}, + {.move = "withdraw", .pp = 40, .max_pp = 40}, + }); +} + +// Regression, console B 2026-11-03: in the trainer's battle before the +// Rocket Grunt, a YES/NO read at a level-up (Lv17: no move to learn) got +// the plan's YES for Bite over Tail Whip, and no move list followed. The +// story still took Tail Whip as Bite, and in Miguel's battle chose it as +// its attack for 7 turns, until the starter fainted. The moves change only +// once the move list was seen. +UnitTestResult test_yes_no_without_move_list(Logger&){ + Supplies supplies; + supplies.lead = squirtle_before_miguel(); + BattleDecisions decisions(supplies, BattleKind::TRAINER); + decisions.turn(GREEN); + const PromptAnswer answer = decisions.prompt(false); + if (answer.answer != YesNo::YES || answer.forget_slot != std::optional(1)){ + return "Expected the plan's YES, Bite over Tail Whip (slot 1)."; + } + const std::vector before{"water-gun", "tail-whip", "bubble", "withdraw"}; + if (move_names(supplies.lead) != before){ + return "Expected the moves unchanged with no move list seen, got " + joined(move_names(supplies.lead)) + "."; + } + const std::vector after{"water-gun", "bite", "bubble", "withdraw"}; + if (!answer.learned || move_names(*answer.learned) != after){ + return "Expected the lead to keep once the move list shows to have Bite over Tail Whip."; + } + return true; +} + +// Regression, console B 2026-11-03, Super Nerd Miguel (pret +// sParty_SuperNerdMiguel: Grimer Lv12, whose moves include Disable): after +// turn 1, Water Gun was turned down 17 times with no turn passing, and +// each try spent a PP of the story's count. Turned down once, it is left +// alone for as long as Disable lasts, its PP given back, and Bubble (not +// Tail Whip) attacks meanwhile. +UnitTestResult test_disabled_move(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 || decisions.turn(GREEN).slot != TOP_LEFT_MOVE){ + return "Expected Water Gun (slot 0) at turns 1 and 2."; + } + decisions.turn_done(TurnChoice::MOVE, TurnResult::REFUSED); + if (supplies.lead.moves[TOP_LEFT_MOVE].pp != 24){ + return std::format("Expected Water Gun at 24 PP after one turn and one refused, got {}.", supplies.lead.moves[TOP_LEFT_MOVE].pp); + } + for (int c = 0; c < 5; c++){ + const TurnAction action = decisions.turn(GREEN); + if (action.choice != TurnChoice::MOVE || action.slot != BOTTOM_LEFT_MOVE){ + return std::format("Expected Bubble (slot 2) at turn {} after Water Gun was turned down, got slot {}.", c + 1, action.slot); + } + } + if (decisions.turn(GREEN).slot != TOP_LEFT_MOVE){ + return "Expected Water Gun again once Disable is over."; + } + 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 +// (a YES/NO's presses, 25 s). +UnitTestResult test_move_refusal_watch(Logger&){ + const WallClock start = current_time(); + MoveRefusalWatch watch; + watch.move_chosen(start); + watch.no_battle_screen(); + if (!watch.refused(start + 5700ms)){ + return "Expected the move list then the menu at 5.7 s read as the move turned down."; + } + watch.move_chosen(start); + if (watch.refused(start + 5000ms)){ + return "Expected no refusal without the move list between."; + } + watch.move_chosen(start); + watch.no_battle_screen(); + if (watch.refused(start + 25000ms)){ + return "Expected no refusal for a menu 25 s after the choice."; + } + watch.no_battle_screen(); + if (watch.refused(start + 26000ms)){ + return "Expected no refusal with no move chosen."; + } + return true; +} + +// Regression, console B 2026-11-03, Miguel's battle (m48): the move list +// opened after YES to "Delete a move to make room for BITE?", and closed +// with no move forgotten, so the game asked "Stop learning BITE?" where +// the story expected the next move's "Delete a move?". NO there and YES +// at "Delete a move?" went round 13 times (75 s), until presses by time +// ended it. A YES/NO right after the move list is "Stop learning?": YES, +// and the lead keeps its moves. +UnitTestResult test_move_list_closed(Logger&){ + enum class Prompt{DELETE, STOP}; + Supplies supplies; + supplies.lead = squirtle_before_miguel(); + BattleDecisions decisions(supplies, BattleKind::TRAINER); + decisions.turn(GREEN); + Prompt prompt = Prompt::DELETE; + for (int answers = 1; answers <= 8; answers++){ + const PromptAnswer answer = decisions.prompt(false); + if (answer.learned){ + // The move list showed, as the loop saw it. + supplies.lead = *answer.learned; + } + if (prompt == Prompt::STOP && answer.answer == YesNo::YES){ + const std::vector before{"water-gun", "tail-whip", "bubble", "withdraw"}; + if (move_names(supplies.lead) != before){ + return "Expected the moves as before Bite was offered, got " + joined(move_names(supplies.lead)) + "."; + } + return true; + } + // The move list closes with nothing forgotten: "Stop learning?", + // as after NO; NO there asks "Delete a move?" again. + prompt = prompt == Prompt::DELETE ? Prompt::STOP : Prompt::DELETE; + } + return "Expected the move prompts to end within 8 answers."; +} + +// However the YES/NOs come, a few after a turn are all the move prompts +// can be (two moves offered, NO then YES each); after those, YES only, +// which ends either prompt ("Delete a move?": the move list, which the +// loop's B closes; "Stop learning?": done), and the moves stay as they are. +UnitTestResult test_move_prompts_bounded(Logger&){ + Supplies supplies; + supplies.lead = with_moves("wartortle", {"tackle", "bite", "water-gun", "withdraw"}, 19); + BattleDecisions decisions(supplies, BattleKind::TRAINER); + decisions.turn(GREEN); + for (int answers = 1; answers <= 12; answers++){ + const PromptAnswer answer = decisions.prompt(false); + if (answers > 4 && (answer.answer != YesNo::YES || answer.forget_slot)){ + return std::format("Expected a plain YES at the move prompt {} after a turn.", answers); + } + } + const std::vector moves{"tackle", "bite", "water-gun", "withdraw"}; + if (move_names(supplies.lead) != moves){ + return "Expected the moves unchanged, got " + joined(move_names(supplies.lead)) + "."; + } + return true; +} + +// Regression, console B 2026-11-03, before Miguel (m48): yellow HP +// (17/55) and no Potion left, and the story went into the battle, as the +// nurse was only for red HP. After the items, the nurse for any HP not +// green, a status, or attacks low on PP. +UnitTestResult test_nurse_before_battle(Logger&){ + Supplies supplies; + supplies.lead = squirtle_before_miguel(); + if (nurse_before_battle(supplies)){ + return "Expected no nurse with green HP, no status and full PP."; + } + supplies.hurt = true; + if (!nurse_before_battle(supplies)){ + return "Expected the nurse for yellow HP that no Potion healed."; + } + supplies.hurt = false; + supplies.status = StatusCondition::OTHER; + if (!nurse_before_battle(supplies)){ + return "Expected the nurse for a status no item cured."; + } + return true; +} + +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 = "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"}, + }, +}; + + +void add_tests_AutoStoryParty(UnitTestDatabase& database){ + for (const auto& scenario : AUTO_STORY_PARTY_CASES){ + database.add(scenario); + } + add_tests_AutoStoryBattleData(database); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h new file mode 100644 index 0000000000..3d3a79aa7f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h @@ -0,0 +1,66 @@ +/* AutoStory Presses + * + * From: https://github.com/PokemonAutomation/ + * + * The story's basic presses: text advanced to its end, a YES/NO read + * and answered, a step onto a trigger and a turn to a wall. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryPresses_H +#define PokemonAutomation_PokemonFRLG_AutoStoryPresses_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonFRLG_AutoStoryStartMenu.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Which row of the standard YES/NO box the arrow is on (true: YES), if +// one shows. +std::optional yes_no_cursor(const ImageViewRGB32& screen); +// Expected screen state when dialogue text finishes. +enum class TextEnd{ + OVERWORLD, + BATTLE, +}; + +// Presses B until the overworld is back or, if `stop_at_battle`, a battle +// shows. Throws OperationFailedException after `timeout`. +TextEnd advance_text(ConsoleHandle& console, ProControllerContext& context, Milliseconds timeout, bool stop_at_battle); + +// advance_text() to the overworld. +void mash_until_overworld(ConsoleHandle& console, ProControllerContext& context, Milliseconds timeout); + +// 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); + +// From the overworld: one step `direction`, onto a trigger or into a door. +// `facing` is the way the player faces, if known; a player facing another +// way is turned first. +void step_once(ProControllerContext& context, Pokemon::Direction direction, std::optional facing); + +// From the overworld, turns to face `direction` without stepping: the +// player must have a wall that way. +void face_wall(ProControllerContext& context, Pokemon::Direction direction); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h new file mode 100644 index 0000000000..784ad4579d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h @@ -0,0 +1,91 @@ +/* AutoStory Save + * + * From: https://github.com/PokemonAutomation/ + * + * The save dialog as the story runs it, and the place the save card + * names. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStorySave_H +#define PokemonAutomation_PokemonFRLG_AutoStorySave_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonFRLG_AutoStoryIntro.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The save dialog after SAVE, as pokefirered's start_menu.c runs it: +// "Would you like to save the game?" YES/NO (YES first). Then, over a save +// of this game, "There is already a saved file. Is it okay to overwrite +// it?" YES/NO (YES first); over another game's save (a new game), "WARNING! +// There is a different game file that is already saved." on four pages, +// ending "...overwrite the other save file?" YES/NO with NO first. Then +// "SAVING... DON'T TURN OFF THE POWER.", "PLAYER saved the game." and, +// without a press, the overworld. NO at any YES/NO brings the START menu +// back; a failed save shows "Save error." and waits for A held. +enum class SaveScreen{ + YES_NO, + // A message with the arrow for the next page. + PAGED_TEXT, + // A message without an arrow: SAVING, or saved. + TEXT, + START_MENU, + // No message and no menu: the overworld, or a frame between two boxes. + NOTHING, +}; +// Action to perform in the save menu loop. +enum class SaveAction{ + WAIT, + ANSWER_YES, + NEXT_PAGE, + // Confirm the overworld (START opens the menu): the game is saved. + CHECK_OVERWORLD, + // The START menu is back: a YES/NO was answered NO. + FAIL_CANCELLED, + // A paged message after the last YES: "Save error." + FAIL_ERROR, +}; +// What save_game() does on each screen it reads after the save card's +// first YES/NO shows. Every YES/NO gets YES; B is never pressed. +class SaveDialog{ +public: + SaveAction next(SaveScreen screen); + +private: + bool m_paged_since_yes = false; + size_t m_nothing_seen = 0; +}; + +// From the overworld: SAVE, YES, and YES again to overwrite an older save +// (see SaveDialog). The menu's cursor is read, since the game remembers it +// and the menu grows. Returns to the overworld; throws +// OperationFailedException if the save wasn't made. +void save_game(ConsoleHandle& console, ProControllerContext& context, StartMenu menu); + +// From the overworld: the place the START menu's SAVE card names (see +// read_save_card_location()), then NO, back to the overworld. Empty if it +// can't be read. The menu's length is read, not assumed, so a save made +// with another START menu (another checkpoint's) is read too. +std::string read_save_place(ConsoleHandle& console, ProControllerContext& context, Language language); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h new file mode 100644 index 0000000000..22d1ad5c1b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h @@ -0,0 +1,66 @@ +/* AutoStory Start Menu + * + * From: https://github.com/PokemonAutomation/ + * + * The START menu as the story grows it, whether the story checks the + * screen, and whether the overworld is up. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryStartMenu_H +#define PokemonAutomation_PokemonFRLG_AutoStoryStartMenu_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Whether the shared check level (Types/Pokemon_StoryCheckLevel.h, set by +// StoryRunOptions) has the story check the screen before and after it +// acts: DEFAULT and above (TESTING, THOROUGH). Then FRLG reads a Mart +// row's item before buying it, the bag's Items pocket after shopping (the +// counts the story then keeps), and an item's name in the bag before +// using it. FAST and SPEEDRUN trust the counts it keeps and the timings. +inline bool checks_screen(Pokemon::StoryCheckLevel level){ + return level <= Pokemon::StoryCheckLevel::DEFAULT; +} + +// The START menu as the story grows it. Before the starter: BAG, the +// player, SAVE, OPTION, EXIT; the starter adds POKEMON on top, the Pokedex +// POKEDEX above that. +enum class StartMenu{ + BEFORE_POKEMON, + BEFORE_POKEDEX, + FULL, +}; +// Total rows in the start menu. +int start_menu_rows(StartMenu menu); +// Row index of the SAVE option in the start menu. +int start_menu_save_row(StartMenu menu); +// Row index of the OPTION item in the start menu. +int start_menu_option_row(StartMenu menu); + + +// Whether the overworld is up: START opens the menu only there, with no +// scene running. If it opened, it is closed again. +bool overworld_shows(ConsoleHandle& console, ProControllerContext& context); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStats.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStats.h new file mode 100644 index 0000000000..e279c0b474 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStats.h @@ -0,0 +1,34 @@ +/* AutoStory Stats + * + * From: https://github.com/PokemonAutomation/ + * + * A Pokemon's stats as POKEMON SKILLS shows them. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryStats_H +#define PokemonAutomation_PokemonFRLG_AutoStoryStats_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// A Pokemon's stats, in the game's order. +struct Stats{ + uint16_t hp = 0; + uint16_t attack = 0; + uint16_t defense = 0; + uint16_t sp_attack = 0; + uint16_t sp_defense = 0; + uint16_t speed = 0; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp new file mode 100644 index 0000000000..f6fe9b27cf --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp @@ -0,0 +1,153 @@ +/* AutoStory Summary + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_PartyDialogs.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_StatsReader.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "PokemonFRLG_AutoStorySummary.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; + + +namespace{ + +void press(ProControllerContext& context, Button button){ + pbf_press_button(context, button, 160ms, 0ms); +} + +void tap(ProControllerContext& context, DpadPosition position, Milliseconds after = 400ms){ + pbf_press_dpad(context, position, 160ms, after); +} + +// Up to `timeout` for `watcher`'s screen, after a press. A screen that +// shows is given a moment to finish drawing before it is read. +bool wait_drawn(ConsoleHandle& console, ProControllerContext& context, VisualInferenceCallback& watcher, Milliseconds timeout){ + context.wait_for_all_requests(); + if (wait_until(console, context, timeout, {watcher}) < 0){ + return false; + } + pbf_wait(context, 500ms); + context.wait_for_all_requests(); + return true; +} + +// POKEMON SKILLS' stats, none unless all six read. +std::optional skills_stats(ConsoleHandle& console, Language language, const ImageViewRGB32& screen){ + PokemonFRLG_Stats read; + StatsReader().read_page2(console, language, screen, read); + if (!read.hp || !read.attack || !read.defense || !read.sp_attack || !read.sp_defense || !read.speed){ + return std::nullopt; + } + return Stats{ + .hp = static_cast(*read.hp), .attack = static_cast(*read.attack), + .defense = static_cast(*read.defense), .sp_attack = static_cast(*read.sp_attack), + .sp_defense = static_cast(*read.sp_defense), .speed = static_cast(*read.speed), + }; +} + +// From the party menu with the cursor on the member: its summary, read. +std::optional read_open_summary(ConsoleHandle& console, ProControllerContext& context, Language language){ + PartySelectionWatcher submenu(COLOR_RED); + press(context, BUTTON_A); + if (!wait_drawn(console, context, submenu, 5000ms)){ + console.log("Summary: the party member's menu didn't show.", COLOR_ORANGE); + return std::nullopt; + } + // SUMMARY, the menu's top row. + SummaryWatcher info(COLOR_RED); + press(context, BUTTON_A); + if (!wait_drawn(console, context, info, 5000ms)){ + console.log("Summary: the summary's first page didn't show.", COLOR_ORANGE); + return std::nullopt; + } + SummaryRead read; + { + VideoSnapshot screen = console.video().snapshot(); + if (!screen){ + return std::nullopt; + } + PokemonFRLG_Stats stats; + StatsReader().read_page1(console, language, screen, stats); + read.species = stats.name; + read.level = stats.level; + } + SummaryPage2Watcher skills(COLOR_RED); + tap(context, DPAD_RIGHT, 0ms); + if (!wait_drawn(console, context, skills, 3000ms)){ + console.log("Summary: POKEMON SKILLS didn't show.", COLOR_ORANGE); + return std::nullopt; + } + if (VideoSnapshot page = console.video().snapshot()){ + read.stats = skills_stats(console, language, page); + } + SummaryPage3Watcher moves(COLOR_RED); + tap(context, DPAD_RIGHT, 0ms); + if (!wait_drawn(console, context, moves, 3000ms)){ + console.log("Summary: KNOWN MOVES didn't show.", COLOR_ORANGE); + return std::nullopt; + } + VideoSnapshot screen = console.video().snapshot(); + if (!screen){ + return std::nullopt; + } + read.moves = read_summary_moves(console, language, screen); + dump_debug_image(console, "AutoStory/summary", "moves", screen); + return read; +} + +} // namespace + +std::optional read_party_summary( + ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language, size_t slot +){ + if (menu == StartMenu::BEFORE_POKEMON){ + return std::nullopt; + } + open_party_menu_from_overworld( + console, context, menu == StartMenu::BEFORE_POKEDEX ? StartMenuContext::NO_DEX : StartMenuContext::STANDARD + ); + context.wait_for_all_requests(); + // The party menu opens on the lead; DOWN steps through the slots. + for (size_t c = 0; c < slot; c++){ + tap(context, DPAD_DOWN); + } + const std::optional read = read_open_summary(console, context, language); + mash_until_overworld(console, context, 20000ms); + if (read){ + std::string moves; + for (const SummaryMove& move : read->moves){ + moves += std::format("{}{} {}/{}", moves.empty() ? "" : ", ", move.move, move.pp, move.max_pp); + } + const std::string stats = read->stats + ? std::format( + "{} HP, {}/{}/{}/{}/{}", read->stats->hp, read->stats->attack, read->stats->defense, + read->stats->sp_attack, read->stats->sp_defense, read->stats->speed + ) + : "stats not read"; + console.log(std::format( + "Summary of party slot {}: {} Lv{}, {}, {}.", + slot + 1, read->species.empty() ? "?" : read->species, + read->level ? std::to_string(*read->level) : "?", stats, moves.empty() ? "no moves read" : moves + )); + } + return read; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h new file mode 100644 index 0000000000..0fd32999f7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h @@ -0,0 +1,57 @@ +/* AutoStory Summary + * + * From: https://github.com/PokemonAutomation/ + * + * Reading a party member's summary from the overworld: its species, + * level and moves, for the battles' move plan and the steps that check a + * level. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStorySummary_H +#define PokemonAutomation_PokemonFRLG_AutoStorySummary_H + +#include +#include +#include +#include +#include "CommonFramework/Language.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryStats.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// A party member as its summary shows it. +struct SummaryRead{ + // The species' slug, empty if not read. + std::string species = {}; + std::optional level = std::nullopt; + // KNOWN MOVES, from the top, up to the first name not read. + std::vector moves = {}; + // POKEMON SKILLS (HP as its maximum), none unless all six were read. + std::optional stats = std::nullopt; +}; + +// From the overworld: the party menu, party slot `slot`'s SUMMARY, its +// first page (species, level), POKEMON SKILLS (stats) and KNOWN MOVES, +// then back to the overworld. +// Each screen is waited for before the next press: a press sent before a +// menu is drawn goes to what was there before (console B, 2026-11-02, the +// PC's menus). Nothing if a screen didn't show, or before the starter +// (`menu` has no POKEMON). +std::optional read_party_summary( + ConsoleHandle& console, ProControllerContext& context, StartMenu menu, Language language, size_t slot +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h new file mode 100644 index 0000000000..b02d288b9a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h @@ -0,0 +1,107 @@ +/* AutoStory Supplies + * + * From: https://github.com/PokemonAutomation/ + * + * What the story carries into a battle: the healing items, the lead's + * status, HP and moves, and the foes it knows; and when to see the nurse. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStorySupplies_H +#define PokemonAutomation_PokemonFRLG_AutoStorySupplies_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattleData.h" +#include "PokemonFRLG_AutoStoryParty.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// A status condition, as far as the story treats them: the two it carries +// items for, and the rest, which only a nurse cures. +enum class StatusCondition{ + NONE, + POISON, + PARALYSIS, + OTHER, // SLP, BRN, FRZ +}; +// String representation of a status condition. +std::string_view status_name(StatusCondition status); + +// The healing items in the Items pocket, in the order they were bought: +// Potions, Antidotes, then Parlyz Heals. +struct Supplies{ + int potions = 0; + int antidotes = 0; + int parlyz_heals = 0; + // The Items pocket's order, by slug (see read_item_list_name()): the + // order bought, or as read from the bag, with "" for a row whose name + // couldn't be read. A counted item with none left takes no row; the + // others always take theirs. + std::vector pocket = {"potion", "antidote", "parlyz-heal"}; + // The starter's status at the last battle screen that showed it, and + // not cured since. + StatusCondition status = StatusCondition::NONE; + // The starter's HP bar wasn't green (or was red) at the last battle + // screen that showed it, and no Potion or nurse healed it since. + bool hurt = false; + bool hp_red = false; + // The starter's HP bar's filled share at the last battle screen that + // showed it, 1 after the nurse or a Potion on the overworld. + double hp_fill = 1.0; + // The starter's moves and their PP, as far as the story knows them: + // a new game's Squirtle unless a checkpoint's row says otherwise. + PartyMember lead = new_member("squirtle", 5); + // Party slots (from 0, the lead) that are never sent in when the lead + // faints, so they gain no EXP and learn or evolve nothing: a member + // kept for later, or one the user keeps for a trade. + std::vector protected_slots = {}; + // The party of the trainer the battle step fights, as its plan lists + // it (the step's "foes"): the lead's attacks are chosen against it + // while the one out isn't known. Empty otherwise; wild battles never + // use it. + std::vector foes = {}; + // That trainer, as its plan names it (the step's "trainer"), "" otherwise. + std::string trainer = {}; + // How carefully that battle is fought (default_battle_risk()). + BattleRisk risk = BattleRisk::LOW; + // The species of the trainer's Pokemon out, as read at the last battle + // menu (read_trainer_foe()), "" if not read: the lead's attacks are + // chosen against it. + std::string foe_out = {}; + // The wild Pokemon of the battle going on, as read at its first battle + // menu (read_wild_foes()): the lead's attacks are chosen against it. + // Empty when it wasn't read; trainer battles never use it. + std::vector wild_foes = {}; +}; + +// The nurse healed the party: HP, status and PP. +void healed_by_nurse(Supplies& supplies); + +// The lead's attacks are low on PP: the nurse before a fight that needs them. +bool attacks_low_on_pp(const Supplies& supplies); + +// Before a trainer's battle, once the items are used: the nurse for HP +// not green (no Potion left to heal it), a status no item cured, or +// attacks low on PP. Yellow HP counts (console B, 2026-11-03: 17/55 HP +// and no Potion into Miguel's battle, which only red would have stopped). +bool nurse_before_battle(const Supplies& supplies); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 1aea88d355..548365efb6 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1925,6 +1925,34 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/PokemonFRLG_Settings.h Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleRisk.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleTurns.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLevelUps.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMoveData.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryNewMembers.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyMember.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStats.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp diff --git a/devtools/maps/RESOURCE_MAPS.md b/devtools/maps/RESOURCE_MAPS.md index 3509e98523..0628e74586 100644 --- a/devtools/maps/RESOURCE_MAPS.md +++ b/devtools/maps/RESOURCE_MAPS.md @@ -33,7 +33,11 @@ modified, extra or unapproved resource data fails before compilation. The pack includes pinned license/provenance. Generated resources and external caches are ignored; the resource lock is checked in. -The duplicate FRLG builder and Python tests are removed. Map-builder tests already live +The duplicate FRLG builder and Python tests are removed. The battle data in +`Programs/AutoStory/BattleData` is cut to what the program reads (each species' +types, each move's type, whether it does damage and its PP, and the type +chart) and has no generator here; a battle's foes come from its step in the +checkpoint's plan. Map-builder tests already live beside their source in PokemonSimulation. Native game tests remain here. The shared Sinnoh decomp CLI remains a separate consumer migration.