diff --git a/docs/design/macros.md b/docs/design/macros.md index cbed22c..3e5aff6 100644 --- a/docs/design/macros.md +++ b/docs/design/macros.md @@ -1650,6 +1650,93 @@ Nothing is ranked or pressed for the fly: frames that were never the fly's deal decoder, the reward catalog, the adapter version, the roles and the compatibility string are untouched. +### 12.26 A counter the fly has a use for is dealt again, and a purchase is done when it is paid (2026-09-24, row 62) + +The operator's reset to milestone 1 was to watch the shop, the Poké Balls and the catching. Eleven +and a half hours later the live fly (v0.6.2) had reached rung 12, Mt. Moon, with the Boulder Badge, +and in the whole event log had done `GO SHOP` twice (the parcel) and nothing else of it: no `BUY`, +no `THROW BALL`, no `GO HEAL`, `HEAL` or nurse's YES. It whited out in Mt. Moon again and again and +walked back from Pallet Town each time. The log records what was chosen, not what was dealt, so +the question was which. Surveyed with a new probe mode (`FLY_PROBE_CATCH=offers` in +`examples/scene_probe.rs`: the service's frame behind a uniform stub, counting per decidable frame +what is on the pad and reading the cartridge beside it) from the live checkpoint and four others. +**It was the pad**, in five places: + +- **The errand was paid by a visit on which the counter could do nothing, and never came back.** + Section 13's "one visit per area per run" is paid on entering, and since row 54 by the + adapter's lifetime map ledger too. The Viridian mart is first entered for Oak's parcel, when + its clerk sells nothing; a centre entered with a full party heals nothing. From then on + `GO SHOP` and `GO HEAL` were off every pad in that area for the run, whatever the party or the + bag read. **`service_needed`** is the other half of the question, read from the cartridge each + time: a centre while the party needs rest (`party_needs_rest`, the byte `HEAL` and the nurse's + prompt already read), a mart while the bag has no ball, the wallet covers one (200) and the bag + does not hold Oak's parcel (until it is delivered the Viridian clerk's text table is the + parcel's). A ball because `THROW BALL` is the one button a purchase has to make possible, and + every Kanto mart stocks it first, within the cursor's reach. It **satisfies itself**: a heal + leaves the party full and a purchase leaves a ball, so the button leaves the pad when its job + is done. `GO SHOP` / `GO HEAL` aim at the area's building while the errand or the need holds. +- **A counter person the session had talked to or reached was retired for the session.** Inside, + with the need, the walk to the counter and `TALK` at it ignore the talked and reached ledgers + (the blocked window is kept); `TALK` at a counter is `facing_service` beside `facing_untalked`. + 12.12's rule is unchanged where it applies: a rested party has no use for the nurse and `TALK` + is off. +- **`HEAL` was off the pad on the one tile it is for.** Its goals were `counter_aims`, which drops + the tile already facing the nurse -- where `GO HEAL` leaves the fly -- and retires a nurse + `GO HEAL` has reached for ten brain minutes. `HEAL`'s goals now keep that tile and read neither + ledger; the party is its satiation. +- **From a centre's door the nurse is off the screen.** A centre is entered at (3, 7) and its + nurse stands at (3, 1), six rows up, so the drawn sprites held nobody behind the counter: on the + arrival frame `HEAL`, `GO HEAL` and the counter's suppression (13.1) were all off, and the pad + was the way out. The counter person is read from the drawn and the off-screen sprites, row 58's + reading of the cartridge's own availability rule. +- **Route 4's centre, the last before Mt. Moon, was on no table.** `MT_MOON_POKECENTER` (`$44`, + Route 4's warp at (11, 5)) is on the map graph, on Route 4's west piece and in the amenity table + as Route 4's centre, so `HEAL` is dealt in it, and a hurt fly in Mt. Moon's first floor (whose + area is Route 4) has `GO HEAL` to walk out to it. + +**Two limits on where a service is wanted** (the row's review, round 2). Both are the existing +rules applied to the new half of the question, and both hold for the errand too. + +- **The building is the area's only from ground whose road to it stays in the area** + (`geography::route_within`). An area is counted by map id, and Route 4 is split: its east side + and Mt. Moon B1F's exit chamber are "in Route 4", but the only road from them to the centre on + the west side runs through B2F, which is in no area. So east of the mountain -- where the fly + arrives hurt -- `GO HEAL` walked down into B2F and left the pad there, while `GO OBJECTIVE` + walked back up toward Cerulean: a two-map ring by construction. The errand had the same fault + under `GO OBJECTIVE` itself (`errand_place` sent it to the centre behind the mountain). From + there Route 4's centre is not the area's; the rung is, and Cerulean's centre is one edge away + and its own area's. Every town is one piece, so nothing moved for them. +- **The room the rung is in is not left for a service.** Row 29's rule (12.5), which already + withholds the ways out while the rung's own target stands in the room untalked and unexcluded, + now withholds `GO HEAL` and `GO SHOP`'s walk out as well. A hurt party in a gym is the usual + case -- its trainers are why -- and row 58's ROM test measured it: four of six arrivals in the + Pewter Gym bounced back out, two by `GO HEAL` and one by `GO SHOP`. The errand needs no such + line: while it stands it *is* the objective. The escape hatch is the rule's own: a target no + walk reaches is excluded for the window and the service is wanted again. + +**And `BUY BALL` reported `done` with nothing bought.** Pressed at the counter it ran 55 times from +the Pewter checkpoint, 55 `done`, the wallet at 1,606 throughout. After the quantity the mart +prints "POKé BALL? / That will be" and **waits for a press** (a `cont`), then prints "¥200. OK?" +and only then draws its YES/NO box; the script's one blind A after a settle was that press, and +the macro ended before the box existed. A purchase now pulses A until the box is drawn (the +general `yes_no_prompt` reading of row 56), presses YES, and is `done` when the wallet reads less +than it did: the cartridge rings the item up a few frames after the press. Either wait running +out is `blocked`. + +**Measured, and what stays the fly's.** `THROW BALL` was never the pad's fault: it is off with no +ball (it cannot work) and dealt on 385 of 1,070 wild-battle frames with one, on both arms; pressed, +it catches. The live run had no ball because nothing on the pad could buy one. Survey totals, ten +twenty-minute uniform-stub runs per arm (`infra/docs/macros-traps.md` row 62): `GO HEAL` dealt +140 -> 2,300 frames, heals 2 -> 12, the whiteout map moved off Pallet Town in 2 -> 9 runs, +whiteouts 14 -> 9; `GO SHOP` dealt 101 -> 569. Whether the fly presses `TALK` at an open counter, +`CONFIRM` at the clerk's greeting and `BUY BALL` on the list is its choice; under the uniform stub +it rarely strings the four together, and with them preferred the chain buys a ball on the +cartridge (the ROM test). + +Nothing ranks a button or presses for the fly: preconditions read the cartridge, and a purchase +waits for the box it answers. The decoder, the reward catalog, the adapter version, the roles and +the compatibility string are untouched. + ### 12.27 An A the cartridge has not let go of is not a press, and a menu it is acting on is not a pad (2026-09-24, row 63) Live on v0.6.2, rung 12, Mt. Moon B2F (map 61), wild battles: per ten minutes `BACK` 62, `ITEM` @@ -1702,7 +1789,8 @@ Knowledge inside macros, never in the choice; the pad still lists buttons and th - **`GO SHOP` / `GO HEAL`** are the errands as buttons of their own too (populations `macro_go_shop`, `macro_go_heal`, from the same MBON/motor pool by the same rule): on the pad when the area's mart / center is unvisited (GO SHOP also needs money), walk to its door and - in; inside, walk to the counter / nurse and face them. + in; inside, walk to the counter / nurse and face them. Since **12.26** also while the building + has a job to do: a centre for a party that needs rest, a mart for a bag with no ball. - **Shop scene.** Buttons are purchases: `BUY POTION`, `BUY BALL`, `BUY ANTIDOTE`, `BUY REPEL`, each bound only when the mart's stock (read from WRAM, `shop_stock` accessor, verified by the survey method) lists it and money allows at least one; each macro buys ONE unit through diff --git a/infra/docs/macros-traps.md b/infra/docs/macros-traps.md index 9bb74a2..67dfed8 100644 --- a/infra/docs/macros-traps.md +++ b/infra/docs/macros-traps.md @@ -3052,6 +3052,101 @@ On `main` `510727c` (v0.6.1, row 59 merged): - `flysim --print-compatibility`, raw and macros: 648 bytes, sha256 `8ce67b97...a8f68`, the same as `main`. Decoder, reward catalog, adapter version and roles untouched. +## 2026-09-24, row 62: the shop, the balls and the nurse, withheld + +### What was live + +v0.6.2, the fresh run since the operator's reset to milestone 1, about eleven and a half hours: +rung 12 (MT. MOON) with the Boulder Badge, 16 trainer wins, 86 wild wins. In the whole event log +(70,357 macro events) `GO SHOP` twice (the parcel errand), then no `BUY`, no `THROW BALL`, no +`GO HEAL`, `HEAL` or nurse's YES, 72 `TALK`. Rung 12 took 3.5 hours: the fly whited out in Mt. +Moon again and again and walked back from the south. The live checkpoint reads one Pokémon at +54/80, 508 money (every whiteout halves it), no ball, the Viridian and Pewter marts and the Mt. +Moon centre in the lifetime map ledger, the Pewter centre not, and **`wLastBlackoutMap` (`$d719`) += `$00`, Pallet Town**: only the nurse's YES writes it (`SetLastBlackoutMap`), and the fly had never +said it. + +### The survey: what the pad dealt + +`FLY_PROBE_CATCH=offers` in `examples/scene_probe.rs` (new): 71,673 frames of the service's frame +behind a uniform stub, per decidable frame (a playable scene, a pad, no macro running) which +watched buttons are dealt, and the cartridge beside it. From the live checkpoint on `main`, twenty +brain minutes in Mt. Moon: `HEAL`, `GO HEAL`, `GO SHOP`, `BUY BALL`, `BUY POTION` and `THROW BALL` +on **0** of 32,178 decidable frames. From row 59's checkpoint inside the Mt. Moon centre at 10/70: +`HEAL` on 31 frames of 28,069, never in that centre. With the chain's buttons preferred (a +survey's driver), from the rung-11 Pewter checkpoint: `GO SHOP` never dealt on `main`; on the +branch before the purchase fix, `BUY BALL` 55 starts, 55 `done`, the wallet at 1,606 throughout. + +| # | trap | trigger | test | fix, or why it is left | +| --- | --- | --- | --- | --- | +| 62 | section 13's errand is paid on entering, also by a visit on which the counter could do nothing (Oak's parcel at the Viridian mart, a centre entered with a full party), and with the lifetime map ledger since row 54 `GO SHOP` / `GO HEAL` never came back for the run | every town after its first visit; live, the whole run after the parcel | `go_heal_comes_back_for_a_hurt_party_after_the_errand_is_paid`, `go_shop_comes_back_while_the_bag_has_no_ball_and_the_money_covers_one`, `row62_go_shop_comes_back_with_no_ball_and_buy_ball_rings_up_a_ball` (ROM) | **fixed**: `palette::service_needed` (a centre while the party needs rest; a mart while the bag has no ball, the wallet covers one and no Oak's parcel is carried); `GO SHOP` / `GO HEAL` aim at the area's building while the errand or the need holds. Self-satisfying. `docs/design/macros.md` 12.26 | +| 62b | a counter person this session had talked to or reached is retired from `TALK` and the counter walk for the session | a second visit to a counter in one session | `a_counter_the_fly_has_a_use_for_opens_again_after_this_session_has_talked_to_it`, `a_declined_heal_writes_the_nurse_into_the_talked_ledger` | **fixed**: with the need, the walk and `TALK` (`facing_service`) ignore talked and reached; blocked kept; a rested party still has no `TALK` at the nurse (12.12) | +| 62c | `HEAL`'s goals were `counter_aims`, which drops the tile already facing the nurse and a nurse `GO HEAL` has reached (ten minutes) | at the counter, and after every `GO HEAL` | `heal_is_dealt_facing_the_nurse_and_after_go_heal_has_reached_her` | **fixed**: `HEAL`'s aims keep the facing tile and read neither ledger | +| 62d | from a centre's door (3, 7) the nurse at (3, 1) is off the screen, so the drawn sprites hold nobody behind the counter: `HEAL`, `GO HEAL` and the counter suppression off on arrival, the way out on the pad | every centre entry | `the_nurse_is_found_from_the_door_when_the_screen_does_not_draw_her` | **fixed**: the counter person is read from the drawn and the off-screen sprites (row 58's `offscreen_npcs`) | +| 62e | Route 4's centre (`$44`) was on no table: no `HEAL` in it, no errand to it | the last centre before Mt. Moon | `the_mt_moon_pokecenter_is_a_centre_and_route_4s`, `row62_heal_is_dealt_in_the_mt_moon_center_and_moves_the_whiteout_map` (ROM) | **fixed**: `MT_MOON_POKECENTER` in LINKS, Route 4's west piece and AMENITIES; Mt. Moon 1F's area is Route 4 | +| 62f | `BUY …` pressed its last A while the price line was still up: after the quantity the mart prints "That will be" and waits for a press (a `cont`), then draws the YES/NO box; the macro reported `done` with nothing bought and the box left to the next hold | every purchase | `a_purchase_answers_the_price_box_once_the_cartridge_has_drawn_it`, the three purchase tests, `row62_go_shop_…` (ROM) | **fixed**: `Step::Prompt` pulses A until the box is drawn, YES, `Step::Paid` waits for the wallet to drop; running out is `blocked` | +| 62g | `THROW BALL` | -- | -- | **not a trap**: off with no ball, dealt on 385 of 1,070 wild-battle frames with one (both arms), catches when pressed. The live run had no ball because 62/62f left no way to buy one | +| 62h | the nurse's YES is dealt only for a hurt party, so a full party passing a centre never moves `wLastBlackoutMap` | a centre visited healthy | -- | **left, operator's**: the prompt's other effect is the whiteout map, which no macro reads; 12.12 keeps the full-party ring closed. With 62/62c/62d a hurt fly heals and moves it (9 of 10 branch surveys) | + +### Before and after + +Ten uniform-stub surveys per arm, 71,673 frames each (twenty brain minutes), `main` `862e343` vs +branch, seeds 20260924 and 7. Checkpoints: `live` the row-62 live one (Mt. Moon 1F); `mtmoonpc` +row 59's, inside the Mt. Moon centre at 10/70; `viridian` the milestone-5 one carried to rung 8 +(Viridian centre, 3,175, before the parcel); `pewter` row 59's rung-11 survey checkpoint (Pewter +gym, 1,606, no ball, errands paid); `route2ball` the 2026-09-22 rung-9 one (Route 2, one Poké Ball). +Cells are "frames dealt / starts". + +| run (checkpoint-arm-seed) | decidable | HEAL dealt/started | GO HEAL dealt/started | GO SHOP dealt/started | BUY BALL dealt/started | BUY POTION dealt/started | THROW BALL dealt/started | heals | balls bought | thrown | catches | whiteouts | blackout map | +| live-base-s20260924 | 32178 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 0 | 0x00 | +| live-base-s7 | 23494 | 0/0 | 48/3 | 1/1 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 | +| live-branch-s20260924 | 31387 | 2/0 | 541/16 | 0/0 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 0 | 0x0f | +| live-branch-s7 | 28546 | 7/0 | 405/8 | 178/6 | 0/0 | 0/0 | 0/0 | 2 | 0 | 0 | 0 | 1 | 0x02 | +| mtmoonpc-base-s20260924 | 28069 | 31/0 | 75/3 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 | +| mtmoonpc-base-s7 | 27696 | 9/0 | 11/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 | +| mtmoonpc-branch-s20260924 | 35812 | 4/0 | 356/9 | 0/0 | 0/0 | 0/0 | 0/0 | 2 | 0 | 0 | 0 | 1 | 0x0f | +| mtmoonpc-branch-s7 | 35128 | 25/2 | 634/7 | 0/0 | 0/0 | 0/0 | 0/0 | 2 | 0 | 0 | 0 | 0 | 0x0f | +| pewter-base-s20260924 | 35351 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 | +| pewter-base-s7 | 33628 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 | +| pewter-branch-s20260924 | 33541 | 1/1 | 42/3 | 72/5 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 1 | 0x02 | +| pewter-branch-s7 | 35554 | 0/0 | 30/1 | 29/2 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 | +| route2ball-base-s20260924 | 32315 | 0/0 | 2/0 | 1/1 | 0/0 | 0/0 | 385/6 | 0 | 0 | 1 | 0 | 1 | 0x00 | +| route2ball-base-s7 | 39135 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 385/6 | 0 | 0 | 1 | 0 | 1 | 0x00 | +| route2ball-branch-s20260924 | 30993 | 41/0 | 209/6 | 38/2 | 9/0 | 9/1 | 385/6 | 1 | 0 | 1 | 0 | 1 | 0x02 | +| route2ball-branch-s7 | 32296 | 1/1 | 57/2 | 0/0 | 0/0 | 0/0 | 385/6 | 1 | 0 | 1 | 0 | 1 | 0x01 | +| viridian-base-s20260924 | 24307 | 2/1 | 2/0 | 34/2 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 3 | 0x01 | +| viridian-base-s7 | 29710 | 1/1 | 1/0 | 65/2 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 4 | 0x01 | +| viridian-branch-s20260924 | 34564 | 3/0 | 25/1 | 158/3 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 1 | 0x01 | +| viridian-branch-s7 | 30238 | 1/1 | 1/0 | 94/2 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 2 | 0x01 | + +Totals, base -> branch: decidable frames 305,883 -> 328,059; `HEAL` dealt 43 -> 85; `GO HEAL` +dealt 140 -> 2,300 (starts 8 -> 53); `GO SHOP` dealt 101 -> 569 (starts 6 -> 20); heals 2 -> 12; +whiteout map off Pallet Town in 2 -> 9 runs; whiteouts 14 -> 9; `THROW BALL` identical (770 / 12, +two thrown). No ball bought under the uniform stub on either arm: the counter opens only on +`TALK`, then `CONFIRM`, then `BUY BALL`, and the stub rarely picks the three in a row. That is +the fly's choice; with the chain preferred, the branch buys (Pewter: 1,606 -> 1,406, one ball) and +`main` cannot (no `GO SHOP`, and a `BUY BALL` that ends before its box). The ROM tests fail on +`main` (`HEAL` never dealt in 3,000 frames in the Mt. Moon centre; `GO SHOP` not on Pewter's pad) +and pass on the branch (healed in 587 frames, `wLastBlackoutMap` `$0f`; one ball, 200 paid). + +The live event log's choices against the pad the survey measured from the live checkpoint on +`main`: `HEAL`, `GO HEAL`, `GO SHOP`, `BUY BALL`, `BUY POTION`, `THROW BALL` dealt on 0 frames and +chosen 0 times, except `GO SHOP` (2 starts in eleven hours, both the parcel errand, dealt only +before it was paid). None of it was the fly's choice. + +**Review round 2** (two blocking findings, fixed in the macros; `docs/design/macros.md` 12.26). +(1) Route 4's centre was dealt as `GO HEAL` (and as the errand under `GO OBJECTIVE`) from Route 4's +east side and B1F's exit chamber, both in Route 4's area, and the road to it runs through B2F, in +no area: the button dropped one hop in, opposite the road to Cerulean. A building is now the area's +only where the route to it stays in the area (`geography::route_within`). ROM, from the live +B2F checkpoint stepped up the ladder: the first round deals `GO HEAL` on 642 of 2,492 hurt frames +east of the mountain and walks back down into B2F; the fix deals it on none (`main` none, no row). +(2) Row 58's gym test failed on the first round (6 arrivals, 4 straight back out, by `GO HEAL` and +`GO SHOP`): a service is not wanted while the rung's own target stands in the room (row 29's rule), +and it passes (2 arrivals, 0 out, the badge won). The live Mt. Moon B2F trap at the ladder (row 64) +is not this mechanism: from its checkpoint all three arms stay on B2F for twenty brain minutes, +identically, and on `main` there is no Route 4 centre to route to. + ## 2026-09-24, row 63: Mt. Moon B2F, ITEM, BACK, BACK ### What was live 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 a125865..dac0e49 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 @@ -56,6 +56,10 @@ pub mod item { pub const POTION: u8 = 20; /// `$1e`. pub const REPEL: u8 = 30; + /// `$46`. The Viridian clerk's parcel for Oak: while the bag holds it, that counter has + /// nothing to sell (`scripts/ViridianMart.asm` keeps the parcel's text table until + /// `EVENT_OAK_GOT_PARCEL`). + pub const OAKS_PARCEL: u8 = 0x46; } /// Mart prices at the pinned pokered commit, for section 3's "if money allows". 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 d1cc28b..dcc6b4f 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 @@ -120,6 +120,16 @@ const SETTLE_FRAMES: u32 = 20; /// because a battle spends whole seconds animating, and a wait presses nothing. const CURSOR_WAIT: u32 = 180; +/// Frames a purchase waits for the mart's YES/NO box before it gives up ([`Step::Prompt`]). +/// +/// The price line is two dozen characters either side of one press, at the cartridge's text +/// speed; six brain seconds is twice what the Pewter counter took. +const PROMPT_WAIT: u32 = 360; + +/// Frames between the presses [`Step::Prompt`] makes while the price line is up: one +/// [`PRESS_HOLD`] of A, then released, so the press is a new one each time. +const PROMPT_PULSE: u32 = 40; + /// 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; @@ -343,6 +353,23 @@ enum Step { /// the presses happened and the conversation may simply have been about something else -- so /// it reports `Next` and the close press still happens. Rested { waited: u32 }, + /// Advance the price line until the mart's YES/NO box is drawn ([`MacroState::yes_no_prompt`]), + /// then move on to the press that answers it; `Blocked` if the box never comes. + /// + /// A purchase's last answer (row 62). After the quantity the mart prints "POKe BALL? / That + /// will be" and **waits for a press** -- the line is a `cont`, with the blinking arrow -- and + /// only after it prints "200. OK?" and draws the box. The script's one blind A after a settle + /// was that press, so the box came up after the macro had reported `done`: 55 `BUY BALL` + /// starts on the cartridge, 55 `done`, the wallet at 1,606 throughout, and the box left to + /// whatever the pad dealt next. So this pulses A every [`PROMPT_PULSE`] frames while no box + /// is drawn -- a press on a line still printing only prints it faster -- and reads the box + /// the way `HEAL` reads the party. `before` is the wallet when the purchase began: if it has + /// dropped, a pulse already answered the box and the purchase is rung up. + Prompt { waited: u32, before: u32 }, + /// Press nothing until the wallet reads less than `before`, which is the purchase rung up; + /// `Blocked` if it never does. The cartridge adds the item and takes the money a few frames + /// after the YES, so a purchase is `done` when the wallet says so and not when the press is. + Paid { waited: u32, before: u32 }, } /// Progress through one A* walk. @@ -1462,6 +1489,32 @@ fn advance(step: &mut Step, state: &mut dyn MacroState) -> Progress { Progress::Hold(buttons::NONE) } } + Step::Paid { waited, before } => { + if state.money() < *before { + Progress::Next + } else if *waited >= PROMPT_WAIT { + Progress::Blocked + } else { + *waited += 1; + Progress::Hold(buttons::NONE) + } + } + Step::Prompt { waited, before } => { + if state.money() < *before { + Progress::Finished + } else if state.yes_no_prompt() { + Progress::Next + } else if *waited >= PROMPT_WAIT { + Progress::Blocked + } else { + *waited += 1; + if *waited % PROMPT_PULSE < PRESS_HOLD { + Progress::Hold(buttons::A) + } else { + Progress::Hold(buttons::NONE) + } + } + } } } @@ -2300,6 +2353,7 @@ fn approach(state: &mut dyn MacroState, targets: &[(Tile, TalkTarget)]) -> Vec Option> { let index = stock_index(state, want)?; + let before = state.money(); let mut steps = Vec::new(); if shop_screen(state)? == ShopScreen::BuySellQuit { // BUY is the counter menu's first entry. @@ -2308,10 +2362,12 @@ fn shop_plan(state: &mut dyn MacroState, want: u8) -> Option> { } steps.push(cursor(index, true)); steps.push(settle()); - // The quantity prompt opens on one, and the price confirmation opens on YES. + // The quantity prompt opens on one, and the price confirmation opens on YES -- once it is + // drawn, which is after the price has finished printing (row 62). steps.push(press(buttons::A)); - steps.push(settle()); + steps.push(Step::Prompt { waited: 0, before }); steps.push(press(buttons::A)); + steps.push(Step::Paid { waited: 0, before }); Some(steps) } 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 351eb35..fffb3cc 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 @@ -160,6 +160,10 @@ const LINKS: &[(u8, u8)] = &[ (maps::MT_MOON_1F, maps::MT_MOON_B1F), (maps::MT_MOON_B1F, maps::MT_MOON_B2F), (maps::MT_MOON_B1F, maps::ROUTE_4), + // Route 4's own Pokémon Center, the door at (11, 5) on the cave mouth's side (row 62). On the + // graph because it is an amenity ([`AMENITIES`]): a centre with no row here is one no errand + // can walk to and no `HEAL` is dealt in. + (maps::MT_MOON_POKECENTER, maps::ROUTE_4), (maps::CERULEAN_GYM, maps::CERULEAN_CITY), (maps::CERULEAN_MART, maps::CERULEAN_CITY), (maps::CERULEAN_POKECENTER, maps::CERULEAN_CITY), @@ -283,7 +287,11 @@ const SPLIT: &[Split] = &[ pieces: &[ Piece { doors: &[(0, 11, 5), (1, 18, 5)], - next: &[Region::whole(maps::ROUTE_3), Region::whole(maps::MT_MOON_1F)], + next: &[ + Region::whole(maps::ROUTE_3), + Region::whole(maps::MT_MOON_POKECENTER), + Region::whole(maps::MT_MOON_1F), + ], }, Piece { doors: &[(2, 24, 5)], @@ -627,6 +635,9 @@ const AMENITIES: &[(u8, Amenity, u8)] = &[ (maps::VIRIDIAN_CITY, Amenity::Center, maps::VIRIDIAN_POKECENTER), (maps::PEWTER_CITY, Amenity::Mart, maps::PEWTER_MART), (maps::PEWTER_CITY, Amenity::Center, maps::PEWTER_POKECENTER), + // Route 4 has no mart, and its centre is the last one before Mt. Moon (row 62): the one the + // cave's first floor is an area with, since Mt. Moon's mouths open onto Route 4. + (maps::ROUTE_4, Amenity::Center, maps::MT_MOON_POKECENTER), (maps::CERULEAN_CITY, Amenity::Mart, maps::CERULEAN_MART), (maps::CERULEAN_CITY, Amenity::Center, maps::CERULEAN_POKECENTER), ]; @@ -654,6 +665,32 @@ pub fn amenity_of(area: u8, kind: Amenity) -> Option { .map(|(_, _, map)| *map) } +/// Whether the route [`next_step`] walks from `from` to the map `to` stays inside `area` on every +/// hop, which is what makes `to` *this area's* building from where the fly stands. +/// +/// An area is counted by map id ([`area_of`]), and a split map's pieces can be in one area while +/// the ground between them is not: Route 4's east side, and Mt. Moon B1F's exit chamber, are "in +/// Route 4" and its centre is on the west side, through B2F, which is in no area at all (row 62, +/// review round 2). A walk that has to leave the area to reach the building is not the area's +/// errand from here -- it is the mountain crossed backwards, and the first hop off the area drops +/// the button that started it. `true` when `from` is already on `to`; `false` when no route is +/// known. +pub fn route_within(from: Region, to: u8, area: u8) -> bool { + let mut here = from; + // A shortest route never revisits a piece, so it is at most as long as the table is big. + for _ in 0..=LINKS.len() + CONNECTIONS.len() { + if here.map == to { + return true; + } + let Some(hop) = next_step(here, to) else { return false }; + if hop.map != to && area_of(hop.map) != Some(area) { + return false; + } + here = hop; + } + 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 @@ -1090,6 +1127,32 @@ mod tests { assert_eq!(amenity_at(maps::VIRIDIAN_CITY), None); } + #[test] + fn route_4s_centre_is_the_areas_only_from_the_mountains_west_side() { + // Row 62, review round 2: Route 4's east side and B1F's exit chamber are in Route 4's + // area, and the only road from them to its centre is through B2F, which is in none. + let centre = maps::MT_MOON_POKECENTER; + let area = maps::ROUTE_4; + assert_eq!(next_step(Region::piece(maps::ROUTE_4, EAST_SIDE), centre).map(|hop| hop.map), Some(maps::MT_MOON_B1F)); + assert_eq!(next_step(Region::piece(maps::MT_MOON_B1F, B1F_EXIT), centre).map(|hop| hop.map), Some(maps::MT_MOON_B2F)); + assert_eq!(area_of(maps::MT_MOON_B2F), None, "the fossil floor opens on no outdoor map"); + assert!(!route_within(Region::piece(maps::ROUTE_4, EAST_SIDE), centre, area)); + assert!(!route_within(Region::piece(maps::MT_MOON_B1F, B1F_EXIT), centre, area)); + // The west side, the first floor and the three chambers a first-floor ladder reaches. + assert!(route_within(Region::piece(maps::ROUTE_4, WEST_SIDE), centre, area)); + assert!(route_within(Region::whole(maps::MT_MOON_1F), centre, area)); + for chamber in [B1F_WEST, B1F_MIDDLE, B1F_SOUTH] { + assert!(route_within(Region::piece(maps::MT_MOON_B1F, chamber), centre, area), "{chamber}"); + } + assert!(route_within(Region::whole(centre), centre, area), "already there"); + // A town is one piece, so every building off it is within: nothing moved for them. + for (town, kind) in [(maps::VIRIDIAN_CITY, Amenity::Mart), (maps::PEWTER_CITY, Amenity::Center)] { + let building = amenity_of(town, kind).unwrap(); + assert!(route_within(Region::whole(town), building, town)); + assert!(route_within(Region::whole(maps::PEWTER_GYM), maps::PEWTER_POKECENTER, maps::PEWTER_CITY)); + } + } + #[test] fn every_amenity_is_on_the_map_graph() { // A building with no `LINKS` row is one `GO OBJECTIVE` and `GO SHOP` could never route to, 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 e956259..2aed2b5 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 @@ -11,7 +11,7 @@ use super::cartridge::{ CHEAPEST_PURCHASE, FACINGS, MART_CURSOR_ROWS, opposite, ExitId, ListKind, Listing, MacroState, Objective, PARTY_CAPACITY, PURCHASES, TalkTarget, - TargetKey, Tile, item, outdoors, + TargetKey, Tile, item, outdoors, price, }; use crate::adapter::PlaceKind; @@ -637,7 +637,13 @@ pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool { // object with a purpose, not a person to chat with: with the party already full her whole // conversation is forty-six text frames that end where they began, which is section // 12.2's trap at conversation scale (section 12.12). - MacroKind::Talk => facing_untalked(state) && !rested_nurse(state), + // ...and, since row 62, at a counter the fly has a use for however many times this + // session has already talked to it ([`facing_service`]): a clerk or a nurse is a service, + // and the talked ledger answers "is there anything left to say", which for a service is + // the party's HP or the bag's balls rather than the last conversation. + MacroKind::Talk => { + (facing_untalked(state) || facing_service(state)) && !rested_nurse(state) + } // The start menu opens from anywhere, and that is exactly why `MENU` is on no pad: // "the precondition is satisfied wherever the fly stands" is section 12.2's trap, and a // macro whose whole effect is a screen its own scene's `BACK` closes again is 12.10's @@ -887,7 +893,7 @@ pub fn errand(state: &mut dyn MacroState, kind: Amenity) -> Option { if kind == Amenity::Mart && state.money() < CHEAPEST_PURCHASE { return None; } - let map = geography::amenity_of(area, kind)?; + let map = amenity_in_reach(state, area, kind)?; // **A building this run has already been inside is an errand already discharged.** The session // ledger above is the errand's own record and it is the one that can be missing: it is written // from the frame the fly stands on the building's map, so a restore starts with it empty and @@ -989,9 +995,16 @@ pub fn stock_index(state: &mut dyn MacroState, item: u8) -> Option { pub fn amenity_goals(state: &mut dyn MacroState, kind: Amenity) -> Vec { let Some(here) = state.player().map(|player| player.map) else { return Vec::new() }; if geography::amenity_at(here) == Some(kind) { + // **A counter the fly has a use for is not retired by the last visit** (row 62). The + // reached and talked ledgers answer "is this job done", and for a service the answer is + // the party or the bag, not the ledger: a nurse reached an hour ago with a party that has + // since been beaten is a job to do again. + if service_needed(state, kind) { + return service_aims(state, kind); + } return counter_aims(state, counter_sprite(kind)); } - match errand(state, kind) { + match amenity_wanted(state, kind) { Some(map) => { let here = state.player().map(|player| Tile::new(player.x, player.y)); goals_toward(state, map) @@ -1019,7 +1032,123 @@ pub fn heal_goals(state: &mut dyn MacroState) -> Vec { if geography::amenity_at(here) != Some(Amenity::Center) { return Vec::new(); } - counter_aims(state, poke_sprite::NURSE) + // **Neither the reached nor the talked ledger, and the counter the fly already faces is + // somewhere to heal from** (row 62). `HEAL` is only dealt while the party needs it, and that + // is its whole satiation: a completed heal leaves a party that reads full. Through + // [`counter_aims`] the button was off the pad on the one tile it is for -- facing the nurse, + // which is where `GO HEAL` leaves the fly, and for ten brain minutes after `GO HEAL` had + // reached her. Only the blocked window is kept: a counter no walk can reach is still that. + person_aims(state, poke_sprite::NURSE, Ledgers::BlockedOnly, true) +} + +/// Whether the building of `kind` has something to do for the fly right now: the party needs the +/// nurse, or the bag has no ball the wallet could buy one of (row 62). +/// +/// The errand (section 13) is "visit each area's building once per run", and it is paid on +/// entering -- by a visit on which the counter could do nothing, too: the Viridian mart is entered +/// first for Oak's parcel, when its clerk sells nothing, and a centre entered with a full party +/// heals nothing. Once paid it was never offered again, whatever the party or the bag read. This +/// is the other half of the same question, read from the cartridge each time it is asked, and +/// **it satisfies itself**: a heal leaves the party full and a purchase leaves a ball in the bag, +/// so the button leaves the pad the moment the job is done. +/// +/// - **Centre**: [`party_needs_rest`], the same byte `HEAL` and the nurse's prompt read. +/// - **Mart**: no ball in the bag, and the money for one. A ball because `THROW BALL` is the one +/// button in the vocabulary that a purchase has to make possible -- with no ball it is never +/// dealt (section 12.9) -- and every mart in Kanto stocks it as its first row +/// (`data/items/marts.asm`), inside the cursor's reach ([`stock_index`]). And not while the bag +/// holds Oak's parcel: until it is delivered the Viridian clerk's text table is the parcel's, +/// and his counter sells nothing (`scripts/ViridianMart.asm`). +pub fn service_needed(state: &mut dyn MacroState, kind: Amenity) -> bool { + match kind { + Amenity::Center => party_needs_rest(state), + Amenity::Mart => { + let bag = state.bag(); + state.money() >= price::POKE_BALL + && !bag.iter().any(|stack| item::BALLS.contains(&stack.id) && stack.count > 0) + && !bag.iter().any(|stack| stack.id == item::OAKS_PARCEL) + } + } +} + +/// The map `GO SHOP` or `GO HEAL` walks toward from elsewhere in the area, or `None`. +/// +/// The errand while it stands ([`errand`]), and otherwise the area's building of that kind while +/// it has something to do ([`service_needed`]). Nothing here ranks the building above anything +/// else on the pad: it is what the button aims at, and the fly chooses the button. +pub fn amenity_wanted(state: &mut dyn MacroState, kind: Amenity) -> Option { + if let Some(map) = errand(state, kind) { + return Some(map); + } + if !service_needed(state, kind) { + return None; + } + // **The room the rung is in is not left for a service** (row 62, review round 2). The same + // rule row 29 gave the ways out ([`exit_tiers`]) and row 58 measured in the Pewter Gym: while + // the thing that earns the rung stands on this map untalked and unexcluded, nothing walks the + // fly out of the room. A hurt party in a gym is the common case -- its trainers are why -- and + // `GO HEAL` / `GO SHOP` from the gym's floor were four of its six doormat bounces. The errand + // above needs no such line: while it stands it *is* the objective, so the rung's target is not + // on this map. The escape hatch is the rule's own: a target no walk reaches is excluded for + // the window, `objective_targets` empties, and the service is wanted again. + if !objective_targets(state).is_empty() { + return None; + } + let area = area_here(state)?; + amenity_in_reach(state, area, kind) +} + +/// `area`'s building of `kind`, when the route to it from the piece of ground the fly stands on +/// stays inside the area ([`geography::route_within`]). +/// +/// Row 62's review, round 2: Route 4's centre is on the mountain's west side, and Route 4's east +/// side and Mt. Moon B1F's exit chamber are in Route 4's area too -- but the only road from them +/// to that door runs through B2F, which is in no area, so the button that started the walk left +/// the pad one hop in, opposite `GO OBJECTIVE`'s road to Cerulean. From there the centre is not +/// this area's building; Cerulean's is one edge away, and it is its own area's. +fn amenity_in_reach(state: &mut dyn MacroState, area: u8, kind: Amenity) -> Option { + let map = geography::amenity_of(area, kind)?; + let from = region_here(state)?; + geography::route_within(from, map, area).then_some(map) +} + +/// Inside a building with a job to do: the tiles to face its counter person from, whatever the +/// ledgers say, and nothing once the fly already faces them -- that is `TALK`'s tile, and a walk +/// that settles where it started is section 12.2's trap. +fn service_aims(state: &mut dyn MacroState, kind: Amenity) -> Vec { + if facing_counter_person(state, kind) { + return Vec::new(); + } + person_aims(state, counter_sprite(kind), Ledgers::BlockedOnly, false) +} + +/// Whether the fly stands facing the clerk or the nurse of the building of `kind` it is in. +fn facing_counter_person(state: &mut dyn MacroState, kind: Amenity) -> bool { + let inside = state.player().is_some_and(|player| geography::amenity_at(player.map) == Some(kind)); + let Some(TalkTarget::Sprite(slot)) = facing_target(state) else { return false }; + inside + && state + .npcs() + .iter() + .any(|npc| npc.slot == slot && npc.picture == counter_sprite(kind)) +} + +/// Whether the fly faces a counter whose service it has a use for: `TALK`'s second reason (row +/// 62). The press that opens a mart's counter or a nurse's conversation, dealt whatever the talked +/// ledger says, while [`service_needed`] holds. +pub fn facing_service(state: &mut dyn MacroState) -> bool { + Amenity::ALL + .into_iter() + .any(|kind| facing_counter_person(state, kind) && service_needed(state, kind)) +} + +/// Which of the target ledgers [`person_aims`] respects. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Ledgers { + /// Talked, reached and blocked: a person whose conversation is a job done once. + All, + /// Blocked alone: a service, whose job is done when the cartridge says so. + BlockedOnly, } /// The picture id of the person who stands behind `kind`'s counter. @@ -1055,10 +1184,29 @@ pub mod poke_sprite { /// Nearest first by Manhattan distance, ties by tile, which is `approach`'s own rule. Whether any /// of the tiles is *reachable* is the route search's answer, not this one's. pub fn counter_aims(state: &mut dyn MacroState, picture: u8) -> Vec { + person_aims(state, picture, Ledgers::All, false) +} + +/// [`counter_aims`] with the ledgers it respects, and whether the tile the fly already faces +/// the person from stays in the list (`HEAL`'s walk may be no steps at all). +fn person_aims( + state: &mut dyn MacroState, + picture: u8, + ledgers: Ledgers, + keep_facing: bool, +) -> Vec { let Some(player) = state.player() else { return Vec::new() }; let here = Tile::new(player.x, player.y); - let mut people: Vec<(u32, Tile, u8)> = state - .npcs() + // **Drawn or not** (row 62). A centre is entered at (3, 7) and its nurse stands at (3, 1), six + // rows up and off the top of the screen, so from the doormat the drawn sprites held nobody + // behind the counter: `HEAL` was off the pad, `GO HEAL` had nobody to walk to and the + // counter's suppression was released, all on the frame the fly walked in -- measured in the + // Pewter centre, where the pad on arrival was the way out. Row 58's reading of the sprites the + // cartridge keeps off the screen is the same table, so the counter person is found from the + // door. + let mut everyone = state.npcs(); + everyone.extend(state.offscreen_npcs()); + let mut people: Vec<(u32, Tile, u8)> = everyone .iter() .filter(|npc| npc.picture == picture) .map(|npc| (Tile::new(npc.x, npc.y).distance(here), Tile::new(npc.x, npc.y), npc.slot)) @@ -1071,10 +1219,11 @@ pub fn counter_aims(state: &mut dyn MacroState, picture: u8) -> Vec { // already been stood in front of, or already talked to, is a job done. Without them // `amenity_goals` never empties, `GO SHOP` never leaves the pad inside the building, and the // suppression in [`ways`] would keep the fly in there for ever. - if state.talked(target) - || state.reached(TargetKey::Thing(target)) - || state.blocked(TargetKey::Thing(target)) - { + let retired = match ledgers { + Ledgers::All => state.talked(target) || state.reached(TargetKey::Thing(target)), + Ledgers::BlockedOnly => false, + }; + if retired || state.blocked(TargetKey::Thing(target)) { return Vec::new(); } let key = Some(TargetKey::Thing(target)); @@ -1112,7 +1261,9 @@ pub fn counter_aims(state: &mut dyn MacroState, picture: u8) -> Vec { // The tile the fly is already standing on facing the right way is not somewhere to walk to: // that is `TALK`'s state, and the same exclusion `untalked` makes (row 4). let ahead = Tile::new(player.x, player.y).step(player.facing); - aims.retain(|aim| aim.tile != here || Some(tile) != ahead); + if !keep_facing { + aims.retain(|aim| aim.tile != here || Some(tile) != ahead); + } aims } 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 6e02400..5336220 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 @@ -19,16 +19,16 @@ use crate::emulator::buttons; use super::cartridge::{ BLOCKED_MINUTES_DEFAULT, CHEAPEST_PURCHASE, Edge, ExitId, FACINGS, LAST_MAP, MacroState, Objective, - TalkTarget, TargetKey, TargetLedger, Targets, Tile, battle_entry, button, item, price, + PURCHASES, TalkTarget, TargetKey, TargetLedger, Targets, Tile, battle_entry, button, item, price, }; -use super::geography::Amenity; +use super::geography::{self, Amenity}; use super::executor::{ FRAME_CAP, FRAMES_PER_PLANNED_TILE, MacroAbort, MacroMachine, MacroRefused, Refusal, WALK_FRAME_CEILING, walk_budget, }; use super::palette::{ - MacroId, MacroKind, Palette, SLOTS, amenity_goals, answer_key, errand, facing_nurse, - healthiest_other, heal_goals, nurse_prompt, rested_nurse, + MacroId, MacroKind, Palette, SLOTS, amenity_goals, amenity_wanted, answer_key, errand, facing_nurse, + 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, }; @@ -194,6 +194,14 @@ struct World { /// beside a cursor the game never clears, and what the palette asks is only "is a choice /// open" (section 12.12). prompt: bool, + /// A mart's price confirmation (row 62): after this many more A presses in the shop the price + /// line starts printing, and the YES/NO box is drawn this many frames later. `None`: the fake + /// draws no price box at all, which is what it did before row 62. + price_after: Option<(u8, u32)>, + /// The frame the price box is drawn on, once the presses above have been made. + price_at: Option, + /// Purchases the fake mart has rung up: an A on its drawn price box. + bought: u32, /// Whether the cartridge is driving the player right now ([`MacroState::scripted`]). scripted: bool, /// A frame at which the cartridge takes the joypad, which is what the Viridian gate does. @@ -275,6 +283,9 @@ impl World { heal_at: None, box_open: false, prompt: false, + price_after: None, + price_at: None, + bought: 0, scripted: false, scripted_at: None, pulses: Vec::new(), @@ -433,6 +444,12 @@ impl World { } self.heal_at = None; } + if let Some(at) = self.price_at + && self.frames >= at + { + self.prompt = true; + self.price_at = None; + } if mask == buttons::NONE && self.previous != buttons::NONE { self.pulses.push(self.previous); self.on_pulse(self.previous); @@ -483,6 +500,24 @@ impl World { // The cartridge has not asked since the A that opened this list: this A is no edge. return; } + if mask == buttons::A && self.scene == Scene::Shop { + if self.prompt { + // YES on the drawn price box: the one press that rings a purchase up, and the + // wallet pays for the item the list's cursor is on. + self.prompt = false; + self.bought += 1; + let item = self.stock.get(usize::from(self.cursor)).copied(); + let price = PURCHASES.iter().find(|(id, _)| Some(*id) == item).map_or(0, |(_, p)| *p); + self.money = self.money.saturating_sub(price); + } else if let Some((left, print)) = self.price_after { + if left <= 1 { + self.price_after = None; + self.price_at = Some(self.frames + print); + } else { + self.price_after = Some((left - 1, print)); + } + } + } if mask == buttons::A && let Some(next) = self.opens.pop_front() { @@ -712,7 +747,7 @@ impl MacroState for World { /// A drawn box is what the reading rests on, so a prompt cannot be open with no box open: /// `pokemon_red::state::yes_no_prompt` gates on `wFontLoaded` before it looks at the tiles. fn yes_no_prompt(&mut self) -> bool { - self.prompt && self.scene == Scene::Dialog + self.prompt && matches!(self.scene, Scene::Dialog | Scene::Shop) } fn move_without_effect(&mut self, id: u8) -> bool { @@ -2430,6 +2465,8 @@ fn buy_potion_takes_buy_then_the_item_then_confirms_twice() { world.list = List::Shop(ShopScreen::BuySellQuit); world.cursor_max = 2; world.stock = vec![item::POKE_BALL, item::POTION]; + // BUY, the item, the quantity, then the press the price line's `cont` waits for (row 62). + world.price_after = Some((4, 40)); world.money = 1000; world.b_to_close = u8::MAX; // A on BUY opens the priced stock list. @@ -2443,10 +2480,11 @@ fn buy_potion_takes_buy_then_the_item_then_confirms_twice() { assert_eq!(world.cursor, 1, "the potion is the second thing the mart stocks"); assert_eq!( world.pulses.iter().filter(|mask| **mask == buttons::A).count(), - 4, - "BUY, the item, the quantity and the price: {:?}", + 5, + "BUY, the item, the quantity, the price line and the YES: {:?}", world.pulses ); + assert_eq!(world.bought, 1, "and the price box was answered once it was drawn"); } #[test] @@ -2458,12 +2496,14 @@ fn buy_ball_skips_the_counter_menu_when_the_buy_list_is_already_up() { world.stock = vec![item::POKE_BALL, item::POTION]; world.money = 1000; world.b_to_close = u8::MAX; + world.price_after = Some((3, 40)); assert_eq!(run(&mut world, MacroKind::BuyBall).unwrap(), MacroAbort::Done); + assert_eq!(world.bought, 1); assert_eq!(world.cursor, 0); assert_eq!( world.pulses.iter().filter(|mask| **mask == buttons::A).count(), - 3, - "the item, the quantity and the price: {:?}", + 4, + "the item, the quantity, the price line and the YES: {:?}", world.pulses ); } @@ -4259,9 +4299,11 @@ fn go_shop_and_go_heal_are_on_the_pad_while_their_errand_stands() { assert!(on_the_pad(&mut world, MacroKind::GoHeal)); // Paid, and the button leaves the pad -- which is section 12's "a precondition failure means - // the button is not on the pad", and what makes the errand impossible to loop on. + // the button is not on the pad", and what makes the errand impossible to loop on. Since row + // 62 that holds while neither building has a job to do: a ball in the bag and a full party. world.areas.insert((Amenity::Mart, maps::VIRIDIAN_CITY)); world.areas.insert((Amenity::Center, maps::VIRIDIAN_CITY)); + world.bag = vec![(item::POKE_BALL, 3)]; assert!(!on_the_pad(&mut world, MacroKind::GoShop)); assert!(!on_the_pad(&mut world, MacroKind::GoHeal)); @@ -4527,6 +4569,7 @@ fn a_purchase_navigates_by_the_items_place_in_the_stock_list() { world.cursor_max = 3; world.stock = vec![item::POKE_BALL, item::ANTIDOTE, 15, 12]; world.money = 3_000; + world.price_after = Some((3, 40)); assert_eq!(run(&mut world, MacroKind::BuyAntidote).unwrap(), MacroAbort::Done); assert_eq!(world.cursor, 1, "the Antidote's own index"); assert_eq!(world.pulses.last(), Some(&buttons::A), "the price confirmation"); @@ -5421,11 +5464,15 @@ fn a_declined_heal_writes_the_nurse_into_the_talked_ledger() { assert_eq!(run(&mut center, MacroKind::No).unwrap(), MacroAbort::Done); assert!(center.talked.contains(&TalkTarget::Sprite(1)), "the nurse: {:?}", center.talked); - // So `TALK` is off the pad there even if the party is hurt later: the ledger is the record - // that this run has had her conversation. + // So `TALK` is off the pad there while the party stays full: the ledger is the record that + // this run has had her conversation, and a full party has nothing to ask her for. center.scene = Scene::Overworld; - center.mons[0].hp = 4; assert!(!precondition(MacroKind::Talk, &mut center)); + + // Row 62: hurt again later, and she is a service with a job to do. The talked ledger said + // "never again" for the session, which was the whole Mt. Moon run's one nurse. + center.mons[0].hp = 4; + assert!(precondition(MacroKind::Talk, &mut center), "a hurt party has a use for her"); } #[test] @@ -5600,3 +5647,277 @@ fn a_trainer_walking_up_teaches_the_ledgers_nothing() { assert!(!world.targets.blocked(world.map, north), "a challenge is not the road refusing"); assert!(world.pushes.is_empty(), "and the ground is as walkable as it was"); } + +// --------------------------------------------------------------------------------------------- +// Row 62: a service the fly has a use for is not withheld by the ledger that paid its errand +// --------------------------------------------------------------------------------------------- + +#[test] +fn go_heal_comes_back_for_a_hurt_party_after_the_errand_is_paid() { + // The live run of 2026-09-24: the fly entered the Viridian centre once with a full party, + // which paid the errand for the run, and was never offered `GO HEAL` in Viridian again -- + // eleven hours, no heal anywhere, and every whiteout sent it back to Pallet Town. + let mut world = viridian(); + world.areas.insert((Amenity::Center, maps::VIRIDIAN_CITY)); + world.seen_maps.insert(maps::VIRIDIAN_POKECENTER); + assert_eq!(errand(&mut world, Amenity::Center), None, "the errand is paid"); + assert!(!on_the_pad(&mut world, MacroKind::GoHeal), "full party: nothing to go for"); + + world.mons[0].hp = 7; + assert!(on_the_pad(&mut world, MacroKind::GoHeal), "hurt: the centre has a job to do"); + assert_eq!( + amenity_goals(&mut world, Amenity::Center).iter().map(|aim| aim.tile).collect::>(), + vec![Tile::new(6, 1)], + "the centre's door" + ); + + // A status counts as the nurse's job too, and a route with no centre has none to go to. + world.mons[0].hp = 20; + world.mons[0].status = Status::Poison; + assert!(on_the_pad(&mut world, MacroKind::GoHeal)); + world.map = maps::ROUTE_1; + assert!(!on_the_pad(&mut world, MacroKind::GoHeal), "no centre in this area"); +} + +#[test] +fn go_shop_comes_back_while_the_bag_has_no_ball_and_the_money_covers_one() { + // The Viridian mart is entered first for Oak's parcel, when its clerk sells nothing, and that + // visit paid the errand for the run: `GO SHOP` was never dealt in Viridian again, `BUY BALL` + // never, `THROW BALL` never (live: GO SHOP 2 starts in eleven hours, both on the parcel). + let mut world = viridian(); + world.areas.insert((Amenity::Mart, maps::VIRIDIAN_CITY)); + world.seen_maps.insert(maps::VIRIDIAN_MART); + assert_eq!(errand(&mut world, Amenity::Mart), None, "the errand is paid"); + assert!(on_the_pad(&mut world, MacroKind::GoShop), "no ball and 3000 to buy one with"); + + // A ball in the bag: nothing to go for. + world.bag = vec![(item::POTION, 1), (item::POKE_BALL, 1)]; + assert!(!on_the_pad(&mut world, MacroKind::GoShop)); + // Thrown, and it is back. + world.bag = vec![(item::POTION, 1)]; + assert!(on_the_pad(&mut world, MacroKind::GoShop)); + // Under a ball's price: nothing it could buy the ball with. + world.money = price::POKE_BALL - 1; + assert!(!on_the_pad(&mut world, MacroKind::GoShop)); + world.money = price::POKE_BALL; + assert!(on_the_pad(&mut world, MacroKind::GoShop)); + // Carrying Oak's parcel the Viridian counter sells nothing (`scripts/ViridianMart.asm`). + world.bag = vec![(item::OAKS_PARCEL, 1)]; + assert!(!on_the_pad(&mut world, MacroKind::GoShop), "the parcel's text table, no counter"); +} + +#[test] +fn heal_is_dealt_facing_the_nurse_and_after_go_heal_has_reached_her() { + // Row 62. `HEAL`'s goals were `counter_aims`, which drops the tile the fly already faces her + // from and retires a nurse `GO HEAL` has reached for ten brain minutes: so `HEAL` was off the + // pad on the one tile it is for, and for ten minutes after the walk that put the fly there. + let mut center = World::center(); + center.player = Tile::new(3, 3); + center.facing = Facing::Up; + center.mons[0].hp = 5; + assert!(facing_nurse(&mut center)); + assert!(on_the_pad(&mut center, MacroKind::Heal), "facing her with a hurt party"); + + let nurse = TargetKey::Thing(TalkTarget::Sprite(1)); + center.targets.record_reached(center.map, nurse); + center.talked.insert(TalkTarget::Sprite(1)); + assert!(on_the_pad(&mut center, MacroKind::Heal), "reached and talked: still her job"); + assert!(on_the_pad(&mut center, MacroKind::Talk), "and the press that opens her box"); + + // It runs from where it stands: no walk, the talk, the YES, and a party that reads full. + center.switch = Some((40, Scene::Dialog)); + center.heal_at = Some(80); + assert_eq!(run(&mut center, MacroKind::Heal).unwrap(), MacroAbort::Done); + assert_eq!(center.player, Tile::new(3, 3)); + assert!(party_rested(&mut center)); + center.scene = Scene::Overworld; + assert!(!on_the_pad(&mut center, MacroKind::Heal), "full: the button leaves the pad"); + assert!(!on_the_pad(&mut center, MacroKind::Talk), "and so does the nurse's conversation"); + + // The blocked window is kept: a counter no walk reaches is still that. + center.mons[0].hp = 5; + center.targets.record_blocked(center.map, nurse); + assert!(!on_the_pad(&mut center, MacroKind::Heal)); +} + +#[test] +fn a_counter_the_fly_has_a_use_for_opens_again_after_this_session_has_talked_to_it() { + // The clerk talked once this session (the parcel, or a visit that bought nothing) was out of + // `TALK`'s reach for the rest of it, and `GO SHOP` inside had nobody to walk to: the counter + // could not be opened again, so `BUY BALL` could not be dealt again. + let mut mart = World::mart(); + mart.talked.insert(TalkTarget::Sprite(1)); + mart.targets.record_reached(mart.map, TargetKey::Thing(TalkTarget::Sprite(1))); + assert!(service_needed(&mut mart, Amenity::Mart)); + assert!(on_the_pad(&mut mart, MacroKind::GoShop), "walk to the clerk: {:?}", pad_of(&mut mart)); + + // At the counter, facing him: the walk is done and the press that opens it is dealt. + mart.player = Tile::new(2, 5); + mart.facing = Facing::Left; + assert!(!on_the_pad(&mut mart, MacroKind::GoShop), "already there"); + assert!(on_the_pad(&mut mart, MacroKind::Talk), "open the counter again"); + + // With a ball in the bag the ledgers answer as they always did. + mart.bag = vec![(item::POKE_BALL, 2)]; + assert!(!on_the_pad(&mut mart, MacroKind::Talk)); + mart.player = Tile::new(3, 6); + assert!(!on_the_pad(&mut mart, MacroKind::GoShop)); +} + +#[test] +fn the_mt_moon_pokecenter_is_a_centre_and_route_4s() { + // Route 4's centre, the last before Mt. Moon, was on no table: `HEAL` was never dealt in it and + // the nurse's prompt was nobody's. Live: the fly stood in it at 10/70 (the row 59 checkpoint) + // and walked back out. + assert_eq!(geography::amenity_at(maps::MT_MOON_POKECENTER), Some(Amenity::Center)); + assert_eq!(geography::area_of(maps::MT_MOON_POKECENTER), Some(maps::ROUTE_4)); + assert_eq!(geography::amenity_of(maps::ROUTE_4, Amenity::Center), Some(maps::MT_MOON_POKECENTER)); + assert_eq!(geography::amenity_of(maps::ROUTE_4, Amenity::Mart), None, "Route 4 has no mart"); + // The cave's first floor opens onto Route 4, so a hurt fly inside it has a centre to go to. + assert_eq!(geography::area_of(maps::MT_MOON_1F), Some(maps::ROUTE_4)); + + let mut center = World::center(); + center.map = maps::MT_MOON_POKECENTER; + center.player = Tile::new(3, 3); + center.facing = Facing::Up; + center.mons[0].hp = 10; + assert!(inside_center(&mut center)); + assert!(on_the_pad(&mut center, MacroKind::Heal)); +} + +#[test] +fn the_nurse_is_found_from_the_door_when_the_screen_does_not_draw_her() { + // Row 62, measured in the Pewter centre: the fly arrives at (3, 7) and the nurse at (3, 1) is + // six rows up, off the top of the screen, so the drawn sprites hold nobody behind the + // counter. The pad on arrival was the way out: no `HEAL`, no `GO HEAL`, and the counter's + // suppression released. + let mut center = World::center(); + center.player = Tile::new(3, 7); + center.mons[0].hp = 6; + center.offscreen = std::mem::take(&mut center.npcs); + assert!( + heal_goals(&mut center).iter().any(|aim| aim.tile == Tile::new(3, 3)), + "over the counter: {:?}", + heal_goals(&mut center) + ); + assert!(on_the_pad(&mut center, MacroKind::Heal)); + assert!(!on_the_pad(&mut center, MacroKind::GoOut), "the counter is still unfaced"); +} + +#[test] +fn a_purchase_answers_the_price_box_once_the_cartridge_has_drawn_it() { + // Row 62, from the rung-11 checkpoint in the Pewter mart: the price line "POKe BALL? That will + // be 200. OK?" prints at text speed after the quantity is chosen, and only then is the YES/NO + // box drawn. The script's last A came one settle after the quantity's and landed on the text + // while it was still printing, so `BUY BALL` reported `done` with nothing bought -- 55 starts, + // 55 `done`, the wallet at 1,606 throughout -- and the box it had not answered was left to + // whatever the pad dealt next. + let mut world = World::room(); + world.scene = Scene::Shop; + world.list = List::Shop(ShopScreen::Buying); + world.cursor_max = 3; + world.stock = vec![item::POKE_BALL, item::POTION, 29, item::ANTIDOTE]; + world.money = 1_606; + world.b_to_close = u8::MAX; + // Measured: the line waits for a press after "That will be", and the box is drawn after + // the rest of it prints. The fake draws it three presses after the item's: the item, the + // quantity, and the press that the `cont` waits for. + world.price_after = Some((3, 30)); + assert_eq!(run(&mut world, MacroKind::BuyBall).unwrap(), MacroAbort::Done); + assert_eq!(world.bought, 1, "YES on the drawn box: {:?}", world.pulses); + assert!(!world.prompt, "and the box is answered, not left up"); + + // A box that never comes is not a purchase: `blocked`, and nothing answered. + let mut world = World::room(); + world.scene = Scene::Shop; + world.list = List::Shop(ShopScreen::Buying); + world.cursor_max = 3; + world.stock = vec![item::POKE_BALL]; + world.money = 1_606; + world.b_to_close = u8::MAX; + assert_eq!(run(&mut world, MacroKind::BuyBall).unwrap(), MacroAbort::Blocked); + assert_eq!(world.bought, 0); +} + +// --------------------------------------------------------------------------------------------- +// Row 62, review round 2: a service is not dealt off the area's ground, nor out of the rung's room +// --------------------------------------------------------------------------------------------- + +/// A hurt fly with no ball and money for one, on `map` at `(x, y)`, the rung in Cerulean. +fn hurt_on(map: u8, x: u8, y: u8) -> World { + let mut world = World::room().at(x, y); + world.map = map; + world.size = MapSize { width: 40, height: 36 }; + world.warps = Vec::new(); + world.mons[0].hp = 7; + world.money = 1_000; + world.objective = Some(Objective { + map: maps::CERULEAN_CITY, + tile: None, + warp: None, + edge: None, + target: None, + }); + world +} + +#[test] +fn east_of_mt_moon_route_4s_centre_is_not_the_areas_errand_or_service() { + // B1: Route 4's east side (where the fly comes out of the mountain, hurt) and B1F's exit + // chamber are "in Route 4", and the centre is on the west side through B2F, which is in no + // area. The pad dealt `GO HEAL` there, its walk took it into B2F, and it left the pad one hop + // in, opposite `GO OBJECTIVE`'s road back up: a two-map ring by construction. + for (map, x, y, place) in [ + (maps::ROUTE_4, 30, 10, "Route 4 east"), + (maps::MT_MOON_B1F, 26, 4, "B1F exit chamber"), + ] { + let mut world = hurt_on(map, x, y); + assert!(party_needs_rest(&mut world)); + assert_eq!(errand(&mut world, Amenity::Center), None, "{place}: not the area's errand from here"); + assert_eq!(amenity_wanted(&mut world, Amenity::Center), None, "{place}: nor its service"); + assert!(amenity_goals(&mut world, Amenity::Center).is_empty(), "{place}"); + assert!(!on_the_pad(&mut world, MacroKind::GoHeal), "{place}: GO HEAL is off the pad"); + assert_eq!( + super::palette::objective_place(&mut world).map(|place| place.map), + Some(maps::CERULEAN_CITY), + "{place}: GO OBJECTIVE is the rung, not the centre behind the mountain" + ); + } + + // West of the mountain, and on the first floor, it is the area's centre as it was. + let mut world = hurt_on(maps::ROUTE_4, 12, 8); + world.warps = vec![Warp { x: 11, y: 5, destination_warp: 0, destination_map: maps::MT_MOON_POKECENTER }]; + assert_eq!(amenity_wanted(&mut world, Amenity::Center), Some(maps::MT_MOON_POKECENTER)); + assert!(on_the_pad(&mut world, MacroKind::GoHeal), "the door is a few tiles away"); + let mut world = hurt_on(maps::MT_MOON_1F, 14, 20); + assert_eq!(amenity_wanted(&mut world, Amenity::Center), Some(maps::MT_MOON_POKECENTER)); +} + +#[test] +fn a_service_does_not_walk_the_fly_out_of_the_rungs_room() { + // B2, row 58's ROM test on the branch: in the Pewter Gym with BROCK up the room, a hurt party + // and an empty bag put `GO HEAL` and `GO SHOP` on the pad, and both walked out of the door the + // fly had just come in by -- four of six arrivals bounced. Row 29's rule is the ways out's and + // is now the services' too. + let mut world = pewter_gym_doormat(); + world.mons[0].hp = 7; + world.money = 1_000; + world.bag = Vec::new(); + assert!(service_needed(&mut world, Amenity::Center)); + assert!(service_needed(&mut world, Amenity::Mart)); + assert!(!super::palette::objective_targets(&mut world).is_empty(), "BROCK is in the room"); + assert_eq!(amenity_wanted(&mut world, Amenity::Center), None); + assert_eq!(amenity_wanted(&mut world, Amenity::Mart), None); + assert!(!on_the_pad(&mut world, MacroKind::GoHeal)); + assert!(!on_the_pad(&mut world, MacroKind::GoShop)); + assert!(on_the_pad(&mut world, MacroKind::GoObjective), "the walk to him is still there"); + + // The rule's own escape hatch: with the room's people talked to (or excluded), the services + // are wanted again and the centre is Pewter's. + for slot in [1, 2] { + world.talked.insert(TalkTarget::Sprite(slot)); + } + assert!(super::palette::objective_targets(&mut world).is_empty()); + assert_eq!(amenity_wanted(&mut world, Amenity::Center), Some(maps::PEWTER_POKECENTER)); + assert_eq!(amenity_wanted(&mut world, Amenity::Mart), Some(maps::PEWTER_MART)); +} diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs index fd1b4e8..f306cf2 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs @@ -86,5 +86,9 @@ pub const MT_MOON_B2F: u8 = 0x3d; pub const CERULEAN_POKECENTER: u8 = 0x40; pub const CERULEAN_GYM: u8 = 0x41; pub const CERULEAN_MART: u8 = 0x43; +/// Route 4's Pokémon Center, the one beside Mt. Moon's mouth: the id straight after +/// `CERULEAN_MART` `$43`, and confirmed by the cartridge rather than by counting -- Route 4's warp +/// table names `$44` at (11, 5) (`tests/rom_macros_mode.rs`, row 59's door survey). +pub const MT_MOON_POKECENTER: u8 = 0x44; pub const ROCK_TUNNEL_1F: u8 = 0x52; pub const INDIGO_PLATEAU_LOBBY: u8 = 0xae; diff --git a/services/flysim/crates/flysim/examples/scene_probe.rs b/services/flysim/crates/flysim/examples/scene_probe.rs index 50cbaa8..bb2f317 100644 --- a/services/flysim/crates/flysim/examples/scene_probe.rs +++ b/services/flysim/crates/flysim/examples/scene_probe.rs @@ -30,6 +30,12 @@ //! | `FLY_TRAP_CHECKPOINT` | `FLY_MACRO_CHECKPOINT` | the `FLYSIM01` checkpoint to start from | //! | `FLY_PROBE_FRAMES` | 200000 | frames to drive before giving up | //! | `FLY_PROBE_STUCK` | 600 | consecutive frames in one non-overworld scene that count as stuck | +//! +//! `FLY_PROBE_CATCH=offers` (row 62) is a different drive: twenty brain minutes of the service's +//! frame behind a uniform stub, counting on every decidable frame which of the shop, centre and +//! ball buttons are on the pad, and reading the cartridge beside it (heals, purchases, throws, +//! catches, whiteouts, `wLastBlackoutMap`). `FLY_PROBE_RNG`, `FLY_PROBE_PREFER`, `FLY_PROBE_PADS` +//! and `FLY_PROBE_TRACE_MACRO` are documented on `offers_survey`. use std::collections::BTreeMap; @@ -1703,6 +1709,303 @@ fn route_survey( }); } +/// Row 62's offer survey: which of the shop, the centre and the ball buttons the pad deals, on how +/// many frames, under which preconditions, and what comes of the ones that are pressed. +/// +/// `FLY_PROBE_CATCH=offers`. The live run bought nothing, threw nothing and healed nowhere for +/// eleven hours, and the event log records only what was chosen, so the question is what was +/// *dealt*. This drives the service's own frame (`flysim::frame::LegacyFrame`) with the macro layer +/// behind a uniform stub: once per hold one of the scene's bound channels is made hot, chosen +/// uniformly (a survey's driver, never the fly's; nothing in the crate reads it). Every frame on +/// which the fly could decide -- a playable scene, a non-empty pad, no macro running -- counts which +/// watched buttons are on the pad; the cartridge is read beside it for what those buttons change. +/// +/// `FLY_PROBE_FRAMES` (default twenty brain minutes) bounds the drive, `FLY_PROBE_RNG` changes the +/// choices, `FLY_PROBE_PREFER` names buttons pressed whenever dealt, `FLY_PROBE_PADS=1` prints +/// every pad change and every macro event (and, in a centre with a hurt party and no `HEAL`, +/// the sprites and the ground the nurse's aims are read from), and `FLY_PROBE_TRACE_MACRO=` +/// prints every frame of that macro's first three runs with the screen as text +/// (`FLY_PROBE_TRACE_SCREEN=all` on every frame rather than on each press). +#[allow(clippy::too_many_lines)] +fn offers_survey( + gb: &mut Emulator, + adapter: &mut PokemonRedReward, + ms: &mut f64, + layer: &mut flysim::macros::MacroLayer, + decoder: &mut PopulationDecoder, + hold_ms: f64, +) { + use flybrain_gb::pokemon_red::macros::cartridge::MacroState; + use flybrain_gb::pokemon_red::macros::geography::{self, Amenity}; + use flybrain_gb::pokemon_red::macros::palette; + + const WATCH: [&str; 12] = [ + "HEAL", "GO HEAL", "GO SHOP", "BUY BALL", "BUY POTION", "THROW BALL", "YES", "NO", "TALK", + "ITEM", "LEAVE", "CONFIRM", + ]; + const POKE_BALL: u8 = 0x04; + const CENTERS: [u8; 11] = [0x29, 0x3a, 0x40, 0x44, 0x51, 0x59, 0x85, 0x8d, 0x9a, 0xab, 0xb6]; + const MARTS: [u8; 3] = [0x2a, 0x38, 0x43]; + let blackout = |gb: &mut Emulator| gb.read8(0xd719); + let balls = |gb: &mut Emulator| { + state::bag(gb).iter().filter(|item| item.id == POKE_BALL).map(|item| u32::from(item.count)).sum::() + }; + let snapshot = |gb: &mut Emulator, adapter: &PokemonRedReward, label: &str| { + let party = state::party(gb); + let hp: Vec = + party.mons.iter().map(|mon| format!("{}/{} {:?}", mon.hp, mon.max_hp, mon.status)).collect(); + let bag: Vec<(u8, u8)> = state::bag(gb).iter().map(|item| (item.id, item.count)).collect(); + let money = state::money(gb); + let last = blackout(gb); + let player = state::player(gb); + let ledger = AdapterLedger(adapter); + let mut poke = flybrain_gb::pokemon_red::state::PokeState::with_ledger(gb, &ledger); + let st: &mut dyn MacroState = &mut poke; + println!("\n## {label}\n"); + println!("- player {player:?}, area {:?}, rank {}", palette::area_here(st), adapter.progress().rank); + println!("- party {hp:?}; needs rest {}", palette::party_needs_rest(st)); + println!("- money {money}, bag {bag:?}"); + println!("- wLastBlackoutMap ($d719) = {last:#04x}"); + let centers: Vec<(String, bool)> = + CENTERS.iter().map(|map| (format!("{map:#04x}"), st.map_visited(*map))).collect(); + let marts: Vec<(String, bool)> = + MARTS.iter().map(|map| (format!("{map:#04x}"), st.map_visited(*map))).collect(); + println!("- centres visited (lifetime): {centers:?}"); + println!("- marts visited (lifetime): {marts:?}"); + println!( + "- errand here: mart {:?}, centre {:?}; amenity at map {:?}", + palette::errand(st, Amenity::Mart), + palette::errand(st, Amenity::Center), + player.and_then(|player| geography::amenity_at(player.map)) + ); + }; + snapshot(gb, adapter, "Before the drive"); + + let budget = env_usize("FLY_PROBE_FRAMES", 71_673); + let mut rng = env_usize("FLY_PROBE_RNG", 20_260_924) as u32 | 1; + let prefer: Vec = std::env::var("FLY_PROBE_PREFER") + .map(|value| value.split(',').map(|name| name.trim().to_string()).collect()) + .unwrap_or_default(); + // `FLY_PROBE_PADS=1` prints every pad the fly could decide on, when it changes. + let pads = std::env::var("FLY_PROBE_PADS").is_ok_and(|value| value == "1"); + let trace_macro = std::env::var("FLY_PROBE_TRACE_MACRO").ok(); + let mut traced = 0u32; + let mut tracing_macro = false; + let mut last_mask = 0u32; + let mut last_pad: Vec = Vec::new(); + let mut legacy = flysim::frame::LegacyFrame::new(); + let mut hot: Option = None; + let mut hot_until = 0.0f64; + let mut next_pick = *ms; + // (button) -> [decidable frames on the pad, starts, done, other outcomes] + let mut tally: BTreeMap<&str, [u64; 4]> = WATCH.iter().map(|name| (*name, [0u64; 4])).collect(); + let mut decidable = 0u64; + let mut context: BTreeMap = BTreeMap::new(); + let mut starts: BTreeMap = BTreeMap::new(); + let mut log: Vec = Vec::new(); + let mut last_balls = balls(gb); + let mut last_money = state::money(gb); + let mut last_blackout = blackout(gb); + let mut last_map = state::player(gb).map(|player| player.map); + let mut was_wiped = false; + let mut was_full = true; + let mut counts: BTreeMap<&str, u64> = BTreeMap::new(); + let mut maps_seen: BTreeMap = BTreeMap::new(); + for frame in 0..budget { + let bound = layer.bound_channels(); + if *ms >= next_pick && !bound.is_empty() && layer.running().is_none() { + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + // `FLY_PROBE_PREFER=BUY BALL,THROW BALL` presses those whenever they are dealt, first + // one first: to see what a button does once pressed, not how often the fly would. + let preferred = prefer.iter().map(|name| format!("macro_{}", name.to_lowercase().replace(' ', "_"))).find(|channel| bound.contains(channel)); + hot = Some(preferred.unwrap_or_else(|| bound[rng as usize % bound.len()].clone())); + hot_until = *ms + BURST_MS; + next_pick = *ms + hold_ms; + } + if *ms >= hot_until { + hot = None; + } + let active = decoder.decode_bound(&rates(hot.as_deref()), *ms, false, None, Some(&bound)); + // What the fly could have pressed on this frame, before the layer acts on it. + let names: Vec = layer.feed_palette().into_iter().map(|slot| slot.name).collect(); + let free = layer.running().is_none() && !names.is_empty(); + if pads && free && names != last_pad { + println!( + " f{frame:<6} {:?} {} pad {names:?}", + state::player(gb).map(|p| (p.map, p.x, p.y, p.facing)), + layer.scene_name() + ); + last_pad = names.clone(); + let party_hurt = state::party(gb).mons.iter().any(|mon| mon.hp < mon.max_hp); + if party_hurt + && state::player(gb).is_some_and(|p| CENTERS.contains(&p.map)) + && !names.iter().any(|name| name == "HEAL") + { + let ledger = AdapterLedger(&*adapter); + let mut poke = flybrain_gb::pokemon_red::state::PokeState::with_ledger(gb, &ledger); + let st: &mut dyn MacroState = &mut poke; + println!(" npcs {:?}", st.npcs()); + println!(" heal_goals {:?}", palette::heal_goals(st)); + let size = st.map_size(); + println!(" size {size:?}"); + if let Some(size) = size { + for y in 0..size.height { + let row: String = (0..size.width) + .map(|x| match st.walkable(x, y) { + flybrain_gb::pokemon_red::macros::state::Walkable::Yes => if st.counter_tile(x, y) { 'c' } else { '.' }, + flybrain_gb::pokemon_red::macros::state::Walkable::No => if st.counter_tile(x, y) { 'C' } else { '#' }, + flybrain_gb::pokemon_red::macros::state::Walkable::Unknown => '?', + }) + .collect(); + println!(" y{y:2} {row}"); + } + } + } + } + if free { + decidable += 1; + for name in &names { + if let Some(entry) = tally.get_mut(name.as_str()) { + entry[0] += 1; + } + } + } + let executed = legacy.execute(Some(layer), &active, 0, *ms, gb, adapter); + // `FLY_PROBE_TRACE_MACRO=BUY BALL` prints every frame of that macro's first three runs: + // the mask, the scene, the counter's screen, the cursor and the wallet. + if let Some(want) = trace_macro.as_deref() + && layer.running() == Some(want) + && traced < 3 + { + let shop = state::shop(gb); + let cur = state::cursor(gb); + println!( + " {want} f{frame} mask {:#04x} scene {} shop {:?} cursor {}/{} top ({},{}) money {} text {:?}", + executed.mask, + layer.scene_name(), + shop.map(|shop| shop.screen), + cur.current, + cur.max, + cur.top_x, + cur.top_y, + state::money(gb), + state::text_box(gb) + ); + if executed.mask != last_mask || std::env::var("FLY_PROBE_TRACE_SCREEN").is_ok_and(|v| v == "all") { + for line in screen_text(gb) { + println!(" | {line}"); + } + } + last_mask = executed.mask; + tracing_macro = true; + } else if tracing_macro { + tracing_macro = false; + traced += 1; + } + for event in &executed.events { + if pads { + println!(" f{frame:<6} event {} hot {hot:?}", event.label()); + } + let key = match event.outcome { None => 1, Some(flysim::snapshot::MacroOutcome::Done) => 2, Some(_) => 3 }; + if let Some(entry) = tally.get_mut(event.name) { + entry[key] += 1; + } + if event.outcome.is_none() { + *starts.entry(event.name.to_string()).or_default() += 1; + } + } + *ms += MS_PER_FRAME; + let evaluated = legacy.stub_advance(Some(layer), gb, adapter, *ms).expect("a frame should complete"); + for reward in &evaluated.rewards { + if reward.label.contains("CAUGHT") || reward.label.contains("CATCH") { log.push(format!("f{frame} {}: {}", reward.kind, reward.label)); } + if reward.kind == "catch" { + *counts.entry("catches").or_default() += 1; + log.push(format!("f{frame} catch: {}", reward.label)); + } + } + // The cartridge beside the pad. + let party = state::party(gb); + let player = state::player(gb); + let map = player.map(|player| player.map); + if let Some(map) = map { + *maps_seen.entry(map).or_default() += 1; + } + let wiped = !party.mons.is_empty() && party.mons.iter().all(|mon| mon.hp == 0); + let full = party.mons.iter().all(|mon| mon.hp == mon.max_hp && matches!(mon.status, flybrain_gb::pokemon_red::macros::state::Status::Healthy)); + if wiped && !was_wiped { + *counts.entry("whiteouts").or_default() += 1; + log.push(format!("f{frame} whiteout on map {map:?}")); + } + if full && !was_full && !wiped && map.is_some_and(|map| CENTERS.contains(&map)) { + *counts.entry("heals at a nurse").or_default() += 1; + log.push(format!("f{frame} healed at a nurse on map {map:?}")); + } + was_wiped = wiped; + was_full = full; + let now_balls = balls(gb); + if now_balls > last_balls { + *counts.entry("balls bought").or_default() += u64::from(now_balls - last_balls); + log.push(format!("f{frame} balls {last_balls} -> {now_balls}")); + } else if now_balls < last_balls { + *counts.entry("balls thrown").or_default() += u64::from(last_balls - now_balls); + log.push(format!("f{frame} balls {last_balls} -> {now_balls}")); + } + last_balls = now_balls; + let money = state::money(gb); + if money < last_money && map.is_some_and(|map| MARTS.contains(&map)) { + *counts.entry("spent at a mart").or_default() += u64::from(last_money - money); + log.push(format!("f{frame} money {last_money} -> {money} on map {map:?}")); + } + last_money = money; + let now_blackout = blackout(gb); + if now_blackout != last_blackout { + log.push(format!("f{frame} wLastBlackoutMap {last_blackout:#04x} -> {now_blackout:#04x}")); + last_blackout = now_blackout; + } + if map != last_map { + if map.is_some_and(|map| CENTERS.contains(&map) || MARTS.contains(&map)) { + log.push(format!("f{frame} entered {map:?} (party full {full}, money {money})")); + } + last_map = map; + } + if free { + let inside = match map { + Some(map) if CENTERS.contains(&map) => "in a centre", + Some(map) if MARTS.contains(&map) => "in a mart", + _ => "elsewhere", + }; + let hurt = if full { "full" } else { "hurt" }; + let scene = layer.scene_name(); + *context.entry(format!("{scene} {inside} party {hurt}")).or_default() += 1; + if scene == "battle" && state::party(gb).active.is_some() { + let ball = if balls(gb) == 0 { "0 balls" } else { ">0 balls" }; + let kind = match gb.read8(ram::wIsInBattle) { 1 => "wild", 2 => "trainer", _ => "other" }; + *context.entry(format!("battle {kind} {ball}")).or_default() += 1; + } + } + } + println!("\n## Offers over {budget} frames ({:.1} brain minutes), {decidable} decidable\n", budget as f64 * MS_PER_FRAME / 60_000.0); + println!("| button | frames on the pad | share of decidable | starts | done | other |"); + println!("| --- | ---: | ---: | ---: | ---: | ---: |"); + for (name, [offered, started, done, other]) in &tally { + println!( + "| {name} | {offered} | {:.2}% | {started} | {done} | {other} |", + if decidable == 0 { 0.0 } else { *offered as f64 * 100.0 / decidable as f64 } + ); + } + println!("\n- decidable frames by context: {context:?}"); + println!("- all starts: {starts:?}"); + println!("- counts: {counts:?}"); + println!("- frames per map: {maps_seen:?}"); + println!("\n### Events\n"); + for line in log.iter().take(200) { + println!("- {line}"); + } + snapshot(gb, adapter, "After the drive"); +} + /// How the candidate readings of "a two-option box is up" separate the frames of a survey. /// /// Three columns, because three things could say it and only a measurement says which: the @@ -1838,6 +2141,12 @@ fn main() { return; } + // Row 62's offer survey: which shop, centre and ball buttons are dealt, frame by frame. + if std::env::var("FLY_PROBE_CATCH").is_ok_and(|value| value == "offers") { + offers_survey(&mut gb, &mut adapter, &mut ms, &mut layer, &mut decoder, hold_ms); + return; + } + // Row 57's pad survey: earn the session's ledgers from the checkpoint with the real palette, // and read the frame the pad comes down to one refusing button on. if std::env::var("FLY_PROBE_CATCH").is_ok_and(|value| value == "route") { diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index 42e84b2..a438f19 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -702,13 +702,8 @@ impl Run { flybrain_gb::pokemon_red::state::money(&mut self.gb) } - /// How many of `item` the bag holds, summed over its stacks. - /// - /// Kept unused for now: the purchase the section-13 test would have counted with it is - /// unit-proven rather than ROM-proven (see `go_shop_enters_the_mart_once_and_walks_to_its_counter` - /// and rows 35 and 36 of `infra/docs/macros-traps.md`), and deleting the reader would mean - /// writing it again with the fix. - #[allow(dead_code)] + /// How many of `item` the bag holds, summed over its stacks: what row 62's purchase is + /// measured by. fn bag_count(&mut self, item: u8) -> u32 { flybrain_gb::pokemon_red::state::bag(&mut self.gb) .iter() @@ -3990,3 +3985,308 @@ fn row63_drive(rom: &[u8], checkpoint: &flysim::store::Checkpoint, prefer: &[&st eprintln!("row 63, pressing {prefer:?} whenever dealt: {out:?}"); out } + +/// `wLastBlackoutMap`, `$d719` at the pinned commit (`ram/wram.asm`, the byte after +/// `wBoulderSpriteIndex`): the map a whiteout returns the player to, written by the nurse's YES +/// (`SetLastBlackoutMap`) and by nothing else a walk can reach. Read by this test only; the macros +/// never read it. +const W_LAST_BLACKOUT_MAP: u16 = 0xd719; +const POKE_BALL: u8 = 0x04; + +/// The live checkpoint from inside the Mt. Moon Pokémon Center with a hurt party, or `None`. +fn row62_center_checkpoint() -> Option { + std::env::var_os("FLY_ROW62_CENTER_CHECKPOINT").map(|path| { + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope") + }) +} + +/// The rung-11 Pewter checkpoint, errands paid, money and no ball, or `None`. +fn row62_mart_checkpoint() -> Option { + std::env::var_os("FLY_ROW62_MART_CHECKPOINT").map(|path| { + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope") + }) +} + +/// Row 62: in Route 4's Pokémon Center with a hurt party, `HEAL` is on the pad and heals, and the +/// cartridge's whiteout map becomes Route 4. +/// +/// **What was live** (2026-09-24, v0.6.2, rung 12 MT. MOON, 3.5 hours on the rung): in eleven +/// hours of the fresh run no `HEAL`, no `GO HEAL` after the first visit, no nurse's YES, so +/// `wLastBlackoutMap` stayed Pallet Town and every whiteout in Mt. Moon walked the fly back from +/// Pallet. This centre was on no table: `HEAL` is dealt by the map id and the map id was not +/// there. The checkpoint is row 59's, taken with the fly in this centre at 10 of 70 HP. +/// +/// ```sh +/// FLY_ROM=/path/to/pokemon-red.gb \ +/// FLY_ROW62_CENTER_CHECKPOINT=.local/checkpoints/release-rank12-mtmoon-center.checkpoint \ +/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row62 +/// ``` +#[test] +fn row62_heal_is_dealt_in_the_mt_moon_center_and_moves_the_whiteout_map() { + let rom = skip_without_rom!(); + let Some(checkpoint) = row62_center_checkpoint() else { + eprintln!("skipped: no FLY_ROW62_CENTER_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert_eq!(run.map(), MT_MOON_POKECENTER, "the checkpoint is Route 4's centre"); + assert!(!run.party_rested(), "and the party is hurt"); + assert_eq!(run.gb.read_wram(W_LAST_BLACKOUT_MAP), 0x00, "whiteouts go to Pallet Town"); + + // `HEAL` on the pad inside the centre. On the base it is never there: the map id is on no + // table, so the rotation walks the fly back out. + run.force_hot = Some("macro_heal"); + let mut heal_dealt = false; + run.drive_until("HEAL on the centre's pad", 3_000, |run| { + heal_dealt |= run.map() == MT_MOON_POKECENTER + && run.layer.bound_channels().iter().any(|channel| channel == "macro_heal"); + heal_dealt + }); + run.drive_until("the party reads back full", 3_000, |run| run.party_rested()); + assert_eq!(run.map(), MT_MOON_POKECENTER, "healed where it stood"); + assert_eq!( + u32::from(run.gb.read_wram(W_LAST_BLACKOUT_MAP)), + ROUTE_4, + "the nurse's YES wrote Route 4 as the whiteout map" + ); + // Full now, so the button leaves the pad rather than being pressed again (12.12). + for _ in 0..120 { + run.frame(); + } + assert!( + !run.layer.bound_channels().iter().any(|channel| channel == "macro_heal"), + "a rested party is no reason to rest: {:?}", + run.layer.bound_channels() + ); +} + +/// Row 62: from Pewter City with both errands paid, 1,606 in the wallet and no ball, `GO SHOP` is +/// on the pad, and the counter it leads to sells the fly a ball. +/// +/// **What was live**: `GO SHOP` twice in eleven hours, both on the parcel; `BUY BALL` never; +/// `THROW BALL` never. Three things stood between the fly and a ball, all measured from this +/// checkpoint: the errand was paid by the first visit and never offered again; a clerk this +/// session had talked to was out of `TALK`'s reach; and `BUY BALL` pressed its last A while the +/// price line was still printing, so it reported `done` with nothing bought (55 of 55 on the +/// cartridge, the wallet unchanged). The drive here leans on one button at a time, in order; it +/// says nothing about which the fly would press. +/// +/// ```sh +/// FLY_ROM=/path/to/pokemon-red.gb \ +/// FLY_ROW62_MART_CHECKPOINT=.local/checkpoints/survey-rank11-pewter.checkpoint \ +/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row62 +/// ``` +#[test] +fn row62_go_shop_comes_back_with_no_ball_and_buy_ball_rings_up_a_ball() { + use flybrain_gb::pokemon_red::macros::PokemonPalette; + use flybrain_gb::{MacroPalette, Outcome, Started}; + let rom = skip_without_rom!(); + let Some(checkpoint) = row62_mart_checkpoint() else { + eprintln!("skipped: no FLY_ROW62_MART_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert_eq!(run.bag_count(POKE_BALL), 0, "no ball at the checkpoint"); + let money = run.money(); + assert!(money >= 200, "and the money for one: {money}"); + + // The palette driven directly, one choice per hold: the chain's buttons whenever they are + // dealt, in this order, and otherwise the first button on the pad. A survey's driver, never + // the fly's -- the claim is about what the pad deals and what the buttons do. + let order = ["BUY BALL", "CONFIRM", "TALK", "GO SHOP"]; + let hold_frames = 48u32; + let mut palette = PokemonPalette::new(SEED); + let mut running: Option<&'static str> = None; + let mut since_decision = hold_frames; + let mut ms = run.ms; + let mut go_shop_on_the_first_pad = None; + let mut entered_the_mart = None; + let mut buy_done_without_a_ball = 0u32; + let mut buy_done_with_a_ball = 0u32; + for frame in 0..30_000u32 { + palette.clock(ms); + let observed = { + let ledger = AdapterLedger(&run.adapter); + palette.observe(&mut run.gb, &ledger) + }; + if go_shop_on_the_first_pad.is_none() && !observed.bindings.is_empty() { + go_shop_on_the_first_pad = + Some(observed.bindings.iter().any(|binding| binding.name == "GO SHOP")); + } + let mut mask = 0u8; + { + let ledger = AdapterLedger(&run.adapter); + if running.is_some() { + match palette.step(&mut run.gb, &ledger) { + Some(held) => mask = held, + None => running = None, + } + } else if since_decision >= hold_frames && !observed.bindings.is_empty() { + since_decision = 0; + let binding = order + .iter() + .find_map(|want| observed.bindings.iter().find(|binding| binding.name == *want)) + .unwrap_or(&observed.bindings[0]); + if let Started::Running(name) = palette.start(binding.slot, &mut run.gb, &ledger) { + running = Some(name); + match palette.step(&mut run.gb, &ledger) { + Some(held) => mask = held, + None => running = None, + } + } + } + } + if let Some((name, outcome)) = palette.take_finished() + && name == "BUY BALL" + && outcome == Outcome::Done + { + if run.bag_count(POKE_BALL) == 0 { + buy_done_without_a_ball += 1; + } else { + buy_done_with_a_ball += 1; + } + } + since_decision += 1; + run.gb.set_buttons(mask); + run.gb.run_frame().expect("a frame should complete"); + ms += MS_PER_FRAME; + run.adapter.sample(&mut run.gb, ms); + if entered_the_mart.is_none() && run.map() == PEWTER_MART { + entered_the_mart = Some(frame); + } + if run.bag_count(POKE_BALL) > 0 && running.is_none() { + break; + } + } + eprintln!( + "GO SHOP on the first pad {go_shop_on_the_first_pad:?}, into the mart at \ + {entered_the_mart:?}, BUY BALL done with a ball {buy_done_with_a_ball} / without \ + {buy_done_without_a_ball}, balls {}, money {} -> {}", + run.bag_count(POKE_BALL), + money, + run.money() + ); + // The errand is paid (the adapter's map ledger has the mart), so on the base `GO SHOP` is on + // no pad in Pewter at all. + assert_eq!(go_shop_on_the_first_pad, Some(true), "`GO SHOP` with no ball and 1,606"); + assert!(entered_the_mart.is_some(), "`GO SHOP` walked into the Pewter mart"); + assert_eq!(buy_done_without_a_ball, 0, "a `BUY BALL` reported done with nothing bought"); + assert_eq!(run.bag_count(POKE_BALL), 1, "one ball, one press"); + assert_eq!(run.money(), money - 200, "and the wallet paid for it"); + // With a ball in the bag the mart has nothing to do for the fly. + let still = { + let ledger = AdapterLedger(&run.adapter); + palette.observe(&mut run.gb, &ledger) + }; + assert!( + !still.bindings.iter().any(|binding| binding.name == "GO SHOP"), + "a ball in the bag: {:?}", + still.bindings.iter().map(|binding| binding.name).collect::>() + ); +} + +/// A checkpoint from Mt. Moon B2F standing on the ladder up to B1F's exit chamber (rank 12, the +/// party hurt), or `None`. +fn row62_east_checkpoint() -> Option { + std::env::var_os("FLY_ROW62_EAST_CHECKPOINT").map(|path| { + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope") + }) +} + +/// Row 62, review round 2: east of Mt. Moon, `GO HEAL` is not dealt to walk a hurt fly back into +/// the mountain. +/// +/// **The fault** (review of the row's first round): Route 4's centre is on the mountain's west +/// side, and Route 4's east side and B1F's exit chamber are in Route 4's area too. The only road +/// from them to that door runs through B2F, which is in no area, so `GO HEAL` walked the fly down +/// into B2F and left the pad there, while `GO OBJECTIVE` walked it back up toward Cerulean: a +/// two-map ring by construction, and a hurt fly is exactly the one that comes out of the mountain. +/// +/// The checkpoint is the live one from B2F standing on the exit chamber's ladder at (5, 7) +/// (v0.6.4, rank 12, 28 of 85 HP). The test's own setup steps the player off the ladder and back +/// on through the joypad, which takes it up into the exit chamber; from there it drives the stub +/// rotation with `GO OBJECTIVE` leaned on, the road out. The claim is about the pad only: on the +/// exit chamber and on Route 4's east side, with the party hurt, `GO HEAL` is never dealt. `main` +/// passes it too -- it has no row for Route 4's centre at all. +/// +/// ```sh +/// FLY_ROM=/path/to/pokemon-red.gb \ +/// FLY_ROW62_EAST_CHECKPOINT=.local/checkpoints/release-rank12-mtmoon-b2f-ladder.checkpoint \ +/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row62_east +/// ``` +#[test] +fn row62_east_of_mt_moon_go_heal_is_not_dealt_back_into_the_mountain() { + use flybrain_gb::emulator::buttons; + use flybrain_gb::pokemon_red::macros::geography::{self, Region}; + const MT_MOON_B1F: u8 = 0x3c; + const MT_MOON_B2F: u8 = 0x3d; + let rom = skip_without_rom!(); + let Some(checkpoint) = row62_east_checkpoint() else { + eprintln!("skipped: no FLY_ROW62_EAST_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert!(run.adapter.progress().rank >= 12, "the checkpoint is on the Mt. Moon rung"); + assert!(!run.party_rested(), "and the party is hurt"); + let at = |run: &mut Run| { + flybrain_gb::pokemon_red::state::player(&mut run.gb).map(|p| (p.map, p.x, p.y)) + }; + assert_eq!(at(&mut run), Some((MT_MOON_B2F, 5, 7)), "on the ladder up to the exit chamber"); + + // Setup, not the fly: off the ladder to the right and back onto it, which climbs it. + for mask in [buttons::RIGHT, buttons::NONE, buttons::LEFT, buttons::NONE] { + for _ in 0..24 { + run.gb.set_buttons(mask); + run.gb.run_frame().expect("a frame"); + } + } + for _ in 0..240 { + if at(&mut run).is_some_and(|(map, _, _)| map == MT_MOON_B1F) { + break; + } + run.gb.set_buttons(buttons::NONE); + run.gb.run_frame().expect("a frame"); + } + assert_eq!(at(&mut run).map(|(map, _, _)| map), Some(MT_MOON_B1F), "up the ladder"); + + let east = |run: &mut Run| { + let Some((map, x, y)) = at(run) else { return false }; + let grid = flybrain_gb::pokemon_red::state::map_grid(&mut run.gb).ok(); + let region = geography::region_on(map, x, y, grid.as_ref()); + region == Region::piece(MT_MOON_B1F, 0) || region == Region::piece(0x0f, 1) + }; + let mut east_frames = 0u32; + let mut on_route_4 = 0u32; + let mut go_heal_east = 0u32; + let mut first: Option<(u32, (u8, u8, u8))> = None; + run.force_hot = Some("macro_go_objective"); + for frame in 0..12_000u32 { + run.frame(); + if !east(&mut run) || run.party_rested() { + continue; + } + east_frames += 1; + if run.map() == ROUTE_4 { + on_route_4 += 1; + } + if run.layer.bound_channels().iter().any(|channel| channel == "macro_go_heal") { + go_heal_east += 1; + if let Some(here) = at(&mut run) { + first.get_or_insert((frame, here)); + } + } + } + eprintln!( + "{:.1} brain minutes: hurt east of the mountain {east_frames} frames ({on_route_4} on Route 4), \ + GO HEAL dealt on {go_heal_east} (first {first:?}), rank {}, route {:?}, macros {:?}", + run.ms / 60_000.0, + run.adapter.progress().rank, + run.route, + run.started + ); + assert!(east_frames > 0, "the fly was never hurt on the exit chamber: {:?}", run.route); + assert_eq!(go_heal_east, 0, "GO HEAL dealt east of the mountain, first at {first:?}"); +}