From e006db3742aa7c3c011cad6fbe9ada9da6fd6ee8 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 18:07:15 +0000 Subject: [PATCH] macros: a ball at low HP is the only attack, and the fly types its catch's name Two operator decisions (2026-09-29, row 69). Throw on low HP only: in a wild battle with THROW BALL dealt and the wild Pokemon at the HP where ItemUseBall's HP factor saturates (W = (MaxHP*255/BallFactor)/max(HP/4,1) >= 255: about a third for a Poke Ball, a half for a Great Ball), MOVE 1-4, SWITCH, RUN and the bag's BACK are withheld. ITEM stays for a hurt thrower. Every precondition of THROW BALL still gates it, so no ball, a caught species or a trainer gives the ordinary pad back. Let the fly name it: the naming screen is read (menu bytes, the keyboard's box, the underscores; wNamingScreenNameLength and wNamingScreenSubmitName pinned from the cartridge's own stores) before the battle test and reads Unknown. Its pad is the fly's own D-pad, A, B and START, passed through Observed::raw while nothing is bound. Once the name is full or sixty brain seconds have run, CONFIRM alone is dealt and presses START until the keyboard closes. Also moves two doc comments row 66 split from their items (review N3). --- .../flysim/crates/flybrain-gb/src/macros.rs | 7 + .../flybrain-gb/src/pokemon_red/fake_wram.rs | 17 ++ .../src/pokemon_red/macros/cartridge.rs | 6 + .../src/pokemon_red/macros/driver.rs | 30 ++- .../src/pokemon_red/macros/executor.rs | 29 ++- .../src/pokemon_red/macros/geography.rs | 10 +- .../src/pokemon_red/macros/palette.rs | 140 ++++++++++- .../src/pokemon_red/macros/state.rs | 25 ++ .../src/pokemon_red/macros/tests.rs | 233 +++++++++++++++++- .../flybrain-gb/src/pokemon_red/scene.rs | 11 +- .../flybrain-gb/src/pokemon_red/state.rs | 86 ++++++- .../src/pokemon_red/state/tests.rs | 40 +++ services/flysim/crates/flysim/src/macros.rs | 62 ++++- 13 files changed, 666 insertions(+), 30 deletions(-) diff --git a/services/flysim/crates/flybrain-gb/src/macros.rs b/services/flysim/crates/flybrain-gb/src/macros.rs index 55bd04a..39e33d8 100644 --- a/services/flysim/crates/flybrain-gb/src/macros.rs +++ b/services/flysim/crates/flybrain-gb/src/macros.rs @@ -188,6 +188,13 @@ pub struct SlotBinding { pub struct Observed { pub scene: SceneId, pub bindings: Vec, + /// The fly's own buttons this scene lets through to the cartridge while no macro is running + /// and nothing is bound, as a joypad mask; 0 for every scene but the one that is typed on. + /// + /// Row 69 (`docs/design/macros.md` 12.32): the naming screen is spelled with the D-pad, A, B + /// and START, and its pad is those buttons rather than a macro per key. The title's raw + /// buttons are not this field -- a scene that is not playable passes all of them, by section 2. + pub raw: u8, } /// How a macro ended: `docs/design/macros.md` section 5's `outcome` field. diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/fake_wram.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/fake_wram.rs index 16e370e..1a01f6c 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/fake_wram.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/fake_wram.rs @@ -238,6 +238,23 @@ impl Wram { self.set(ram::wFontLoaded, poke::BIT_FONT_LOADED).draw_box(0, 12, 19, 17) } + /// The naming screen as `DisplayNamingScreen` leaves it (row 69): the keyboard's box at + /// (0, 4)-(19, 14), `capacity` underscores from (10, 3) with the raised one under the next + /// letter, the keyboard's menu bytes, and `length` letters typed. + pub fn naming_screen(&mut self, length: u8, capacity: u8) -> &mut Self { + let (left, top, right, bottom) = poke::NAMING_BOX; + self.draw_box(left, top, right, bottom); + let (x, y) = poke::NAMING_UNDERSCORES; + for place in 0..u16::from(capacity) { + let raised = place == u16::from(length.min(capacity - 1)); + let tile = + if raised { poke::NAMING_UNDERSCORE_RAISED } else { poke::NAMING_UNDERSCORE }; + self.screen_tile(x + place, y, tile); + } + self.cursor(poke::NAMING_TOP_Y, 1, 1, poke::NAMING_MAX_ITEM, 0xff) + .set(poke::NAMING_LENGTH, length) + } + /// The two-option YES/NO box where a Pokémon Center's script draws it (row 41): the box at /// (11, 6)-(19, 11) over the dialogue box, with the cursor parked in its first interior column. pub fn yes_no_prompt(&mut self) -> &mut Self { diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs index 15622e2..5eb6046 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs @@ -637,6 +637,12 @@ pub trait MacroState: GameState { true } + /// The naming screen, when it is up (row 69). `None` for any other screen, and for a state + /// that cannot read it, so a reader without it deals no naming pad. + fn naming(&mut self) -> Option { + None + } + /// Where the ladder's next unreached rung is, when the adapter's rung catalog knows. /// /// `None` leaves `GO OBJECTIVE` unbound, which is section 9's own fall-through: the plan's diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs index 8760063..733a84b 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs @@ -120,6 +120,9 @@ pub struct PokemonPalette { /// ledgers wrote what it had been aiming at against the new map's id. settled: Option, tear_frames: u16, + /// The brain millisecond the naming screen was first read on, while it is up (row 69, + /// `palette::NAMING_BOUND_MS`). Session state, never checkpointed. + naming_since: Option, /// The brain clock of the frame being decided, from [`MacroPalette::clock`]. /// /// The blocked ledger is a *window*, so it needs the same clock the loop publishes rather @@ -149,6 +152,7 @@ impl PokemonPalette { nearer: false, settled: None, tear_frames: 0, + naming_since: None, now_ms: 0.0, } } @@ -303,11 +307,16 @@ impl MacroPalette for PokemonPalette { } fn observe(&mut self, memory: &mut dyn MemoryReader, ledger: &dyn RunLedger) -> Observed { - let torn = { + let (torn, naming) = { let mut state = PokeState::new(memory); - self.tear(&mut state) + (self.tear(&mut state), state.naming()) }; - let (scene, bindings, standing, stepping, approach) = { + // Row 69: the naming screen's clock. Session state like the ledgers: it starts on the + // first frame the keyboard is read and is dropped on the first frame it is not, so each + // name gets the whole bound and a restore starts it again. + self.naming_since = naming.map(|_| self.naming_since.unwrap_or(self.now_ms)); + let naming_elapsed = self.naming_since.map_or(0.0, |since| (self.now_ms - since).max(0.0)); + let (scene, bindings, raw, standing, stepping, approach) = { let Self { machine, mode, @@ -337,10 +346,15 @@ impl MacroPalette for PokemonPalette { // the `TALK` gave the buttons back, so the machine is given every frame rather than // only the ones it owns (`docs/design/macros.md` section 12.4). machine.observe_frame(&mut state); - let palette = match mode { - PaletteMode::Palette => Palette::for_scene(scene, &mut state), - PaletteMode::Plan => plan::plan_for(scene, &mut state), + let naming = naming.filter(|_| scene == Scene::Unknown); + let palette = match (naming, mode) { + // Row 69: the keyboard's pad is the fly's own buttons until the name is full or + // the bound has run, then `CONFIRM` alone (`palette::naming_set`). + (Some(naming), _) => Palette::for_naming(scene, naming, naming_elapsed), + (None, PaletteMode::Palette) => Palette::for_scene(scene, &mut state), + (None, PaletteMode::Plan) => plan::plan_for(scene, &mut state), }; + let raw = if naming.is_some() { palette::naming_raw(&palette) } else { 0 }; let bindings = bindings(&palette); // Where the fly is standing, for the ledger below. Only on a frame the fly is its own // master: while the cartridge is walking it -- a warp in flight, a ledge hop, a script @@ -359,7 +373,7 @@ impl MacroPalette for PokemonPalette { Some((objective.map, hops)) }); *cached = Some(palette); - (scene, bindings, standing, stepping, approach) + (scene, bindings, raw, standing, stepping, approach) }; // Section 12.7: the macro layer's own answer to "has the run stood here", because the // adapter's reward ledger cannot record a doormat. @@ -411,7 +425,7 @@ impl MacroPalette for PokemonPalette { // The talked entry `observe_frame` may just have earned, into the ledger the next frame // reads. self.record_talk(); - Observed { scene: scene_id(scene), bindings } + Observed { scene: scene_id(scene), bindings, raw } } fn start( diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs index df2c6e8..9f3e6c0 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs @@ -131,6 +131,10 @@ const PROMPT_WAIT: u32 = 360; /// [`PRESS_HOLD`] of A, then released, so the press is a new one each time. const PROMPT_PULSE: u32 = 40; +/// Frames `CONFIRM` on the naming screen waits for the keyboard to close ([`Step::Submit`]). +/// The cartridge whites the screen out over three frames and clears it; four pulses of START fit. +const SUBMIT_WAIT: u32 = 160; + /// Extra presses a cursor navigation may spend beyond twice the length of its list, to cover a /// press the game swallows while a menu is still drawing. const CURSOR_SLACK: u8 = 6; @@ -377,6 +381,11 @@ enum Step { /// [`Step::Prompt`] does and reads the screen every frame, so the menu is caught before the /// next pulse could choose BUY on it. Counter { waited: u32 }, + /// Pulse START until the naming screen is gone, which is the name handed back (row 69); + /// `Blocked` if it is still up after [`SUBMIT_WAIT`] frames. START is `.pressedStart` in + /// `DisplayNamingScreen`, taken on its edge, so each pulse is a new press like + /// [`Step::Prompt`]'s. + Submit { waited: u32 }, } /// Progress through one A* walk. @@ -1607,6 +1616,20 @@ fn advance(step: &mut Step, state: &mut dyn MacroState) -> Progress { Progress::Hold(buttons::NONE) } } + Step::Submit { waited } => { + if state.naming().is_none() { + Progress::Finished + } else if *waited >= SUBMIT_WAIT { + Progress::Blocked + } else { + *waited += 1; + if *waited % PROMPT_PULSE < PRESS_HOLD { + Progress::Hold(buttons::START) + } else { + Progress::Hold(buttons::NONE) + } + } + } Step::Counter { waited } => { if shop_screen(state) == Some(ShopScreen::BuySellQuit) { if stock_index(state, item::POKE_BALL) == Some(0) { @@ -2122,6 +2145,9 @@ fn script( // A is YES and B is NO in every yes/no box Red draws. Agent A's seam reports no cursor // for one, so there is none to read and nothing to navigate: these are the two presses // the table names and no more. + // On the naming screen `CONFIRM` is the bound's one button (row 69): it hands the name + // back with START, whatever the fly has spelled, and is done when the keyboard is gone. + MacroKind::Confirm if state.naming().is_some() => vec![Step::Submit { waited: 0 }], MacroKind::Yes | MacroKind::Confirm => vec![press(buttons::A)], MacroKind::No | MacroKind::Back => vec![press(buttons::B)], MacroKind::Close | MacroKind::Leave => { @@ -2169,7 +2195,8 @@ fn script( // Section 14's addition: the ball comes out of the bag, so the script is `ITEM`'s with a // ball's index instead of a potion's -- and it stops at the confirmation. The throw // animation, the shake count, the "Gotcha!" and the nickname prompt are all text the fly - // answers with the between-turns `NEXT` and the dialog's `NO` (section 12). + // answers with the between-turns `NEXT` (a YES at the prompt), and the keyboard after it + // is the fly's own buttons (row 69, section 12.32). MacroKind::ThrowBall => { let bag_slot = throw_slot(state)?; let mut steps = Vec::new(); diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs index 9ca1e92..21057bf 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs @@ -761,17 +761,17 @@ pub fn route_within(from: Region, to: u8, area: u8) -> bool { false } -/// Which kind of amenity `map` *is*, when it is one. -/// -/// The reverse lookup, and what tells the fly it is standing in a mart rather than in a house: the -/// shop scene's own buttons and the centre's `HEAL` are dealt on this answer rather than on a -/// tileset read, because a map id is a byte the adapter already has and a tileset is not. /// The marts on [`AMENITIES`] whose counter stocks `POKE_BALL` as its first row /// (`data/items/marts.asm` at the pinned commit): Viridian, Pewter and Cerulean all open their buy /// list on it. `BUY BALL` from the floor (row 66) is offered only in these, and its script still /// reads the stock once the counter is open and refuses if the first row is anything else. pub const BALL_FIRST_MARTS: [u8; 3] = [maps::VIRIDIAN_MART, maps::PEWTER_MART, maps::CERULEAN_MART]; +/// Which kind of amenity `map` *is*, when it is one. +/// +/// The reverse lookup, and what tells the fly it is standing in a mart rather than in a house: the +/// shop scene's own buttons and the centre's `HEAL` are dealt on this answer rather than on a +/// tileset read, because a map id is a byte the adapter already has and a tileset is not. pub fn amenity_at(map: u8) -> Option { AMENITIES.iter().find(|(_, _, id)| *id == map).map(|(_, kind, _)| *kind) } diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs index db0b40f..23e40fc 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs @@ -17,7 +17,8 @@ use crate::adapter::PlaceKind; use super::geography::{self, Amenity}; use super::path::{self, Exit, Way}; -use super::state::{BattleMenu, Facing, Mon, Move, Scene, ShopScreen, Status}; +use super::state::{BattleKind, BattleMenu, Facing, Mon, Move, Naming, Scene, ShopScreen, Status}; +use crate::emulator::buttons; /// Slots in one palette: **one per macro type**, so a cell never moves. /// @@ -447,6 +448,24 @@ impl Palette { slots[usize::from(kind.slot())] = Some(MacroSpec::of(kind)); } } + // Row 69, the operator's "throw on low HP only": with `THROW BALL` on this pad and the + // wild Pokémon's HP where a ball's HP factor is already at its best, the ball is the only + // answer on the attack side ([`throw_only`], [`WITHHELD_FOR_THE_THROW`]). + if slots[usize::from(MacroKind::ThrowBall.slot())].is_some() && throw_only(state) { + for kind in WITHHELD_FOR_THE_THROW { + slots[usize::from(kind.slot())] = None; + } + } + Self { scene, slots } + } + + /// The naming screen's pad (row 69, `docs/design/macros.md` 12.32): [`naming_set`] with the + /// session's clock, which [`Palette::for_scene`] does not have. + pub fn for_naming(scene: Scene, naming: Naming, elapsed_ms: f64) -> Self { + let mut slots: [Option; SLOTS] = [None; SLOTS]; + for kind in naming_set(naming, elapsed_ms) { + slots[usize::from(kind.slot())] = Some(MacroSpec::of(kind)); + } Self { scene, slots } } @@ -492,8 +511,14 @@ pub fn scene_set(scene: Scene, state: &mut dyn MacroState) -> Vec { // 47 minutes, 189 of them on map `0x02` with no box on screen at all. So the pad is // empty there and the fly waits, which is the doctrine's own answer for a scene with // nothing sensible to press -- and the cartridge gives the buttons back by itself. + // The naming screen (row 69) is an `Unknown` with a pad of its own: the fly's raw + // buttons, and `CONFIRM` alone once the name is full or the bound has run + // ([`naming_set`]). Asked here with no clock, so only the full name ends it; + // [`Palette::for_naming`] is the same rule with the session's clock. Scene::Unknown => { - if state.text_open() { + if let Some(naming) = state.naming() { + naming_set(naming, 0.0) + } else if state.text_open() { vec![Next, Back] } else { Vec::new() @@ -611,6 +636,113 @@ pub fn scene_set(scene: Scene, state: &mut dyn MacroState) -> Vec { } } +/// How long the fly spells a name before `CONFIRM` is the only button, in brain milliseconds +/// (row 69). +/// +/// The operator's bound: "the stream can't sit on the keyboard forever". A minute is room for the +/// ten letters a Pokémon's name holds at the readout's own pace -- `a` fires at most every 480 ms +/// and a direction is held 800 ms -- several times over, and short enough to be one beat of the +/// stream rather than a stall. +pub const NAMING_BOUND_MS: f64 = 60_000.0; + +/// The fly's own buttons on the naming screen (row 69): the D-pad moves over the keyboard, `A` +/// types the letter under the cursor (or ED, which hands the name back, or the case switch), `B` +/// deletes the last letter, `START` hands the name back. `SELECT` (the case switch as a button) +/// is not the operator's list and is left off. +pub const NAMING_RAW: u8 = buttons::UP + | buttons::DOWN + | buttons::LEFT + | buttons::RIGHT + | buttons::A + | buttons::B + | buttons::START; + +/// The naming screen's macro buttons (row 69): **none** while the fly is spelling, so the pad is +/// its raw buttons ([`NAMING_RAW`]); `CONFIRM` alone once the name is full or [`NAMING_BOUND_MS`] +/// has run since the screen opened, and then the raw buttons are off. +/// +/// Why not `CONFIRM` beside the raw buttons from the start: the macro group decides every 800 ms +/// among the bound buttons and a group of one always has a winner, so a lone `CONFIRM` would hand +/// back an empty name within a second of the keyboard appearing. The fly can end the name itself +/// all along -- ED is a key on the keyboard and `START` is one of its buttons -- and the bound is +/// the only thing that ends it for it. A name handed back empty is the species' own name: that is +/// the cartridge (`AskName.declinedNickname`), not this. +pub fn naming_set(naming: Naming, elapsed_ms: f64) -> Vec { + if naming.full() || elapsed_ms >= NAMING_BOUND_MS { + vec![MacroKind::Confirm] + } else { + Vec::new() + } +} + +/// The raw buttons the naming screen lets through for this pad (row 69): [`NAMING_RAW`] while the +/// pad has no macro button on it, nothing once it has. +pub fn naming_raw(palette: &Palette) -> u8 { + if palette.bound() == 0 { NAMING_RAW } else { 0 } +} + +/// What `THROW BALL` takes off the pad beside it when it is the throw's turn (row 69): every move, +/// `SWITCH`, `RUN`, and the bag's `BACK`. +/// +/// The operator's decision is that the ball is the only *attack-side* answer, and the moves are +/// that side. Of the rest, what stays is `ITEM`: it is only ever dealt for a Pokémon that is out, +/// under half its HP, with a Potion the cartridge would take (section 13.1, row 63), so it is the +/// one non-attack need that keeps the thrower standing while it throws. What goes: +/// +/// - `SWITCH`'s reason is a healthier *fighter*, and there is nothing left to fight for; +/// - `RUN` is bound on the fly's own Pokémon losing, and the enemy is at the weakest it will be: +/// fleeing forfeits the catch the pad exists for, and a whiteout is the cartridge's own end; +/// - `BACK` in the bag leads to the top-level menu, whose pad is the same ball. +pub const WITHHELD_FOR_THE_THROW: [MacroKind; 7] = [ + MacroKind::Move1, + MacroKind::Move2, + MacroKind::Move3, + MacroKind::Move4, + MacroKind::Switch, + MacroKind::Run, + MacroKind::Back, +]; + +/// Whether it is the throw's turn (row 69): a wild battle whose Pokémon has HP left, at or under +/// the HP where the ball the fly would throw has its best odds. +/// +/// **"Low" is the cartridge's own number** (`ItemUseBall`, `engine/items/item_effects.asm`). The +/// HP half of Red's catch test is `W = (MaxHP * 255 / BallFactor) / max(HP / 4, 1)`, floored at +/// each step, with a `BallFactor` of 8 for a Great Ball and 12 for every other; the ball holds +/// when a second random byte is at most `W`, so at `W >= 255` it always holds and HP no longer +/// matters. For a Poké Ball that is HP at about a third of its maximum -- 7 of a Weedle's 20 -- +/// and for a Great Ball about a half. Lower HP buys nothing more; what is left is the catch rate +/// and the status, which the fly's own presses cannot change. So "low" is exactly where the +/// throw stops getting better. The ball is the one [`throw_slot`] would throw; a Master Ball skips +/// the test in the cartridge and is read with a factor of 12 here, which only waits a little. +/// +/// Everything else `THROW BALL` needs is its own precondition ([`throw_slot`]): a wild battle, a +/// ball, room in the party, a species the party does not hold. With no ball left, or a species +/// already caught, the button is off the pad and so is this, and the ordinary pad is back. +pub fn throw_only(state: &mut dyn MacroState) -> bool { + let Some(battle) = state.battle() else { return false }; + if battle.kind != BattleKind::Wild { + return false; + } + let Some(enemy) = battle.enemy else { return false }; + let Some(index) = throw_slot(state) else { return false }; + let Some(ball) = state.bag().get(usize::from(index)).map(|stack| stack.id) else { + return false; + }; + ball_holds_on_hp(enemy.hp, enemy.max_hp, ball) +} + +/// `ItemUseBall`'s HP test, whole: whether `W` reaches 255 for `ball` at this HP (row 69). +pub fn ball_holds_on_hp(hp: u16, max_hp: u16, ball: u8) -> bool { + if hp == 0 || max_hp == 0 || hp > max_hp { + return false; + } + let factor: u32 = if ball == item::GREAT_BALL { 8 } else { 12 }; + // `srl b / rr a` twice and only `a` kept: the low byte of HP / 4, and 1 for a quotient of 0. + let quarter = u32::from((hp >> 2) as u8).max(1); + (u32::from(max_hp) * 255 / factor) / quarter >= 255 +} + /// Section 3's preconditions, one arm each. pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool { match kind { @@ -675,8 +807,8 @@ pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool { move_slot_bound(state, kind) } // Section 14's addition (the operator: "throw pokeball should be a macro"). A wild battle, a ball - // in the bag, and room in the party. No catch-rate and no HP knowledge: when to throw is - // the fly's. + // in the bag, and room in the party. No catch-rate and no HP knowledge here: the enemy's + // HP decides only what else is on the pad beside it (row 69, [`throw_only`]). MacroKind::ThrowBall => throw_slot(state).is_some(), MacroKind::Switch => healthiest_other(state).is_some(), // ...and a Potion the cartridge would take (row 63): `ItemUseMedicine` answers "It won't diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs index 245fdb2..853c01d 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs @@ -269,6 +269,31 @@ pub struct TextBox { pub waiting: bool, } +/// The naming screen, while it is up (`DisplayNamingScreen`, `engine/menus/naming_screen.asm`; +/// row 69, `docs/design/macros.md` 12.32). +/// +/// The keyboard the cartridge draws for a Pokémon's nickname, the Name Rater, and the player's and +/// rival's names at the start of a game. The last two are before the game timer starts and read +/// as the title (section 2), so this is only ever asked of the first two in practice. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Naming { + /// Letters typed so far (`wNamingScreenNameLength`). + pub length: u8, + /// How many letters the name can hold: ten for a Pokémon, seven for the player or the rival + /// (`NAME_LENGTH - 1`, `PLAYER_NAME_LENGTH - 1`), counted from the underscores on screen. + pub capacity: u8, + /// START or ED has been taken and the name is being handed back (`wNamingScreenSubmitName`). + pub submitted: bool, +} + +impl Naming { + /// Whether no further letter fits. The cartridge moves the cursor onto ED itself then + /// (`PrintNicknameAndUnderscores`), and an A press on a letter adds nothing. + pub fn full(self) -> bool { + self.length >= self.capacity + } +} + /// A menu cursor, as `HandleMenuInput` keeps it. Shared by every menu in the game. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Cursor { diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs index 4258eae..0188ebb 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs @@ -32,13 +32,15 @@ use super::palette::{ healthiest_other, heal_goals, inside_center, nurse_prompt, rested_nurse, service_needed, listing, losing, move_slot_bound, objective_goals, party_needs_rest, party_rested, poke_sprite, precondition, throw_slot, untalked_objects, untalked_people, ways, + NAMING_BOUND_MS, NAMING_RAW, WITHHELD_FOR_THE_THROW, ball_holds_on_hp, naming_raw, naming_set, + throw_only, }; use super::path::{self, Exit, Way}; use super::super::maps; use super::plan; use super::state::{ Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, MapSize, - Mon, Move, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, Status, TextBox, + Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, Status, TextBox, Walkable, Warp, }; @@ -184,6 +186,11 @@ struct World { heal_at: Option, /// Oak has not been given the parcel yet (row 66); false in every fixture unless set. parcel_undelivered: bool, + /// The naming screen, while it is up (row 69). A START press on it hands the name back and + /// closes it, as `DisplayNamingScreen.pressedStart` does. + naming: Option, + /// A keyboard that never closes, for the bound on `CONFIRM`'s own wait. + glue_naming: bool, /// Whether a text box is drawn on a scene that is not [`Scene::Dialog`] /// ([`MacroState::text_open`]). /// @@ -306,6 +313,8 @@ impl World { switch: None, heal_at: None, parcel_undelivered: false, + naming: None, + glue_naming: false, box_open: false, prompt: false, price_after: None, @@ -533,6 +542,10 @@ impl World { } fn on_pulse(&mut self, mask: u8) { + // The keyboard hands the name back on START and closes (row 69), unless glued. + if mask == buttons::START && self.naming.is_some() && !self.glue_naming { + self.naming = None; + } if self.scene == Scene::Overworld { if mask == buttons::START { self.start_to_open = self.start_to_open.saturating_sub(1); @@ -887,6 +900,10 @@ impl MacroState for World { !self.parcel_undelivered } + fn naming(&mut self) -> Option { + self.naming + } + fn refused_here(&mut self, slot: u8) -> bool { self.targets.refused(self.map, slot, self.player) } @@ -4891,8 +4908,8 @@ fn the_last_resort_prefers_the_exit_toward_the_objective() { /// Section 14's `THROW BALL` (the operator: "throw pokeball should be a macro"). /// /// The precondition is three facts and no judgement: a wild battle, a ball in the bag, and room in -/// the party. When to throw is the fly's -- there is no catch-rate and no enemy-HP knowledge here, -/// and there is none anywhere in this crate. +/// the party. There is no catch-rate and no enemy-HP knowledge in this precondition; since row 69 +/// the enemy's HP decides only what else is dealt beside the ball (`palette::throw_only`). #[test] fn throw_ball_needs_a_wild_battle_a_ball_and_room_in_the_party() { let mut world = World::battle(); @@ -6388,3 +6405,213 @@ fn a_same_map_teleport_is_somewhere_the_way_out_took_the_fly() { dead.duds = world.duds.clone(); assert_eq!(run(&mut dead, MacroKind::GoWarp), Ok(MacroAbort::Blocked)); } + + +// --------------------------------------------------------------------------------------------- +// Row 69 (the operator, 2026-09-29): "throw on low HP only" and "let the fly name it". +// --------------------------------------------------------------------------------------------- + +fn pad_kinds(world: &mut World) -> Vec { + let scene = world.scene(); + plan::plan_for(scene, world).slots.iter().flatten().map(|spec| spec.kind).collect() +} + +/// `ItemUseBall`'s HP half, number for number (`engine/items/item_effects.asm`): +/// `W = (MaxHP * 255 / BallFactor) / max(HP / 4, 1)`, the ball holds on HP when `W >= 255`. +#[test] +fn row69_low_is_where_the_balls_hp_factor_is_at_its_best() { + // A Weedle's 20: 20 * 255 / 12 = 425; HP 7 -> 425 / 1 = 425, HP 8 -> 425 / 2 = 212. + assert!(ball_holds_on_hp(7, 20, item::POKE_BALL)); + assert!(!ball_holds_on_hp(8, 20, item::POKE_BALL)); + assert!(ball_holds_on_hp(1, 20, item::POKE_BALL)); + // A Great Ball's factor is 8: 20 * 255 / 8 = 637; HP 11 -> 637 / 2 = 318, HP 12 -> 212. + assert!(ball_holds_on_hp(11, 20, item::GREAT_BALL)); + assert!(!ball_holds_on_hp(12, 20, item::GREAT_BALL)); + // Every other ball reads with 12, as the cartridge's does. + assert!(!ball_holds_on_hp(8, 20, item::ULTRA_BALL)); + // A third, near enough, at any size: 120 * 255 / 12 = 2550; HP 40 -> 2550 / 10 = 255. + assert!(ball_holds_on_hp(40, 120, item::POKE_BALL)); + assert!(!ball_holds_on_hp(44, 120, item::POKE_BALL)); + // Fainted, full, or nothing read: never. + assert!(!ball_holds_on_hp(0, 20, item::POKE_BALL)); + assert!(!ball_holds_on_hp(20, 20, item::POKE_BALL)); + assert!(!ball_holds_on_hp(5, 0, item::POKE_BALL)); +} + +/// The throw's turn: a wild battle, a ball `THROW BALL` would throw, an enemy at low HP. Then the +/// ball is the only attack-side button; above it the pad is the ordinary one. +#[test] +fn row69_at_low_hp_in_a_wild_battle_the_ball_is_the_only_attack() { + let mut world = World::battle(); + world.mons.truncate(1); + world.mons[0].hp = 20; + world.bag = vec![(item::POKE_BALL, 2)]; + world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 20, max_hp: 20 }); + + // Full HP: the ordinary pad, moves and the ball side by side. + assert!(!throw_only(&mut world)); + let pad = pad_kinds(&mut world); + assert!(pad.contains(&MacroKind::Move1) && pad.contains(&MacroKind::ThrowBall), "{pad:?}"); + + // Low HP: the ball alone. + world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 7, max_hp: 20 }); + assert!(throw_only(&mut world)); + assert_eq!(pad_kinds(&mut world), vec![MacroKind::ThrowBall]); + for kind in WITHHELD_FOR_THE_THROW { + assert!(!on_the_pad(&mut world, kind), "{} withheld", kind.name()); + } +} + +/// `ITEM` stays beside the ball: a hurt Pokémon out with a Potion the cartridge would take is the +/// one non-attack need kept. `SWITCH` and `RUN` go. +#[test] +fn row69_the_throws_pad_keeps_a_potion_for_a_hurt_thrower_and_nothing_else() { + let mut world = World::battle(); + // The Pokémon out is at 4 of 20 with a healthy reserve: SWITCH, RUN (losing) and ITEM are all + // dealt on the ordinary pad. + world.bag = vec![(item::POTION, 1), (item::POKE_BALL, 1)]; + world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 20, max_hp: 20 }); + let ordinary = pad_kinds(&mut world); + assert!(ordinary.contains(&MacroKind::Switch), "{ordinary:?}"); + assert!(ordinary.contains(&MacroKind::Item), "{ordinary:?}"); + + world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 3, max_hp: 20 }); + let pad = pad_kinds(&mut world); + assert_eq!(pad, vec![MacroKind::Item, MacroKind::ThrowBall]); +} + +/// Every way out of the rule returns the ordinary pad: a trainer's Pokémon, no ball left, a +/// species the party holds, a full party, a fainted enemy, nothing read. +#[test] +fn row69_the_ordinary_pad_comes_back_whenever_the_ball_cannot_be_thrown() { + let low = Some(EnemyMon { species: 0x70, level: 6, hp: 2, max_hp: 20 }); + let base = || { + let mut world = World::battle(); + world.mons.truncate(1); + world.mons[0].hp = 20; + world.bag = vec![(item::POKE_BALL, 1)]; + world.enemy = low; + world + }; + let mut world = base(); + assert_eq!(pad_kinds(&mut world), vec![MacroKind::ThrowBall]); + + let mut trainer = base(); + trainer.battle = Some((BattleKind::Trainer, true, false)); + assert!(!throw_only(&mut trainer)); + assert!(on_the_pad(&mut trainer, MacroKind::Move1), "a trainer's battle is never the throw's"); + + let mut spent = base(); + spent.bag = vec![(item::POKE_BALL, 0)]; + assert!(!throw_only(&mut spent)); + assert!(on_the_pad(&mut spent, MacroKind::Move1), "no ball, the moves are back"); + + let mut owned = base(); + owned.mons[0].species = 0x70; + assert!(!throw_only(&mut owned)); + assert!(on_the_pad(&mut owned, MacroKind::Move1), "a species already caught"); + + let mut full = base(); + full.mons = (0..6).map(|slot| mon(slot, 20, 20, &[(33, 30)])).collect(); + full.active = Some(0); + assert!(!throw_only(&mut full)); + + let mut fainted = base(); + fainted.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 0, max_hp: 20 }); + assert!(!throw_only(&mut fainted)); + + let mut unread = base(); + unread.enemy = None; + assert!(!throw_only(&mut unread), "HP the seam cannot read is not low"); + assert!(on_the_pad(&mut unread, MacroKind::Move1)); +} + +/// In the bag, the throw's pad is the ball (and a Potion for a hurt thrower); `BACK` would lead to +/// the menu whose pad is the same ball. +#[test] +fn row69_in_the_bag_at_low_hp_back_is_withheld() { + let mut world = World::battle(); + world.mons.truncate(1); + world.mons[0].hp = 20; + world.bag = vec![(item::POKE_BALL, 1)]; + world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 20, max_hp: 20 }); + world.list = List::BattleBag; + world.cursor_max = 1; + world.grid = false; + assert!(on_the_pad(&mut world, MacroKind::Back)); + world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 5, max_hp: 20 }); + assert_eq!(pad_kinds(&mut world), vec![MacroKind::ThrowBall]); +} + +/// A failed throw is an ordinary turn: the pad between turns is `NEXT` and the next own turn is +/// the throw's again while a ball is left. Nothing here keeps a count. +#[test] +fn row69_between_turns_the_pad_is_next_whatever_the_hp() { + let mut world = World::battle(); + world.bag = vec![(item::POKE_BALL, 1)]; + world.enemy = Some(EnemyMon { species: 0x70, level: 6, hp: 2, max_hp: 20 }); + world.scene = Scene::Battle { own_turn: false, forced_switch: false }; + world.list = List::None; + assert_eq!(pad_kinds(&mut world), vec![MacroKind::Next]); +} + +fn keyboard(length: u8, capacity: u8) -> Naming { + Naming { length, capacity, submitted: false } +} + +/// The naming screen's pad: nothing bound while the fly spells (its raw buttons are the pad), +/// `CONFIRM` alone once the name is full or the bound has run. +#[test] +fn row69_the_keyboard_is_the_flys_own_buttons_until_the_name_is_full_or_the_bound_runs() { + assert!(naming_set(keyboard(0, 10), 0.0).is_empty()); + assert!(naming_set(keyboard(9, 10), NAMING_BOUND_MS - 1.0).is_empty()); + assert_eq!(naming_set(keyboard(10, 10), 0.0), vec![MacroKind::Confirm], "full"); + assert_eq!(naming_set(keyboard(7, 7), 0.0), vec![MacroKind::Confirm], "a player's seven"); + assert_eq!(naming_set(keyboard(3, 10), NAMING_BOUND_MS), vec![MacroKind::Confirm], "bound"); + + let spelling = Palette::for_naming(Scene::Unknown, keyboard(2, 10), 1_000.0); + assert_eq!(spelling.bound(), 0); + assert_eq!(naming_raw(&spelling), NAMING_RAW); + assert_eq!( + NAMING_RAW, + buttons::UP | buttons::DOWN | buttons::LEFT | buttons::RIGHT | buttons::A | buttons::B + | buttons::START, + "the D-pad, A, B and START; not SELECT" + ); + let ending = Palette::for_naming(Scene::Unknown, keyboard(2, 10), NAMING_BOUND_MS); + assert_eq!(ending.bound(), 1); + assert_eq!(naming_raw(&ending), 0, "once CONFIRM is dealt the raw buttons are off"); + + // The dealer without a clock: the same screen reads as the fly's own buttons, and the plain + // `Unknown` pad (`NEXT`, `BACK`) is not dealt on it. + let mut world = World::room(); + world.scene = Scene::Unknown; + world.box_open = true; + assert_eq!(pad_kinds(&mut world), vec![MacroKind::Next, MacroKind::Back]); + world.naming = Some(keyboard(1, 10)); + assert!(pad_kinds(&mut world).is_empty()); + world.naming = Some(keyboard(10, 10)); + assert_eq!(pad_kinds(&mut world), vec![MacroKind::Confirm]); +} + +/// `CONFIRM` on the keyboard hands the name back with START and is done when the screen is gone. +#[test] +fn row69_confirm_on_the_keyboard_presses_start_until_it_closes() { + let mut world = World::room(); + world.scene = Scene::Unknown; + world.naming = Some(keyboard(10, 10)); + assert_eq!(run(&mut world, MacroKind::Confirm).unwrap(), MacroAbort::Done); + assert!(world.naming.is_none()); + assert!(world.pulses.contains(&buttons::START), "{:?}", world.pulses); + assert!(!world.pulses.contains(&buttons::A), "not the A that types a letter"); +} + +/// And a keyboard that never closes is `blocked`, not a macro that holds the pad for ever. +#[test] +fn row69_confirm_on_a_keyboard_that_does_not_close_is_blocked() { + let mut world = World::room(); + world.scene = Scene::Unknown; + world.naming = Some(keyboard(10, 10)); + world.glue_naming = true; + assert_eq!(run(&mut world, MacroKind::Confirm).unwrap(), MacroAbort::Blocked); +} diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/scene.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/scene.rs index 2dc18f2..f7df056 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/scene.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/scene.rs @@ -30,7 +30,9 @@ use super::symbols::ram; /// The order of the tests is the contract: /// /// 1. **Not started** — `wStatusFlags6`'s game-timer bit is clear, so the cartridge is on the -/// title, in the intro or on a naming screen: [`Scene::Title`]. +/// title, in the intro or on a naming screen: [`Scene::Title`]. After it, **the naming +/// screen** once the game has started -- the keyboard, in or out of a battle -- is +/// [`Scene::Unknown`], whose pad the palette deals from [`state::naming_screen`] (row 69). /// 2. **Not readable** — the map header or the party count is outside its range, which is what a /// frame in the middle of a load or a warp looks like: [`Scene::Unknown`]. /// 3. **Battle** — `wIsInBattle` says a wild or trainer battle is running: @@ -47,6 +49,13 @@ pub fn detect(memory: &mut dyn MemoryReader) -> Scene { if !state::started(memory) { return Scene::Title; } + // The naming screen (row 69) before the battle test: a nickname is typed with `wIsInBattle` + // still set, and the keyboard is no battle menu. It has no scene of its own on the feed's + // closed set; it is the `Unknown` that 13.1 already listed it under, and its pad is the fly's + // own buttons (`docs/design/macros.md` 12.32). + if state::naming_screen(memory).is_some() { + return Scene::Unknown; + } if state::map_size(memory).is_none() || memory.read8(ram::wPartyCount) > 6 { return Scene::Unknown; } diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs index 958ca39..b9bcb5f 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs @@ -33,7 +33,7 @@ use super::macros::geography::Amenity; use super::mapgrid::{self, MapGrids}; use super::macros::state::{ BagItem, Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, - MapGrid, MapSize, Mon, Move, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, + MapGrid, MapSize, Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, Status, TextBox, Walkable, Warp, }; use super::symbols::ram; @@ -128,6 +128,30 @@ pub mod poke { pub const MOVE_LIST_CURSOR_Y: u8 = 12; pub const MOVE_LIST_CURSOR_X: u8 = 5; + /// The naming screen (row 69, `engine/menus/naming_screen.asm`). + /// + /// `wNamingScreenNameLength` and `wNamingScreenSubmitName` are two consecutive bytes in a + /// `UNION` of `ram/wram.asm` and are not in the reviewed address list, so they are pinned the + /// way `H_JOY_LAST` is: read from the operands of the cartridge's own instructions and checked + /// by the ROM-gated test. `PrintNicknameAndUnderscores` opens `call CalcStringLength / ld a, c + /// / ld [wNamingScreenNameLength], a / hlcoord 10, 2`, whose store is `$CEE9`, and + /// `DisplayNamingScreen.pressedStart` is `ld a, 1 / ld [wNamingScreenSubmitName], a / ret`, + /// whose store is `$CEEA`, the next byte. + pub const NAMING_LENGTH: u16 = 0xcee9; + pub const NAMING_SUBMIT: u16 = 0xceea; + /// `DisplayNamingScreen`'s box: `TextBoxBorder` at (0, 4), nine rows by eighteen, so its + /// corners are (0, 4) and (19, 14). The keyboard is inside it. + pub const NAMING_BOX: (u16, u16, u16, u16) = (0, 4, 19, 14); + /// Where the underscores under the name start (`hlcoord 10, 3`), and their two tiles: `$76` + /// for an empty place and `$77` for the raised one under the next letter. + pub const NAMING_UNDERSCORES: (u16, u16) = (10, 3); + pub const NAMING_UNDERSCORE: u8 = 0x76; + pub const NAMING_UNDERSCORE_RAISED: u8 = 0x77; + /// The keyboard's menu: `wTopMenuItemY` 3, `wMaxMenuItem` 7 and every key watched (`$ff`), + /// written once by `DisplayNamingScreen` and by nothing else in the game in that combination. + pub const NAMING_TOP_Y: u8 = 3; + pub const NAMING_MAX_ITEM: u8 = 7; + /// `constants/ram_constants.asm`: `wMiscFlags` bit 3. pub const BIT_USING_GENERIC_PC: u8 = 1 << 3; /// `wFontLoaded` bit 0. @@ -1044,6 +1068,49 @@ pub fn yes_no_prompt(memory: &mut dyn MemoryReader) -> bool { two_option_box_drawn(memory, cursor.top_x, cursor.top_y) } +/// The naming screen, when it is up (row 69, `docs/design/macros.md` 12.32). +/// +/// Red has no "the keyboard is open" byte, so this is the construction `yes_no_prompt` makes: the +/// menu bytes `DisplayNamingScreen` writes (`wTopMenuItemY` 3, `wMaxMenuItem` 7, every key +/// watched), **and** the figure it draws -- the keyboard's whole `TextBoxBorder` at (0, 4)-(19, 14) +/// and the underscores under the name at (10, 3). Both halves, because the menu bytes are not +/// cleared when the screen closes. +/// +/// The capacity is the underscores counted on screen (seven or ten), and the length is +/// `wNamingScreenNameLength`, which `PrintNicknameAndUnderscores` writes after every key that +/// changes the name. +pub fn naming_screen(memory: &mut dyn MemoryReader) -> Option { + let cursor = cursor(memory); + if cursor.top_y != poke::NAMING_TOP_Y + || cursor.max != poke::NAMING_MAX_ITEM + || cursor.watched_keys != 0xff + { + return None; + } + let (left, top, right, bottom) = poke::NAMING_BOX; + if !border_drawn(memory, left, top, right, bottom) { + return None; + } + let (x, y) = poke::NAMING_UNDERSCORES; + let capacity = (x..poke::SCREEN_WIDTH) + .take_while(|column| { + matches!( + screen_tile(memory, *column, y), + poke::NAMING_UNDERSCORE | poke::NAMING_UNDERSCORE_RAISED + ) + }) + .count(); + // `PLAYER_NAME_LENGTH - 1` or `NAME_LENGTH - 1`: nothing else is the keyboard. + if capacity != 7 && capacity != 10 { + return None; + } + Some(Naming { + length: read(memory, poke::NAMING_LENGTH), + capacity: capacity as u8, + submitted: read(memory, poke::NAMING_SUBMIT) != 0, + }) +} + /// Whether `DisplayTwoOptionMenu`'s own box is drawn around the cursor the game parked in it. /// /// One fact about the routine rather than about any one script (row 56): the cursor goes in the @@ -1076,6 +1143,12 @@ fn two_option_box_drawn(memory: &mut dyn MemoryReader, cursor_x: u8, cursor_y: u }) } +/// Whether the battle bag's list box is whole on screen ([`poke::ITEM_LIST_BOX`], row 66). +fn item_list_drawn(memory: &mut dyn MemoryReader) -> bool { + let (left, top, right, bottom) = poke::ITEM_LIST_BOX; + border_drawn(memory, left, top, right, bottom) +} + /// Whether `MoveSelectionMenu`'s own box is the figure on screen (`infra/docs/macros-traps.md`, /// row 50). /// @@ -1094,12 +1167,6 @@ fn two_option_box_drawn(memory: &mut dyn MemoryReader, cursor_x: u8, cursor_y: u /// becomes a horizontal run and (10, 12) becomes the `┘` junction with the PP box above. The /// mimic and relearn menus draw at row 7 and never reach a battle's own turn. Read whole, like /// every other box in this module, because a single tile id is an ordinary character. -/// Whether the battle bag's list box is whole on screen ([`poke::ITEM_LIST_BOX`], row 66). -fn item_list_drawn(memory: &mut dyn MemoryReader) -> bool { - let (left, top, right, bottom) = poke::ITEM_LIST_BOX; - border_drawn(memory, left, top, right, bottom) -} - fn move_list_drawn(memory: &mut dyn MemoryReader) -> bool { let (left, top, right, bottom) = poke::MOVE_LIST_BOX; if screen_tile(memory, left, top) != poke::frame::HORIZONTAL @@ -2345,6 +2412,11 @@ impl MacroState for PokeState<'_> { read(self.memory, ram::wEventFlags + (bit >> 3)) & (1 << (bit & 7)) != 0 } + /// The naming screen (row 69), [`naming_screen`]. + fn naming(&mut self) -> Option { + naming_screen(self.memory) + } + /// Where the ladder's next unreached rung is (`GO OBJECTIVE`). /// /// The adapter's [`crate::adapter::MapPlace`] in the executor's own types, which is the only diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs index a461e0b..b08bfdc 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs @@ -1372,3 +1372,43 @@ fn the_joypad_latch_is_hjoylast_bit_zero() { wram.set(poke::H_JOY_LAST, poke::pad::DOWN); assert!(!a_latched(&mut wram), "a direction down is not an A down"); } + +/// Row 69: the naming screen is the keyboard's menu bytes **and** its figure on screen. +#[test] +fn the_naming_screen_is_its_menu_and_its_box_and_its_underscores() { + let mut wram = Wram::new(); + wram.started().naming_screen(3, 10); + let naming = naming_screen(&mut wram).expect("the keyboard"); + assert_eq!((naming.length, naming.capacity, naming.submitted), (3, 10, false)); + assert!(!naming.full()); + + let mut wram = Wram::new(); + wram.started().naming_screen(7, 7); + assert!(naming_screen(&mut wram).expect("a player's keyboard").full()); + + let mut wram = Wram::new(); + wram.started().naming_screen(0, 10).set(poke::NAMING_SUBMIT, 1); + assert!(naming_screen(&mut wram).unwrap().submitted); + + // The menu bytes outlive the screen: with the box cleared it is not the keyboard. + let mut wram = Wram::new(); + wram.started().naming_screen(3, 10).fill_screen(0x7f); + assert_eq!(naming_screen(&mut wram), None); + + // And another menu with every key watched is not it either. + let mut wram = Wram::new(); + wram.started().naming_screen(3, 10).cursor(3, 1, 1, 6, 0xff); + assert_eq!(naming_screen(&mut wram), None); +} + +/// Row 69: the keyboard is `Unknown` even inside a battle, where a nickname is typed. +#[test] +fn the_naming_screen_reads_unknown_in_a_battle_and_title_before_the_game() { + let mut wram = Wram::new(); + wram.started().battle(1).naming_screen(0, 10); + assert_eq!(crate::pokemon_red::scene::detect(&mut wram), Scene::Unknown); + // The player's name at the start of the game is before the game timer: the title's raw pad. + let mut wram = Wram::new(); + wram.naming_screen(0, 7); + assert_eq!(crate::pokemon_red::scene::detect(&mut wram), Scene::Title); +} diff --git a/services/flysim/crates/flysim/src/macros.rs b/services/flysim/crates/flysim/src/macros.rs index 95f5be5..d3395dc 100644 --- a/services/flysim/crates/flysim/src/macros.rs +++ b/services/flysim/crates/flysim/src/macros.rs @@ -184,6 +184,8 @@ pub struct MacroLayer { last_decision_ms: Option, scene: SceneId, bindings: Vec, + /// The raw buttons the last observation lets through ([`flybrain_gb::Observed::raw`]). + raw: u8, running: Option, finished: Option, /// The brain millisecond the pad became empty in a playable scene, or `None` while it has @@ -241,6 +243,7 @@ impl MacroLayer { // `observe` has not happened and guessing the intro would be a guess. scene: SceneId::Unknown, bindings: Vec::new(), + raw: 0, running: None, finished: None, pad_empty_since_ms: None, @@ -285,6 +288,18 @@ impl MacroLayer { }; } + // Row 69: a scene typed on with the fly's own buttons (the naming screen). With nothing + // bound and nothing running, the readout's buttons reach the cartridge through the + // scene's mask, exactly as the title's do; the macro group has nothing to choose from. + if self.raw != 0 && self.bindings.is_empty() && self.running.is_none() { + let mask = raw_mask & u32::from(self.raw); + return Decision { + mask, + events: Vec::new(), + silence: (mask == 0).then_some(Silence::Channels), + }; + } + // Rule one: a running macro owns the buttons, whatever the channels are doing. Its own // `step` ends it on a scene change or at the frame cap. if let Some(running) = self.running { @@ -377,6 +392,7 @@ impl MacroLayer { let observed = self.palette.observe(memory, ledger); self.scene = observed.scene; self.bindings = observed.bindings; + self.raw = observed.raw; self.watch_pad(ms); let mut decision = Decision::default(); if !self.scene.playable() @@ -415,7 +431,11 @@ impl MacroLayer { /// Only a *playable* scene counts: the title screen deals no palette by contract (section 2), /// and raw mode has no palette at all, so neither is an empty pad in the sense that matters. fn watch_pad(&mut self, ms: f64) { - let empty = self.scene.playable() && self.bindings.is_empty() && self.running.is_none(); + // A scene whose pad is the fly's own buttons (row 69) is not empty. + let empty = self.scene.playable() + && self.bindings.is_empty() + && self.raw == 0 + && self.running.is_none(); match (empty, self.pad_empty_since_ms) { (false, _) => self.pad_empty_since_ms = None, (true, None) => self.pad_empty_since_ms = Some(ms), @@ -436,6 +456,12 @@ impl MacroLayer { } } + /// The fly's own buttons the last observation lets through while nothing is bound (row 69's + /// naming screen), as a joypad mask; 0 in every other scene. For a survey line and the tests. + pub fn raw_buttons(&self) -> u8 { + self.raw + } + /// The scene the last [`MacroLayer::observe`] found. pub fn scene(&self) -> FeedScene { FeedScene::from_adapter(self.scene) @@ -612,6 +638,8 @@ mod tests { /// Name sets the next `observe`s use instead, oldest first: a plan whose head changes. rename: Vec>, bound: Vec, + /// The raw buttons the scene lets through (row 69). + raw: u8, /// Masks `step` returns, in order; a `None` ends the macro. plan: Vec>, running: Option<&'static str>, @@ -629,6 +657,7 @@ mod tests { names: Vec::new(), rename: Vec::new(), bound: Vec::new(), + raw: 0, plan: Vec::new(), running: None, finished: None, @@ -652,6 +681,7 @@ mod tests { } Observed { scene: self.scene, + raw: self.raw, bindings: self .bound .iter() @@ -924,6 +954,36 @@ mod tests { assert_eq!(layer.counts().done, 1); } + /// Row 69: the naming screen's pad is the fly's own buttons, through the scene's mask, while + /// nothing is bound; it is not an empty pad; and once a button is bound the raw path is shut. + #[test] + fn a_scene_typed_on_passes_the_raw_buttons_through_its_mask_while_nothing_is_bound() { + let naming = 0b0111_1111; + let mut layer = layer(Fake { scene: SceneId::Unknown, raw: naming, ..Fake::default() }); + // Up and A, pressed by the readout: through. Select: not in the mask. + let decision = decide(&mut layer, &channels(&["up", "a"]), 0b0001_0001, 0.0); + assert_eq!(decision.mask, 0b0001_0001); + assert!(decision.events.is_empty()); + let decision = decide(&mut layer, &channels(&["select"]), 0b1000_0000, 16.0); + assert_eq!(decision.mask, 0, "SELECT is not one of the keyboard's buttons"); + assert_eq!(decision.silence, Some(Silence::Channels)); + layer.observe(&mut Zeroes, &NoLedger, 1_000.0); + assert_eq!(layer.pad_empty_ms(9_000.0), 0.0, "the fly's own buttons are a pad"); + + // A bound button (the bound's `CONFIRM`) shuts the raw path: only the macro can press. + let mut ending = super::tests::layer(Fake { + scene: SceneId::Unknown, + raw: 0, + bound: vec![0], + plan: vec![Some(0b0100_0000), None], + ..Fake::default() + }); + let decision = decide(&mut ending, &channels(&["up"]), 0b0000_0001, 0.0); + assert_eq!(decision.mask, 0, "raw UP does not reach the cartridge beside a bound button"); + let decision = decide(&mut ending, &holding(0), 0b0000_0001, 16.0); + assert_eq!(decision.mask, 0b0100_0000, "the macro's START"); + } + #[test] fn the_title_screen_presses_the_raw_mask_and_runs_no_macro() { let mut layer = layer(Fake { scene: SceneId::Title, ..Fake::default() });