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"); +}