From 5269c2f142572f1330490debe970754d12011585 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:55:23 +0000 Subject: [PATCH 1/5] state: the battle bag is open only while its box is on screen wListMenuID keeps ITEMLISTMENU after the list closes, so from a catch to the end of the battle (caught text, Pokedex page, nickname offer, naming screen) the pad read as the bag: BACK and THROW BALL, whose A presses typed the name. The bag now also needs its TextBoxBorder at (4,2)-(19,12). rom_catch: row66 test (THROW BALL dealt after the catch: base 666 frames, branch 0), and both tests retry from idle offsets because one ball misses about two throws in three and frame timing decides which. --- .../flybrain-gb/src/pokemon_red/state.rs | 19 +- .../src/pokemon_red/state/tests.rs | 7 + .../flysim/crates/flysim/tests/rom_catch.rs | 198 ++++++++++++++++-- 3 files changed, 206 insertions(+), 18 deletions(-) diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs index ce75a01..4b42bcb 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs @@ -119,6 +119,10 @@ pub mod poke { /// four tall, then writes a horizontal run over its top-left corner and a `┘` over (10, 12). /// Values rather than symbols, like `YES_NO_BOX`: this is a figure on screen, not a byte. pub const MOVE_LIST_BOX: (u16, u16, u16, u16) = (4, 12, 19, 17); + /// The bag's own box in a battle (row 66): `DisplayListMenuID` draws a `TextBoxBorder` at + /// (4, 2), nine rows by fourteen, so its corners are (4, 2) and (19, 12). Surveyed on the + /// cartridge: whole on every frame the list is up, gone on the frame it closes. + pub const ITEM_LIST_BOX: (u16, u16, u16, u16) = (4, 2, 19, 12); pub const MOVE_LIST_JOIN: u16 = 10; /// Where `MoveSelectionMenu` parks the shared cursor: row 12, column 5. pub const MOVE_LIST_CURSOR_Y: u8 = 12; @@ -631,12 +635,19 @@ pub fn battle(memory: &mut dyn MemoryReader) -> Option { BattleMenu::Moves { cursor: slot, count } } else if party_list(memory) { BattleMenu::Party { cursor: cursor.current } - } else if read(memory, ram::wListMenuID) == poke::ITEM_LIST_MENU { + } else if read(memory, ram::wListMenuID) == poke::ITEM_LIST_MENU && item_list_drawn(memory) { // The bag, opened from the battle menu's ITEM entry. `DisplayListMenuID` keeps its // position in the same shared cursor every other menu uses, and the entry count is the // bag's own, so the scripts that reach into it (`ITEM`, `THROW BALL`) navigate by reading // rather than by counting presses -- which is what section 4 requires of them and what // they could not do while this read as no list at all. + // + // **And only while its box is on screen** (row 66), row 50's rule for the move list: + // `wListMenuID` is written when the list opens and never cleared, so after a ball was + // thrown every frame to the end of the battle -- "All right! WEEDLE was caught!", the + // Pokédex page, the nickname offer and the naming screen -- read as an open bag, the pad + // was `BACK` and `THROW BALL`, and the ball's A presses typed the nickname: 6,900 frames + // from the catch to the end of the battle, under a `THROW BALL` that threw nothing. let count = bag(memory).len().min(usize::from(poke::BAG_CAPACITY)); BattleMenu::Bag { cursor: cursor.current, count: u8::try_from(count).unwrap_or(0) } } else { @@ -1083,6 +1094,12 @@ fn two_option_box_drawn(memory: &mut dyn MemoryReader, cursor_x: u8, cursor_y: u /// becomes a horizontal run and (10, 12) becomes the `┘` junction with the PP box above. The /// mimic and relearn menus draw at row 7 and never reach a battle's own turn. Read whole, like /// every other box in this module, because a single tile id is an ordinary character. +/// Whether the battle bag's list box is whole on screen ([`poke::ITEM_LIST_BOX`], row 66). +fn item_list_drawn(memory: &mut dyn MemoryReader) -> bool { + let (left, top, right, bottom) = poke::ITEM_LIST_BOX; + border_drawn(memory, left, top, right, bottom) +} + fn move_list_drawn(memory: &mut dyn MemoryReader) -> bool { let (left, top, right, bottom) = poke::MOVE_LIST_BOX; if screen_tile(memory, left, top) != poke::frame::HORIZONTAL diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs index 5aa3af4..a461e0b 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs @@ -382,6 +382,13 @@ fn a_battle_frame_with_a_cursor_accepting_input_is_the_flys_turn() { let mut wram = Wram::overworld(); battler(&mut wram); wram.bag(&[(crate::pokemon_red::macros::cartridge::item::POTION, 2)]).set(ram::wListMenuID, poke::ITEM_LIST_MENU); + // Row 66: the list byte alone is not the bag. It is never cleared, so it outlives the list + // into the rest of the battle -- after a ball, the catch, the Pokédex page, the nickname. + let fight = battle(&mut wram).unwrap(); + assert_eq!(fight.menu, BattleMenu::None, "the list byte without the list's box on screen"); + assert!(!fight.own_turn, "text after the bag closed is nobody's turn"); + let (left, top, right, bottom) = poke::ITEM_LIST_BOX; + wram.draw_box(left, top, right, bottom); let fight = battle(&mut wram).unwrap(); assert_eq!(fight.menu, BattleMenu::Bag { cursor: 0, count: 1 }); assert!(fight.own_turn, "the battle bag is a cursor accepting input"); diff --git a/services/flysim/crates/flysim/tests/rom_catch.rs b/services/flysim/crates/flysim/tests/rom_catch.rs index f731ebd..5f6feea 100644 --- a/services/flysim/crates/flysim/tests/rom_catch.rs +++ b/services/flysim/crates/flysim/tests/rom_catch.rs @@ -54,7 +54,15 @@ const SEED: u32 = 20_260_922; const HOT: f64 = 16.0; const REST: f64 = 10.0; /// `THROW BALL`'s channel (`pokemon_red::macros::palette`). +/// +/// Row 66's note: this is the button's *tag*; its channel is `macro_throw_ball` +/// ([`THROW_BALL_CHANNEL`]), so the lean below sets a rate the decoder does not read and the drive +/// in a wild battle is the calibrated tie. It is kept as it is because that drive is the one that +/// catches from the forest checkpoint (with the real channel hot the checkpoint's one ball misses +/// on this frame timing), and the row 66 test reuses it up to the catch. const BALL: &str = "MB·BALL"; +/// `THROW BALL`'s channel as the macro layer binds it. +const THROW_BALL_CHANNEL: &str = "macro_throw_ball"; /// Frames the stub leans on one channel before the rotation moves on, the shape of the real /// group's hysteresis-then-fatigue rotation. const BURST_FRAMES: u32 = 24; @@ -190,9 +198,9 @@ fn a_catch_on_the_cartridge_pays_the_catch_rule_once_with_the_species_in_its_lab eprintln!("skipped: no FLY_CATCH_CHECKPOINT"); return; }; - let mut run = Run::resume(&rom, &checkpoint); - let balls = run.balls(); + let balls = Run::resume(&rom, &checkpoint).balls(); if balls == 0 { + let run = Run::resume(&rom, &checkpoint); eprintln!( "skipped: the checkpoint's bag holds no ball (map {:#04x}). `BUY BALL` can buy one \ inside a mart; point FLY_CATCH_CHECKPOINT at a state that already has one.", @@ -200,24 +208,47 @@ fn a_catch_on_the_cartridge_pays_the_catch_rule_once_with_the_species_in_its_lab ); return; } - eprintln!("bag holds {balls} balls; map {:#04x}", run.adapter.map_id().unwrap_or(u32::MAX)); + eprintln!("bag holds {balls} balls"); - // Twenty brain minutes is generous for a forest checkpoint: the live run threw 28 balls in - // its first Viridian Forest session (`pokemon_red::macros::palette`). - let budget = 20 * 60 * 60; - let mut battles = 0u32; - let mut was_in_battle = false; - for _ in 0..budget { - run.step(); - let now = run.in_wild_battle(); - if now && !was_in_battle { - battles += 1; + // Five brain minutes per attempt is generous for a forest checkpoint: the live run threw 28 + // balls in its first Viridian Forest session (`pokemon_red::macros::palette`). An attempt + // starts after `5 * attempt` frames with nothing pressed, so each one meets the wild battle, + // and the ball meets the random number, on a different frame (row 66): one ball misses about + // two throws in three, and which throw a checkpoint's one ball is depends on frame timing + // that any change to the pad moves. + let budget = 5 * 60 * 60; + let mut battles; + let mut attempt = 0u32; + let mut run = loop { + let mut run = Run::resume(&rom, &checkpoint); + for _ in 0..attempt * 5 { + run.ms += MS_PER_FRAME; + run.frame += 1; + let evaluated = run + .legacy + .stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms) + .expect("a frame should complete"); + run.payouts.extend(evaluated.rewards); } - was_in_battle = now; - if !run.catches().is_empty() { - break; + battles = 0; + let mut was_in_battle = false; + for _ in 0..budget { + run.step(); + let now = run.in_wild_battle(); + if now && !was_in_battle { + battles += 1; + } + was_in_battle = now; + if !run.catches().is_empty() { + break; + } } - } + if !run.catches().is_empty() || attempt == 23 { + break run; + } + eprintln!("attempt {attempt}: no catch ({battles} wild battles, {} balls left)", run.balls()); + attempt += 1; + }; let catches = run.catches(); assert!( @@ -255,3 +286,136 @@ fn a_catch_on_the_cartridge_pays_the_catch_rule_once_with_the_species_in_its_lab // sets the bit the `species` rule reads, whether or not it was new to this run. assert!(run.balls() < balls, "a ball was spent"); } + +/// What one drive from the checkpoint saw after its catch. +struct AfterCatch { + caught_at: u32, + ended_at: u32, + /// Frames between the catch and the battle's end on which `THROW BALL` was on the pad. + ball_dealt: u32, + /// Every pad the fly could decide on in that stretch. + pads: std::collections::BTreeSet>, +} + +/// One drive: `idle` frames with nothing pressed first (so each attempt reaches the wild battle +/// on a different frame, and the ball meets a different random number), then the first test's +/// drive up to the catch, then the pad's own buttons in turn. `None` when no ball kept anything +/// within the budget: one ball in the bag misses about two throws in three. +fn drive_past_a_catch(rom: &[u8], checkpoint: &flysim::store::Checkpoint, idle: u32) -> Option { + let mut run = Run::resume(rom, checkpoint); + for _ in 0..idle { + run.ms += MS_PER_FRAME; + run.frame += 1; + let evaluated = run + .legacy + .stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms) + .expect("a frame should complete"); + run.payouts.extend(evaluated.rewards); + } + let budget = 5 * 60 * 60; + let mut caught_at: Option = None; + let mut ball_dealt = 0u32; + let mut pads = std::collections::BTreeSet::new(); + let mut hold = 0usize; + for frame in 0..budget { + let bound = run.layer.bound_channels(); + let hot = if caught_at.is_none() { + if run.in_wild_battle() { + Some(BALL.to_string()) + } else { + let slot = (run.frame / BURST_FRAMES) as usize % run.channels.len(); + Some(run.channels[slot].to_string()) + } + } else if bound.is_empty() { + None + } else { + if frame % BURST_FRAMES == 0 { + hold += 1; + } + Some(bound[hold % bound.len()].clone()) + }; + if caught_at.is_some() { + if bound.iter().any(|channel| channel == THROW_BALL_CHANNEL) { + ball_dealt += 1; + } + if run.layer.running().is_none() && !bound.is_empty() { + pads.insert(bound.clone()); + } + } + let active = run.decoder.decode_bound(&rates(hot.as_deref()), run.ms, false, None, Some(&bound)); + run.legacy.execute(Some(&mut run.layer), &active, 0, run.ms, &mut run.gb, &run.adapter); + run.ms += MS_PER_FRAME; + run.frame += 1; + let evaluated = run + .legacy + .stub_advance(Some(&mut run.layer), &mut run.gb, &mut run.adapter, run.ms) + .expect("a frame should complete"); + run.payouts.extend(evaluated.rewards); + if caught_at.is_none() && run.byte(ram::wCapturedMonSpecies) != 0 { + caught_at = Some(frame); + } + if let Some(caught_at) = caught_at + && run.byte(ram::wIsInBattle) == 0 + { + assert!(!run.catches().is_empty(), "the catch pays at the battle's end"); + return Some(AfterCatch { caught_at, ended_at: frame, ball_dealt, pads }); + } + } + assert!(caught_at.is_none(), "a battle still running {budget} frames after its catch"); + None +} + +/// Row 66: once a ball has kept a Pokémon, nothing to the end of the battle is the bag. +/// +/// After the throw `wListMenuID` still says `ITEMLISTMENU` -- it is written when a list opens and +/// never cleared -- so on v0.6.5 every frame from "All right! … was caught!" through the Pokédex +/// page, the nickname offer and the naming screen read as an open battle bag. The pad was `BACK` +/// and `THROW BALL`, a `THROW BALL` that threw nothing and whose A presses typed the nickname; +/// driven from the rung-8 survey checkpoint the battle took 6,900 frames to end after the catch. +/// +/// The drive after the catch leans on the pad's own buttons in turn (not the whole channel +/// list), so what it measures is what the pad offers, not how often a rotation over every channel +/// lands on it. +#[test] +fn row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let Some(checkpoint) = checkpoint() else { + eprintln!("skipped: no FLY_CATCH_CHECKPOINT"); + return; + }; + if Run::resume(&rom, &checkpoint).balls() == 0 { + eprintln!("skipped: the checkpoint's bag holds no ball"); + return; + } + let after = (0..24) + .find_map(|attempt| { + let after = drive_past_a_catch(&rom, &checkpoint, attempt * 5); + if after.is_none() { + eprintln!("attempt {attempt}: the ball missed"); + } + after + }) + .expect("one of 24 attempts should keep a Pokémon"); + eprintln!( + "caught at f{}, battle over at f{} ({} frames); THROW BALL dealt on {} of them; pads {:?}", + after.caught_at, + after.ended_at, + after.ended_at - after.caught_at, + after.ball_dealt, + after.pads + ); + assert_eq!(after.ball_dealt, 0, "THROW BALL on the pad after the catch: {:?}", after.pads); + assert!( + after.pads.iter().all(|pad| !pad.iter().any(|channel| channel == "macro_back")), + "BACK on the pad after the catch, with no list up: {:?}", + after.pads + ); + assert!( + after.ended_at - after.caught_at < 3_000, + "the battle took {} frames to end after the catch", + after.ended_at - after.caught_at + ); +} From 36325d82ddbe0b1b82f42f5ab38b3779df94c5ca Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:55:23 +0000 Subject: [PATCH 2/5] palette: a counter the fly walked away from is not walked back to for the window Row 62 re-deals GO SHOP/GO HEAL whenever the service is needed, with no window. Live on v0.6.5 from the rung-8 archive that was a ring: GO SHOP to the Viridian clerk, GO OUT/GO OBJECTIVE back out without TALK, GO SHOP again (33 in 35 minutes). A completed GO SHOP/GO HEAL facing the counter person now records TargetKey::Counter on the building's map; the service walk toward it is withheld for the reached window, from the street and inside. TALK at the counter is unchanged. ROM row66 test (FLY_ROW66_MART_CHECKPOINT): base 31 street GO SHOPs in 10,000 frames, branch 0. --- .../src/pokemon_red/macros/cartridge.rs | 12 ++ .../src/pokemon_red/macros/driver.rs | 6 +- .../src/pokemon_red/macros/executor.rs | 20 +++ .../src/pokemon_red/macros/palette.rs | 31 ++++- .../src/pokemon_red/macros/tests.rs | 40 ++++++ .../flybrain-gb/src/pokemon_red/state.rs | 5 + .../crates/flysim/tests/rom_macros_mode.rs | 123 ++++++++++++++++++ 7 files changed, 234 insertions(+), 3 deletions(-) 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 dac0e49..1f98833 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 @@ -312,6 +312,11 @@ pub enum TargetKey { /// the box belongs to is whatever the fly is standing in front of, and the box is the only /// thing on screen while it is open. Answer { at: Tile, yes: bool }, + /// A mart's or a Pokémon Center's counter, walked to by `GO SHOP` or `GO HEAL` and faced + /// (row 66). Keyed by the building's map and nothing else, because the question it answers is + /// asked from *outside* the building, where no sprite slot of it means anything: has the fly + /// just stood at this counter and walked away from it ([`MacroState::counter_walked_to`]). + Counter, } /// Which list the shared cursor belongs to right now. @@ -617,6 +622,13 @@ pub trait MacroState: GameState { false } + /// Whether a `GO SHOP` or `GO HEAL` has walked the fly to the counter of the building on + /// `map` and faced it, inside the reached window (row 66). Asked of any map, not only the + /// loaded one: it is what the service walk from the street outside reads. + fn counter_walked_to(&mut self, _map: u8) -> bool { + false + } + /// Where the ladder's next unreached rung is, when the adapter's rung catalog knows. /// /// `None` leaves `GO OBJECTIVE` unbound, which is section 9's own fall-through: the plan's diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs index 23f9fa6..8760063 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs @@ -19,7 +19,8 @@ use crate::macros::{ use super::super::mapgrid::MapGrids; use super::super::state::PokeState; use super::cartridge::{ - Areas, Frontiers, LAST_MAP, MacroState, Pushed, Stood, Talked, Targets, Tile, outdoors, + Areas, Frontiers, LAST_MAP, MacroState, Pushed, Stood, Talked, TargetKey, Targets, Tile, + outdoors, }; use super::geography; use super::executor::{MacroAbort, MacroMachine, Refusal}; @@ -271,6 +272,9 @@ impl PokemonPalette { if let Some((map, target)) = self.machine.take_reached() { self.targets.record_reached(map, target); } + if let Some(map) = self.machine.take_counter() { + self.targets.record_reached(map, TargetKey::Counter); + } // A tile the cartridge drove the fly off: no window, because the map is like that until // the event that unlocks it, and nothing here knows which event that is (row 37). while let Some((map, tile)) = self.machine.take_pushed() { 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 783c48b..11d6cff 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 @@ -648,6 +648,9 @@ pub struct MacroMachine { /// that finds no route to *any* of its goals has failed at all of them, and each is a key. blocked: Vec<(u8, TargetKey)>, reached: Option<(u8, TargetKey)>, + /// The building whose counter a completed `GO SHOP` or `GO HEAL` has just faced, for the + /// reached ledger under [`TargetKey::Counter`] (row 66). + counter: Option, /// A map whose frontier a `GO FRONTIER` has just proved unreachable, waiting to be taken /// into the session's ledger ([`super::cartridge::Frontiers`], section 12.14). /// @@ -754,6 +757,7 @@ impl MacroMachine { outcome: None, blocked: Vec::new(), reached: None, + counter: None, exhausted: None, pushed_tile: Vec::new(), refused_at: None, @@ -1000,6 +1004,11 @@ impl MacroMachine { self.reached.take() } + /// The building whose counter a completed `GO SHOP` or `GO HEAL` faced, taken (row 66). + pub fn take_counter(&mut self) -> Option { + self.counter.take() + } + /// The map a `no route` from `GO FRONTIER` earned, taken rather than read (section 12.14). pub fn take_exhausted(&mut self) -> Option { self.exhausted.take() @@ -1040,6 +1049,7 @@ impl MacroMachine { // that so a cancelled queue cannot leak into the next macro's finish. self.blocked.clear(); self.reached = None; + self.counter = None; // A rollback is not the map pushing the fly anywhere, and it is not the frontier being // out of reach either: the fly is about to be somewhere else entirely. self.pushed_tile.clear(); @@ -1411,6 +1421,16 @@ impl MacroMachine { && let Some(entry) = active.target { self.reached = Some(entry); + // **The counter itself, by the building's map** (row 66): a service walk + // that ended facing the clerk or the nurse. From the street the question + // is "has the fly just stood at this counter", and outside the building + // no sprite slot of it can be named. + if matches!(active.kind, MacroKind::GoShop | MacroKind::GoHeal) + && let (map, TargetKey::Thing(_)) = entry + && super::geography::amenity_at(map).is_some() + { + self.counter = Some(map); + } // And a completed `HEAL` has *had* the conversation: the box was opened, // answered and closed by this macro's own presses, so the nurse is talked // to and `TALK` has nothing left to open (section 12.12). Without it the 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 317dbf4..327d188 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 @@ -999,7 +999,9 @@ pub fn amenity_goals(state: &mut dyn MacroState, kind: Amenity) -> Vec { // 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) { + // ...unless this counter is the one the fly has just walked to and walked away from + // ([`counter_walked_away`], row 66): then the ledgers answer, as they do for any person. + if service_needed(state, kind) && !state.counter_walked_to(here) { return service_aims(state, kind); } return counter_aims(state, counter_sprite(kind)); @@ -1095,7 +1097,32 @@ pub fn amenity_wanted(state: &mut dyn MacroState, kind: Amenity) -> Option { return None; } let area = area_here(state)?; - amenity_in_reach(state, area, kind) + let map = amenity_in_reach(state, area, kind)?; + if counter_walked_away(state, map) { + return None; + } + Some(map) +} + +/// Whether the fly has just stood at the counter of the building on `map`, facing it, and is now +/// outside that building: what takes the service walk toward it off the pad for the reached window +/// (row 66). +/// +/// **A counter the fly walked away from is not walked back to at once.** Row 62 made a service +/// dealt again whenever the cartridge says it is needed, whatever the ledgers say, and that is a +/// ring by construction when the fly does not use the counter: live on v0.6.5 from the rung-8 +/// archive, `GO SHOP` 33 times in 35 minutes, each one a walk in from the street and up to the +/// Viridian clerk, then `GO OUT` or `GO OBJECTIVE` back out of the door without a `TALK`, and +/// outside `GO SHOP` on the pad again because the bag still had no ball. Reproduced from a +/// post-parcel checkpoint of the Viridian mart with the connectome: three laps in eighteen brain +/// seconds. It is section 12.1's ledger doing what it does for every other walk -- a target +/// arrived at and faced is not re-walked for the window -- applied to the one walk row 62 took it +/// away from. The fly standing at the counter still has `TALK` (its precondition reads the +/// service, not this), the nurse's `HEAL` still walks from anywhere in the centre, and when the +/// window closes the counter is a service again. +fn counter_walked_away(state: &mut dyn MacroState, map: u8) -> bool { + let here = state.player().map(|player| player.map); + here != Some(map) && state.counter_walked_to(map) } /// `area`'s building of `kind`, when the route to it from the piece of ground the fly stands on 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 98b96e5..8bc6737 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 @@ -875,6 +875,10 @@ impl MacroState for World { self.targets.reached(self.map, target) } + fn counter_walked_to(&mut self, map: u8) -> bool { + self.targets.reached(map, TargetKey::Counter) + } + fn refused_here(&mut self, slot: u8) -> bool { self.targets.refused(self.map, slot, self.player) } @@ -5805,6 +5809,42 @@ fn go_shop_comes_back_while_the_bag_has_no_ball_and_the_money_covers_one() { assert!(!on_the_pad(&mut world, MacroKind::GoShop), "the parcel's text table, no counter"); } +#[test] +fn a_counter_the_fly_walked_away_from_is_not_walked_back_to_for_the_window() { + // Row 66. Live on v0.6.5 from the rung-8 archive: `GO SHOP` 33 times in 35 minutes, in from + // the street to the Viridian clerk and back out of the door without a `TALK`, and `GO SHOP` on + // the street's pad again because the bag still had no ball -- row 62's "dealt again while + // needed", with no window at all. + let mut world = viridian(); + world.areas.insert((Amenity::Mart, maps::VIRIDIAN_CITY)); + world.seen_maps.insert(maps::VIRIDIAN_MART); + assert!(on_the_pad(&mut world, MacroKind::GoShop), "no ball, and the money for one"); + + // A `GO SHOP` has just stood the fly at that counter; it walked back out. + world.targets.record_reached(maps::VIRIDIAN_MART, TargetKey::Counter); + assert!(!on_the_pad(&mut world, MacroKind::GoShop), "not straight back in: {:?}", pad_of(&mut world)); + assert_eq!(amenity_wanted(&mut world, Amenity::Mart), None); + + // The window closes and the counter is a service again. + world.targets.clock(BLOCKED_MINUTES_DEFAULT * 60_000.0 + 1.0); + assert!(on_the_pad(&mut world, MacroKind::GoShop), "after the window"); + + // Inside, inside the window: no walk back to the counter, and at the counter its press. + let mut mart = World::mart(); + mart.targets.record_reached(mart.map, TargetKey::Counter); + 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), "{:?}", pad_of(&mut mart)); + mart.player = Tile::new(2, 5); + mart.facing = Facing::Left; + assert!(on_the_pad(&mut mart, MacroKind::Talk), "the counter still opens where the fly stands"); + + // Only the counter: another person reached in the building is not the counter. + let mut mart = World::mart(); + mart.targets.record_reached(mart.map, TargetKey::Thing(TalkTarget::Sprite(1))); + assert!(on_the_pad(&mut mart, MacroKind::GoShop), "row 62's rule stands without a counter visit"); +} + #[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 diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs index 4b42bcb..366207a 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs @@ -2334,6 +2334,11 @@ impl MacroState for PokeState<'_> { self.targets.reached(map, target) } + /// Whether the counter of the building on `map` was walked to inside the window (row 66). + fn counter_walked_to(&mut self, map: u8) -> bool { + self.targets.reached(map, TargetKey::Counter) + } + /// Where the ladder's next unreached rung is (`GO OBJECTIVE`). /// /// The adapter's [`crate::adapter::MapPlace`] in the executor's own types, which is the only diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index 7940255..e356b45 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -4554,3 +4554,126 @@ fn row65_the_fly_leaves_the_cerulean_badge_houses_back_yard() { assert!(worst_empty < 600, "an empty pad in the yard for {worst_empty} frames: {:?}", run.started); assert!(left.is_some(), "the fly never left the yard: {:?} {:?}", run.route, run.started); } + +fn row66_mart_checkpoint() -> Option { + std::env::var_os("FLY_ROW66_MART_CHECKPOINT").map(|path| { + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope") + }) +} + +/// Row 66: a fly that walks up to the Viridian clerk and away again without a `TALK` is not +/// walked straight back in by `GO SHOP`. +/// +/// **What was live** (v0.6.5, restored from the rung-8 archive): `GO SHOP` done 33 times in 35 +/// minutes, `TALK` 5, `BUY BALL` never dealt -- in from the street to the counter, `GO OUT` or +/// `GO OBJECTIVE` back out of the door, and `GO SHOP` on the street's pad again because the bag +/// still held no ball (row 62's "dealt again while the service is needed", with no window). +/// Reproduced with the connectome from this checkpoint: three laps in eighteen brain seconds. +/// +/// The drive declines the counter on purpose: `GO SHOP` whenever it is dealt, then the ways out, +/// never `TALK`. It says nothing about which button the fly would press; the claim is that the pad +/// does not deal the walk back to a counter the fly has just walked away from (section 12.1's +/// reached window, applied to the service walk). +/// +/// ```sh +/// FLY_ROM=/path/to/pokemon-red.gb \ +/// FLY_ROW66_MART_CHECKPOINT=.local/checkpoints/survey-rank8-row66-viridian-mart.checkpoint \ +/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row66 +/// ``` +#[test] +fn row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop() { + use flybrain_gb::pokemon_red::macros::PokemonPalette; + use flybrain_gb::{MacroPalette, Outcome, Started}; + let rom = skip_without_rom!(); + let Some(checkpoint) = row66_mart_checkpoint() else { + eprintln!("skipped: no FLY_ROW66_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"); + assert!(run.money() >= 200, "and the money for one: {}", run.money()); + + let order = ["GO SHOP", "GO OUT", "GO OBJECTIVE"]; + 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; + // `GO SHOP` walks that finished facing the counter, `TALK` dealt there, and `GO SHOP` walks + // started from the street outside after the first of those. + let mut at_the_counter = 0u32; + let mut talk_dealt_at_the_counter = false; + let mut from_the_street_after = 0u32; + let mut laps = 0u32; + let mut last_map = run.map(); + for _ in 0..10_000u32 { + palette.clock(ms); + let observed = { + let ledger = AdapterLedger(&run.adapter); + palette.observe(&mut run.gb, &ledger) + }; + 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; + if at_the_counter > 0 + && run.map() == VIRIDIAN_MART + && observed.bindings.iter().any(|binding| binding.name == "TALK") + { + talk_dealt_at_the_counter = true; + } + let binding = order + .iter() + .find_map(|want| observed.bindings.iter().find(|binding| binding.name == *want)) + .or_else(|| observed.bindings.iter().find(|binding| binding.name != "TALK")) + .unwrap_or(&observed.bindings[0]); + if binding.name == "GO SHOP" && run.map() != VIRIDIAN_MART && at_the_counter > 0 { + from_the_street_after += 1; + } + 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 == "GO SHOP" + && outcome == Outcome::Done + && run.map() == VIRIDIAN_MART + { + at_the_counter += 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); + let map = run.map(); + if map == VIRIDIAN_MART && last_map == VIRIDIAN_CITY { + laps += 1; + } + last_map = map; + } + eprintln!( + "GO SHOP done in the mart {at_the_counter}, TALK dealt at the counter \ + {talk_dealt_at_the_counter}, GO SHOP from the street after that {from_the_street_after}, \ + walks back into the mart {laps}, balls {}", + run.bag_count(POKE_BALL) + ); + assert!(at_the_counter >= 1, "the first GO SHOP walks the fly to the clerk"); + assert!(talk_dealt_at_the_counter, "and the press that opens the counter is on the pad there"); + assert_eq!( + from_the_street_after, 0, + "GO SHOP dealt on the street again after the fly walked away from the counter" + ); +} From 96e3ffeeb1c817cb31fa3ed4fc03e0232a9da00f Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:55:23 +0000 Subject: [PATCH 3/5] examples: row 66 survey counters trap_hunt: a shop/ball/catch tally (pad frames, starts, outcomes, balls, party+box, Pokedex owned, mart entries) and FLY_TRAP_LOG_MACROS=1. scene_probe offers: catch, party and Pokedex counts, FLY_PROBE_SCREEN_* screen dumps, FLY_PROBE_SAVE_MART to save a mart entrance. --- .../crates/flysim/examples/scene_probe.rs | 53 +++++++++- .../crates/flysim/examples/trap_hunt.rs | 100 ++++++++++++++++++ 2 files changed, 151 insertions(+), 2 deletions(-) diff --git a/services/flysim/crates/flysim/examples/scene_probe.rs b/services/flysim/crates/flysim/examples/scene_probe.rs index 6950d94..1bba3dc 100644 --- a/services/flysim/crates/flysim/examples/scene_probe.rs +++ b/services/flysim/crates/flysim/examples/scene_probe.rs @@ -1743,6 +1743,7 @@ fn offers_survey( layer: &mut flysim::macros::MacroLayer, decoder: &mut PopulationDecoder, hold_ms: f64, + checkpoint: &flysim::store::Checkpoint, ) { use flybrain_gb::pokemon_red::macros::cartridge::MacroState; use flybrain_gb::pokemon_red::macros::geography::{self, Amenity}; @@ -1764,6 +1765,9 @@ fn offers_survey( 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 owned: u32 = (0..19u16).map(|i| gb.read8(ram::wPokedexOwned + i).count_ones()).sum(); + let species: Vec = party.mons.iter().map(|mon| mon.species).collect(); + let row66 = format!("- row66: party count {} species {species:?}, box count {}, pokedex owned {owned}", gb.read8(ram::wPartyCount), gb.read8(0xda80)); let money = state::money(gb); let last = blackout(gb); let player = state::player(gb); @@ -1775,6 +1779,7 @@ fn offers_survey( println!("- party {hp:?}; needs rest {}", palette::party_needs_rest(st)); println!("- money {money}, bag {bag:?}"); println!("- wLastBlackoutMap ($d719) = {last:#04x}"); + println!("{row66}"); let centers: Vec<(String, bool)> = CENTERS.iter().map(|map| (format!("{map:#04x}"), st.map_visited(*map))).collect(); let marts: Vec<(String, bool)> = @@ -1820,6 +1825,10 @@ fn offers_survey( let mut was_full = true; let mut counts: BTreeMap<&str, u64> = BTreeMap::new(); let mut maps_seen: BTreeMap = BTreeMap::new(); + let owned_now = |gb: &mut Emulator| -> u32 { (0..19u16).map(|i| gb.read8(ram::wPokedexOwned + i).count_ones()).sum() }; + let mut last_owned = owned_now(gb); + let mut last_mons = u32::from(gb.read8(ram::wPartyCount)) + u32::from(gb.read8(0xda80)); + let mut was_wild = false; for frame in 0..budget { let bound = layer.bound_channels(); if *ms >= next_pick && !bound.is_empty() && layer.running().is_none() { @@ -1882,6 +1891,15 @@ fn offers_survey( } } let executed = legacy.execute(Some(layer), &active, 0, *ms, gb, adapter); + if let (Some(from), Some(to)) = (std::env::var("FLY_PROBE_SCREEN_FROM").ok().and_then(|v| v.parse::().ok()), std::env::var("FLY_PROBE_SCREEN_TO").ok().and_then(|v| v.parse::().ok())) + && frame >= from && frame <= to && (frame - from) % env_usize("FLY_PROBE_SCREEN_EVERY", 100) == 0 + { + let battle = state::battle(gb).map(|battle| format!("{:?}", battle.menu)); + println!(" screen f{frame} mask {:#04x} scene {} pad {names:?} running {:?} battle-menu {battle:?} text {:?} prompt {} wIsInBattle {} boxes {:?} listid {:#04x} itemlist {:02x?} shop {:?} stock {:?}", executed.mask, layer.scene_name(), layer.running(), state::text_box(gb), state::yes_no_prompt(gb), gb.read8(ram::wIsInBattle), state::drawn_boxes(gb), gb.read8(ram::wListMenuID), (0..6u16).map(|i| gb.read8(ram::wItemList + i)).collect::>(), state::shop(gb).map(|s| s.screen), state::shop_stock(gb)); + for line in screen_text(gb) { + println!(" | {line}"); + } + } // `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() @@ -1953,6 +1971,23 @@ fn offers_survey( } was_wiped = wiped; was_full = full; + let owned = owned_now(gb); + if owned > last_owned { + *counts.entry("row66 pokedex owned +").or_default() += u64::from(owned - last_owned); + log.push(format!("f{frame} pokedex owned {last_owned} -> {owned}")); + } + last_owned = owned; + let mons = u32::from(gb.read8(ram::wPartyCount)) + u32::from(gb.read8(0xda80)); + if mons > last_mons && mons <= 26 { + *counts.entry("row66 mons gained (party+box)").or_default() += u64::from(mons - last_mons); + log.push(format!("f{frame} party+box {last_mons} -> {mons}")); + } + if mons <= 26 { last_mons = mons; } + let wild = gb.read8(ram::wIsInBattle) == 1; + if wild && !was_wild { + *counts.entry(if balls(gb) > 0 { "row66 wild battles with a ball" } else { "row66 wild battles, no ball" }).or_default() += 1; + } + was_wild = wild; let now_balls = balls(gb); if now_balls > last_balls { *counts.entry("balls bought").or_default() += u64::from(now_balls - last_balls); @@ -1974,8 +2009,22 @@ fn offers_survey( last_blackout = now_blackout; } if map != last_map { + // Row 66: `FLY_PROBE_SAVE_MART=` with `FLY_PROBE_SAVE` writes the first frame the fly + // walks into that mart with the money for a ball, no ball and no parcel. + if let (Some(want), Some(path)) = (std::env::var("FLY_PROBE_SAVE_MART").ok().and_then(|v| u8::from_str_radix(v.trim_start_matches("0x"), 16).ok()), std::env::var_os("FLY_PROBE_SAVE")) + && map == Some(want) + && money >= 200 + && frame >= env_usize("FLY_PROBE_SAVE_AFTER", 0) + && balls(gb) == 0 + && !state::bag(gb).iter().any(|item| item.id == 0x46) + && !std::path::Path::new(&path).exists() + { + let bytes = save_state(checkpoint, gb, adapter, frame, &path); + log.push(format!("f{frame} saved {bytes} bytes to {}", std::path::Path::new(&path).display())); + } if map.is_some_and(|map| CENTERS.contains(&map) || MARTS.contains(&map)) { - log.push(format!("f{frame} entered {map:?} (party full {full}, money {money})")); + let parcel = state::bag(gb).iter().any(|item| item.id == 0x46); + log.push(format!("f{frame} entered {map:?} (party full {full}, money {money}, balls {}, parcel {parcel})", balls(gb))); } last_map = map; } @@ -2152,7 +2201,7 @@ fn main() { // 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); + offers_survey(&mut gb, &mut adapter, &mut ms, &mut layer, &mut decoder, hold_ms, &checkpoint); return; } diff --git a/services/flysim/crates/flysim/examples/trap_hunt.rs b/services/flysim/crates/flysim/examples/trap_hunt.rs index b5ad5e5..7c5947e 100644 --- a/services/flysim/crates/flysim/examples/trap_hunt.rs +++ b/services/flysim/crates/flysim/examples/trap_hunt.rs @@ -235,6 +235,39 @@ struct Trace { payouts_by_kind: BTreeMap<&'static str, (u64, f64)>, move_starts: (u64, u64), wall_seconds: f64, + row66: Row66, +} + +/// Row 66's shop/ball/catch tally: pad frames, starts and outcomes of the watched buttons, and +/// the cartridge beside them. +#[derive(Default)] +struct Row66 { + /// channel -> [free frames on the pad, starts, done, other outcomes] + tally: BTreeMap<&'static str, [u64; 4]>, + free_frames: u64, + counts: BTreeMap<&'static str, u64>, + log: Vec, + last: Option<(u32, u32, u32, u32, u8)>, + was_wild: bool, +} + +const ROW66_WATCH: [&str; 8] = [ + "GO SHOP", "TALK", "CONFIRM", "BUY BALL", "BUY POTION", "LEAVE", "THROW BALL", "GO HEAL", +]; + +fn row66_read(gb: &mut flybrain_gb::Emulator) -> (u32, u32, u32, u32, u8) { + use flybrain_gb::MemoryReader; + use flybrain_gb::pokemon_red::symbols::ram; + let balls: u32 = flybrain_gb::pokemon_red::state::bag(gb) + .iter() + .filter(|item| (0x01..=0x04).contains(&item.id)) + .map(|item| u32::from(item.count)) + .sum(); + let money = flybrain_gb::pokemon_red::state::money(gb); + let mons = u32::from(gb.read8(ram::wPartyCount)) + u32::from(gb.read8(0xda80)); + let owned: u32 = (0..19u16).map(|i| gb.read8(ram::wPokedexOwned + i).count_ones()).sum(); + let map = flybrain_gb::pokemon_red::state::player(gb).map_or(0xff, |player| player.map); + (balls, money, mons, owned, map) } /// Which sub-state of a battle this frame is, or `None` when no battle is running. @@ -330,6 +363,20 @@ impl FrameObserver for Hunt { .then(|| flybrain_gb::pokemon_red::state::player(parts.emulator).map(|p| p.map)) .flatten(); self.battle_sub = battle_sub_state(parts.emulator); + if let Some(layer) = parts.macros.as_deref() + && layer.running().is_none() + { + let names: Vec = layer.feed_palette().into_iter().map(|slot| slot.name).collect(); + if !names.is_empty() { + let row = &mut self.trace.row66; + row.free_frames += 1; + for watch in ROW66_WATCH { + if names.iter().any(|name| name == watch) { + row.tally.entry(watch).or_default()[0] += 1; + } + } + } + } if let Some(sub) = self.battle_sub { *self.trace.battle_frames.entry(sub).or_insert(0) += 1; let pad = self.trace.battle_pads.entry(sub).or_default(); @@ -344,6 +391,20 @@ impl FrameObserver for Hunt { let location = frame.location; let trace = &mut self.trace; for event in &executed.events { + if std::env::var("FLY_TRAP_LOG_MACROS").is_ok_and(|value| value == "1") { + let pad: Vec = parts.macros.as_deref().map(|layer| layer.feed_palette().into_iter().map(|slot| slot.name).collect()).unwrap_or_default(); + println!( + "macro {:8.2}s {:?} {} {} pad {pad:?}", + (ms - trace.began_ms) / 1000.0, + location, + event.name, + event.outcome.map_or("start", |outcome| outcome.as_str()) + ); + } + if let Some(watch) = ROW66_WATCH.iter().find(|watch| **watch == event.name) { + let key = match event.outcome { None => 1, Some(o) if o.as_str() == "done" => 2, Some(_) => 3 }; + trace.row66.tally.entry(watch).or_default()[key] += 1; + } match event.outcome { None => { trace.starts.push((ms, event.name)); @@ -564,6 +625,7 @@ fn run( payouts_by_kind: BTreeMap::new(), move_starts: (0, 0), wall_seconds: 0.0, + row66: Row66::default(), seeded: seeded_note, refusals: BTreeMap::new(), refusal_run: (None, 0), @@ -640,6 +702,32 @@ fn run( ); } + { + use flybrain_gb::MemoryReader; + let minute = (ms - began_ms) / MINUTE_MS; + let now = row66_read(parts.emulator); + let wild = parts.emulator.read8(flybrain_gb::pokemon_red::symbols::ram::wIsInBattle) == 1; + let row = &mut hunt.trace.row66; + if wild && !row.was_wild { + *row.counts.entry(if now.0 > 0 { "wild battles with a ball" } else { "wild battles, no ball" }).or_default() += 1; + } + row.was_wild = wild; + if let Some(last) = row.last { + if now.0 > last.0 { *row.counts.entry("balls gained").or_default() += u64::from(now.0 - last.0); row.log.push(format!("{minute:.2} min balls {} -> {} (map {:#04x})", last.0, now.0, now.4)); } + if now.0 < last.0 { *row.counts.entry("balls spent").or_default() += u64::from(last.0 - now.0); row.log.push(format!("{minute:.2} min balls {} -> {} (map {:#04x})", last.0, now.0, now.4)); } + if now.1 < last.1 && [0x2a, 0x38].contains(&now.4) { row.log.push(format!("{minute:.2} min money {} -> {} in mart {:#04x}", last.1, now.1, now.4)); } + if now.2 > last.2 && now.2 <= 26 { *row.counts.entry("mons gained (party+box)").or_default() += u64::from(now.2 - last.2); row.log.push(format!("{minute:.2} min party+box {} -> {}", last.2, now.2)); } + if now.3 > last.3 { *row.counts.entry("pokedex owned +").or_default() += u64::from(now.3 - last.3); row.log.push(format!("{minute:.2} min pokedex owned {} -> {}", last.3, now.3)); } + if now.4 != last.4 && [0x2a, 0x38, 0x43].contains(&now.4) { + *row.counts.entry("mart entries").or_default() += 1; + let parcel = flybrain_gb::pokemon_red::state::bag(parts.emulator).iter().any(|item| item.id == 0x46); + row.log.push(format!("{minute:.2} min entered mart {:#04x} (money {}, balls {}, parcel {parcel})", now.4, now.1, now.0)); + } + } else { + row.log.push(format!("start: balls {} money {} party+box {} owned {} map {:#04x}", now.0, now.1, now.2, now.3, now.4)); + } + row.last = Some(now); + } let location = frame.location; if let Some((map, x, y)) = location { hunt.trace.steps.push((ms, map, x, y)); @@ -1000,6 +1088,18 @@ fn main() { trace.ended_in.0, trace.ended_in.1, trace.ended_why ); walk_report(&trace); + { + let row = &trace.row66; + println!("\n## Row 66: shop, balls, catches\n\n{} free frames with a pad\n", row.free_frames); + println!("| button | frames on the pad | starts | done | other |\n| --- | ---: | ---: | ---: | ---: |"); + for watch in ROW66_WATCH { + let [a, b, c, d] = row.tally.get(watch).copied().unwrap_or_default(); + println!("| {watch} | {a} | {b} | {c} | {d} |"); + } + println!("\n- counts: {:?}", row.counts); + if let Some(last) = row.last { println!("- end: balls {} money {} party+box {} owned {} map {:#04x}", last.0, last.1, last.2, last.3, last.4); } + for line in row.log.iter().take(150) { println!("- {line}"); } + } for (rank, label, ms) in &trace.rungs { println!("- rung {rank} {label} at {:.2} brain minutes", ms / MINUTE_MS); } From 5da77454c3d088cb8002580af0e3eba63490dbe5 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 14:09:02 +0000 Subject: [PATCH 4/5] macros: BUY BALL is one button from a mart's floor, like HEAL Operator decision on row 66. Measured with the connectome, the fly walked to the Viridian clerk again and again and never chose TALK, so the four choices a purchase took at the counter never happened. BUY BALL is now also offered on the overworld pad inside a mart whose first stock row is a Poke Ball (Viridian, Pewter, Cerulean), while service_needed holds (no ball, money for one, no Oak's parcel) and the clerk is not in the blocked window. One press walks to the clerk, talks, advances the greeting to BUY/SELL/QUIT (checking the first row is a Poke Ball), buys one, answers the price box and is done when the wallet drops. The open-counter BUY BALL is unchanged. Unit test for each offer condition; ROM row66 floor purchase from FLY_ROW66_MART_CHECKPOINT: base never dealt on the floor, no ball; branch dealt, started, done, one ball, 200 paid. --- .../src/pokemon_red/macros/executor.rs | 60 ++++++++- .../src/pokemon_red/macros/geography.rs | 6 + .../src/pokemon_red/macros/palette.rs | 36 +++++- .../src/pokemon_red/macros/tests.rs | 63 ++++++++++ .../crates/flysim/tests/rom_macros_mode.rs | 114 ++++++++++++++++++ 5 files changed, 276 insertions(+), 3 deletions(-) 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 11d6cff..df2c6e8 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 @@ -30,7 +30,8 @@ use super::cartridge::{ }; use super::geography::Amenity; use super::palette::{ - MacroId, MacroKind, Palette, amenity_goals, frontier_aims, heal_goals, healthiest_other, + MacroId, MacroKind, Palette, amenity_goals, floor_ball_goals, frontier_aims, heal_goals, + healthiest_other, facing_target, listing, move_index, move_list, nurse_prompt, objective_goals, party_rested, potion_slot, precondition, @@ -370,6 +371,12 @@ enum Step { /// `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 }, + /// Advance the clerk's greeting until the counter's BUY / SELL / QUIT menu is drawn, then + /// move on; `Blocked` if it never comes, or if the counter's first stock row is not a Poké + /// Ball once its list can be read (row 66, `BUY BALL` from the floor). Pulses A the way + /// [`Step::Prompt`] does and reads the screen every frame, so the menu is caught before the + /// next pulse could choose BUY on it. + Counter { waited: u32 }, } /// Progress through one A* walk. @@ -846,6 +853,9 @@ impl MacroMachine { } // A walk's cap is its own; every other script keeps section 4's flat ten seconds. let cap = match plan.front() { + // `BUY BALL` from the floor is a walk and then a whole purchase (row 66): the walk's + // budget, and a script's ten seconds for the counter after it. + Some(Step::Walk(walk)) if spec.kind == MacroKind::BuyBall => walk.budget + FRAME_CAP, Some(Step::Walk(walk)) => walk.budget, _ => FRAME_CAP, }; @@ -1597,6 +1607,24 @@ fn advance(step: &mut Step, state: &mut dyn MacroState) -> Progress { Progress::Hold(buttons::NONE) } } + Step::Counter { waited } => { + if shop_screen(state) == Some(ShopScreen::BuySellQuit) { + if stock_index(state, item::POKE_BALL) == Some(0) { + Progress::Next + } else { + Progress::Blocked + } + } 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) + } + } + } Step::Prompt { waited, before } => { if state.money() < *before { Progress::Finished @@ -1828,6 +1856,8 @@ fn beside(state: &mut dyn MacroState, here: Tile) -> Vec { const fn spanned(kind: MacroKind) -> &'static [Class] { match kind { MacroKind::Heal => &[Class::Overworld, Class::Talking], + // Row 66: from the floor, `BUY BALL` walks, opens the counter (text) and buys (the shop). + MacroKind::BuyBall => &[Class::Overworld, Class::Talking, Class::Shop], _ => &[], } } @@ -2187,7 +2217,33 @@ fn script( vec![cursor_on(battle_entry::RUN, true, Some(ListKind::BattleMain))] } MacroKind::BuyPotion => shop_plan(state, item::POTION)?, - MacroKind::BuyBall => shop_plan(state, item::POKE_BALL)?, + // At the open counter, the purchase; from the mart's floor (row 66), `HEAL`'s shape for a + // mart: walk to the clerk, the A that talks to him, the greeting advanced until BUY / SELL + // / QUIT is drawn, and the same purchase from there -- BUY, the first row (a Poké Ball in + // every mart this is offered in, checked once the list is readable), quantity one, the + // price box's YES, done when the wallet drops. + MacroKind::BuyBall if state.shop().is_some() => shop_plan(state, item::POKE_BALL)?, + MacroKind::BuyBall => { + let goals = aim_goals(floor_ball_goals(state)); + unreachable.extend(goal_keys(&goals)); + let (walk, target) = walk_then(state, goals, true)?; + aimed = target; + let before = state.money(); + vec![ + Step::Walk(walk), + press(buttons::A), + settle(), + Step::Counter { waited: 0 }, + cursor(0, true), + settle(), + cursor(0, true), + settle(), + press(buttons::A), + Step::Prompt { waited: 0, before }, + press(buttons::A), + Step::Paid { waited: 0, before }, + ] + } MacroKind::BuyAntidote => shop_plan(state, item::ANTIDOTE)?, MacroKind::BuyRepel => shop_plan(state, item::REPEL)?, // Section 13's two errands: the same walk `GO OBJECTIVE` makes, aimed at the area's mart 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 39c8efc..9ca1e92 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 @@ -766,6 +766,12 @@ pub fn route_within(from: Region, to: u8, area: u8) -> bool { /// The reverse lookup, and what tells the fly it is standing in a mart rather than in a house: the /// shop scene's own buttons and the centre's `HEAL` are dealt on this answer rather than on a /// tileset read, because a map id is a byte the adapter already has and a tileset is not. +/// The marts on [`AMENITIES`] whose counter stocks `POKE_BALL` as its first row +/// (`data/items/marts.asm` at the pinned commit): Viridian, Pewter and Cerulean all open their buy +/// list on it. `BUY BALL` from the floor (row 66) is offered only in these, and its script still +/// reads the stock once the counter is open and refuses if the first row is anything else. +pub const BALL_FIRST_MARTS: [u8; 3] = [maps::VIRIDIAN_MART, maps::PEWTER_MART, maps::CERULEAN_MART]; + pub fn amenity_at(map: u8) -> Option { AMENITIES.iter().find(|(_, _, id)| *id == map).map(|(_, kind, _)| *kind) } diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs index 327d188..31d0282 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 @@ -529,6 +529,11 @@ pub fn scene_set(scene: Scene, state: &mut dyn MacroState) -> Vec { if inside_center(state) { set.push(Heal); } + // Row 66: the mart's `HEAL`. One button from the floor that walks to the clerk, + // opens the counter and buys one ball ([`floor_ball_goals`]). + if inside_mart(state) { + set.push(BuyBall); + } set.extend([GoShop, GoHeal, GoItem, GoNpc, GoFrontier, Talk]); set } @@ -692,7 +697,12 @@ pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool { | MacroKind::BuyBall | MacroKind::BuyAntidote | MacroKind::BuyRepel => match kind.purchase() { - Some((id, cost)) => affordable(state, id, cost), + Some((id, cost)) => { + affordable(state, id, cost) + || (kind == MacroKind::BuyBall + && state.scene() == Scene::Overworld + && !floor_ball_goals(state).is_empty()) + } // Unreachable while [`MacroKind::purchase`] covers the four arms above, and a `false` // rather than a panic if it ever stops: an unpriced purchase is a button off the pad. None => false, @@ -1043,6 +1053,30 @@ pub fn heal_goals(state: &mut dyn MacroState) -> Vec { person_aims(state, poke_sprite::NURSE, Ledgers::BlockedOnly, true) } +/// `BUY BALL`'s walk from the floor of a mart: the tiles the clerk can be talked to from (row 66). +/// +/// The operator's decision on row 66: buying a ball is one macro, modelled on `HEAL` -- walk to +/// the clerk, talk, open BUY, take the first row, answer the price box, done when the wallet says +/// it is paid. Measured with the connectome before it: `GO SHOP` walked the fly to the Viridian +/// clerk again and again and the fly never once chose `TALK` there, so the four choices in a row +/// that a purchase took (`TALK`, the greeting, `CONFIRM`, `BUY BALL`) never happened. The fly +/// still has to choose this button; it is only on the pad while it can work: +/// +/// - in a mart whose first stock row is a Poké Ball ([`geography::BALL_FIRST_MARTS`]); +/// - while [`service_needed`] holds for the mart: no ball in the bag, the money for one, and no +/// Oak's parcel (the Viridian clerk's text table while it is carried sells nothing); +/// - with the clerk reachable: the blocked window is kept, the talked and reached ledgers are not +/// (a counter is a service), and the tile already facing him is a goal (no walk at all). +/// +/// Empty anywhere else, which is the other half of the precondition. +pub fn floor_ball_goals(state: &mut dyn MacroState) -> Vec { + let Some(here) = state.player().map(|player| player.map) else { return Vec::new() }; + if !geography::BALL_FIRST_MARTS.contains(&here) || !service_needed(state, Amenity::Mart) { + return Vec::new(); + } + person_aims(state, poke_sprite::CLERK, 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). /// 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 8bc6737..b3558cf 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 @@ -28,6 +28,7 @@ use super::executor::{ }; use super::palette::{ MacroId, MacroKind, Palette, SLOTS, amenity_goals, amenity_wanted, answer_key, errand, facing_nurse, + floor_ball_goals, 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, @@ -5845,6 +5846,68 @@ fn a_counter_the_fly_walked_away_from_is_not_walked_back_to_for_the_window() { assert!(on_the_pad(&mut mart, MacroKind::GoShop), "row 62's rule stands without a counter visit"); } +#[test] +fn buy_ball_is_offered_from_a_marts_floor_only_while_a_ball_can_be_bought() { + // Row 66, the operator's decision: buying a ball is one button, modelled on `HEAL`. + let mut mart = World::mart(); + assert_eq!(mart.scene, Scene::Overworld); + assert!(on_the_pad(&mut mart, MacroKind::BuyBall), "no ball, 3000, the clerk: {:?}", pad_of(&mut mart)); + assert!(!floor_ball_goals(&mut mart).is_empty()); + + // Facing the clerk already: still offered, with no walk (the tile he is faced from is a goal). + mart.player = Tile::new(2, 5); + mart.facing = Facing::Left; + assert!(on_the_pad(&mut mart, MacroKind::BuyBall), "at the counter"); + mart.player = Tile::new(3, 6); + + // A ball in the bag: nothing to buy it for. + mart.bag = vec![(item::POKE_BALL, 1)]; + assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "a ball already"); + mart.bag = vec![(item::GREAT_BALL, 1)]; + assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "any ball counts"); + mart.bag = Vec::new(); + + // Under a ball's price. + mart.money = price::POKE_BALL - 1; + assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "199"); + mart.money = price::POKE_BALL; + assert!(on_the_pad(&mut mart, MacroKind::BuyBall), "200"); + + // Oak's parcel: the Viridian clerk's text table is the parcel's and he sells nothing. + mart.bag = vec![(item::OAKS_PARCEL, 1)]; + assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "carrying the parcel"); + mart.bag = Vec::new(); + + // The talked and reached ledgers do not retire a counter; the blocked window does. + mart.talked.insert(TalkTarget::Sprite(1)); + mart.targets.record_reached(mart.map, TargetKey::Thing(TalkTarget::Sprite(1))); + mart.targets.record_reached(mart.map, TargetKey::Counter); + assert!(on_the_pad(&mut mart, MacroKind::BuyBall), "talked, reached, walked away: still a service"); + mart.targets.record_blocked(mart.map, TargetKey::Thing(TalkTarget::Sprite(1))); + assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "a clerk no walk reaches"); + + // Only in a mart whose first row is a ball, and never outside one. + let mut pewter = World::mart(); + pewter.map = maps::PEWTER_MART; + assert!(on_the_pad(&mut pewter, MacroKind::BuyBall), "Pewter's first row is a ball"); + let mut street = viridian(); + street.money = 3_000; + assert!(!on_the_pad(&mut street, MacroKind::BuyBall), "not from the street"); + let mut elsewhere = World::mart(); + elsewhere.map = maps::OAKS_LAB; + assert!(floor_ball_goals(&mut elsewhere).is_empty(), "not a mart"); + + // The open counter keeps its own rule: the greeting is no screen a purchase starts from. + let mut counter = World::mart(); + counter.scene = Scene::Shop; + counter.list = List::Shop(ShopScreen::Talking); + counter.stock = vec![item::POKE_BALL]; + assert!(!precondition(MacroKind::BuyBall, &mut counter), "the clerk is still talking"); + counter.list = List::Shop(ShopScreen::BuySellQuit); + counter.cursor_max = 2; + assert!(precondition(MacroKind::BuyBall, &mut counter), "BUY / SELL / QUIT"); +} + #[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 diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index e356b45..e53665c 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -4677,3 +4677,117 @@ fn row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop() { "GO SHOP dealt on the street again after the fly walked away from the counter" ); } + +/// Row 66, the operator's decision: `BUY BALL` is one button from a mart's floor, modelled on +/// `HEAL`, and pressed it rings up a ball. +/// +/// From the post-parcel Viridian mart (793 in the wallet, no ball): `BUY BALL` whenever it is +/// dealt, otherwise a uniform pick among the buttons on the pad. The claim is about the pad and the +/// script, not the fly's choice: on the floor of the mart the button is dealt, and one press of it +/// walks to the clerk, opens the counter and rings up one ball. On v0.6.5 it was dealt only at an +/// open counter, which took `TALK`, the greeting and `CONFIRM` first, and the connectome never +/// chose `TALK` there (three laps of `GO SHOP` and out in eighteen brain seconds). +/// +/// ```sh +/// FLY_ROM=/path/to/pokemon-red.gb \ +/// FLY_ROW66_MART_CHECKPOINT=.local/checkpoints/survey-rank8-row66-viridian-mart.checkpoint \ +/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row66 +/// ``` +#[test] +fn row66_buy_ball_from_the_marts_floor_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) = row66_mart_checkpoint() else { + eprintln!("skipped: no FLY_ROW66_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(); + + 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 rng = 0x2026_0929u32; + let mut dealt_on_the_floor = 0u32; + let mut started = 0u32; + let mut done = 0u32; + let mut bought_at = None; + for frame in 0..20_000u32 { + palette.clock(ms); + let observed = { + let ledger = AdapterLedger(&run.adapter); + palette.observe(&mut run.gb, &ledger) + }; + 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; + if run.map() == VIRIDIAN_MART + && observed.bindings.iter().any(|binding| binding.name == "BUY BALL") + && !observed.bindings.iter().any(|binding| binding.name == "LEAVE") + { + dealt_on_the_floor += 1; + } + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + let binding = observed + .bindings + .iter() + .find(|binding| binding.name == "BUY BALL") + .unwrap_or(&observed.bindings[rng as usize % observed.bindings.len()]); + if binding.name == "BUY BALL" + && flybrain_gb::pokemon_red::scene::detect(&mut run.gb) + == flybrain_gb::pokemon_red::macros::state::Scene::Overworld + { + started += 1; + } + 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 + { + done += 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 run.bag_count(POKE_BALL) > 0 && bought_at.is_none() { + bought_at = Some(frame); + } + if bought_at.is_some() && running.is_none() { + break; + } + } + eprintln!( + "BUY BALL dealt on the floor on {dealt_on_the_floor} holds, started {started}, done {done}; \ + a ball at {bought_at:?}; balls {}, money {money} -> {}", + run.bag_count(POKE_BALL), + run.money() + ); + assert!(dealt_on_the_floor > 0, "BUY BALL is on the mart floor's pad"); + assert!(started > 0, "and started from the floor"); + assert_eq!(run.bag_count(POKE_BALL), 1, "one ball rung up"); + assert_eq!(run.money(), money - 200, "and paid for"); + assert!(done >= 1, "the macro reports done when paid"); +} From a69a258edd103da86a219752b7e2d98e9e0e13c3 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 15:38:51 +0000 Subject: [PATCH 5/5] macros: no floor BUY BALL in Viridian before Oak has the parcel; docs for row 66 On the first visit the Viridian clerk's script hands the parcel over, and his counter sells nothing until Oak has it. MacroState::parcel_delivered reads EVENT_OAK_GOT_PARCEL (defaulted true). docs/design/macros.md 12.30 and infra/docs/macros-traps.md row 66: the GO SHOP ring, the one-button purchase, the bag after a catch, and the measured choices with the connectome. --- docs/design/macros.md | 58 ++++++++++++++++++ infra/docs/macros-traps.md | 60 +++++++++++++++++++ .../src/pokemon_red/macros/cartridge.rs | 8 +++ .../src/pokemon_red/macros/palette.rs | 8 ++- .../src/pokemon_red/macros/tests.rs | 11 ++++ .../flybrain-gb/src/pokemon_red/state.rs | 6 ++ 6 files changed, 150 insertions(+), 1 deletion(-) diff --git a/docs/design/macros.md b/docs/design/macros.md index 522ed19..ff99941 100644 --- a/docs/design/macros.md +++ b/docs/design/macros.md @@ -1913,6 +1913,64 @@ a door is taken the way the cartridge takes it, and the map graph says what the decoder, the reward catalog, the adapter version, the roles and the compatibility string are untouched. +### 12.30 A counter walked away from is not walked back to, a ball is bought with one button, and a closed bag is not the pad (2026-09-29, row 66) + +The operator restarted the live run from the rung-8 archive (VIRIDIAN CITY) to watch the fly shop, +buy Poké Balls and catch. On v0.6.5, 35 minutes in: `GO SHOP` done 33 times, `TALK` 5, `BUY BALL` +never dealt, `THROW BALL` 0, no catch. Three findings, two of them the pad. + +**`GO SHOP` and the way out were a ring.** Row 62 (12.26) deals a service walk whenever the +cartridge says the service is needed, whatever the ledgers say. When the fly stands at the counter +and does not use it, that is a ring by construction: `GO SHOP` from the street to the Viridian +clerk, `GO OUT` or `GO OBJECTIVE` back out of the door, and `GO SHOP` on the street's pad again, +because the bag still holds no ball. Reproduced with the connectome from a post-parcel checkpoint +of the Viridian mart (`survey-rank8-row66-viridian-mart`, saved by the offers survey): three laps in +eighteen brain seconds. A `GO SHOP` or `GO HEAL` that finishes facing the counter person now +records the building's counter (`TargetKey::Counter`, keyed by the building's map, because the +question is asked from the street, where none of the building's sprite slots means anything). For +the reached window the service walk toward that building is not dealt, from the street or inside. +That is 12.1's ledger doing for the service walk what it does for every other walk: a target +arrived at and faced is not walked to again at once. `TALK` at the counter, `HEAL` in a centre and +`BUY BALL` in a mart are unchanged by it. When the window closes the counter is a service again. + +**A ball is one button (the operator's decision).** Even without the ring the fly did not buy. +A purchase took four choices in a row at the counter: `TALK`, a press at the greeting, `CONFIRM` +on BUY, and `BUY BALL` on the list. With the connectome the fly walked to the clerk every time and +never once chose `TALK` there. So `BUY BALL` is now also the mart's `HEAL`. On the overworld pad +inside a mart, one press walks to the clerk, talks, advances the greeting until BUY / SELL / QUIT +is drawn, buys the first row, answers the price box as 12.26's purchase does, and is `done` when +the wallet drops. It is offered only while it can work: + +- in a mart whose first stock row is a Poké Ball (`geography::BALL_FIRST_MARTS`: Viridian, Pewter, + Cerulean, `data/items/marts.asm`). The script reads the stock once the counter is open and + refuses if the first row is anything else; +- while `service_needed` holds for the mart: no ball in the bag, 200 in the wallet, no Oak's parcel + (while it is carried the Viridian clerk's text table is the parcel's and he sells nothing). In + Viridian it is also not offered before Oak has the parcel (`EVENT_OAK_GOT_PARCEL`); +- with the clerk not in the blocked window. The talked and reached ledgers do not retire him, as + for the nurse. + +The fly still chooses it, as it chooses `HEAL`. The open-counter `BUY BALL` is unchanged. + +**After a catch the pad read the bag.** `wListMenuID` is written when a list opens and never +cleared. After a ball was thrown, every frame to the end of the battle read as an open battle bag: +"All right! WEEDLE was caught!", the Pokédex page, the nickname offer and the naming screen. The pad +was `BACK` and `THROW BALL`, a `THROW BALL` that threw nothing. Its A presses said YES to the +nickname and typed it, 6,900 frames from the catch to the battle's end on a stub survey. The bag +is now the bag only while its box, a `TextBoxBorder` at (4, 2)-(19, 12), is on screen: row 50's rule +for the move list. After the catch the pad is `NEXT`. `NEXT` answers the nickname offer with YES +and names the Pokémon with A's. Offering the offer's two answers inside a battle is a pad change +not made here. + +ROM tests: `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` and +`row66_buy_ball_from_the_marts_floor_rings_up_a_ball` (`FLY_ROW66_MART_CHECKPOINT`), +`row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` (`FLY_CATCH_CHECKPOINT`). Survey +numbers are in `infra/docs/macros-traps.md` row 66. + +Nothing ranks a button or presses for the fly. The walk back is withheld for a window, a purchase +is one offer, and the bag is read off the screen. The decoder, the reward catalog, the adapter +version, the roles and the compatibility string are untouched. + ## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a ## priority to visit the shop at least once per area; make shop macros item purchases. same ## for the Pokécenter. heal should be a macro.") diff --git a/infra/docs/macros-traps.md b/infra/docs/macros-traps.md index 11bb093..0512066 100644 --- a/infra/docs/macros-traps.md +++ b/infra/docs/macros-traps.md @@ -3370,3 +3370,63 @@ gives these results: - **65b to 65d**: out, but seed 3 then stands outside the front door with an empty pad for the rest of the window (65e). - **branch**: all six leave with no empty pad, and three win the Cascade Badge. + +## 2026-09-29, row 66: shop, Poké Balls and catching from the rung-8 restart + +### What was found + +The operator restarted the live run from the rung-8 archive (VIRIDIAN CITY) on v0.6.5 to watch +shopping and catching. In the first 35 minutes: `GO SHOP` done 33, `TALK` 5, `BUY BALL` never +dealt, `THROW BALL` 0, no catch. The sequences after `GO SHOP` were `GO SHOP`, `GO OUT`, `GO SHOP`, +`GO OUT` (`docs/design/macros.md` 12.30). + +### Reproduction + +- `survey-rank8-row66-viridian-mart.checkpoint` (`FLY_ROW66_MART_CHECKPOINT`, not committed) was + saved by the offers survey (`FLY_PROBE_SAVE_MART=2a`, `FLY_PROBE_SAVE_AFTER=3000`) from + `survey-rank7-row62` on the frame the fly walked into the Viridian mart after delivering the + parcel: 793 in the wallet, no ball. +- The connectome from it (`trap_hunt`, `FLY_TRAP_LOG_MACROS=1`): `GO SHOP` from the door to the + clerk, `GO OBJECTIVE` out of the door, `GO SHOP` from the street. Three laps in 18 brain seconds. + `TALK` was on the pad at the counter every time and was never chosen. +- A catch on the stub survey (`FLY_PROBE_SCREEN_*` dumps): from "All right! WEEDLE was caught!" + to the end of the battle, 6,900 frames under a pad of `BACK` and `THROW BALL`. `THROW BALL`'s A + said YES to the nickname and typed AAAAAAAAAA. + +| # | trap | trigger | test | fix, or why it is left | +| --- | --- | --- | --- | --- | +| 66 | row 62's service walk is dealt again whenever the service is needed, with no window, so a fly that walks away from the counter is walked straight back | the Viridian mart after the parcel, no ball, money for one | `a_counter_the_fly_walked_away_from_is_not_walked_back_to_for_the_window`, `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` | **fixed**: a completed `GO SHOP` / `GO HEAL` facing the counter records `TargetKey::Counter` on the building's map. The service walk toward it is withheld for the reached window | +| 66b | a purchase took four choices in a row at the counter (`TALK`, the greeting, `CONFIRM`, `BUY BALL`). The connectome never chose `TALK` there | any mart | `buy_ball_is_offered_from_a_marts_floor_only_while_a_ball_can_be_bought`, `row66_buy_ball_from_the_marts_floor_rings_up_a_ball` | **operator decision, built**: `BUY BALL` is also one button from the mart's floor, like `HEAL`. It walks to the clerk, talks, opens BUY, buys the first row and is done when paid. It is offered only in Viridian (after Oak has the parcel), Pewter and Cerulean, with no ball, 200 in the wallet, no parcel, and the clerk not blocked | +| 66c | `wListMenuID` outlives the battle bag, so every frame after a throw read as an open bag | a catch (the Pokédex page, the nickname, the naming screen) and the text after any throw or potion | `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends`, the state unit test | **fixed**: the bag is the bag only while its box (4, 2)-(19, 12) is drawn | +| 66d | after a catch, `NEXT` says YES to the nickname offer and names the Pokémon with A's | every catch | -- | **left, named**: offering the box's two answers in a battle is a pad change for the operator | +| 66e | the connectome did not choose `THROW BALL` in any wild battle with a ball (35 decisions over seven battles, three runs) | Viridian Forest with a ball bought by 66b | -- | **left, the fly's**: dealt as designed (12.9). Whether to make throwing likelier is the operator's | +| 66f | whiteouts halve the wallet: 3,175 to 793 to 396 to 0 on one stub run before Pewter | early fights lost | -- | **left**: the cartridge's rule. It is why the restart rung matters | +| 66g | `rom_catch`'s `BALL` is the button's tag (`MB·BALL`), not its channel, so the lean sets a rate nobody reads | the test's drive | -- | **left, documented**: that drive is the one that catches from `FLY_CATCH_CHECKPOINT`. Both tests now retry from idle offsets, because one ball misses about two throws in three | + +### Before and after + +ROM tests (rom-env sourced): + +| test | v0.6.5 | branch | +| --- | --- | --- | +| `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` (10,000 frames, the drive declines the counter) | 31 street `GO SHOP`s, 31 walks back in. **Fails** | 0 and 0. Passes | +| `row66_buy_ball_from_the_marts_floor_rings_up_a_ball` | `BUY BALL` never dealt on the floor, no ball. **Fails** | dealt, started, done. One ball, 793 to 593, at f491. Passes | +| `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` | `THROW BALL` dealt on 666 frames after the catch, pad `BACK`/`THROW BALL`. **Fails** | 0, pad `NEXT`, battle over 1,463 frames after the catch. Passes | + +With the connectome (`trap_hunt`, one sweep thread). `FLY_TRAP_SEED` seeds only the palette, and +three seeds from one checkpoint were byte-identical. So the runs vary the starting state: three +post-parcel Viridian mart entrances saved from stub seeds 1, 3 and 5, and the Pewter gym +(`survey-rank11-row59`, 1,606 in the wallet). A decision is a macro start whose pad held the +button. + +| run | brain min | counter `TALK` dealt / chosen | floor `BUY BALL` dealt / chosen / done | balls bought | `THROW BALL` dealt / chosen | +| --- | ---: | ---: | ---: | ---: | ---: | +| base, Viridian mart (s1 entrance) | 5 | 4 / 0 | -- | 0 | 0 / 0 | +| branch, Viridian mart (s1 entrance) | 5 | 1 / 0 | 2 / 0 / 0 | 0 | 0 / 0 | +| branch, Viridian mart (s3 entrance) | 5 | 3 / 0 | 3 / 1 / 1 | 1 (431 to 231) | 4 / 0 | +| branch, Viridian mart (s5 entrance) | 5 | 3 / 0 | 4 / 1 / 1 | 1 (1,587 to 1,387) | 16 / 0 | +| branch, Pewter gym, then the Pewter mart | 10 | 1 / 0 | 4 / 1 / 1 | 1 (1,606 to 1,406) | 15 / 0 | + +`TALK` at a counter: 0 of 12 decisions on either arm. The floor `BUY BALL`: chosen 3 of 13, and +done (paid) all 3 times. The ring: 4 mart entries in 16 brain seconds on base, one visit on the +branch. 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 1f98833..15622e2 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 @@ -629,6 +629,14 @@ pub trait MacroState: GameState { false } + /// Whether Oak has been given his parcel (`EVENT_OAK_GOT_PARCEL`). Until then the Viridian + /// clerk's text table is the parcel's and his counter sells nothing (row 66: `BUY BALL` from + /// the floor is not offered there before it). Defaulted to true, so a state that cannot read + /// the event flags withholds nothing on its account. + fn parcel_delivered(&mut self) -> bool { + true + } + /// Where the ladder's next unreached rung is, when the adapter's rung catalog knows. /// /// `None` leaves `GO OBJECTIVE` unbound, which is section 9's own fall-through: the plan's diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs index 31d0282..db0b40f 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 @@ -1064,7 +1064,8 @@ pub fn heal_goals(state: &mut dyn MacroState) -> Vec { /// /// - in a mart whose first stock row is a Poké Ball ([`geography::BALL_FIRST_MARTS`]); /// - while [`service_needed`] holds for the mart: no ball in the bag, the money for one, and no -/// Oak's parcel (the Viridian clerk's text table while it is carried sells nothing); +/// Oak's parcel (the Viridian clerk's text table while it is carried sells nothing) -- and in +/// Viridian not before Oak has the parcel at all ([`MacroState::parcel_delivered`]); /// - with the clerk reachable: the blocked window is kept, the talked and reached ledgers are not /// (a counter is a service), and the tile already facing him is a goal (no walk at all). /// @@ -1074,6 +1075,11 @@ pub fn floor_ball_goals(state: &mut dyn MacroState) -> Vec { if !geography::BALL_FIRST_MARTS.contains(&here) || !service_needed(state, Amenity::Mart) { return Vec::new(); } + // Before the parcel is even in the bag the Viridian counter is the parcel's too: the clerk's + // script hands it over on the fly's first visit, and sells nothing until Oak has it. + if here == super::super::maps::VIRIDIAN_MART && !state.parcel_delivered() { + return Vec::new(); + } person_aims(state, poke_sprite::CLERK, Ledgers::BlockedOnly, true) } 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 b3558cf..4258eae 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 @@ -182,6 +182,8 @@ struct World { /// A frame at which the cartridge heals the party, which is what a Pokémon Center does while /// its text box is open (`docs/design/macros.md` section 13). heal_at: Option, + /// Oak has not been given the parcel yet (row 66); false in every fixture unless set. + parcel_undelivered: bool, /// Whether a text box is drawn on a scene that is not [`Scene::Dialog`] /// ([`MacroState::text_open`]). /// @@ -303,6 +305,7 @@ impl World { refused_items: BTreeSet::new(), switch: None, heal_at: None, + parcel_undelivered: false, box_open: false, prompt: false, price_after: None, @@ -880,6 +883,10 @@ impl MacroState for World { self.targets.reached(map, TargetKey::Counter) } + fn parcel_delivered(&mut self) -> bool { + !self.parcel_undelivered + } + fn refused_here(&mut self, slot: u8) -> bool { self.targets.refused(self.map, slot, self.player) } @@ -5877,6 +5884,10 @@ fn buy_ball_is_offered_from_a_marts_floor_only_while_a_ball_can_be_bought() { mart.bag = vec![(item::OAKS_PARCEL, 1)]; assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "carrying the parcel"); mart.bag = Vec::new(); + // ...or before the clerk has even handed it over: nothing to buy until Oak has it. + mart.parcel_undelivered = true; + assert!(!on_the_pad(&mut mart, MacroKind::BuyBall), "before the parcel"); + mart.parcel_undelivered = false; // The talked and reached ledgers do not retire a counter; the blocked window does. mart.talked.insert(TalkTarget::Sprite(1)); diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs index 366207a..958ca39 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs @@ -2339,6 +2339,12 @@ impl MacroState for PokeState<'_> { self.targets.reached(map, TargetKey::Counter) } + /// `EVENT_OAK_GOT_PARCEL`, bit 56 of `wEventFlags`. + fn parcel_delivered(&mut self) -> bool { + let bit = super::symbols::events::EVENT_OAK_GOT_PARCEL; + read(self.memory, ram::wEventFlags + (bit >> 3)) & (1 << (bit & 7)) != 0 + } + /// Where the ladder's next unreached rung is (`GO OBJECTIVE`). /// /// The adapter's [`crate::adapter::MapPlace`] in the executor's own types, which is the only