diff --git a/docs/design/macros-wram.md b/docs/design/macros-wram.md index 3525d0e..352dd93 100644 --- a/docs/design/macros-wram.md +++ b/docs/design/macros-wram.md @@ -1024,3 +1024,22 @@ the latch keeps that A until the next list first asks. Measured on the Potion's list reads open on the frame after the pulse, an A in the next 22 frames is lost, and across 120 rollback delays `hJoyLast`, `hJoyPressed`, `hJoyHeld` and `hJoy5` are the only bytes of WRAM and HRAM whose values never overlap between lost and answered frames. + +## 15. The naming screen (2026-09-29, `docs/design/macros.md` 12.32) + +Row 69. Two bytes of a `UNION` in `ram/wram.asm` that the reviewed list does not carry, pinned the +way `hJoyLast` is and read back from the code that stores them by +`row69_the_naming_bytes_are_where_the_cartridge_stores_them` (FLY_ROM). + +| name | where | what reads it | +| --- | --- | --- | +| `wNamingScreenNameLength` | `$CEE9` | the letters typed; the operand of `PrintNicknameAndUnderscores`'s `ld [wNamingScreenNameLength], a` before `hlcoord 10, 2` | +| `wNamingScreenSubmitName` | `$CEEA` | non-zero once START or ED is taken; the operand of `.pressedStart`'s `ld [wNamingScreenSubmitName], a` | + +**`state::naming_screen`** is the keyboard only when the menu bytes `DisplayNamingScreen` writes +(`wTopMenuItemY` 3, `wMaxMenuItem` 7, `wMenuWatchedKeys` `$ff`) **and** its figure are on screen: +the whole `TextBoxBorder` at (0, 4)-(19, 14) and a run of seven or ten underscores (`$76`, the raised +one `$77`) from (10, 3). The run's length is the capacity (`PLAYER_NAME_LENGTH - 1` or +`NAME_LENGTH - 1`). The menu bytes outlive the screen, so both halves are needed, as for +`yes_no_prompt`. The player's and rival's names at the start of a game are this screen before +`wStatusFlags6`'s game-timer bit is set, and `scene::detect` answers `Title` for them first. diff --git a/docs/design/macros.md b/docs/design/macros.md index 9c4ff77..280e77a 100644 --- a/docs/design/macros.md +++ b/docs/design/macros.md @@ -2009,6 +2009,76 @@ checkpoint (`FLY_ROW67_CHECKPOINT`). Nothing is ranked, weighted or pressed for the fly. The decoder, the reward catalog, the adapter version, the roles and the compatibility string are untouched. +### 12.32 A ball at low HP is the only attack, and the fly spells its catch's name (2026-09-29, row 69) + +(12.31 is row 67.) Two operator decisions of 2026-09-29, after row 66 measured the connectome +choosing `THROW BALL` 0 times in 35 decisions with a ball in the bag, and every catch named +`AAAAAAAAAA` by `NEXT`'s A presses on the keyboard. + +**"Throw on low HP only."** In a wild battle, when `THROW BALL` is on the pad and the wild +Pokémon's HP is low, the ball is the only attack-side button: `MOVE 1` to `MOVE 4` are withheld on +the top-level menu, and so are `SWITCH` and `RUN`, and `BACK` in the bag. + +- **Low is the cartridge's number.** `ItemUseBall` (`engine/items/item_effects.asm`) computes + `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 on HP when a random byte is at most + `W`, so at `W >= 255` HP stops mattering. For a Poké Ball that is HP at about a third of its + maximum (7 of a Weedle's 20), for a Great Ball about a half. Lower HP buys nothing more; what is + left is the catch rate and the status, which no press changes. So low is where the throw stops + getting better (`palette::ball_holds_on_hp`, `palette::throw_only`), for the ball + `THROW BALL` would throw. +- **What stays beside the ball.** `ITEM`, because it is dealt only for a Pokémon that is out, + under half its HP, with a Potion the cartridge would take: the one non-attack need that keeps + the thrower standing. `SWITCH` is about a healthier fighter; `RUN` forfeits the catch the pad + exists for, with the enemy at its weakest; `BACK` in the bag leads to a menu whose pad is the + same ball. `palette::WITHHELD_FOR_THE_THROW` is the list. +- **It cannot loop.** It applies only while `THROW BALL` itself is dealt, so every precondition + of that button still holds it: a wild battle, a ball, room in the party, a species the party does + not hold. A missed throw is an ordinary turn (`NEXT` between turns, the ball again on the next + own turn while one is left). With no ball left the button is off the pad and so is the rule, and + the moves are back. An enemy that faints ends the battle as always. A catch goes to the nickname + offer, which `NEXT` answers YES as before. + +**"Let the fly name it."** The keyboard (`DisplayNamingScreen`) is a screen of its own. It reads +`Unknown` in or out of a battle (the detector checks it before `wIsInBattle`), and its pad is the +fly's **own buttons**: the D-pad moves over the letters, A types one (or ED, which hands the name +back, or the case switch), B deletes, START hands the name back. SELECT is not on the operator's +list and is masked. No macro is dealt while the fly spells. + +- **Why raw buttons and not a macro per key.** A macro per key is new types, and a new type + re-deals every macro population (`docs/readout.md`). The fly's raw buttons are already decoded + every frame in macros mode, and the title already passes them through (section 2). The player's + and rival's names at the start of a game are the same screen before the game timer starts, so + they read `Title` and the fly has always typed them with these buttons; the nickname is now + consistent with them. `Observed::raw` carries the scene's mask and the layer presses + `raw_mask & raw` while nothing is bound and nothing runs. +- **The bound.** Once the name is full (`wNamingScreenNameLength` at the capacity the underscores + show, ten or seven; the cartridge moves the cursor onto ED itself then), or sixty brain seconds + after the keyboard opened (`palette::NAMING_BOUND_MS`), the raw buttons are shut and `CONFIRM` + is the only button. On the keyboard `CONFIRM` pulses START until the screen is gone + (`Step::Submit`), `blocked` after 160 frames. `CONFIRM` is not offered earlier: a macro group of + one always has a winner at its next decision, so a lone `CONFIRM` would hand back an empty name + within a second. +- **What the name is.** Whatever the fly typed stays. An empty name is the species' own name, + which is the cartridge (`AskName.declinedNickname`). +- **The reading.** Red has no "keyboard open" byte, so `state::naming_screen` is the construction + `yes_no_prompt` makes: the menu bytes `DisplayNamingScreen` writes (`wTopMenuItemY` 3, + `wMaxMenuItem` 7, every key watched), the keyboard's whole box at (0, 4)-(19, 14), and the + underscores at (10, 3). `wNamingScreenNameLength` (`$CEE9`) and `wNamingScreenSubmitName` + (`$CEEA`) are read from the operands of the cartridge's own instructions, like `hJoyLast`, and + pinned by the ROM tests. +- `game.scene` is `unknown` on the keyboard, `game.palette` is `[]` while the fly spells, and + `game.padEmptyMs` stays 0: the fly's own buttons are a pad. + +ROM tests (`tests/rom_catch.rs`): `row69_at_low_hp_a_wild_battles_pad_is_the_ball` +(`FLY_ROW69_CHECKPOINT`), `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends` +and `row69_a_fly_that_types_nothing_is_ended_by_the_bound` (`FLY_CATCH_CHECKPOINT`). Survey +numbers are in `infra/docs/macros-traps.md` row 69. + +Nothing presses for the fly on the keyboard but the bound's one button, dealt as a button and +chosen by the fly's own macro group. The decoder, the reward catalog, the adapter version, the +roles and the compatibility string are untouched. + ## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a ## priority to visit the shop at least once per area; make shop macros item purchases. same ## for the Pokécenter. heal should be a macro.") @@ -2089,7 +2159,9 @@ observe is not a precondition, it is a guess. | Dialog, a readable YES/NO box (**the box the cartridge drew**, 12.20) | YES, NO — or **one of them** at a Pokémon Center's nurse | **new, 12.12.** `NEXT` is off it: an A press at a two-option menu confirms the option the cursor is on, which is what `YES` is, so the two are one press under two names (12.10). At the nurse's own prompt the bound answer is the one that changes something — `YES` with a hurt or statused party, `NO` with a full one. An answer whose prompt comes straight back is excluded for the blocked window, and the exclusion never empties the pad | | Menu (the start menu) | CLOSE, CONFIRM, BACK | unchanged as a *scene*, and since **12.11** nothing on any other pad opens it: the fly reaches it with the **raw** START button, which still reaches the cartridge in macros mode, and moves its cursor with the raw D-pad. A SAVE or a POKéDEX button would be a macro per start-menu entry and is not asked for -- which is precisely why `MENU` had nothing behind it | | Menu (the bag, an elevator, the party list outside a battle) | CLOSE, CONFIRM, BACK | unchanged | -| Unknown (the Pokédex, the trainer card, OPTION, a naming screen, a mid-warp frame) | NEXT, **BACK** | **BACK added** (row 9): B is what leaves the first three, and A leaves none of them | +| Unknown (the Pokédex, the trainer card, OPTION, a mid-warp frame) | NEXT, **BACK** | **BACK added** (row 9): B is what leaves the first three, and A leaves none of them | +| Unknown, the naming screen (**12.32**) | the fly's own D-pad, A, B and START; **CONFIRM** alone once the name is full or after sixty brain seconds | new, row 69: read before the battle test, so a nickname typed in a battle is here too | +| Battle, own turn, main menu, a wild Pokémon at low HP with THROW BALL dealt (**12.32**) | THROW BALL, and ITEM for a hurt thrower | new, row 69: the moves, SWITCH and RUN withheld; the bag's BACK too | | Battle, own turn, main menu | MOVE 1..4, SWITCH, ITEM, THROW BALL, RUN (whose cursor indices are FIGHT 0, **ITEM 1, PKMN 2**, RUN 3 -- two columns, 12.11) | four move buttons for `ATTACK` (section 14); THROW BALL added, and gated on the species since 12.9; **RUN gated**, below. No `BACK`: the four entries are the answers to this menu. **`NEXT` removed by 12.10** — an A press here confirms FIGHT and reopens the list the move list's `BACK` just closed, and `MOVE 1` is the backstop instead, bound here whatever the battler reads as | | Battle, own turn, move list (**the box on screen**, 12.18) | MOVE 1..4, BACK -- or **MOVE 1 alone** | as above, plus **12.11**: `BACK` is dealt here only while `wBattleMon*` reads, because a list that binds no `MOVE n` has a pad whose one button closes the list `MOVE 1` underneath had just opened. With nothing readable the pad is `MOVE 1` and its script confirms where the cursor stands | | Battle, own turn, party list | SWITCH, BACK | unchanged | @@ -2140,7 +2212,7 @@ measured where it cannot. | a running macro aborts and the pad is not re-dealt until the next frame | not a cause: `observe` runs after every frame and the decoder is handed the bound channels again on the very next one | | a restore, before the first `observe` | not a cause: the loop calls `observe` once at the end of boot and once after a ratchet recovery, so the first frame is decided on a real palette | | the title screen, and raw mode | not an empty pad by contract: the readout's boot variant applies and no palette is dealt | -| a scene the detector cannot name | `Unknown` deals `NEXT` and `BACK`; a screen neither press leaves (the naming screen, row 14) is a genuine stall and still needs START, which is a contract change | +| a scene the detector cannot name | `Unknown` deals `NEXT` and `BACK`. The naming screen (row 14), which neither press leaves, is read since **12.32** and its pad is the fly's own buttons, then `CONFIRM` (START) once the name is full or the bound runs | | an `Unknown` frame that is the **overworld with the cartridge driving** -- a warp in flight, a scripted push-back, a guide walking the fly through a door | **empty on purpose** (12.13). There is no box to advance and no screen to leave, so an A or a B press is a press into somebody else's script: it changes nothing and completes where the fly stands. This is the one empty pad that ends itself -- the cartridge gives the buttons back within a few frames -- and `game.padEmptyMs` reports it like any other | | the fly's own turn while the cartridge holds the A it last took (`hJoyLast`) | **empty on purpose** (12.27): a menu the game is acting on or has not started reading. Ends itself on the game's next joypad read | | the fly's own turn where the seam cannot read the battler, now that `NEXT` is off that row (12.10) | **fixed**: `MOVE 1` is bound over the top-level menu whatever `wBattleMon*` reads as, because FIGHT is one of that menu's four entries and always opens | diff --git a/docs/feed-protocol.md b/docs/feed-protocol.md index d90642c..6af7380 100644 --- a/docs/feed-protocol.md +++ b/docs/feed-protocol.md @@ -187,7 +187,8 @@ before. The Rust producer always sends all five, in both modes. - **`game.padEmptyMs`** is how long the pad has had nothing on it **in a playable scene**, in brain milliseconds, and 0 otherwise — in raw mode, on the title screen, when something is bound, - and while a macro is running, because a running macro owns the pad. It is **report only**: no + on the naming screen, whose pad is the fly's own buttons (`docs/design/macros.md` 12.32), and + while a macro is running, because a running macro owns the pad. It is **report only**: no producer acts on it and no consumer should, and nothing in the loop reads it back. It exists because an empty pad is the doctrine working — nothing presses for the fly, so a scene with no button waits — and on screen that is indistinguishable from a hang diff --git a/infra/docs/macros-traps.md b/infra/docs/macros-traps.md index 63e0930..e605678 100644 --- a/infra/docs/macros-traps.md +++ b/infra/docs/macros-traps.md @@ -3498,3 +3498,57 @@ is harness choice, not the fly's: (13 to 46 `MOVE n`, 1 to 4 wins each) are not flagged. The ladder's restart does not change the readout, and a reset to PEWTER CITY replays the same gym. Only the reset to the rung below adds forest battles, and whether that is enough was not measured. + +## 2026-09-29, row 69: throw on low HP only, and the fly names its catch + +### What was asked + +Two operator decisions after row 66 (`docs/design/macros.md` 12.32). Row 66 measured the connectome +choosing `THROW BALL` 0 times in 35 decisions with a ball in the bag (66e), and every catch named +`AAAAAAAAAA`: `NEXT` answered the nickname offer YES and its A presses typed on the keyboard (66d). + +| # | trap | trigger | test | fix, or why it is left | +| --- | --- | --- | --- | --- | +| 69 | at low HP the ball sat beside four moves, `SWITCH` and `RUN`, and the fly never chose it (66e) | a wild battle with a ball, the enemy at a third of its HP | `row69_at_low_hp_in_a_wild_battle_the_ball_is_the_only_attack` and four more unit tests, `row69_at_low_hp_a_wild_battles_pad_is_the_ball` (`FLY_ROW69_CHECKPOINT`) | **operator decision, built**: with `THROW BALL` dealt and `ItemUseBall`'s HP factor saturated (`W >= 255`), the moves, `SWITCH`, `RUN` and the bag's `BACK` are withheld; `ITEM` stays for a hurt thrower | +| 69b | the keyboard read as the battle's between-turns frame, so `NEXT` typed the name (66d) | every catch | `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends`, `the_naming_screen_is_its_menu_and_its_box_and_its_underscores` | **operator decision, built**: the keyboard reads `Unknown` and its pad is the fly's own D-pad, A, B and START | +| 69c | a keyboard nobody ends is a stall: B never leaves it and A stops typing at ten letters | a fly that does not press ED or START | `row69_a_fly_that_types_nothing_is_ended_by_the_bound`, `row69_confirm_on_the_keyboard_presses_start_until_it_closes` | **fixed**: once the name is full or sixty brain seconds have run, `CONFIRM` alone, which presses START until the keyboard closes (`blocked` after 160 frames) | +| 69d | row 66's `unknown_pads_with_no_box` counted the bound's `CONFIRM` on the keyboard, which is drawn without the text font | the rung-10 Pewter gym drive, which buys a ball and catches | `the_fly_reaches_the_pewter_gym_from_the_rung_ten_checkpoint` | **fixed in the test**: the keyboard is a drawn screen | +| 69e | the catch checkpoint's lead one-shots every forest Pokémon, so no wild HP is ever low there | `FLY_CATCH_CHECKPOINT` | -- | **left, named**: the low-HP ROM test uses a rung-9 Route 2 checkpoint (rung-9 A below: a Bulbasaur at 5/30, one ball) as `FLY_ROW69_CHECKPOINT` | + +### Before and after + +ROM tests (rom-env sourced, the build box), a69a258 against the branch: + +| test | a69a258 | branch | +| --- | --- | --- | +| `row69_at_low_hp_a_wild_battles_pad_is_the_ball` | 664 low-HP frames with the ball dealt, pad `MOVE 1`, `MOVE 2`, `MOVE 3`, `THROW BALL`. **Fails** | 58 frames, pad `THROW BALL` alone, thrown. Passes | +| `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends` | keyboard 511 frames, 11 `NEXT` starts, 0 raw frames, name `AAAAAAAAAA`. **Fails** | keyboard 1,516 frames, no macro, 1,516 frames of the fly's buttons, 7 letters at most, name `RIJ?`, closed by the fly (ED). Passes | +| `row69_a_fly_that_types_nothing_is_ended_by_the_bound` | `NEXT` types ten A's and ED. **Fails** | nothing typed; `CONFIRM` dealt once at the bound, span 3,587 frames, name empty (the species' own). Passes | +| `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` | passes | passes (battle over 2,468 frames after the catch) | + +With the connectome (`trap_hunt`, one sweep thread, 15 brain minutes, macro log). The runs vary the +starting state, as row 66's did: four rung-9 checkpoints with one ball each. + +| checkpoint (lead, balls) | arm | wild battles with a ball | `THROW BALL` dealt frames / chosen | the throw's pad (frames) | catches | keyboard | rung, tiles, windows flagged | +| --- | --- | ---: | ---: | ---: | ---: | --- | --- | +| rung-9 A, Route 2 (Bulbasaur 5/30, 1) | a69a258 | 5 | 414 / 0 | -- | 0 | -- | 10, 520, 40 | +| | branch | 2 | 96 / 1, at low HP from the pad `THROW BALL` alone | 32 | 1 | 16.8 brain s, A 32, B 30, longest 1, name empty (the species'), ended by the fly (ED) | 10, 482, 51 | +| rung-9 B, Route 2 (Wartortle 9/70, 1) | a69a258 | 1 | 32 / 1, at full HP on the first frame | 0 | 1 | `NEXT` | 9, 300, 46 | +| | branch | 1 | 32 / 1, the same throw | 0 | 1 | 28.1 brain s, A 55, B 52, longest 1, name empty, ended by the fly (ED) | 9, 236, 43 | +| rung-9 C, the forest (`FLY_CATCH_CHECKPOINT`, Wartortle 18/70, 1) | both, identical | 1 | 32 / 1, at full HP, missed | 0 | 0 | -- | 9, 278, 18 | +| rung-9 D, the forest (the no-PP state, Bulbasaur 6/34, 1) | both, identical | 2 | 282 / 0 | 0 (never low with the ball dealt) | 0 | -- | 9, 285, 21 | + +- **Throws and catches.** Three balls thrown in four runs on the branch, two catches; on a69a258 + two thrown and one catch. The one run where they differ is the one whose wild HP passed a third + with the ball dealt: the fly threw from the throw's pad at once and caught. Two of the throws + were the fly's own choice from the ordinary pad on a battle's first frame, on both arms. +- **Names.** Both keyboards were ended by the fly's own A on ED, in 17 and 28 brain seconds, well + inside the bound. The brain's A and B fire at nearly the same rate there, so each letter it typed + it deleted again and both names came out empty, which the cartridge turns into the species' + name. That is the fly's spelling, kept as it is. +- **Stalls.** None from this row. Every run ends its battles; no keyboard reached the bound. The + flagged windows are `NEXT` runs through battle text on both arms (and on the branch's rung-9 A run + five `GO ROUTE, GO HEAL` windows, row 62's tug, 65h). The branch's rung-9 B run covers fewer tiles + after the keyboard because its frames after the catch differ from a69a258's (the keyboard took + 28 brain seconds instead of `NEXT`'s few), not because anything waited: 635 macros started, 633 + done, one refusal and one timeout, against 803, 802, one and one. 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/examples/trap_hunt.rs b/services/flysim/crates/flysim/examples/trap_hunt.rs index 7c5947e..8543fda 100644 --- a/services/flysim/crates/flysim/examples/trap_hunt.rs +++ b/services/flysim/crates/flysim/examples/trap_hunt.rs @@ -236,6 +236,37 @@ struct Trace { move_starts: (u64, u64), wall_seconds: f64, row66: Row66, + row69: Row69, +} + +/// Row 69's tally: frames the throw's pad was up, and every naming screen -- how long, the fly's +/// own presses on it, the name, and what ended it. +#[derive(Default)] +struct Row69 { + throw_pad_frames: u64, + keyboard_frames: u64, + keyboard_presses: u64, + /// The keyboard up now: brain ms it opened, frames, presses, longest, name, CONFIRM started. + open: Option<(f64, u64, u64, u8, String, bool)>, + keyboards: Vec, + previous_mask: u32, + /// A, B and START going down on the keyboard, over the run. + keys: BTreeMap<&'static str, u64>, +} + +/// `wStringBuffer` (`CalcStringLength`'s operand on the cartridge), in Red's charmap. +fn row69_name(gb: &mut flybrain_gb::Emulator) -> String { + use flybrain_gb::MemoryReader; + (0..11u16) + .map(|index| gb.read8(0xcf4b + index)) + .take_while(|byte| *byte != 0x50) + .map(|byte| match byte { + 0x80..=0x99 => char::from(b'A' + (byte - 0x80)), + 0xa0..=0xb9 => char::from(b'a' + (byte - 0xa0)), + 0x7f => ' ', + _ => '?', + }) + .collect() } /// Row 66's shop/ball/catch tally: pad frames, starts and outcomes of the watched buttons, and @@ -367,6 +398,9 @@ impl FrameObserver for Hunt { && layer.running().is_none() { let names: Vec = layer.feed_palette().into_iter().map(|slot| slot.name).collect(); + if names == ["THROW BALL"] || names == ["ITEM", "THROW BALL"] { + self.trace.row69.throw_pad_frames += 1; + } if !names.is_empty() { let row = &mut self.trace.row66; row.free_frames += 1; @@ -390,6 +424,51 @@ impl FrameObserver for Hunt { let ms = parts.agent.network.ms; let location = frame.location; let trace = &mut self.trace; + { + let naming = flybrain_gb::pokemon_red::state::naming_screen(parts.emulator); + let row = &mut trace.row69; + match (naming, row.open.take()) { + (Some(naming), open) => { + let (since, frames, presses, longest, _, confirm) = + open.unwrap_or((ms, 0, 0, 0, String::new(), false)); + // A press is a button going down while no macro runs: each of the eight bits + // on its own edge, since the D-pad group is almost always holding one. + let press = if executed.events.is_empty() { + (executed.mask & !row.previous_mask).count_ones() + } else { + 0 + }; + let letters = executed.mask & !row.previous_mask; + for (bit, name) in [(0x10u32, "A"), (0x20, "B"), (0x40, "START")] { + if executed.events.is_empty() && letters & bit != 0 { + *row.keys.entry(name).or_default() += 1; + } + } + let confirm = confirm || executed.events.iter().any(|event| event.name == "CONFIRM"); + row.keyboard_frames += 1; + row.keyboard_presses += u64::from(press); + row.open = Some(( + since, + frames + 1, + presses + u64::from(press), + longest.max(naming.length), + row69_name(parts.emulator), + confirm, + )); + } + (None, Some((since, frames, presses, longest, name, confirm))) => { + row.keyboards.push(format!( + "{:.2} min: {frames} frames ({:.1} brain s), {presses} presses, longest {longest}, \ + name {name:?}, ended by {}", + (since - trace.began_ms) / MINUTE_MS, + (ms - since) / 1000.0, + if confirm { "CONFIRM (the bound)" } else { "the fly (ED or START)" } + )); + } + (None, None) => {} + } + row.previous_mask = executed.mask; + } for event in &executed.events { if std::env::var("FLY_TRAP_LOG_MACROS").is_ok_and(|value| value == "1") { let pad: Vec = parts.macros.as_deref().map(|layer| layer.feed_palette().into_iter().map(|slot| slot.name).collect()).unwrap_or_default(); @@ -626,6 +705,7 @@ fn run( move_starts: (0, 0), wall_seconds: 0.0, row66: Row66::default(), + row69: Row69::default(), seeded: seeded_note, refusals: BTreeMap::new(), refusal_run: (None, 0), @@ -1100,6 +1180,25 @@ fn main() { if let Some(last) = row.last { println!("- end: balls {} money {} party+box {} owned {} map {:#04x}", last.0, last.1, last.2, last.3, last.4); } for line in row.log.iter().take(150) { println!("- {line}"); } } + { + let row = &trace.row69; + println!( + "\n## Row 69: the throw's pad and the keyboard\n\n- free frames with the throw's pad \ + (THROW BALL alone, or with ITEM): {}\n- keyboard frames {}, the fly's own button presses \ + on it {} (of them {:?})", + row.throw_pad_frames, row.keyboard_frames, row.keyboard_presses, row.keys + ); + for line in &row.keyboards { + println!("- keyboard at {line}"); + } + if let Some((since, frames, presses, longest, name, _)) = &row.open { + println!( + "- keyboard still up at the end: opened {:.2} min, {frames} frames, {presses} presses, \ + longest {longest}, name {name:?}", + (since - trace.began_ms) / MINUTE_MS + ); + } + } for (rank, label, ms) in &trace.rungs { println!("- rung {rank} {label} at {:.2} brain minutes", ms / MINUTE_MS); } 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() }); diff --git a/services/flysim/crates/flysim/tests/rom_catch.rs b/services/flysim/crates/flysim/tests/rom_catch.rs index 5f6feea..80303a2 100644 --- a/services/flysim/crates/flysim/tests/rom_catch.rs +++ b/services/flysim/crates/flysim/tests/rom_catch.rs @@ -33,6 +33,7 @@ //! different test's question; this one says out loud that it skipped. use flybrain_core::decoder::PopulationDecoder; +use flybrain_core::decoder::gameboy::to_button_mask; use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; use flybrain_core::ordered::NumberMap; use flybrain_gb::adapter::RewardEvent; @@ -295,6 +296,59 @@ struct AfterCatch { ball_dealt: u32, /// Every pad the fly could decide on in that stretch. pads: std::collections::BTreeSet>, + /// Row 69: the naming screen, as this test reads it off the cartridge ([`keyboard`]). + keyboard: Keyboard, +} + +/// Row 69: what the naming screen saw, read by this test itself rather than by the palette. +#[derive(Debug, Default)] +struct Keyboard { + /// Frames the keyboard was up. + frames: u32, + /// Frames on it with no macro running on which the cartridge was given a button: the fly's + /// own presses. + raw_frames: u32, + /// Macros started while it was up, by name. + starts: Vec<&'static str>, + /// Pads dealt on it, while nothing ran. + pads: std::collections::BTreeSet>, + /// The longest the name got, and the name on its last frame (`wStringBuffer`, decoded). + longest: u8, + name: String, + /// Frames from its first frame to its last. + span: u32, + closed: bool, +} + +/// `wStringBuffer`, from `CalcStringLength`'s `ld hl, wStringBuffer` on the cartridge (row 69). +const STRING_BUFFER: u16 = 0xcf4b; +/// `wNamingScreenNameLength` (row 69, `pokemon_red::state::poke::NAMING_LENGTH`). +const NAMING_LENGTH: u16 = 0xcee9; + +/// The naming screen, as this test reads it: the keyboard's menu bytes, its box's corner at +/// (0, 4), and an underscore under the name at (10, 3). The letters typed, or `None`. +fn keyboard(run: &mut Run) -> Option { + let tile = |run: &mut Run, x: u16, y: u16| run.byte(ram::wTileMap + y * 20 + x); + let menu = run.byte(ram::wTopMenuItemY) == 3 + && run.byte(ram::wMaxMenuItem) == 7 + && run.byte(ram::wMenuWatchedKeys) == 0xff; + (menu && tile(run, 0, 4) == 0x79 && tile(run, 19, 14) == 0x7e + && matches!(tile(run, 10, 3), 0x76 | 0x77)) + .then(|| run.byte(NAMING_LENGTH)) +} + +/// The name in `wStringBuffer`, in Red's charmap: capitals from `$80`, small letters from `$a0`. +fn typed(run: &mut Run) -> String { + (0..11u16) + .map(|index| run.byte(STRING_BUFFER + index)) + .take_while(|byte| *byte != 0x50) + .map(|byte| match byte { + 0x80..=0x99 => char::from(b'A' + (byte - 0x80)), + 0xa0..=0xb9 => char::from(b'a' + (byte - 0xa0)), + 0x7f => ' ', + _ => '?', + }) + .collect() } /// One drive: `idle` frames with nothing pressed first (so each attempt reaches the wild battle @@ -302,6 +356,17 @@ struct AfterCatch { /// drive up to the catch, then the pad's own buttons in turn. `None` when no ball kept anything /// within the budget: one ball in the bag misses about two throws in three. fn drive_past_a_catch(rom: &[u8], checkpoint: &flysim::store::Checkpoint, idle: u32) -> Option { + drive_past_a_catch_typing(rom, checkpoint, idle, true) +} + +/// [`drive_past_a_catch`], and on the keyboard lean on A and B (`type_keys`) or on nothing, so +/// only the D-pad group's own rotation reaches it and the row 69 bound is what ends it. +fn drive_past_a_catch_typing( + rom: &[u8], + checkpoint: &flysim::store::Checkpoint, + idle: u32, + type_keys: bool, +) -> Option { let mut run = Run::resume(rom, checkpoint); for _ in 0..idle { run.ms += MS_PER_FRAME; @@ -317,9 +382,22 @@ fn drive_past_a_catch(rom: &[u8], checkpoint: &flysim::store::Checkpoint, idle: let mut ball_dealt = 0u32; let mut pads = std::collections::BTreeSet::new(); let mut hold = 0usize; + let mut board = Keyboard::default(); + let mut board_from: Option = None; for frame in 0..budget { let bound = run.layer.bound_channels(); - let hot = if caught_at.is_none() { + let on_keyboard = keyboard(&mut run); + let hot = if caught_at.is_some() && on_keyboard.is_some() && bound.is_empty() && !type_keys { + None + } else if caught_at.is_some() && on_keyboard.is_some() && bound.is_empty() { + // Row 69: the keyboard's pad is the fly's own buttons. The stub leans on A (a letter) + // mostly and on B (a deletion) now and then; the D-pad is the direction group's own + // rotation. What the name comes out as is the stub's, as it will be the brain's. + if frame % BURST_FRAMES == 0 { + hold += 1; + } + Some(if hold % 4 == 3 { "command_5".to_string() } else { "command_4".to_string() }) + } else if caught_at.is_none() { if run.in_wild_battle() { Some(BALL.to_string()) } else { @@ -343,7 +421,34 @@ fn drive_past_a_catch(rom: &[u8], checkpoint: &flysim::store::Checkpoint, idle: } } let active = run.decoder.decode_bound(&rates(hot.as_deref()), run.ms, false, None, Some(&bound)); - run.legacy.execute(Some(&mut run.layer), &active, 0, run.ms, &mut run.gb, &run.adapter); + // The readout's own buttons as raw mode would press them: the layer passes them to the + // cartridge only where a scene says so (the title, and since row 69 the keyboard). + let raw = to_button_mask(&active); + let idle = run.layer.running().is_none(); + let executed = + run.legacy.execute(Some(&mut run.layer), &active, raw, run.ms, &mut run.gb, &run.adapter); + if let Some(length) = on_keyboard { + board.frames += 1; + board_from.get_or_insert(frame); + board.span = frame - board_from.unwrap_or(frame); + board.longest = board.longest.max(length); + board.name = typed(&mut run); + if idle { + if !bound.is_empty() { + board.pads.insert(bound.clone()); + } + if executed.mask != 0 && executed.events.is_empty() { + board.raw_frames += 1; + } + } + for event in &executed.events { + if event.outcome.is_none() { + board.starts.push(event.name); + } + } + } else if board.frames > 0 { + board.closed = true; + } run.ms += MS_PER_FRAME; run.frame += 1; let evaluated = run @@ -358,7 +463,7 @@ fn drive_past_a_catch(rom: &[u8], checkpoint: &flysim::store::Checkpoint, idle: && run.byte(ram::wIsInBattle) == 0 { assert!(!run.catches().is_empty(), "the catch pays at the battle's end"); - return Some(AfterCatch { caught_at, ended_at: frame, ball_dealt, pads }); + return Some(AfterCatch { caught_at, ended_at: frame, ball_dealt, pads, keyboard: board }); } } assert!(caught_at.is_none(), "a battle still running {budget} frames after its catch"); @@ -419,3 +524,286 @@ fn row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends() { after.ended_at - after.caught_at ); } + +/// Row 69 ("let the fly name it"): after a catch the nickname offer is answered YES as before, +/// and the keyboard's pad is the fly's own buttons -- the D-pad, A, B, START -- with no macro on +/// it, until the name is full (or the bound runs), when `CONFIRM` alone hands the name back. The +/// keyboard closes and the battle ends. +/// +/// On a69a258 (row 66) the keyboard read as the battle's between-turns frame and its pad was +/// `NEXT`, whose A presses typed the name. +#[test] +fn row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let Some(checkpoint) = checkpoint() else { + eprintln!("skipped: no FLY_CATCH_CHECKPOINT"); + return; + }; + if Run::resume(&rom, &checkpoint).balls() == 0 { + eprintln!("skipped: the checkpoint's bag holds no ball"); + return; + } + let after = (0..24) + .find_map(|attempt| drive_past_a_catch(&rom, &checkpoint, attempt * 5)) + .expect("one of 24 attempts should keep a Pokémon"); + let board = &after.keyboard; + eprintln!( + "caught at f{}, battle over at f{}; keyboard {} frames over {} (raw {}), longest {}, \ + name {:?}, starts {:?}, pads {:?}, closed {}", + after.caught_at, + after.ended_at, + board.frames, + board.span, + board.raw_frames, + board.longest, + board.name, + board.starts, + board.pads, + board.closed + ); + assert!(board.frames > 0, "a catch goes to the keyboard (the nickname offer answered YES)"); + assert!(board.raw_frames > 0, "the fly's own buttons reached the keyboard"); + assert!(board.longest > 0, "the fly typed a letter"); + assert!( + board.starts.iter().all(|name| *name == "CONFIRM"), + "no macro types on the keyboard: {:?}", + board.starts + ); + assert!( + board.pads.iter().all(|pad| pad == &vec!["macro_confirm".to_string()]), + "the keyboard deals CONFIRM alone or nothing: {:?}", + board.pads + ); + assert_ne!(board.name, "AAAAAAAAAA", "not the name NEXT's A presses typed on a69a258"); + assert!(board.closed, "the keyboard closed"); + // The bound is sixty brain seconds, about 3,600 frames; the stub fills the name long before. + assert!(board.span < 3_700, "the keyboard was up for {} frames", board.span); + assert!(after.ended_at - after.caught_at < 6_000, "the battle ended"); +} + +/// `ItemUseBall`'s HP test, this file's own reading of it (`engine/items/item_effects.asm`): for +/// the first ball in the bag, `(MaxHP * 255 / BallFactor) / max(HP / 4, 1) >= 255`, a factor of 8 +/// for a Great Ball and 12 for the rest. +fn enemy_low(run: &mut Run) -> bool { + let word = |run: &mut Run, address: u16| { + u16::from(run.byte(address)) * 256 + u16::from(run.byte(address + 1)) + }; + let hp = word(run, ram::wEnemyMonHP); + let max = word(run, ram::wEnemyMonMaxHP); + let Some(ball) = state::bag(&mut run.gb) + .iter() + .find(|item| (0x01..=0x04).contains(&item.id) && item.count > 0) + .map(|item| item.id) + else { + return false; + }; + if hp == 0 || max == 0 || hp > max { + return false; + } + let factor: u32 = if ball == 0x03 { 8 } else { 12 }; + let quarter = u32::from((hp >> 2) as u8).max(1); + (u32::from(max) * 255 / factor) / quarter >= 255 +} + +/// Row 69's checkpoint for the low-HP drive, or the catch checkpoint when it is not set. +/// +/// The catch checkpoint's lead is a level-twenty Wartortle that takes every forest Pokémon from +/// full HP to nothing in one hit, so no wild Pokémon is ever *low* there. `FLY_ROW69_CHECKPOINT` +/// names a rung-9 state whose lead is weak enough for a wild Pokémon's HP to pass through a third +/// on its way down, with a ball in the bag. +fn row69_checkpoint() -> Option { + let path = std::env::var_os("FLY_ROW69_CHECKPOINT")?; + Some( + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope"), + ) +} + +/// Row 69 ("throw on low HP only"): in a wild battle, with a ball in the bag and the wild +/// Pokémon's HP where the ball's HP factor is at its best, `THROW BALL` is the only attack-side +/// button on the pad -- no `MOVE n`, no `SWITCH`, no `RUN` -- and the throw happens. +/// +/// The stub leans on the pad's own buttons in turn, leaving `THROW BALL` alone while HP is high +/// so the checkpoint's one ball is not spent before the HP is low. On a69a258 the low-HP pads +/// hold the moves beside the ball. +#[test] +fn row69_at_low_hp_a_wild_battles_pad_is_the_ball() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let Some(checkpoint) = row69_checkpoint() else { + eprintln!("skipped: no FLY_ROW69_CHECKPOINT"); + return; + }; + if Run::resume(&rom, &checkpoint).balls() == 0 { + eprintln!("skipped: the checkpoint's bag holds no ball"); + return; + } + let mut low_pads: std::collections::BTreeSet> = Default::default(); + let mut high_ball_pads: std::collections::BTreeSet> = Default::default(); + let mut low_frames = 0u32; + let mut thrown_low = 0u32; + let mut battles = 0u32; + let mut hp_log: Vec<(u8, u16, u16, u16)> = Vec::new(); + for attempt in 0..16u32 { + let mut run = Run::resume(&rom, &checkpoint); + for _ in 0..attempt * 7 { + run.ms += MS_PER_FRAME; + run.frame += 1; + let _ = run + .legacy + .stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms) + .expect("a frame should complete"); + } + let mut hold = 0usize; + let mut was_wild = false; + for frame in 0..3 * 60 * 60u32 { + let bound = run.layer.bound_channels(); + let wild = run.in_wild_battle(); + if wild && !was_wild { + battles += 1; + } + was_wild = wild; + let low = wild && enemy_low(&mut run); + if wild { + let hp = u16::from(run.byte(ram::wEnemyMonHP)) * 256 + + u16::from(run.byte(ram::wEnemyMonHP + 1)); + let max = u16::from(run.byte(ram::wEnemyMonMaxHP)) * 256 + + u16::from(run.byte(ram::wEnemyMonMaxHP + 1)); + let own = u16::from(run.byte(ram::wBattleMonHP)) * 256 + + u16::from(run.byte(ram::wBattleMonHP + 1)); + let seen = (run.byte(ram::wEnemyMonSpecies), hp, max, own); + if hp_log.last() != Some(&seen) { + hp_log.push(seen); + } + } + let idle = run.layer.running().is_none(); + if idle && wild && bound.iter().any(|channel| channel == THROW_BALL_CHANNEL) { + if low { + low_frames += 1; + low_pads.insert(bound.clone()); + } else { + high_ball_pads.insert(bound.clone()); + } + } + let hot = if wild && !bound.is_empty() { + if frame % BURST_FRAMES == 0 { + hold += 1; + } + // Not `RUN` either: a fled battle never reaches low HP. + let choices: Vec<&String> = bound + .iter() + .filter(|channel| low || *channel != THROW_BALL_CHANNEL) + .filter(|channel| *channel != "macro_run") + .collect(); + choices.get(hold % choices.len().max(1)).map(|channel| channel.to_string()) + } else { + let slot = (run.frame / BURST_FRAMES) as usize % run.channels.len(); + Some(run.channels[slot].to_string()) + }; + let balls = run.balls(); + let active = + run.decoder.decode_bound(&rates(hot.as_deref()), run.ms, false, None, Some(&bound)); + run.legacy.execute(Some(&mut run.layer), &active, 0, run.ms, &mut run.gb, &run.adapter); + run.ms += MS_PER_FRAME; + run.frame += 1; + let evaluated = run + .legacy + .stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms) + .expect("a frame should complete"); + run.payouts.extend(evaluated.rewards); + if run.balls() < balls { + if low { + thrown_low += 1; + } + break; + } + } + if thrown_low > 0 && low_frames > 0 { + break; + } + } + eprintln!( + "{battles} wild battles; {low_frames} low-HP frames with the ball dealt; thrown at low HP \ + {thrown_low}; low pads {low_pads:?}; high pads with the ball {high_ball_pads:?}" + ); + eprintln!("(species, enemy hp, max, own hp) as it changed: {:?}", &hp_log[..hp_log.len().min(120)]); + assert!(low_frames > 0, "no wild battle reached low HP with a ball dealt"); + let allowed = [THROW_BALL_CHANNEL, "macro_item"]; + for pad in &low_pads { + assert!( + pad.iter().all(|channel| allowed.contains(&channel.as_str())), + "a low-HP pad with more than the ball on its attack side: {pad:?}" + ); + } + assert!(thrown_low > 0, "the ball was thrown at low HP"); +} + +/// Row 69's bound: a fly that types nothing is not left on the keyboard. After sixty brain seconds +/// (`palette::NAMING_BOUND_MS`) `CONFIRM` alone is dealt, hands the name back empty, and the +/// cartridge keeps the species' own name. The stub presses no letter: only the D-pad group's own +/// rotation reaches the keyboard. +#[test] +fn row69_a_fly_that_types_nothing_is_ended_by_the_bound() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let Some(checkpoint) = checkpoint() else { + eprintln!("skipped: no FLY_CATCH_CHECKPOINT"); + return; + }; + if Run::resume(&rom, &checkpoint).balls() == 0 { + eprintln!("skipped: the checkpoint's bag holds no ball"); + return; + } + let after = (0..24) + .find_map(|attempt| drive_past_a_catch_typing(&rom, &checkpoint, attempt * 5, false)) + .expect("one of 24 attempts should keep a Pokémon"); + let board = &after.keyboard; + eprintln!( + "keyboard {} frames over {} (raw {}), longest {}, name {:?}, starts {:?}, pads {:?}, \ + closed {}", + board.frames, + board.span, + board.raw_frames, + board.longest, + board.name, + board.starts, + board.pads, + board.closed + ); + assert_eq!(board.longest, 0, "nothing typed"); + assert_eq!(board.starts, vec!["CONFIRM"], "the bound's one button, once"); + assert_eq!( + board.pads.iter().cloned().collect::>(), + vec![vec!["macro_confirm".to_string()]] + ); + // Sixty brain seconds at 59.7275 frames a second is 3,584 frames, and a little for the press. + assert!((3_500..3_800).contains(&board.span), "the bound ran: {} frames", board.span); + assert!(board.closed); +} + +/// Row 69: the two naming-screen bytes the palette reads are where the cartridge's own +/// instructions store them. `PrintNicknameAndUnderscores`: `ld a, c / ld [wNamingScreenNameLength], +/// a / hlcoord 10, 2` (`$79 $EA lo hi $21 $D2 $C3`); `DisplayNamingScreen.pressedStart`: +/// `ld a, 1 / ld [wNamingScreenSubmitName], a / ret` (`$3E $01 $EA lo hi $C9`). +#[test] +fn row69_the_naming_bytes_are_where_the_cartridge_stores_them() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + use flybrain_gb::pokemon_red::state::poke; + let [lo, hi] = poke::NAMING_LENGTH.to_le_bytes(); + let length = [0x79, 0xea, lo, hi, 0x21, 0xd2, 0xc3]; + assert!(rom.windows(length.len()).any(|window| window == length), "wNamingScreenNameLength"); + let [lo, hi] = poke::NAMING_SUBMIT.to_le_bytes(); + let submit = [0x3e, 0x01, 0xea, lo, hi, 0xc9]; + assert!(rom.windows(submit.len()).any(|window| window == submit), "wNamingScreenSubmitName"); + assert_eq!(poke::NAMING_SUBMIT, poke::NAMING_LENGTH + 1, "consecutive in the UNION"); +} diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index 15020bd..980ad75 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -1011,8 +1011,11 @@ impl Run { } } // Section 12.13's claim, per frame: an `Unknown` with nothing drawn deals nothing. + // The keyboard (row 69) is drawn -- its own box, not the text font -- and its bound's + // `CONFIRM` is a pad on something drawn, so it is not counted. if self.layer.scene_name() == "unknown" && !flybrain_gb::pokemon_red::state::text_box(&mut self.gb).open + && flybrain_gb::pokemon_red::state::naming_screen(&mut self.gb).is_none() && !self.layer.bound_channels().is_empty() { self.unknown_pads_with_no_box += 1;