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).
This commit is contained in:
acamilo 2026-09-29 18:07:15 +00:00
parent a69a258edd
commit e006db3742
13 changed files with 666 additions and 30 deletions

View file

@ -188,6 +188,13 @@ pub struct SlotBinding {
pub struct Observed { pub struct Observed {
pub scene: SceneId, pub scene: SceneId,
pub bindings: Vec<SlotBinding>, pub bindings: Vec<SlotBinding>,
/// 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. /// How a macro ended: `docs/design/macros.md` section 5's `outcome` field.

View file

@ -238,6 +238,23 @@ impl Wram {
self.set(ram::wFontLoaded, poke::BIT_FONT_LOADED).draw_box(0, 12, 19, 17) 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 /// 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. /// (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 { pub fn yes_no_prompt(&mut self) -> &mut Self {

View file

@ -637,6 +637,12 @@ pub trait MacroState: GameState {
true 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<super::state::Naming> {
None
}
/// Where the ladder's next unreached rung is, when the adapter's rung catalog knows. /// 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 /// `None` leaves `GO OBJECTIVE` unbound, which is section 9's own fall-through: the plan's

View file

@ -120,6 +120,9 @@ pub struct PokemonPalette {
/// ledgers wrote what it had been aiming at against the new map's id. /// ledgers wrote what it had been aiming at against the new map's id.
settled: Option<u8>, settled: Option<u8>,
tear_frames: u16, 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<f64>,
/// The brain clock of the frame being decided, from [`MacroPalette::clock`]. /// 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 /// The blocked ledger is a *window*, so it needs the same clock the loop publishes rather
@ -149,6 +152,7 @@ impl PokemonPalette {
nearer: false, nearer: false,
settled: None, settled: None,
tear_frames: 0, tear_frames: 0,
naming_since: None,
now_ms: 0.0, now_ms: 0.0,
} }
} }
@ -303,11 +307,16 @@ impl MacroPalette for PokemonPalette {
} }
fn observe(&mut self, memory: &mut dyn MemoryReader, ledger: &dyn RunLedger) -> Observed { fn observe(&mut self, memory: &mut dyn MemoryReader, ledger: &dyn RunLedger) -> Observed {
let torn = { let (torn, naming) = {
let mut state = PokeState::new(memory); 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 { let Self {
machine, machine,
mode, mode,
@ -337,10 +346,15 @@ impl MacroPalette for PokemonPalette {
// the `TALK` gave the buttons back, so the machine is given every frame rather than // 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). // only the ones it owns (`docs/design/macros.md` section 12.4).
machine.observe_frame(&mut state); machine.observe_frame(&mut state);
let palette = match mode { let naming = naming.filter(|_| scene == Scene::Unknown);
PaletteMode::Palette => Palette::for_scene(scene, &mut state), let palette = match (naming, mode) {
PaletteMode::Plan => plan::plan_for(scene, &mut state), // 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); let bindings = bindings(&palette);
// Where the fly is standing, for the ledger below. Only on a frame the fly is its own // 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 // 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)) Some((objective.map, hops))
}); });
*cached = Some(palette); *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 // 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. // 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 // The talked entry `observe_frame` may just have earned, into the ledger the next frame
// reads. // reads.
self.record_talk(); self.record_talk();
Observed { scene: scene_id(scene), bindings } Observed { scene: scene_id(scene), bindings, raw }
} }
fn start( fn start(

View file

@ -131,6 +131,10 @@ const PROMPT_WAIT: u32 = 360;
/// [`PRESS_HOLD`] of A, then released, so the press is a new one each time. /// [`PRESS_HOLD`] of A, then released, so the press is a new one each time.
const PROMPT_PULSE: u32 = 40; 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 /// 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. /// press the game swallows while a menu is still drawing.
const CURSOR_SLACK: u8 = 6; 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 /// [`Step::Prompt`] does and reads the screen every frame, so the menu is caught before the
/// next pulse could choose BUY on it. /// next pulse could choose BUY on it.
Counter { waited: u32 }, 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. /// Progress through one A* walk.
@ -1607,6 +1616,20 @@ fn advance(step: &mut Step, state: &mut dyn MacroState) -> Progress {
Progress::Hold(buttons::NONE) 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 } => { Step::Counter { waited } => {
if shop_screen(state) == Some(ShopScreen::BuySellQuit) { if shop_screen(state) == Some(ShopScreen::BuySellQuit) {
if stock_index(state, item::POKE_BALL) == Some(0) { 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 // 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 // for one, so there is none to read and nothing to navigate: these are the two presses
// the table names and no more. // 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::Yes | MacroKind::Confirm => vec![press(buttons::A)],
MacroKind::No | MacroKind::Back => vec![press(buttons::B)], MacroKind::No | MacroKind::Back => vec![press(buttons::B)],
MacroKind::Close | MacroKind::Leave => { 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 // 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 // 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 // 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 => { MacroKind::ThrowBall => {
let bag_slot = throw_slot(state)?; let bag_slot = throw_slot(state)?;
let mut steps = Vec::new(); let mut steps = Vec::new();

View file

@ -761,17 +761,17 @@ pub fn route_within(from: Region, to: u8, area: u8) -> bool {
false 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 /// 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 /// (`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 /// 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. /// 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]; 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<Amenity> { pub fn amenity_at(map: u8) -> Option<Amenity> {
AMENITIES.iter().find(|(_, _, id)| *id == map).map(|(_, kind, _)| *kind) AMENITIES.iter().find(|(_, _, id)| *id == map).map(|(_, kind, _)| *kind)
} }

View file

@ -17,7 +17,8 @@ use crate::adapter::PlaceKind;
use super::geography::{self, Amenity}; use super::geography::{self, Amenity};
use super::path::{self, Exit, Way}; 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. /// 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)); 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<MacroSpec>; SLOTS] = [None; SLOTS];
for kind in naming_set(naming, elapsed_ms) {
slots[usize::from(kind.slot())] = Some(MacroSpec::of(kind));
}
Self { scene, slots } Self { scene, slots }
} }
@ -492,8 +511,14 @@ pub fn scene_set(scene: Scene, state: &mut dyn MacroState) -> Vec<MacroKind> {
// 47 minutes, 189 of them on map `0x02` with no box on screen at all. So the pad is // 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 // 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. // 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 => { 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] vec![Next, Back]
} else { } else {
Vec::new() Vec::new()
@ -611,6 +636,113 @@ pub fn scene_set(scene: Scene, state: &mut dyn MacroState) -> Vec<MacroKind> {
} }
} }
/// 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<MacroKind> {
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. /// Section 3's preconditions, one arm each.
pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool { pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool {
match kind { match kind {
@ -675,8 +807,8 @@ pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool {
move_slot_bound(state, kind) move_slot_bound(state, kind)
} }
// Section 14's addition (the operator: "throw pokeball should be a macro"). A wild battle, a ball // 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 // in the bag, and room in the party. No catch-rate and no HP knowledge here: the enemy's
// the fly's. // HP decides only what else is on the pad beside it (row 69, [`throw_only`]).
MacroKind::ThrowBall => throw_slot(state).is_some(), MacroKind::ThrowBall => throw_slot(state).is_some(),
MacroKind::Switch => healthiest_other(state).is_some(), MacroKind::Switch => healthiest_other(state).is_some(),
// ...and a Potion the cartridge would take (row 63): `ItemUseMedicine` answers "It won't // ...and a Potion the cartridge would take (row 63): `ItemUseMedicine` answers "It won't

View file

@ -269,6 +269,31 @@ pub struct TextBox {
pub waiting: bool, 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. /// A menu cursor, as `HandleMenuInput` keeps it. Shared by every menu in the game.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cursor { pub struct Cursor {

View file

@ -32,13 +32,15 @@ use super::palette::{
healthiest_other, heal_goals, inside_center, nurse_prompt, rested_nurse, service_needed, healthiest_other, heal_goals, inside_center, nurse_prompt, rested_nurse, service_needed,
listing, losing, move_slot_bound, objective_goals, party_needs_rest, party_rested, listing, losing, move_slot_bound, objective_goals, party_needs_rest, party_rested,
poke_sprite, precondition, throw_slot, untalked_objects, untalked_people, ways, 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::path::{self, Exit, Way};
use super::super::maps; use super::super::maps;
use super::plan; use super::plan;
use super::state::{ use super::state::{
Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, MapSize, 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, Walkable, Warp,
}; };
@ -184,6 +186,11 @@ struct World {
heal_at: Option<u32>, heal_at: Option<u32>,
/// Oak has not been given the parcel yet (row 66); false in every fixture unless set. /// Oak has not been given the parcel yet (row 66); false in every fixture unless set.
parcel_undelivered: bool, 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<Naming>,
/// 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`] /// Whether a text box is drawn on a scene that is not [`Scene::Dialog`]
/// ([`MacroState::text_open`]). /// ([`MacroState::text_open`]).
/// ///
@ -306,6 +313,8 @@ impl World {
switch: None, switch: None,
heal_at: None, heal_at: None,
parcel_undelivered: false, parcel_undelivered: false,
naming: None,
glue_naming: false,
box_open: false, box_open: false,
prompt: false, prompt: false,
price_after: None, price_after: None,
@ -533,6 +542,10 @@ impl World {
} }
fn on_pulse(&mut self, mask: u8) { 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 self.scene == Scene::Overworld {
if mask == buttons::START { if mask == buttons::START {
self.start_to_open = self.start_to_open.saturating_sub(1); self.start_to_open = self.start_to_open.saturating_sub(1);
@ -887,6 +900,10 @@ impl MacroState for World {
!self.parcel_undelivered !self.parcel_undelivered
} }
fn naming(&mut self) -> Option<Naming> {
self.naming
}
fn refused_here(&mut self, slot: u8) -> bool { fn refused_here(&mut self, slot: u8) -> bool {
self.targets.refused(self.map, slot, self.player) 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"). /// 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 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, /// the party. There is no catch-rate and no enemy-HP knowledge in this precondition; since row 69
/// and there is none anywhere in this crate. /// the enemy's HP decides only what else is dealt beside the ball (`palette::throw_only`).
#[test] #[test]
fn throw_ball_needs_a_wild_battle_a_ball_and_room_in_the_party() { fn throw_ball_needs_a_wild_battle_a_ball_and_room_in_the_party() {
let mut world = World::battle(); 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(); dead.duds = world.duds.clone();
assert_eq!(run(&mut dead, MacroKind::GoWarp), Ok(MacroAbort::Blocked)); 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<MacroKind> {
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);
}

View file

@ -30,7 +30,9 @@ use super::symbols::ram;
/// The order of the tests is the contract: /// The order of the tests is the contract:
/// ///
/// 1. **Not started** — `wStatusFlags6`'s game-timer bit is clear, so the cartridge is on the /// 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 /// 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`]. /// 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: /// 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) { if !state::started(memory) {
return Scene::Title; 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 { if state::map_size(memory).is_none() || memory.read8(ram::wPartyCount) > 6 {
return Scene::Unknown; return Scene::Unknown;
} }

View file

@ -33,7 +33,7 @@ use super::macros::geography::Amenity;
use super::mapgrid::{self, MapGrids}; use super::mapgrid::{self, MapGrids};
use super::macros::state::{ use super::macros::state::{
BagItem, Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, 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, Status, TextBox, Walkable, Warp,
}; };
use super::symbols::ram; use super::symbols::ram;
@ -128,6 +128,30 @@ pub mod poke {
pub const MOVE_LIST_CURSOR_Y: u8 = 12; pub const MOVE_LIST_CURSOR_Y: u8 = 12;
pub const MOVE_LIST_CURSOR_X: u8 = 5; 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. /// `constants/ram_constants.asm`: `wMiscFlags` bit 3.
pub const BIT_USING_GENERIC_PC: u8 = 1 << 3; pub const BIT_USING_GENERIC_PC: u8 = 1 << 3;
/// `wFontLoaded` bit 0. /// `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) 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<Naming> {
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. /// 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 /// 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`, /// Whether `MoveSelectionMenu`'s own box is the figure on screen (`infra/docs/macros-traps.md`,
/// row 50). /// 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 /// 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 /// 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. /// 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 { fn move_list_drawn(memory: &mut dyn MemoryReader) -> bool {
let (left, top, right, bottom) = poke::MOVE_LIST_BOX; let (left, top, right, bottom) = poke::MOVE_LIST_BOX;
if screen_tile(memory, left, top) != poke::frame::HORIZONTAL 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 read(self.memory, ram::wEventFlags + (bit >> 3)) & (1 << (bit & 7)) != 0
} }
/// The naming screen (row 69), [`naming_screen`].
fn naming(&mut self) -> Option<super::macros::state::Naming> {
naming_screen(self.memory)
}
/// Where the ladder's next unreached rung is (`GO OBJECTIVE`). /// 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 /// The adapter's [`crate::adapter::MapPlace`] in the executor's own types, which is the only

View file

@ -1372,3 +1372,43 @@ fn the_joypad_latch_is_hjoylast_bit_zero() {
wram.set(poke::H_JOY_LAST, poke::pad::DOWN); wram.set(poke::H_JOY_LAST, poke::pad::DOWN);
assert!(!a_latched(&mut wram), "a direction down is not an A 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);
}

View file

@ -184,6 +184,8 @@ pub struct MacroLayer {
last_decision_ms: Option<f64>, last_decision_ms: Option<f64>,
scene: SceneId, scene: SceneId,
bindings: Vec<SlotBinding>, bindings: Vec<SlotBinding>,
/// The raw buttons the last observation lets through ([`flybrain_gb::Observed::raw`]).
raw: u8,
running: Option<Running>, running: Option<Running>,
finished: Option<Finished>, finished: Option<Finished>,
/// The brain millisecond the pad became empty in a playable scene, or `None` while it has /// 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. // `observe` has not happened and guessing the intro would be a guess.
scene: SceneId::Unknown, scene: SceneId::Unknown,
bindings: Vec::new(), bindings: Vec::new(),
raw: 0,
running: None, running: None,
finished: None, finished: None,
pad_empty_since_ms: 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 // 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. // `step` ends it on a scene change or at the frame cap.
if let Some(running) = self.running { if let Some(running) = self.running {
@ -377,6 +392,7 @@ impl MacroLayer {
let observed = self.palette.observe(memory, ledger); let observed = self.palette.observe(memory, ledger);
self.scene = observed.scene; self.scene = observed.scene;
self.bindings = observed.bindings; self.bindings = observed.bindings;
self.raw = observed.raw;
self.watch_pad(ms); self.watch_pad(ms);
let mut decision = Decision::default(); let mut decision = Decision::default();
if !self.scene.playable() 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), /// 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. /// 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) { 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) { match (empty, self.pad_empty_since_ms) {
(false, _) => self.pad_empty_since_ms = None, (false, _) => self.pad_empty_since_ms = None,
(true, None) => self.pad_empty_since_ms = Some(ms), (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. /// The scene the last [`MacroLayer::observe`] found.
pub fn scene(&self) -> FeedScene { pub fn scene(&self) -> FeedScene {
FeedScene::from_adapter(self.scene) 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. /// Name sets the next `observe`s use instead, oldest first: a plan whose head changes.
rename: Vec<Vec<&'static str>>, rename: Vec<Vec<&'static str>>,
bound: Vec<u8>, bound: Vec<u8>,
/// The raw buttons the scene lets through (row 69).
raw: u8,
/// Masks `step` returns, in order; a `None` ends the macro. /// Masks `step` returns, in order; a `None` ends the macro.
plan: Vec<Option<u8>>, plan: Vec<Option<u8>>,
running: Option<&'static str>, running: Option<&'static str>,
@ -629,6 +657,7 @@ mod tests {
names: Vec::new(), names: Vec::new(),
rename: Vec::new(), rename: Vec::new(),
bound: Vec::new(), bound: Vec::new(),
raw: 0,
plan: Vec::new(), plan: Vec::new(),
running: None, running: None,
finished: None, finished: None,
@ -652,6 +681,7 @@ mod tests {
} }
Observed { Observed {
scene: self.scene, scene: self.scene,
raw: self.raw,
bindings: self bindings: self
.bound .bound
.iter() .iter()
@ -924,6 +954,36 @@ mod tests {
assert_eq!(layer.counts().done, 1); 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] #[test]
fn the_title_screen_presses_the_raw_mask_and_runs_no_macro() { fn the_title_screen_presses_the_raw_mask_and_runs_no_macro() {
let mut layer = layer(Fake { scene: SceneId::Title, ..Fake::default() }); let mut layer = layer(Fake { scene: SceneId::Title, ..Fake::default() });