Merge fix/loop-row63
This commit is contained in:
commit
6d11e437e5
13 changed files with 1213 additions and 4 deletions
|
|
@ -995,3 +995,32 @@ power, from `engine/battle/effects.asm` and `MoveHitTest`:
|
|||
Confuse Ray and Supersonic on a confused target, Leech Seed on a seeded or Grass target, Focus
|
||||
Energy, Mist, Reflect and Light Screen already up, Disable on a disabled target, and a damaging
|
||||
move the type chart makes "doesn't affect" (the chart is another ROM table).
|
||||
|
||||
## 14. What an item will do, and the joypad the cartridge last read (2026-09-24, `docs/design/macros.md` 12.27)
|
||||
|
||||
Row 63. Two addresses, both pinned and read back from the code that uses them by
|
||||
`row63_the_joypad_latch_and_the_item_table_are_where_the_cartridge_says` (FLY_ROM).
|
||||
|
||||
| name | where | what reads it |
|
||||
| --- | --- | --- |
|
||||
| `ItemUsePtrTable` | `$03:$55E1` | one little-endian routine pointer per item id, `MASTER_BALL` (1) to `MAX_ELIXER` (`$53`); the operand of `UseItem_`'s `ld hl` |
|
||||
| `hJoyLast` | `$FFB1` (HRAM) | the buttons `_Joypad` saw down last time the game asked; the operand of `_Joypad`'s `ldh a, [hJoyLast]` at `$03:$4000` |
|
||||
|
||||
**`state::item_routine`** reads an item's pointer and refuses a table where the five balls or the
|
||||
potions and status heals do not share one routine. **`state::battle_item_use`** classes an item by
|
||||
its routine, never by its id: the routine of `POKE_BALL`, `POTION`, `POKE_DOLL`, `ETHER`, or one of
|
||||
`X_ACCURACY`, `GUARD_SPEC`, `DIRE_HIT`, `X_ATTACK`, `POKE_FLUTE`, and answers each one's check before
|
||||
it acts (`engine/items/item_effects.asm`): a ball in a wild battle (a full party is `None`, the box
|
||||
count unread; a trainer is `false`); medicine with somebody it would change, `ItemUseMedicine`'s
|
||||
own id order (Revive: fainted; Full Heal and the status heals: that status; Full Restore: hurt or
|
||||
statused; the HP items: neither fainted nor full), the Pokémon that is out read from the battle's
|
||||
copy; a Poké Doll in a wild battle; the X items and the flute in any battle; a PP restore with a
|
||||
move below its PP (PP Ups counted). Every other routine refuses in a battle. A TM or an HM goes to
|
||||
`ItemUseTMHM` before the table and is `None`.
|
||||
|
||||
**`state::a_latched`** is `hJoyLast` bit 0 (`PAD_A`). `hJoyPressed` is `hJoyInput & ~hJoyLast`,
|
||||
and the game only calls `_Joypad` while something reads input, so after the A that confirms a list
|
||||
the latch keeps that A until the next list first asks. Measured on the Potion's party list: the
|
||||
list reads open on the frame after the pulse, an A in the next 22 frames is lost, and across 120
|
||||
rollback delays `hJoyLast`, `hJoyPressed`, `hJoyHeld` and `hJoy5` are the only bytes of WRAM and
|
||||
HRAM whose values never overlap between lost and answered frames.
|
||||
|
|
|
|||
|
|
@ -1650,6 +1650,44 @@ Nothing is ranked or pressed for the fly: frames that were never the fly's deal
|
|||
decoder, the reward catalog, the adapter version, the roles and the compatibility string are
|
||||
untouched.
|
||||
|
||||
### 12.27 An A the cartridge has not let go of is not a press, and a menu it is acting on is not a pad (2026-09-24, row 63)
|
||||
|
||||
Live on v0.6.2, rung 12, Mt. Moon B2F (map 61), wild battles: per ten minutes `BACK` 62, `ITEM`
|
||||
28, `RUN` 21, `MOVE 1` 10, no game event; the log ITEM, BACK, BACK, ITEM, BACK ... then RUN, and
|
||||
MOVE 1, BACK. Reproduced from the live checkpoint (`scene_probe`, `FLY_PROBE_CATCH=bag`).
|
||||
|
||||
- **The bag was not the problem.** Wartortle out at 8/86 with an Antidote, a Potion and TM34. The
|
||||
cartridge's own `ItemUsePtrTable` (`$03:$55E1`) and each routine's checks say: the Potion would
|
||||
be taken, the Antidote has nobody poisoned, TM34 is never usable in a battle. `ITEM` was dealt
|
||||
correctly and it never used the Potion.
|
||||
- **`ITEM`'s last press was no press.** The A that chose the Potion opens the party list. Its
|
||||
cursor bytes read open at once, and with one Pokémon the cursor is already on its target, so the
|
||||
script confirmed on the first frame. But `_Joypad` makes a press out of an edge against
|
||||
`hJoyLast`, and the game does not ask again until the list is drawn: the Potion's A is still
|
||||
`hJoyLast`, and an A pressed into that window is down on both sides of the comparison. Measured
|
||||
by rollback: an A in the first 22 frames after the pulse is lost every time, and `hJoyLast`
|
||||
alone separates lost from answered frames (every other WRAM and HRAM byte overlaps). `ITEM`
|
||||
reported done over a list still waiting; `BACK` left it (the item unused, back to the bag) and
|
||||
`BACK` left the bag. The pair was `ITEM` and `BACK`, and `ITEM` never did anything.
|
||||
- **A confirming A waits for the cartridge to let go of the last one** (`state::a_latched`, the
|
||||
cursor step). A wait presses nothing and shares the cursor step's budget. It applies to every
|
||||
confirm, so SWITCH, a move, a ball and a purchase get the same guarantee.
|
||||
- **A battle menu the cartridge still holds an A on deals no pad.** The same latch after an
|
||||
answer: RUN's A is taken and the menu's box stays up to sixteen frames while the game acts on
|
||||
it. A macro dealt there pressed at a menu already gone and held the pad for its three-second
|
||||
cursor wait over "Got away safely!". Empty for those frames, 12.13's reading.
|
||||
- **`MOVE 1` over the menu is FIGHT's backstop only while nothing else is a move** (12.8, 12.23).
|
||||
Slot one spent beside slot four with PP, it was dealt anyway; its script confirms FIGHT and
|
||||
stops, which opens the list its `BACK` closes. That is 12.11's pair, and `MOVE 4` is on the same
|
||||
menu. With nothing usable it is the backstop as before.
|
||||
- `ITEM` also asks the cartridge about its Potion (`item_refused`). With `hurt` it always agrees.
|
||||
It is the same kind of rule as 12.23, and it is there for the day `hurt`'s reading and the
|
||||
cartridge's part.
|
||||
|
||||
Nothing is ranked, weighted or pressed for the fly: a press waits for the cartridge to read it,
|
||||
and a menu nobody is reading has no pad. 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.")
|
||||
|
|
@ -1733,6 +1771,7 @@ observe is not a precondition, it is a guess.
|
|||
| Battle, own turn, main menu | MOVE 1..4, SWITCH, ITEM, THROW BALL, RUN (whose cursor indices are FIGHT 0, **ITEM 1, PKMN 2**, RUN 3 -- two columns, 12.11) | four move buttons for `ATTACK` (section 14); THROW BALL added, and gated on the species since 12.9; **RUN gated**, below. No `BACK`: the four entries are the answers to this menu. **`NEXT` removed by 12.10** — an A press here confirms FIGHT and reopens the list the move list's `BACK` just closed, and `MOVE 1` is the backstop instead, bound here whatever the battler reads as |
|
||||
| Battle, own turn, move list (**the box on screen**, 12.18) | MOVE 1..4, BACK -- or **MOVE 1 alone** | as above, plus **12.11**: `BACK` is dealt here only while `wBattleMon*` reads, because a list that binds no `MOVE n` has a pad whose one button closes the list `MOVE 1` underneath had just opened. With nothing readable the pad is `MOVE 1` and its script confirms where the cursor stands |
|
||||
| Battle, own turn, party list | SWITCH, BACK | unchanged |
|
||||
| Battle, own turn, any menu the cartridge still holds an A on (**12.27**) | nothing | new: the answer is taken or the list is not yet asking; the pad is back on the first frame the game reads the joypad |
|
||||
| Battle, own turn, the bag | ITEM, THROW BALL, **BACK** | the bag reports a *cursor* (`macros-wram.md` 7.1), and since **12.10** it is the own turn, because a cursor accepting input is one. Its pad is the list's own answers; `NEXT` and `CONFIRM` are both off it, being the same blind A press that *uses* whatever the cursor holds |
|
||||
| Battle, forced switch | SWITCH, NEXT | unchanged (row 8). The one arm that keeps `NEXT` with a cursor up, because it cannot be cancelled and has no `BACK` to undo it |
|
||||
| Battle, between turns | NEXT | since **12.18** this row is most of a battle, and correctly so: a frame whose move list is remembered rather than drawn lands here. `BACK` was added here for the bag and **taken back out by 12.9**: on a frame of battle text there is no list to leave, and a `BACK` that changes nothing is the trap of section 12.2. Since **12.10** the bag is not on this row at all, so `NEXT` here is only ever the A that advances text |
|
||||
|
|
@ -1781,6 +1820,7 @@ measured where it cannot.
|
|||
| the title screen, and raw mode | not an empty pad by contract: the readout's boot variant applies and no palette is dealt |
|
||||
| a scene the detector cannot name | `Unknown` deals `NEXT` and `BACK`; a screen neither press leaves (the naming screen, row 14) is a genuine stall and still needs START, which is a contract change |
|
||||
| an `Unknown` frame that is the **overworld with the cartridge driving** -- a warp in flight, a scripted push-back, a guide walking the fly through a door | **empty on purpose** (12.13). There is no box to advance and no screen to leave, so an A or a B press is a press into somebody else's script: it changes nothing and completes where the fly stands. This is the one empty pad that ends itself -- the cartridge gives the buttons back within a few frames -- and `game.padEmptyMs` reports it like any other |
|
||||
| the fly's own turn while the cartridge holds the A it last took (`hJoyLast`) | **empty on purpose** (12.27): a menu the game is acting on or has not started reading. Ends itself on the game's next joypad read |
|
||||
| the fly's own turn where the seam cannot read the battler, now that `NEXT` is off that row (12.10) | **fixed**: `MOVE 1` is bound over the top-level menu whatever `wBattleMon*` reads as, because FIGHT is one of that menu's four entries and always opens |
|
||||
|
||||
And because "closed where a macro can close it" is not "closed":
|
||||
|
|
|
|||
|
|
@ -3051,3 +3051,64 @@ On `main` `510727c` (v0.6.1, row 59 merged):
|
|||
- `npm test` 663 passed; `npm run typecheck` clean; `infra/tests/lint.sh` ALL CHECKS PASSED.
|
||||
- `flysim --print-compatibility`, raw and macros: 648 bytes, sha256 `8ce67b97...a8f68`, the same
|
||||
as `main`. Decoder, reward catalog, adapter version and roles untouched.
|
||||
|
||||
## 2026-09-24, row 63: Mt. Moon B2F, ITEM, BACK, BACK
|
||||
|
||||
### What was live
|
||||
|
||||
Map 61 (Mt. Moon B2F), rung 12, v0.6.2, wild battles, about 03:05 to 03:15 UTC: per ten minutes
|
||||
`BACK` 62, `ITEM` 28, `RUN` 21, `MOVE 1` 10, no game event. The log: ITEM, BACK, BACK, ITEM, BACK
|
||||
... RUN, and MOVE 1, BACK, RUN. The checkpoint is a wild Geodude L9 with the battle bag open:
|
||||
Wartortle L28 at 8/86, BITE, TAIL WHIP and BUBBLE at 0 PP and WATER GUN at 25; the bag an
|
||||
Antidote, a Potion, TM34.
|
||||
|
||||
### The survey
|
||||
|
||||
`scene_probe` `FLY_PROBE_CATCH=bag` (uniform pick among dealt buttons, trace per macro) and
|
||||
`=potion` (the Potion pressed by hand, then A tried after every delay 0..120 in a rollback).
|
||||
|
||||
- The cartridge's `ItemUsePtrTable` says the Potion would be taken, the Antidote not (nobody
|
||||
poisoned), TM34 never in a battle. `ITEM` is dealt correctly (hurt, a Potion).
|
||||
- `ITEM` presses ITEM, the Potion, and the party list opens on the frame after the pulse with
|
||||
the one Pokémon under the cursor; the script's confirm goes in at once and the list stays up.
|
||||
`ITEM done`; `BACK` closes the list (`UseItem` fails, back to the bag); `BACK` closes the bag.
|
||||
- By rollback: A lost for 22 frames after the pulse, answered from then on; `hJoyLast` (and the
|
||||
three joypad bytes after it) the only bytes that separate the two.
|
||||
- `MOVE 1` is dealt over the menu with slot one spent beside slot four; it opens the list, whose
|
||||
`BACK` closes it.
|
||||
- With the confirm fixed: RUN's A is taken, the menu's box stays for up to sixteen frames with
|
||||
`hJoyLast` = A, and a macro dealt there (the survey: `MOVE 4` after every `RUN` from FIGHT's
|
||||
column, 324 of 324) presses at a menu that is gone and blocks for 180 frames.
|
||||
|
||||
| # | trap | trigger | test | fix, or why it is left |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 63 | a cursor step's confirming A goes into a list that reads open before the cartridge has let go of the A that opened it; the press is no edge, the macro reports done over a waiting list, and `BACK` twice undoes it | any list opened by an A whose target is under the cursor at once; the Potion's party list with one Pokémon | `items_last_press_waits_for_the_cartridge_to_let_go_of_the_potions_a`, `row63_item_uses_the_potion_and_the_battle_menu_deals_no_list_it_only_opens` (ROM) | **fixed**: `state::a_latched` (`hJoyLast`, `$FFB1`); the confirm waits while it holds. `docs/design/macros.md` 12.27 |
|
||||
| 63b | `MOVE 1` over the battle menu with slot one spent beside a usable move only opens the list its `BACK` closes | a spent first move | `move_one_is_not_fights_backstop_beside_a_usable_move`, the ROM test's second drive | **fixed**: the backstop only while no move is usable |
|
||||
| 63c | a battle menu the cartridge has taken an A on stays on screen; a macro dealt on it presses at a menu already gone | RUN, and any answer whose box lingers | `a_battle_menu_the_cartridge_still_holds_an_a_on_deals_no_pad` | **fixed**: no own-turn pad while `hJoyLast` holds A |
|
||||
| 63d | `ITEM` is dealt while the cartridge would refuse the Potion | none reached: `hurt` implies it is taken | `item_is_off_the_pad_while_the_cartridge_would_refuse_the_potion`, `the_row_63_bag_holds_one_item_the_cartridge_would_take` | **guarded**: `state::battle_item_use` from `ItemUsePtrTable` (`$03:$55E1`) |
|
||||
| 63e | a party list opened by an item reads as the battle's party list: its pad is `SWITCH`, `BACK`, and `SWITCH` there would use the item on the healthiest other Pokémon | only if `ITEM` stops before its last press; not reached with 63 fixed | -- | **left**: `ITEM` now finishes; naming the item's list is a seam change for when it is reached |
|
||||
|
||||
### Before and after
|
||||
|
||||
Ten seeds per arm, 71,673 frames each (20 brain minutes), uniform pick among the dealt buttons,
|
||||
from the row-63 checkpoint. Base: `main` plus the seam reader and the probe; branch: the fix.
|
||||
`build/loop-row63/survey-summary.md` has the per-seed table.
|
||||
|
||||
| | base | branch |
|
||||
| --- | ---: | ---: |
|
||||
| `ITEM` starts | 244 | 10 (each one used the Potion) |
|
||||
| `BACK` starts | 559 | 0 |
|
||||
| `MOVE 1` starts | 173 | 0 |
|
||||
| longest ITEM/BACK run | 6 | 0 |
|
||||
| battle macros blocked | 0 | 0 |
|
||||
| battles | 392 | 343 |
|
||||
| battle frames | 448,282 | 366,049 |
|
||||
| mean / longest battle | 1,144 / 2,006 | 1,067 / 1,651 |
|
||||
| wins (enemy seen at 0 HP) | 185 | 166 |
|
||||
| rewards: battle / exploration / boundary+item | 67 / 3 / 0 | 73 / 19 / 24 |
|
||||
|
||||
ROM-gated, `row63_item_uses_the_potion_and_the_battle_menu_deals_no_list_it_only_opens`: base,
|
||||
pressing `ITEM` whenever dealt, 12,000 frames in the one battle, `ITEM` 119 and `BACK` 119, the
|
||||
party list left waiting 119 times, the Potion never used, and pressing `BACK` then `MOVE 1`
|
||||
whenever dealt, `MOVE 1` 125 and `BACK` 125, the battle never ends: **fails**. Branch: the Potion
|
||||
used (8 to 28 HP) and the battle over in 555 frames; `MOVE 4` and the battle over in 773: passes.
|
||||
|
|
|
|||
|
|
@ -430,6 +430,35 @@ impl Wram {
|
|||
self
|
||||
}
|
||||
|
||||
/// The cartridge's `ItemUsePtrTable`, one pointer per item id, grouped the way the pinned
|
||||
/// commit groups them: the balls share one routine, the potions, drinks, status heals and
|
||||
/// revives another, the four X stat items another, the four PP restores another, and every
|
||||
/// item with no use in a battle points at `UnusableItem` here (the real table spreads those
|
||||
/// over a dozen routines, all of which refuse inside a battle). The addresses are the
|
||||
/// cartridge's own; only their grouping is under test.
|
||||
pub fn item_table(&mut self) -> &mut Self {
|
||||
use super::state::poke::items::{LAST_ITEM, TABLE_ADDRESS, TABLE_BANK};
|
||||
for id in 1..=LAST_ITEM {
|
||||
let routine: u16 = match id {
|
||||
0x01..=0x04 | 0x08 => 0x5687,
|
||||
0x0b..=0x14 | 0x34..=0x36 | 0x3c..=0x3e => 0x5abb,
|
||||
0x2e => 0x6013,
|
||||
0x33 => 0x60cd,
|
||||
0x37 => 0x60dc,
|
||||
0x3a => 0x60f5,
|
||||
0x41..=0x44 => 0x6104,
|
||||
0x49 => 0x6140,
|
||||
0x50..=0x53 => 0x631e,
|
||||
_ => 0x6476,
|
||||
};
|
||||
let at = TABLE_ADDRESS + 2 * u16::from(id - 1);
|
||||
let [low, high] = routine.to_le_bytes();
|
||||
self.rom.insert((TABLE_BANK, at), low);
|
||||
self.rom.insert((TABLE_BANK, at + 1), high);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// One byte of a fake cartridge bank.
|
||||
pub fn rom_byte(&mut self, bank: u8, address: u16, byte: u8) -> &mut Self {
|
||||
self.rom.insert((bank, address), byte);
|
||||
|
|
|
|||
|
|
@ -388,6 +388,26 @@ pub trait MacroState: GameState {
|
|||
false
|
||||
}
|
||||
|
||||
/// Whether the cartridge would refuse bag item `id` if the fly chose it from the battle bag on
|
||||
/// this frame -- "It won't have any effect.", "This isn't the time to use that!", a ball at a
|
||||
/// trainer's Pokémon -- and put the fly back in the bag with nothing changed.
|
||||
///
|
||||
/// Row 63 (`docs/design/macros.md` 12.27), read from the cartridge's own `ItemUsePtrTable`
|
||||
/// and the checks each routine makes ([`crate::pokemon_red::state::battle_item_use`]). The
|
||||
/// default is `false`: a state that cannot read the table has proved nothing.
|
||||
fn item_refused(&mut self, _id: u8) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether the cartridge still holds `A` down from the last time it read the joypad, so an
|
||||
/// `A` pressed now is no edge and is not a press (row 63,
|
||||
/// [`crate::pokemon_red::state::a_latched`]). A confirming press waits while this holds. The
|
||||
/// default is `false`: a state that cannot read the latch presses when the list reads open,
|
||||
/// which is what every script did before.
|
||||
fn a_latched(&mut self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether a `GO FRONTIER` on this map has already proved its frontier unreachable.
|
||||
///
|
||||
/// [`FrontierLedger`] is the evidence and the measurement. The default is `false`: a state
|
||||
|
|
|
|||
|
|
@ -1725,6 +1725,22 @@ fn cursor_frame(cursor: &mut Cursor, state: &mut dyn MacroState) -> Progress {
|
|||
if !cursor.confirm {
|
||||
return Progress::Next;
|
||||
}
|
||||
// **The confirming A waits for the cartridge to have seen A let go** (row 63). A list
|
||||
// opened by an A reads open from its cursor bytes before the game has asked the joypad
|
||||
// again, and until it asks, the A that opened it is still down in `hJoyLast`: an A
|
||||
// pressed into that window is no edge and the cartridge never sees it. The Potion's party
|
||||
// list is the case that found it -- one Pokémon, so the cursor is on its target on the
|
||||
// first frame and the confirm went straight into the window, `ITEM` reported done over a
|
||||
// list that was still waiting, and the fly backed out of it and the bag with two `BACK`s.
|
||||
// A wait presses nothing, and it is the same budget as a list that is not up at all.
|
||||
if state.a_latched() {
|
||||
cursor.waited += 1;
|
||||
return if cursor.waited > CURSOR_WAIT {
|
||||
Progress::Blocked
|
||||
} else {
|
||||
Progress::Hold(buttons::NONE)
|
||||
};
|
||||
}
|
||||
cursor.confirmed = true;
|
||||
cursor.phase = 0;
|
||||
return pulse(buttons::A, &mut cursor.phase, PRESS_HOLD, PRESS_GAP);
|
||||
|
|
|
|||
|
|
@ -547,6 +547,16 @@ pub fn scene_set(scene: Scene, state: &mut dyn MacroState) -> Vec<MacroKind> {
|
|||
// list* closed it again; neither spent a turn, and the two of them were half the pad
|
||||
// between them. Two buttons that undo each other with nothing else changing are section
|
||||
// 12.2's trap spread over two sub-states of one turn.
|
||||
// **A battle menu the cartridge is still holding an A on is not the fly's to answer**
|
||||
// (row 63). The A that chose RUN, FIGHT or the Potion is taken, and the game stops asking
|
||||
// the joypad while it acts on it -- so `hJoyLast` keeps that A, and the menu's box and
|
||||
// cursor bytes stay on screen for as many as sixteen frames after its answer. A macro dealt
|
||||
// there presses at a menu that is already gone: measured from the row-63 checkpoint, every
|
||||
// `RUN` from FIGHT's column was followed by a `MOVE 4` dealt on the frame after, which
|
||||
// pressed UP at "Got away safely!" and held the pad for its whole cursor wait. The pad is
|
||||
// empty for those frames, which is 12.13's reading: the cartridge is driving, and it gives
|
||||
// the buttons back on the first frame it asks again.
|
||||
Scene::Battle { own_turn: true, .. } if state.a_latched() => Vec::new(),
|
||||
Scene::Battle { own_turn: true, .. } => match battle_menu(state) {
|
||||
// The move list. `BACK` is a button here because there is a list to leave (12.9) --
|
||||
// but only while the moves can be *read*: a battler the seam cannot place leaves all
|
||||
|
|
@ -658,7 +668,13 @@ pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool {
|
|||
// the fly's.
|
||||
MacroKind::ThrowBall => throw_slot(state).is_some(),
|
||||
MacroKind::Switch => healthiest_other(state).is_some(),
|
||||
MacroKind::Item => hurt(state) && potion_slot(state).is_some(),
|
||||
// ...and a Potion the cartridge would take (row 63): `ItemUseMedicine` answers "It won't
|
||||
// have any effect." to a Pokémon that is fainted or full, and the fly is back in the bag
|
||||
// with nothing changed. `hurt` already says the one that is out is neither, so this is
|
||||
// the cartridge agreeing rather than a second opinion.
|
||||
MacroKind::Item => {
|
||||
hurt(state) && potion_slot(state).is_some() && !state.item_refused(item::POTION)
|
||||
}
|
||||
// A wild battle the fly is *losing* (`docs/design/macros.md` section 13.1, the operator: "we run
|
||||
// away a lot"). Knowledge inside the macro, as a precondition: nothing ranks `RUN` below
|
||||
// `ATTACK` -- the button simply is not there while the fight is still worth having.
|
||||
|
|
@ -1985,8 +2001,14 @@ pub fn move_slot_bound(state: &mut dyn MacroState, kind: MacroKind) -> bool {
|
|||
}
|
||||
let any_useful = useful.iter().any(|flag| *flag);
|
||||
let entry = holds(usize::from(index)).copied();
|
||||
// `MOVE 1` over the menu is FIGHT's backstop **only while nothing else is a move**: Struggle,
|
||||
// or nothing that would do anything (row 34, row 60). Beside a usable move a spent slot one is
|
||||
// what it is over the list -- not a move -- and its script, "confirm FIGHT and stop", only
|
||||
// opens the list whose `BACK` closes it again: row 63 measured `MOVE 1`, `BACK` ten times in
|
||||
// ten minutes on Mt. Moon B2F with `MOVE 4` usable, 12.11's pair once more. The usable move is
|
||||
// on this pad itself, and it is the button that ends the turn.
|
||||
if index == 0 && main {
|
||||
return !any_useful || useful[0] || entry.is_none_or(|entry| entry.pp == 0);
|
||||
return !any_useful || useful[0];
|
||||
}
|
||||
let Some(entry) = entry else { return false };
|
||||
if entry.pp > 0 {
|
||||
|
|
|
|||
|
|
@ -168,6 +168,14 @@ struct World {
|
|||
opens_draw_in: u32,
|
||||
/// The list an A press opened and the frame it starts accepting input on.
|
||||
pending: Option<(u32, Opens)>,
|
||||
/// Frames the cartridge keeps the A that opened a list as its last joypad reading before it
|
||||
/// asks again (row 63): an A pressed inside them is no edge and changes nothing, while the
|
||||
/// list already reads open. Zero everywhere but the tests this is for.
|
||||
a_latch: u32,
|
||||
/// The frame the cartridge next asks the joypad, while an A is latched.
|
||||
latched_until: u32,
|
||||
/// Item ids the cartridge would refuse from the battle bag on this frame (row 63).
|
||||
refused_items: BTreeSet<u8>,
|
||||
/// A scene the world switches to at this frame, for the abort rule.
|
||||
switch: Option<(u32, Scene)>,
|
||||
/// A frame at which the cartridge heals the party, which is what a Pokémon Center does while
|
||||
|
|
@ -260,6 +268,9 @@ impl World {
|
|||
opens: VecDeque::new(),
|
||||
opens_draw_in: 0,
|
||||
pending: None,
|
||||
a_latch: 0,
|
||||
latched_until: 0,
|
||||
refused_items: BTreeSet::new(),
|
||||
switch: None,
|
||||
heal_at: None,
|
||||
box_open: false,
|
||||
|
|
@ -468,9 +479,14 @@ impl World {
|
|||
self.list = List::None;
|
||||
}
|
||||
}
|
||||
if mask == buttons::A && self.frames < self.latched_until {
|
||||
// The cartridge has not asked since the A that opened this list: this A is no edge.
|
||||
return;
|
||||
}
|
||||
if mask == buttons::A
|
||||
&& let Some(next) = self.opens.pop_front()
|
||||
{
|
||||
self.latched_until = self.frames + self.a_latch;
|
||||
if self.opens_draw_in > 0 {
|
||||
self.pending = Some((self.frames + self.opens_draw_in, next));
|
||||
} else {
|
||||
|
|
@ -703,6 +719,14 @@ impl MacroState for World {
|
|||
self.no_effect.contains(&id)
|
||||
}
|
||||
|
||||
fn item_refused(&mut self, id: u8) -> bool {
|
||||
self.refused_items.contains(&id)
|
||||
}
|
||||
|
||||
fn a_latched(&mut self) -> bool {
|
||||
self.frames < self.latched_until
|
||||
}
|
||||
|
||||
fn shop_stock(&mut self) -> Vec<u8> {
|
||||
self.stock.clone()
|
||||
}
|
||||
|
|
@ -2310,6 +2334,95 @@ fn item_reaches_the_potion_by_reading_the_bags_cursor() {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_last_press_waits_for_the_cartridge_to_let_go_of_the_potions_a() {
|
||||
// Row 63, Mt. Moon B2F: Wartortle out at 8 of 86, one Pokémon, a Potion in the bag. The A
|
||||
// that chose the Potion opened the party list, whose cursor bytes read open at once and whose
|
||||
// one entry is already under the cursor -- so `ITEM` confirmed on the first frame, while the
|
||||
// cartridge still held that A as its last reading. No edge, no press: `ITEM` reported done over
|
||||
// a list still waiting for its answer, and the fly left it and the bag with `BACK`, `BACK`.
|
||||
let mut world = World::battle();
|
||||
world.mons = vec![mon(0, 8, 86, &[(44, 0), (55, 25)])];
|
||||
world.bag = vec![(item::ANTIDOTE, 1), (item::POTION, 1), (0xea, 1)];
|
||||
world.list = List::BattleBag;
|
||||
world.grid = false;
|
||||
world.cursor = 0;
|
||||
world.cursor_max = 2;
|
||||
// Measured: the list reads open at once, and an A is lost until about 30 frames after the
|
||||
// Potion's A was let go. This fake takes a press on its release, eight frames after the edge
|
||||
// the cartridge would see, so its window is those 30 and the 8 and a little: 40.
|
||||
world.a_latch = 40;
|
||||
world.opens.push_back(Opens { list: List::BattleParty, cursor: 0, max: 0, grid: false });
|
||||
// What the honoured A does: the Potion is used, and the screen is battle text.
|
||||
world.opens.push_back(Opens { list: List::None, cursor: 0, max: 0, grid: false });
|
||||
assert_eq!(run(&mut world, MacroKind::Item).unwrap(), MacroAbort::Done);
|
||||
assert_eq!(world.list, List::None, "the party list was answered, not left waiting");
|
||||
assert!(world.opens.is_empty(), "both A presses were taken: {:?}", world.pulses);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_confirm_is_not_held_back_when_nothing_is_latched() {
|
||||
// The wait costs nothing where there is nothing to wait for: a list that reads open with the
|
||||
// cartridge's last reading clear is confirmed on the frame it is reached, as before.
|
||||
let mut world = World::battle();
|
||||
world.mons = vec![mon(0, 8, 86, &[(44, 0), (55, 25)])];
|
||||
world.bag = vec![(item::POTION, 1)];
|
||||
world.list = List::BattleBag;
|
||||
world.grid = false;
|
||||
world.cursor_max = 0;
|
||||
world.opens.push_back(Opens { list: List::BattleParty, cursor: 0, max: 0, grid: false });
|
||||
world.opens.push_back(Opens { list: List::None, cursor: 0, max: 0, grid: false });
|
||||
assert_eq!(run(&mut world, MacroKind::Item).unwrap(), MacroAbort::Done);
|
||||
assert_eq!(world.list, List::None);
|
||||
assert!(world.frames < 120, "no wait: {} frames", world.frames);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_is_off_the_pad_while_the_cartridge_would_refuse_the_potion() {
|
||||
let mut world = World::battle();
|
||||
world.bag = vec![(item::POTION, 1)];
|
||||
assert!(precondition(MacroKind::Item, &mut world));
|
||||
world.refused_items.insert(item::POTION);
|
||||
assert!(!precondition(MacroKind::Item, &mut world), "\"It won't have any effect.\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_one_is_not_fights_backstop_beside_a_usable_move() {
|
||||
// Row 63's second pair, the same ten minutes: slot one spent, slot four with 25 PP. `MOVE 1`
|
||||
// over the menu confirmed FIGHT and stopped, which opens the list and chooses nothing, and the
|
||||
// list's `BACK` closed it again -- `MOVE 1`, `BACK`, ten times. `MOVE 4` is on this menu too,
|
||||
// and it is the button that ends the turn.
|
||||
let mut world = World::battle();
|
||||
world.mons = vec![mon(0, 8, 86, &[(44, 0), (39, 0), (145, 0), (55, 25)])];
|
||||
let moves: Vec<&str> =
|
||||
pad_of(&mut world).into_iter().filter(|name| name.starts_with("MOVE")).collect();
|
||||
assert_eq!(moves, ["MOVE 4"]);
|
||||
// With nothing usable it is the backstop again: Struggle is behind FIGHT (row 34).
|
||||
world.mons = vec![mon(0, 8, 86, &[(44, 0), (39, 0), (145, 0), (55, 0)])];
|
||||
let moves: Vec<&str> =
|
||||
pad_of(&mut world).into_iter().filter(|name| name.starts_with("MOVE")).collect();
|
||||
assert_eq!(moves, ["MOVE 1"]);
|
||||
// And with slot one usable it is slot one's own button.
|
||||
world.mons = vec![mon(0, 8, 86, &[(44, 3), (55, 25)])];
|
||||
let moves: Vec<&str> =
|
||||
pad_of(&mut world).into_iter().filter(|name| name.starts_with("MOVE")).collect();
|
||||
assert_eq!(moves, ["MOVE 1", "MOVE 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_battle_menu_the_cartridge_still_holds_an_a_on_deals_no_pad() {
|
||||
// Row 63: RUN's A is taken, and the menu's box stays up while the game stops asking the
|
||||
// joypad. The frame after `RUN` finished dealt `MOVE 4` over that box, which pressed at "Got
|
||||
// away safely!" and held the pad through its whole cursor wait. Until the cartridge asks
|
||||
// again the menu is not the fly's to answer.
|
||||
let mut world = World::battle();
|
||||
assert!(!pad_of(&mut world).is_empty());
|
||||
world.latched_until = world.frames + 10;
|
||||
assert_eq!(pad_of(&mut world), Vec::<&str>::new(), "the cartridge is acting on its last A");
|
||||
world.frames += 10;
|
||||
assert!(pad_of(&mut world).contains(&"MOVE 1"), "and the pad is back when it asks again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buy_potion_takes_buy_then_the_item_then_confirms_twice() {
|
||||
let mut world = World::room();
|
||||
|
|
|
|||
|
|
@ -43,6 +43,13 @@ use super::symbols::ram;
|
|||
/// `const`s that no symbol table carries, so each one names its file.
|
||||
pub mod poke {
|
||||
/// `constants/hardware.inc`.
|
||||
/// `ram/hram.asm`: `hJoyLast`, the buttons `_Joypad` saw down the last time the game asked
|
||||
/// (`engine/joypad.asm`). The first of the seven joypad bytes (`hJoyLast`, `hJoyReleased`,
|
||||
/// `hJoyPressed`, `hJoyHeld`, `hJoy5`..`hJoy7`) at `$FFB1`: read from the operand of
|
||||
/// `_Joypad`'s `ldh a, [hJoyLast]` on the cartridge, and pinned by the ROM-gated test that
|
||||
/// reads it back from there (row 63, `docs/design/macros.md` 12.27).
|
||||
pub const H_JOY_LAST: u16 = 0xffb1;
|
||||
|
||||
pub mod pad {
|
||||
pub const A: u8 = 1 << 0;
|
||||
pub const B: u8 = 1 << 1;
|
||||
|
|
@ -285,6 +292,47 @@ pub mod poke {
|
|||
pub const TYPE_GROUND: u8 = 0x04;
|
||||
pub const TYPE_ELECTRIC: u8 = 0x17;
|
||||
}
|
||||
|
||||
/// The cartridge's item-use dispatch and the ids that name its routines (row 63,
|
||||
/// `docs/design/macros.md` 12.27).
|
||||
pub mod items {
|
||||
/// `engine/items/item_effects.asm`: `UseItem_` jumps through `ItemUsePtrTable`, one
|
||||
/// little-endian pointer per item id from `MASTER_BALL` (1) to `MAX_ELIXER` (`$53`), in
|
||||
/// `SECTION "bank3"`. At the pinned commit the table is at `$03:$55E1`: read from the
|
||||
/// operand of `UseItem_`'s `ld hl, ItemUsePtrTable` and checked by
|
||||
/// [`super::super::item_routine`] against the table's own shape on every read.
|
||||
pub const TABLE_BANK: u8 = 0x03;
|
||||
pub const TABLE_ADDRESS: u16 = 0x55e1;
|
||||
pub const LAST_ITEM: u8 = 0x53;
|
||||
|
||||
/// `constants/item_constants.asm`. Each id below stands for the routine the table gives
|
||||
/// it, and every other item is classed by the routine the table gives *it*: an item whose
|
||||
/// pointer is `POTION`'s is medicine, whatever its id.
|
||||
pub const MASTER_BALL: u8 = 0x01;
|
||||
pub const POKE_BALL: u8 = 0x04;
|
||||
pub const SAFARI_BALL: u8 = 0x08;
|
||||
pub const ANTIDOTE: u8 = 0x0b;
|
||||
pub const BURN_HEAL: u8 = 0x0c;
|
||||
pub const ICE_HEAL: u8 = 0x0d;
|
||||
pub const AWAKENING: u8 = 0x0e;
|
||||
pub const PARLYZ_HEAL: u8 = 0x0f;
|
||||
pub const FULL_RESTORE: u8 = 0x10;
|
||||
pub const POTION: u8 = 0x14;
|
||||
pub const HP_UP: u8 = 0x23;
|
||||
pub const X_ACCURACY: u8 = 0x2e;
|
||||
pub const POKE_DOLL: u8 = 0x33;
|
||||
pub const FULL_HEAL: u8 = 0x34;
|
||||
pub const REVIVE: u8 = 0x35;
|
||||
pub const MAX_REVIVE: u8 = 0x36;
|
||||
pub const GUARD_SPEC: u8 = 0x37;
|
||||
pub const DIRE_HIT: u8 = 0x3a;
|
||||
pub const X_ATTACK: u8 = 0x41;
|
||||
pub const POKE_FLUTE: u8 = 0x49;
|
||||
pub const ETHER: u8 = 0x50;
|
||||
|
||||
/// `constants/pokemon_data_constants.asm`: `PARTY_LENGTH`.
|
||||
pub const PARTY_LENGTH: u8 = 6;
|
||||
}
|
||||
}
|
||||
|
||||
fn read(memory: &mut dyn MemoryReader, address: u16) -> u8 {
|
||||
|
|
@ -786,6 +834,147 @@ pub fn move_without_effect(memory: &mut dyn MemoryReader, id: u8) -> Option<bool
|
|||
})
|
||||
}
|
||||
|
||||
/// The routine the cartridge's `ItemUsePtrTable` runs for item `id`, as its bank-3 address.
|
||||
///
|
||||
/// `None` when the seam has no cartridge behind it, when `id` is not an item the table covers
|
||||
/// (a TM or an HM goes to `ItemUseTMHM` before the table is asked, and is never usable in a
|
||||
/// battle), or when the table is not the one the disassembly describes: the five balls share one
|
||||
/// routine and the potions and status heals share another, so a table where `POKE_BALL` and
|
||||
/// `SAFARI_BALL` or `POTION` and `ANTIDOTE` part company is somebody else's bytes and answers
|
||||
/// nothing.
|
||||
pub fn item_routine(memory: &mut dyn MemoryReader, id: u8) -> Option<u16> {
|
||||
use poke::items::*;
|
||||
let entry = |memory: &mut dyn MemoryReader, id: u8| -> Option<u16> {
|
||||
let at = TABLE_ADDRESS + 2 * u16::from(id - 1);
|
||||
let low = memory.read_rom(TABLE_BANK, at)?;
|
||||
let high = memory.read_rom(TABLE_BANK, at + 1)?;
|
||||
Some(u16::from_le_bytes([low, high])).filter(|address| (0x4000..0x8000).contains(address))
|
||||
};
|
||||
if id == 0 || id > LAST_ITEM {
|
||||
return None;
|
||||
}
|
||||
let ball = entry(memory, POKE_BALL)?;
|
||||
let medicine = entry(memory, POTION)?;
|
||||
if [MASTER_BALL, SAFARI_BALL].into_iter().any(|other| entry(memory, other) != Some(ball))
|
||||
|| entry(memory, ANTIDOTE) != Some(medicine)
|
||||
|| ball == medicine
|
||||
{
|
||||
return None;
|
||||
}
|
||||
entry(memory, id)
|
||||
}
|
||||
|
||||
/// Whether the cartridge would **take** bag item `id` if the fly chose it from the battle bag on
|
||||
/// this frame: the item is used and the turn goes on, rather than "This isn't the time to use
|
||||
/// that!", "It won't have any effect." or a ball thrown at a trainer's Pokémon, after which the
|
||||
/// fly is back in the bag with nothing changed.
|
||||
///
|
||||
/// Row 63 (`docs/design/macros.md` 12.27). Which routine an item runs is the cartridge's own
|
||||
/// `ItemUsePtrTable` ([`item_routine`]), and each routine's answer is the check it makes before
|
||||
/// it does anything, on bytes already in WRAM (`engine/items/item_effects.asm`):
|
||||
///
|
||||
/// - a **ball** (`ItemUseBall`): a wild battle; against a trainer it is "The trainer blocked the
|
||||
/// BALL!", the ball spent for nothing. With a full party the box decides, and the box count is
|
||||
/// not read here, so that answer is `None`;
|
||||
/// - **medicine** (`ItemUseMedicine`): somebody in the party it would change -- for an HP item a
|
||||
/// Pokémon neither fainted nor full (a Full Restore also cures a status at full HP), for a
|
||||
/// Revive a fainted one, for a status heal a Pokémon with that status (a Full Heal any). The
|
||||
/// Pokémon that is out is read from the battle's own copy, which is the one the engine damages;
|
||||
/// - `X_ACCURACY`, `GUARD_SPEC`, `DIRE_HIT`, the four X stat items and the `POKE_FLUTE`: any
|
||||
/// battle;
|
||||
/// - `POKE_DOLL`: a wild battle;
|
||||
/// - `ETHER` and its three siblings: a party move below its PP (PP Ups are counted);
|
||||
/// - every other routine -- a vitamin, a stone, a repel, an Escape Rope, a key item, a badge
|
||||
/// pseudo-item -- refuses inside a battle.
|
||||
///
|
||||
/// `None` outside a battle this module understands, or when the table cannot be read: a refusal
|
||||
/// this module cannot read is not one it reports.
|
||||
pub fn battle_item_use(memory: &mut dyn MemoryReader, id: u8) -> Option<bool> {
|
||||
use poke::items::*;
|
||||
let kind = in_battle(memory)?;
|
||||
let routine = item_routine(memory, id)?;
|
||||
let of = |memory: &mut dyn MemoryReader, anchor: u8| item_routine(memory, anchor);
|
||||
if Some(routine) == of(memory, POKE_BALL) {
|
||||
if kind != BattleKind::Wild {
|
||||
return Some(false);
|
||||
}
|
||||
return (read(memory, ram::wPartyCount) < PARTY_LENGTH).then_some(true);
|
||||
}
|
||||
if Some(routine) == of(memory, POKE_DOLL) {
|
||||
return Some(kind == BattleKind::Wild);
|
||||
}
|
||||
if [X_ACCURACY, GUARD_SPEC, DIRE_HIT, X_ATTACK, POKE_FLUTE]
|
||||
.into_iter()
|
||||
.any(|anchor| of(memory, anchor) == Some(routine))
|
||||
{
|
||||
return Some(true);
|
||||
}
|
||||
// The party as the item routines see it, with the Pokémon that is out read from the battle's
|
||||
// copy: `ReadPlayerMonCurHPAndStatus` writes it back to the party struct at the top of every
|
||||
// turn, and the battle copy is the one the damage went to.
|
||||
let mut mons = party(memory).mons;
|
||||
if let Some(out) = own_mon(memory)
|
||||
&& let Some(mon) = mons.iter_mut().find(|mon| mon.slot == out.slot)
|
||||
{
|
||||
mon.hp = out.hp;
|
||||
mon.status = out.status;
|
||||
}
|
||||
if Some(routine) == of(memory, POTION) {
|
||||
let cures = |status: Status| -> bool {
|
||||
match id {
|
||||
ANTIDOTE => status == Status::Poison,
|
||||
BURN_HEAL => status == Status::Burn,
|
||||
ICE_HEAL => status == Status::Freeze,
|
||||
AWAKENING => matches!(status, Status::Sleep(_)),
|
||||
PARLYZ_HEAL => status == Status::Paralysis,
|
||||
_ => status != Status::Healthy,
|
||||
}
|
||||
};
|
||||
// `ItemUseMedicine`'s own order: Revive and Max Revive, then Full Heal, then the HP items
|
||||
// (Full Restore to Potion, and the three drinks past Revive), then the status heals.
|
||||
let takes = |mon: &Mon| -> bool {
|
||||
let fainted = mon.hp == 0;
|
||||
match id {
|
||||
REVIVE | MAX_REVIVE => fainted,
|
||||
FULL_HEAL => !fainted && cures(mon.status),
|
||||
FULL_RESTORE => !fainted && (mon.hp < mon.max_hp || cures(mon.status)),
|
||||
_ if id > MAX_REVIVE || (FULL_RESTORE..=POTION).contains(&id) => {
|
||||
!fainted && mon.hp < mon.max_hp
|
||||
}
|
||||
_ if id < FULL_RESTORE => !fainted && cures(mon.status),
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
return Some(mons.iter().any(takes));
|
||||
}
|
||||
if Some(routine) == of(memory, ETHER) {
|
||||
let spent = |memory: &mut dyn MemoryReader, entry: &Move| -> bool {
|
||||
let ups = entry.pp_up;
|
||||
match move_data(memory, entry.id) {
|
||||
Some(data) => entry.pp < data.pp + (data.pp / 5) * ups,
|
||||
None => true,
|
||||
}
|
||||
};
|
||||
let moves: Vec<Move> = mons.iter().flat_map(|mon| mon.moves.iter().flatten().copied()).collect();
|
||||
return Some(moves.iter().any(|entry| spent(memory, entry)));
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
|
||||
/// Whether the cartridge still has `A` down from the last time it read the joypad.
|
||||
///
|
||||
/// Row 63 (`docs/design/macros.md` 12.27). `_Joypad` makes a press out of an *edge* --
|
||||
/// `hJoyPressed` is what is down now and was not down in `hJoyLast` -- and the game only asks
|
||||
/// while something is reading input. So after the A that confirms a list, the game stops asking
|
||||
/// while it draws the next one, `hJoyLast` keeps that A, and an A issued before the new list's
|
||||
/// first read is down on both sides of the comparison: no edge, no press. Measured on the
|
||||
/// Potion's party list from the row-63 checkpoint: the list's cursor bytes read open at once, an
|
||||
/// A in the first 22 frames is swallowed every time, and `hJoyLast` separates the refused frames
|
||||
/// from the answered ones exactly (`infra/docs/macros-traps.md` row 63).
|
||||
pub fn a_latched(memory: &mut dyn MemoryReader) -> bool {
|
||||
read(memory, poke::H_JOY_LAST) & poke::pad::A != 0
|
||||
}
|
||||
|
||||
/// Whether a text box is open, and whether the bottom-of-screen dialogue box is the one drawn.
|
||||
///
|
||||
/// `open` is `wFontLoaded`'s bit 0, which `DisplayTextIDInit` sets for every text display — the
|
||||
|
|
@ -1974,6 +2163,14 @@ impl MacroState for PokeState<'_> {
|
|||
move_without_effect(self.memory, id).unwrap_or(false)
|
||||
}
|
||||
|
||||
fn item_refused(&mut self, id: u8) -> bool {
|
||||
battle_item_use(self.memory, id) == Some(false)
|
||||
}
|
||||
|
||||
fn a_latched(&mut self) -> bool {
|
||||
a_latched(self.memory)
|
||||
}
|
||||
|
||||
/// The whole loaded map's walkability, from the cache when it is for this map
|
||||
/// (`docs/design/macros.md` section 15).
|
||||
///
|
||||
|
|
|
|||
|
|
@ -1253,3 +1253,115 @@ fn a_trainers_challenge_is_the_cartridges_until_its_battle_is_over() {
|
|||
assert_eq!(PokeState::new(&mut after).scene(), Scene::Overworld);
|
||||
assert!(!PokeState::new(&mut after).scripted());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Row 63: what the cartridge does with an item chosen from the battle bag, and its joypad latch
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const ANTIDOTE: u8 = 0x0b;
|
||||
const POTION: u8 = 0x14;
|
||||
const POKE_BALL: u8 = 0x04;
|
||||
const ESCAPE_ROPE: u8 = 0x1d;
|
||||
const X_ATTACK: u8 = 0x41;
|
||||
const POKE_DOLL: u8 = 0x33;
|
||||
const REVIVE: u8 = 0x35;
|
||||
const ETHER: u8 = 0x50;
|
||||
const TM34: u8 = 0xea;
|
||||
|
||||
/// The row-63 battle: a wild Geodude, and Wartortle out at 8 of 86 with the bag the live fly
|
||||
/// carried (an Antidote, a Potion and TM34).
|
||||
fn bag_battle() -> Wram {
|
||||
let mut wram = Wram::new();
|
||||
wram.party_mon(0, 0xb3, 28, 8, 86, 0, &[(44, 0), (55, 25)])
|
||||
.battle_mon(0, 0xb3, 28, 8, 86, 0, &[(44, 0), (55, 25)])
|
||||
.enemy_mon(0xa9, 9, 28, 28)
|
||||
.battle(1)
|
||||
.bag(&[(ANTIDOTE, 1), (POTION, 1), (TM34, 1)])
|
||||
.item_table();
|
||||
wram
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_item_table_is_read_by_id_and_checked_against_its_own_shape() {
|
||||
let mut wram = bag_battle();
|
||||
assert_eq!(item_routine(&mut wram, POKE_BALL), item_routine(&mut wram, 0x01));
|
||||
assert_eq!(item_routine(&mut wram, POTION), item_routine(&mut wram, ANTIDOTE));
|
||||
assert_ne!(item_routine(&mut wram, POTION), item_routine(&mut wram, POKE_BALL));
|
||||
assert_eq!(item_routine(&mut wram, 0), None, "no item zero");
|
||||
assert_eq!(item_routine(&mut wram, TM34), None, "a TM is ItemUseTMHM's, before the table");
|
||||
assert_eq!(item_routine(&mut Wram::new(), POTION), None, "no cartridge, no answer");
|
||||
// A table that is not where the disassembly says: the Safari Ball parts company with the
|
||||
// other balls, and nothing is read from it.
|
||||
let at = poke::items::TABLE_ADDRESS + 2 * u16::from(poke::items::SAFARI_BALL - 1);
|
||||
wram.rom_byte(poke::items::TABLE_BANK, at, 0x00);
|
||||
assert_eq!(item_routine(&mut wram, POTION), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_row_63_bag_holds_one_item_the_cartridge_would_take() {
|
||||
let mut wram = bag_battle();
|
||||
assert_eq!(battle_item_use(&mut wram, POTION), Some(true), "8 of 86 is somebody to heal");
|
||||
assert_eq!(battle_item_use(&mut wram, ANTIDOTE), Some(false), "nobody is poisoned");
|
||||
assert_eq!(battle_item_use(&mut wram, TM34), None, "the table does not cover it");
|
||||
assert_eq!(battle_item_use(&mut wram, ESCAPE_ROPE), Some(false), "not inside a battle");
|
||||
|
||||
// The battle's copy is the one the damage went to; the party struct catches up at the top of
|
||||
// the turn. A full party struct under a hurt battler is still somebody to heal.
|
||||
wram.set_word_be(ram::wPartyMon1 + 1, 86);
|
||||
assert_eq!(battle_item_use(&mut wram, POTION), Some(true));
|
||||
wram.set_word_be(ram::wBattleMonHP, 86);
|
||||
assert_eq!(battle_item_use(&mut wram, POTION), Some(false), "full: no effect");
|
||||
|
||||
// A status heal answers the status it cures, and only that one.
|
||||
wram.set(ram::wBattleMonStatus, 1 << poke::PSN);
|
||||
assert_eq!(battle_item_use(&mut wram, ANTIDOTE), Some(true));
|
||||
wram.set(ram::wBattleMonStatus, 1 << poke::PAR);
|
||||
assert_eq!(battle_item_use(&mut wram, ANTIDOTE), Some(false));
|
||||
|
||||
// A Revive wants somebody fainted, and a Potion does not.
|
||||
wram.set_word_be(ram::wBattleMonHP, 0);
|
||||
assert_eq!(battle_item_use(&mut wram, POTION), Some(false));
|
||||
assert_eq!(battle_item_use(&mut wram, REVIVE), Some(true));
|
||||
|
||||
// Outside a battle this is not a question this reader answers.
|
||||
wram.battle(0);
|
||||
assert_eq!(battle_item_use(&mut wram, POTION), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ball_and_a_poke_doll_are_for_a_wild_battle_and_the_x_items_for_any() {
|
||||
let mut wram = bag_battle();
|
||||
assert_eq!(battle_item_use(&mut wram, POKE_BALL), Some(true));
|
||||
assert_eq!(battle_item_use(&mut wram, POKE_DOLL), Some(true));
|
||||
assert_eq!(battle_item_use(&mut wram, X_ATTACK), Some(true));
|
||||
// A full party leaves the ball to the box, whose count is not read: no answer.
|
||||
for slot in 1..6 {
|
||||
wram.party_mon(slot, 0xb3, 5, 10, 10, 0, &[(33, 10)]);
|
||||
}
|
||||
assert_eq!(battle_item_use(&mut wram, POKE_BALL), None);
|
||||
// A trainer blocks the ball and the doll does nothing; an X item still works.
|
||||
wram.battle(2);
|
||||
assert_eq!(battle_item_use(&mut wram, POKE_BALL), Some(false));
|
||||
assert_eq!(battle_item_use(&mut wram, POKE_DOLL), Some(false));
|
||||
assert_eq!(battle_item_use(&mut wram, X_ATTACK), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ether_wants_a_move_below_its_pp() {
|
||||
let mut wram = bag_battle();
|
||||
wram.move_table(&[(44, 0, 60, 0), (55, 0, 40, 0x15)]);
|
||||
// Slot one at 0 PP (the fake's move table gives every move 35).
|
||||
assert_eq!(battle_item_use(&mut wram, ETHER), Some(true));
|
||||
wram.set(ram::wPartyMon1 + 29, 35).set(ram::wPartyMon1 + 30, 35);
|
||||
assert_eq!(battle_item_use(&mut wram, ETHER), Some(false), "every move is full");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_joypad_latch_is_hjoylast_bit_zero() {
|
||||
let mut wram = Wram::new();
|
||||
assert!(!a_latched(&mut wram));
|
||||
wram.set(poke::H_JOY_LAST, poke::pad::A);
|
||||
assert!(a_latched(&mut wram));
|
||||
wram.set(poke::H_JOY_LAST, poke::pad::DOWN);
|
||||
assert!(!a_latched(&mut wram), "a direction down is not an A down");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1276,3 +1276,36 @@ fn after_the_starter_the_way_out_of_pallet_town_is_north() {
|
|||
eprintln!("GO OBJECTIVE walked from {:?} to {:?} in {macros} macros", (start_x, start_y), (x, y));
|
||||
assert!(y < start_y, "the fly went north, toward Route 1 and the parcel beyond it");
|
||||
}
|
||||
|
||||
/// Row 63's two pinned addresses, read back from the code that uses them.
|
||||
///
|
||||
/// `_Joypad` (`engine/joypad.asm`, the first thing in `SECTION "bank3"`) opens `ldh a,
|
||||
/// [hJoyInput]`, `cp PAD_BUTTONS`, `jp z, TrySoftReset`, `ld b, a`, `ldh a, [hJoyLast]`: the
|
||||
/// operand of that second `ldh` is the latch `state::a_latched` reads. `UseItem_` loads
|
||||
/// `ItemUsePtrTable` with `ld hl, nn` fourteen bytes in, and that is the table
|
||||
/// `state::item_routine` reads.
|
||||
#[test]
|
||||
fn row63_the_joypad_latch_and_the_item_table_are_where_the_cartridge_says() {
|
||||
use flybrain_gb::pokemon_red::state::poke;
|
||||
let rom = skip_without_rom!();
|
||||
let gb = emulator(&rom);
|
||||
let bank3 = |address: u16| gb.read_rom_bank(0x03, address).expect("bank 3");
|
||||
let joypad: Vec<u8> = (0x4000..0x400b).map(bank3).collect();
|
||||
assert_eq!(&joypad[0..1], &[0xf0], "ldh a, [hJoyInput]");
|
||||
assert_eq!(&joypad[2..4], &[0xfe, 0x0f], "cp PAD_BUTTONS");
|
||||
assert_eq!(joypad[4], 0xca, "jp z, TrySoftReset");
|
||||
assert_eq!(&joypad[7..9], &[0x47, 0xf0], "ld b, a; ldh a, [hJoyLast]");
|
||||
assert_eq!(0xff00 | u16::from(joypad[9]), poke::H_JOY_LAST);
|
||||
|
||||
// `UseItem_`: ld a, 1 / ld [wActionResultOrTookBattleTurn], a / ld a, [wCurItem] /
|
||||
// cp HM01 / jp nc, ItemUseTMHM / ld hl, ItemUsePtrTable.
|
||||
let start = (0x4000u16..0x7ff0)
|
||||
.find(|address| {
|
||||
let at = |offset: u16| bank3(address + offset);
|
||||
at(0) == 0x3e && at(1) == 0x01 && at(2) == 0xea && at(5) == 0xfa && at(8) == 0xfe
|
||||
&& at(9) == 0xc4 && at(10) == 0xd2 && at(13) == 0x21
|
||||
})
|
||||
.expect("UseItem_ in bank 3");
|
||||
let table = u16::from_le_bytes([bank3(start + 14), bank3(start + 15)]);
|
||||
assert_eq!(table, poke::items::TABLE_ADDRESS);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1787,6 +1787,14 @@ fn main() {
|
|||
dump(&mut gb, "At the checkpoint");
|
||||
pad(&mut gb, &adapter, "The pad at the checkpoint");
|
||||
|
||||
if std::env::var("FLY_PROBE_CATCH").is_ok_and(|value| value == "bag") {
|
||||
bag_survey(&mut gb, &mut adapter, &mut ms, &mut layer, &mut decoder, hold_ms);
|
||||
return;
|
||||
}
|
||||
if std::env::var("FLY_PROBE_CATCH").is_ok_and(|value| value == "potion") {
|
||||
potion_survey(&mut gb, &mut adapter, &mut ms);
|
||||
return;
|
||||
}
|
||||
let catch_nurse = std::env::var("FLY_PROBE_CATCH").is_ok_and(|value| value == "nurse");
|
||||
if catch_nurse {
|
||||
nurse_survey(&mut gb, &mut adapter, &mut ms);
|
||||
|
|
@ -2148,3 +2156,348 @@ fn battle_line(gb: &mut Emulator) -> Option<String> {
|
|||
gb.read8(ram::wEnemyMonStatus),
|
||||
))
|
||||
}
|
||||
|
||||
/// Row 63: `FLY_PROBE_CATCH=bag`. The live loop was a wild battle on Mt. Moon B2F with the pad
|
||||
/// dealing `ITEM` and the bag's `BACK` in turn -- ITEM, BACK, BACK, ITEM, BACK -- until `RUN`.
|
||||
///
|
||||
/// Drives the layer with a uniform pick among the buttons dealt on each hold (seeded by
|
||||
/// `FLY_PROBE_RNG`), so what is counted is the pad and not a readout's favourite. Prints the bag
|
||||
/// and the party first, and then per battle its length in frames, its end, and the `ITEM` and
|
||||
/// `BACK` starts inside it; `FLY_PROBE_TRACE=1` adds every macro event with the battle menu it
|
||||
/// left and the screen on the frames the bag is open.
|
||||
fn bag_survey(
|
||||
gb: &mut Emulator,
|
||||
adapter: &mut PokemonRedReward,
|
||||
ms: &mut f64,
|
||||
layer: &mut flysim::macros::MacroLayer,
|
||||
decoder: &mut PopulationDecoder,
|
||||
hold_ms: f64,
|
||||
) {
|
||||
use flybrain_gb::pokemon_red::macros::cartridge::MacroState;
|
||||
use flybrain_gb::pokemon_red::macros::state::BattleMenu;
|
||||
|
||||
let menu_of = |gb: &mut Emulator, adapter: &PokemonRedReward| {
|
||||
let ledger = AdapterLedger(adapter);
|
||||
let mut poke = flybrain_gb::pokemon_red::state::PokeState::with_ledger(gb, &ledger);
|
||||
let state: &mut dyn MacroState = &mut poke;
|
||||
state.battle().map(|battle| battle.menu)
|
||||
};
|
||||
battle_dump(gb, adapter, &layer.bound_channels(), "Before the drive");
|
||||
let items: Vec<String> = state::bag(gb)
|
||||
.iter()
|
||||
.map(|stack| {
|
||||
format!(
|
||||
"{:#04x} x{} usable here: {:?}",
|
||||
stack.id,
|
||||
stack.count,
|
||||
state::battle_item_use(gb, stack.id)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
println!("- the bag, as the cartridge would answer each item in this battle: {items:#?}");
|
||||
|
||||
let budget = env_usize("FLY_PROBE_FRAMES", 71_673);
|
||||
let trace = std::env::var("FLY_PROBE_TRACE").is_ok_and(|value| value == "1");
|
||||
let trace_macro = std::env::var("FLY_PROBE_TRACE_MACRO").ok();
|
||||
let prefer: Vec<String> = std::env::var("FLY_PROBE_PREFER")
|
||||
.map(|value| value.split(',').map(|name| name.trim().to_string()).collect())
|
||||
.unwrap_or_default();
|
||||
let mut rng = env_usize("FLY_PROBE_RNG", 20_260_924) as u32 | 1;
|
||||
let mut legacy = flysim::frame::LegacyFrame::new();
|
||||
let mut hot: Option<String> = None;
|
||||
let mut hot_until = 0.0f64;
|
||||
let mut next_pick = *ms;
|
||||
let mut starts: BTreeMap<String, u64> = BTreeMap::new();
|
||||
let mut outcomes: BTreeMap<String, u64> = BTreeMap::new();
|
||||
// Frames the fly could decide on in a battle, and on how many of them each button was dealt.
|
||||
let mut decidable = 0u64;
|
||||
let mut dealt: BTreeMap<String, u64> = BTreeMap::new();
|
||||
let mut dealt_item_main_unusable = 0u64;
|
||||
let mut bag_frames = 0u64;
|
||||
let mut rewards: BTreeMap<String, u64> = BTreeMap::new();
|
||||
// (frames, item starts, back starts, how it ended)
|
||||
let mut battles: Vec<(u64, u64, u64, String)> = Vec::new();
|
||||
let mut current: Option<(u64, u64, u64)> = None;
|
||||
// Whether the Pokémon on the other side has been seen at 0 HP in the battle that is running:
|
||||
// the win, read from the battle and not from the reward, which pays a key three times at most.
|
||||
// Seen living first, as the adapter's own wild-KO rule does: the enemy's struct reads 0 HP on
|
||||
// the battle's opening frames, before it is loaded.
|
||||
let mut enemy_fainted = false;
|
||||
let mut enemy_living = false;
|
||||
let mut alternation = 0u32;
|
||||
let mut longest_alternation = 0u32;
|
||||
let mut last_start: Option<&'static str> = None;
|
||||
let mut last_reward = String::new();
|
||||
for frame in 0..budget {
|
||||
let bound = layer.bound_channels();
|
||||
if *ms >= next_pick && !bound.is_empty() && layer.running().is_none() {
|
||||
rng ^= rng << 13;
|
||||
rng ^= rng >> 17;
|
||||
rng ^= rng << 5;
|
||||
// `FLY_PROBE_PREFER=ITEM` presses that button whenever it is dealt: to see what it
|
||||
// does once pressed, not how often the fly would press it.
|
||||
let preferred = prefer
|
||||
.iter()
|
||||
.map(|name| format!("macro_{}", name.to_lowercase().replace(' ', "_")))
|
||||
.find(|channel| bound.contains(channel));
|
||||
hot = Some(preferred.unwrap_or_else(|| bound[rng as usize % bound.len()].clone()));
|
||||
hot_until = *ms + BURST_MS;
|
||||
next_pick = *ms + hold_ms;
|
||||
}
|
||||
if *ms >= hot_until {
|
||||
hot = None;
|
||||
}
|
||||
let in_battle = gb.read8(ram::wIsInBattle) != 0 && gb.read8(ram::wIsInBattle) != 0xff;
|
||||
let names: Vec<String> = layer.feed_palette().into_iter().map(|slot| slot.name).collect();
|
||||
if in_battle && layer.running().is_none() && !names.is_empty() {
|
||||
decidable += 1;
|
||||
for name in &names {
|
||||
*dealt.entry(name.clone()).or_default() += 1;
|
||||
}
|
||||
let menu = menu_of(gb, adapter);
|
||||
if matches!(menu, Some(BattleMenu::Bag { .. })) {
|
||||
bag_frames += 1;
|
||||
}
|
||||
if matches!(menu, Some(BattleMenu::Main { .. }))
|
||||
&& names.iter().any(|name| name == "ITEM")
|
||||
&& !state::bag(gb).iter().any(|stack| state::battle_item_use(gb, stack.id).is_some())
|
||||
{
|
||||
dealt_item_main_unusable += 1;
|
||||
}
|
||||
}
|
||||
let active = decoder.decode_bound(&rates(hot.as_deref()), *ms, false, None, Some(&bound));
|
||||
let before = if trace { menu_of(gb, adapter) } else { None };
|
||||
let executed = legacy.execute(Some(layer), &active, 0, *ms, gb, adapter);
|
||||
// `FLY_PROBE_TRACE_MACRO=ITEM` prints every frame that macro runs: the mask it pressed,
|
||||
// the menu the seam reads, and the cursor bytes under it.
|
||||
if let Some(want) = trace_macro.as_deref()
|
||||
&& (layer.running() == Some(want) || executed.events.iter().any(|event| event.name == want))
|
||||
{
|
||||
let cursor = state::cursor(gb);
|
||||
println!(
|
||||
" {want} f{frame} mask {:#04x} menu {:?} cursor {}/{} top ({},{}) keys {:#04x} list {:#04x} party-type {:#04x} hJoyLast {:#04x}",
|
||||
executed.mask,
|
||||
menu_of(gb, adapter),
|
||||
cursor.current,
|
||||
cursor.max,
|
||||
cursor.top_x,
|
||||
cursor.top_y,
|
||||
cursor.watched_keys,
|
||||
gb.read8(ram::wListMenuID),
|
||||
gb.read8(ram::wPartyMenuTypeOrMessageID),
|
||||
gb.read8(flybrain_gb::pokemon_red::state::poke::H_JOY_LAST),
|
||||
);
|
||||
}
|
||||
for event in &executed.events {
|
||||
match event.outcome {
|
||||
None => {
|
||||
*starts.entry(event.name.to_string()).or_default() += 1;
|
||||
if let Some(battle) = current.as_mut() {
|
||||
if event.name == "ITEM" {
|
||||
battle.1 += 1;
|
||||
}
|
||||
if event.name == "BACK" {
|
||||
battle.2 += 1;
|
||||
}
|
||||
}
|
||||
let pair = matches!(
|
||||
(last_start, event.name),
|
||||
(Some("ITEM"), "BACK") | (Some("BACK"), "ITEM") | (Some("BACK"), "BACK")
|
||||
);
|
||||
alternation = if pair { alternation + 1 } else { 0 };
|
||||
longest_alternation = longest_alternation.max(alternation);
|
||||
last_start = Some(event.name);
|
||||
}
|
||||
Some(outcome) => {
|
||||
*outcomes.entry(format!("{} {}", event.name, outcome.as_str())).or_default() += 1;
|
||||
}
|
||||
}
|
||||
if trace {
|
||||
println!(
|
||||
" f{frame:<6} {:<16} menu {before:?} -> {:?}",
|
||||
event.label(),
|
||||
menu_of(gb, adapter)
|
||||
);
|
||||
}
|
||||
}
|
||||
if trace && matches!(menu_of(gb, adapter), Some(BattleMenu::Bag { .. })) && frame % 30 == 0 {
|
||||
for line in screen_text(gb).iter().take(12) {
|
||||
println!(" | {line}");
|
||||
}
|
||||
}
|
||||
*ms += MS_PER_FRAME;
|
||||
let evaluated =
|
||||
legacy.stub_advance(Some(layer), gb, adapter, *ms).expect("a frame should complete");
|
||||
for reward in &evaluated.rewards {
|
||||
*rewards.entry(reward.kind.to_string()).or_default() += 1;
|
||||
last_reward = format!("{} {}", reward.kind, reward.label);
|
||||
}
|
||||
let in_battle_now = gb.read8(ram::wIsInBattle) != 0 && gb.read8(ram::wIsInBattle) != 0xff;
|
||||
if in_battle_now && let Some(enemy) = state::battle(gb).and_then(|battle| battle.enemy) {
|
||||
enemy_living |= enemy.hp > 0;
|
||||
enemy_fainted |= enemy_living && enemy.hp == 0;
|
||||
}
|
||||
match (current.as_mut(), in_battle_now) {
|
||||
(Some(battle), true) => battle.0 += 1,
|
||||
(Some(_), false) => {
|
||||
let (frames, item, back) = current.take().expect("a battle is running");
|
||||
let party_hp: u32 =
|
||||
state::party(gb).mons.iter().map(|mon| u32::from(mon.hp)).sum();
|
||||
let end = if party_hp == 0 {
|
||||
"lost".to_string()
|
||||
} else if enemy_fainted {
|
||||
"won".to_string()
|
||||
} else {
|
||||
"fled or caught".to_string()
|
||||
};
|
||||
if trace {
|
||||
println!(" f{frame:<6} battle over: {frames} frames, {end}");
|
||||
}
|
||||
battles.push((frames, item, back, end));
|
||||
last_reward.clear();
|
||||
enemy_fainted = false;
|
||||
enemy_living = false;
|
||||
}
|
||||
(None, true) => current = Some((1, 0, 0)),
|
||||
(None, false) => {}
|
||||
}
|
||||
}
|
||||
if let Some((frames, item, back)) = current {
|
||||
battles.push((frames, item, back, "still running".to_string()));
|
||||
}
|
||||
|
||||
println!("\n## Row 63 survey: {budget} frames, seed {}\n", env_usize("FLY_PROBE_RNG", 20_260_924));
|
||||
println!("- macro starts: {starts:?}");
|
||||
println!("- macro outcomes: {outcomes:?}");
|
||||
println!("- decidable battle frames {decidable}; frames with the bag open {bag_frames}");
|
||||
println!("- dealt on those frames: {dealt:?}");
|
||||
println!(
|
||||
"- `ITEM` dealt on the battle menu with nothing in the bag the cartridge would use: {dealt_item_main_unusable}"
|
||||
);
|
||||
println!("- longest ITEM/BACK run of starts: {longest_alternation}");
|
||||
println!("- rewards: {rewards:?}");
|
||||
let won = battles.iter().filter(|battle| battle.3 == "won").count();
|
||||
let frames: u64 = battles.iter().map(|battle| battle.0).sum();
|
||||
let longest = battles.iter().map(|battle| battle.0).max().unwrap_or(0);
|
||||
println!(
|
||||
"- battles {}: won {won}, frames {frames} (mean {}, longest {longest}), ITEM starts inside {}, BACK starts inside {}",
|
||||
battles.len(),
|
||||
if battles.is_empty() { 0 } else { frames / battles.len() as u64 },
|
||||
battles.iter().map(|battle| battle.1).sum::<u64>(),
|
||||
battles.iter().map(|battle| battle.2).sum::<u64>(),
|
||||
);
|
||||
for (index, battle) in battles.iter().enumerate() {
|
||||
println!(" - battle {index}: {} frames, ITEM {}, BACK {}, {}", battle.0, battle.1, battle.2, battle.3);
|
||||
}
|
||||
battle_dump(gb, adapter, &layer.bound_channels(), "After the drive");
|
||||
}
|
||||
|
||||
/// Row 63: `FLY_PROBE_CATCH=potion`, from a checkpoint with the battle bag open and a Potion in
|
||||
/// it. Raw presses put the bag's cursor on the Potion and confirm it; once the party list reads
|
||||
/// open, every delay from 0 to `FLY_PROBE_STUCK` frames is tried in a rollback -- wait that
|
||||
/// long, pulse A, watch 180 frames -- and the ones after which the Pokémon's HP went up are
|
||||
/// printed. That is the window in which `ITEM`'s last press is answered.
|
||||
fn potion_survey(gb: &mut Emulator, adapter: &mut PokemonRedReward, ms: &mut f64) {
|
||||
use flybrain_gb::buttons;
|
||||
use flybrain_gb::pokemon_red::macros::cartridge::MacroState;
|
||||
use flybrain_gb::pokemon_red::macros::state::BattleMenu;
|
||||
|
||||
let menu = |gb: &mut Emulator, adapter: &PokemonRedReward| {
|
||||
let ledger = AdapterLedger(adapter);
|
||||
let mut poke = flybrain_gb::pokemon_red::state::PokeState::with_ledger(gb, &ledger);
|
||||
let state: &mut dyn MacroState = &mut poke;
|
||||
state.battle().map(|battle| battle.menu)
|
||||
};
|
||||
let hp = |gb: &mut Emulator| {
|
||||
u16::from(gb.read8(ram::wBattleMonHP)) * 256 + u16::from(gb.read8(ram::wBattleMonHP + 1))
|
||||
};
|
||||
let mut pulse = |gb: &mut Emulator, adapter: &mut PokemonRedReward, mask: u8| {
|
||||
for phase in 0..16 {
|
||||
gb.set_buttons(if phase < 8 { mask } else { 0 });
|
||||
gb.run_frame().expect("a frame should complete");
|
||||
*ms += MS_PER_FRAME;
|
||||
adapter.sample(gb, *ms);
|
||||
}
|
||||
};
|
||||
let potion = state::bag(gb).iter().position(|stack| stack.id == 0x14);
|
||||
println!("\n## Row 63: the Potion, pressed by hand\n\n- bag {:?}, potion at {potion:?}, menu {:?}, hp {}", state::bag(gb), menu(gb, adapter), hp(gb));
|
||||
let Some(potion) = potion else { return };
|
||||
for _ in 0..8 {
|
||||
match menu(gb, adapter) {
|
||||
Some(BattleMenu::Bag { cursor, .. }) if usize::from(cursor) == potion => break,
|
||||
Some(BattleMenu::Bag { cursor, .. }) if usize::from(cursor) < potion => {
|
||||
pulse(gb, adapter, buttons::DOWN)
|
||||
}
|
||||
_ => pulse(gb, adapter, buttons::UP),
|
||||
}
|
||||
}
|
||||
println!("- on the Potion: {:?}", menu(gb, adapter));
|
||||
pulse(gb, adapter, buttons::A);
|
||||
let mut opened = None;
|
||||
for frame in 0..240 {
|
||||
if matches!(menu(gb, adapter), Some(BattleMenu::Party { .. })) {
|
||||
opened = Some(frame);
|
||||
break;
|
||||
}
|
||||
gb.set_buttons(0);
|
||||
gb.run_frame().expect("a frame should complete");
|
||||
}
|
||||
println!("- the party list reads open {opened:?} frames after the confirming pulse");
|
||||
for line in screen_text(gb) {
|
||||
println!(" | {line}");
|
||||
}
|
||||
let before = hp(gb);
|
||||
let mut answered = Vec::new();
|
||||
let mut texts = Vec::new();
|
||||
let mut separator = Separator::new();
|
||||
let span = env_usize("FLY_PROBE_STUCK", 120);
|
||||
for delay in 0..span {
|
||||
let save = gb.export_state().expect("export");
|
||||
for _ in 0..delay {
|
||||
gb.set_buttons(0);
|
||||
gb.run_frame().expect("a frame should complete");
|
||||
}
|
||||
let text = state::text_box(gb);
|
||||
let reading = format!(
|
||||
"box {} seam {:?}",
|
||||
box_rows(gb),
|
||||
menu(gb, adapter)
|
||||
);
|
||||
let probe = gb.export_state().expect("export");
|
||||
let screen = if [0usize, 10, 20, 21, 22, 23, 30].contains(&delay) { screen_text(gb) } else { Vec::new() };
|
||||
gb.import_state(&probe).expect("import");
|
||||
for phase in 0..16 {
|
||||
gb.set_buttons(if phase < 8 { buttons::A } else { 0 });
|
||||
gb.run_frame().expect("a frame should complete");
|
||||
}
|
||||
for _ in 0..180 {
|
||||
gb.set_buttons(0);
|
||||
gb.run_frame().expect("a frame should complete");
|
||||
}
|
||||
let healed = hp(gb) > before;
|
||||
if healed {
|
||||
answered.push(delay);
|
||||
}
|
||||
if delay % 10 == 0 || (18..26).contains(&delay) {
|
||||
texts.push(format!("d{delay} text {text:?} {reading} healed {healed}"));
|
||||
}
|
||||
for line in screen {
|
||||
texts.push(format!(" d{delay} | {line}"));
|
||||
}
|
||||
gb.import_state(&save).expect("import");
|
||||
for _ in 0..delay {
|
||||
gb.set_buttons(0);
|
||||
gb.run_frame().expect("a frame should complete");
|
||||
}
|
||||
separator.observe(gb, healed);
|
||||
gb.import_state(&save).expect("import");
|
||||
}
|
||||
println!("- WRAM/HRAM addresses whose values never overlap between refused and answered frames (refused, answered):");
|
||||
for (address, refused, honoured) in separator.disjoint().into_iter().take(25) {
|
||||
println!(" - {address:#06x}: {refused:?} / {honoured:?}");
|
||||
}
|
||||
println!("- A after these delays healed ({} of {span}): {answered:?}", answered.len());
|
||||
for line in texts {
|
||||
println!(" - {line}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -778,8 +778,10 @@ impl Run {
|
|||
// picks among exactly those (`docs/design/macros.md` section 12).
|
||||
let bound = self.layer.bound_channels();
|
||||
// Only the fly's *own* turn. Battle text between turns is a pad of one `NEXT` by design
|
||||
// (the v0.2.4 deadlock fix), so counting it would measure the wrong thing.
|
||||
if self.own_turn() {
|
||||
// (the v0.2.4 deadlock fix), so counting it would measure the wrong thing. Nor a menu the
|
||||
// cartridge still holds an A on, whose pad is empty on purpose (12.27): the answer is
|
||||
// taken or the list is not yet asking, and it is back on the game's next joypad read.
|
||||
if self.own_turn() && !flybrain_gb::pokemon_red::state::a_latched(&mut self.gb) {
|
||||
self.move_button_on_battle_pad |=
|
||||
bound.iter().any(|channel| channel.starts_with("macro_move_"));
|
||||
let dealt = bound.len();
|
||||
|
|
@ -3806,3 +3808,185 @@ fn a_trainers_challenge_does_not_wall_the_road_to_the_forests_north_gate() {
|
|||
assert!(route_2_north.is_some(), "nor Route 2 through it: {arrivals:?}");
|
||||
assert!(pewter.is_some(), "nor Pewter City: {arrivals:?}");
|
||||
}
|
||||
|
||||
/// The row-63 checkpoint (Mt. Moon B2F, a wild battle with the bag open), or `None` to skip.
|
||||
fn row63_checkpoint() -> Option<flysim::store::Checkpoint> {
|
||||
std::env::var_os("FLY_ROW63_CHECKPOINT").map(|path| {
|
||||
flysim::store::load(std::path::Path::new(&path))
|
||||
.expect("the checkpoint should be a FLYSIM01 envelope")
|
||||
})
|
||||
}
|
||||
|
||||
/// Mt. Moon B2F, from the checkpoint taken mid-trap: Wartortle out at 8 of 86 against a wild
|
||||
/// Geodude, the bag open on an Antidote, a Potion and TM34.
|
||||
///
|
||||
/// **What was live** (2026-09-24, v0.6.2, rank 12): per ten minutes `BACK` 62, `ITEM` 28, `RUN`
|
||||
/// 21, `MOVE 1` 10, no game event -- ITEM, BACK, BACK, ITEM, BACK ... then RUN. The bag is not
|
||||
/// the problem: the Potion is one the cartridge would take. `ITEM`'s last press, the A on the
|
||||
/// party list, went in while the cartridge still held the A that chose the Potion, so it was no
|
||||
/// press; `ITEM` reported done over the waiting list and the fly left it and the bag with two
|
||||
/// `BACK`s. Beside it `MOVE 1` was dealt over the menu with slot one spent and slot four usable,
|
||||
/// and only opened the list its `BACK` closed (`infra/docs/macros-traps.md` row 63).
|
||||
///
|
||||
/// The driver is the real palette, pressing `ITEM` whenever the pad deals it and otherwise a
|
||||
/// uniform choice per hold -- a harness choice, not the fly's. The claims:
|
||||
///
|
||||
/// - **the Potion is used**: Wartortle's HP goes up and the Potion leaves the bag;
|
||||
/// - **no `ITEM` ends with its party list still up**, so no `BACK` is needed to leave it;
|
||||
/// - **`MOVE 1` is not dealt over the menu while slot one is spent beside a usable move**;
|
||||
/// - **the battle ends**.
|
||||
///
|
||||
/// ```sh
|
||||
/// FLY_ROM=/path/to/pokemon-red.gb \
|
||||
/// FLY_ROW63_CHECKPOINT=.local/checkpoints/release-rank12-row63.checkpoint \
|
||||
/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row63
|
||||
/// ```
|
||||
#[test]
|
||||
fn row63_item_uses_the_potion_and_the_battle_menu_deals_no_list_it_only_opens() {
|
||||
let rom = skip_without_rom!();
|
||||
let Some(checkpoint) = row63_checkpoint() else {
|
||||
eprintln!("skipped: no FLY_ROW63_CHECKPOINT");
|
||||
return;
|
||||
};
|
||||
// The Potion, pressed whenever it is dealt.
|
||||
let item = row63_drive(&rom, &checkpoint, &["ITEM"]);
|
||||
assert!(item.starts.get("ITEM").copied().unwrap_or(0) > 0, "ITEM was never pressed");
|
||||
assert_eq!(item.item_left_a_list, 0, "an ITEM ended with its party list still waiting");
|
||||
assert!(item.hp_rose, "the Potion never reached Wartortle");
|
||||
assert_eq!(item.potions_left, 0, "the Potion is still in the bag");
|
||||
assert!(item.ended_at.is_some(), "the battle did not end: {item:?}");
|
||||
// Out of the bag, then `MOVE 1` whenever it is dealt: over the menu it may only be the
|
||||
// backstop, and the menu with slot one spent beside slot four is reached.
|
||||
let move_one = row63_drive(&rom, &checkpoint, &["BACK", "MOVE 1"]);
|
||||
assert!(move_one.spent_menu_frames > 0, "the menu with slot one spent was never up");
|
||||
assert_eq!(move_one.spent_move_one_dealt, 0, "MOVE 1 opened a list beside a usable move");
|
||||
assert!(move_one.ended_at.is_some(), "the battle did not end: {move_one:?}");
|
||||
}
|
||||
|
||||
/// What one drive from the row-63 checkpoint measured.
|
||||
#[derive(Debug)]
|
||||
struct Row63 {
|
||||
starts: std::collections::BTreeMap<&'static str, u32>,
|
||||
item_left_a_list: u32,
|
||||
spent_move_one_dealt: u32,
|
||||
/// Free frames on the menu with slot one spent and another move usable.
|
||||
spent_menu_frames: u32,
|
||||
hp_rose: bool,
|
||||
potions_left: u32,
|
||||
battle_frames: u32,
|
||||
ended_at: Option<u32>,
|
||||
}
|
||||
|
||||
/// The real palette from the row-63 checkpoint, pressing the first of `prefer` the pad deals and
|
||||
/// otherwise a uniform choice per hold, until the battle ends or 12,000 frames pass.
|
||||
fn row63_drive(rom: &[u8], checkpoint: &flysim::store::Checkpoint, prefer: &[&str]) -> Row63 {
|
||||
use flybrain_gb::pokemon_red::macros::PokemonPalette;
|
||||
use flybrain_gb::pokemon_red::macros::state::BattleMenu;
|
||||
use flybrain_gb::pokemon_red::state;
|
||||
use flybrain_gb::pokemon_red::symbols::ram;
|
||||
use flybrain_gb::{MacroPalette, MemoryReader, Started};
|
||||
const POTION: u8 = 0x14;
|
||||
let mut run = Run::resume(rom, MacroMode::Macros, checkpoint);
|
||||
assert_eq!(run.gb.read8(ram::wIsInBattle), 1, "the checkpoint is inside the wild battle");
|
||||
let potions = |gb: &mut Emulator| -> u32 {
|
||||
state::bag(gb).iter().filter(|stack| stack.id == POTION).map(|stack| u32::from(stack.count)).sum()
|
||||
};
|
||||
assert_eq!(potions(&mut run.gb), 1);
|
||||
assert_eq!(state::battle_item_use(&mut run.gb, POTION), Some(true), "the cartridge takes it");
|
||||
let hp_before = state::battle(&mut run.gb).and_then(|battle| battle.own).map(|own| own.hp);
|
||||
|
||||
let budget = 12_000u32;
|
||||
let hold_frames = 48u32;
|
||||
let mut palette = PokemonPalette::new(SEED);
|
||||
let mut rng = 20_260_924u32;
|
||||
let mut running: Option<&'static str> = None;
|
||||
let mut since_decision = hold_frames;
|
||||
let mut ms = run.ms;
|
||||
let mut out = Row63 {
|
||||
starts: std::collections::BTreeMap::new(),
|
||||
item_left_a_list: 0,
|
||||
spent_move_one_dealt: 0,
|
||||
spent_menu_frames: 0,
|
||||
hp_rose: false,
|
||||
potions_left: 0,
|
||||
battle_frames: 0,
|
||||
ended_at: None,
|
||||
};
|
||||
for frame in 0..budget {
|
||||
palette.clock(ms);
|
||||
let observed = {
|
||||
let ledger = AdapterLedger(&run.adapter);
|
||||
palette.observe(&mut run.gb, &ledger)
|
||||
};
|
||||
let names: Vec<&str> = observed.bindings.iter().map(|binding| binding.name).collect();
|
||||
if running.is_none()
|
||||
&& let Some(battle) = state::battle(&mut run.gb)
|
||||
&& matches!(battle.menu, BattleMenu::Main { .. })
|
||||
&& let Some(own) = battle.own
|
||||
{
|
||||
let spent = own.moves[0].is_some_and(|entry| entry.pp == 0);
|
||||
let usable = own.moves.iter().flatten().any(|entry| entry.id != 0 && entry.pp > 0);
|
||||
if spent && usable {
|
||||
out.spent_menu_frames += 1;
|
||||
if names.contains(&"MOVE 1") {
|
||||
out.spent_move_one_dealt += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut mask = 0u8;
|
||||
{
|
||||
let ledger = AdapterLedger(&run.adapter);
|
||||
if let Some(name) = running {
|
||||
match palette.step(&mut run.gb, &ledger) {
|
||||
Some(held) => mask = held,
|
||||
None => {
|
||||
running = None;
|
||||
if name == "ITEM"
|
||||
&& state::battle(&mut run.gb)
|
||||
.is_some_and(|battle| matches!(battle.menu, BattleMenu::Party { .. }))
|
||||
{
|
||||
out.item_left_a_list += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if since_decision >= hold_frames && !observed.bindings.is_empty() {
|
||||
since_decision = 0;
|
||||
rng ^= rng << 13;
|
||||
rng ^= rng >> 17;
|
||||
rng ^= rng << 5;
|
||||
let binding = prefer
|
||||
.iter()
|
||||
.find_map(|want| observed.bindings.iter().find(|binding| binding.name == *want))
|
||||
.unwrap_or(&observed.bindings[rng as usize % observed.bindings.len()]);
|
||||
if let Started::Running(_) = palette.start(binding.slot, &mut run.gb, &ledger) {
|
||||
*out.starts.entry(binding.name).or_default() += 1;
|
||||
running = Some(binding.name);
|
||||
match palette.step(&mut run.gb, &ledger) {
|
||||
Some(held) => mask = held,
|
||||
None => running = None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 let (Some(before), Some(now)) = (
|
||||
hp_before,
|
||||
state::battle(&mut run.gb).and_then(|battle| battle.own).map(|own| own.hp),
|
||||
) && now > before
|
||||
{
|
||||
out.hp_rose = true;
|
||||
}
|
||||
if run.gb.read8(ram::wIsInBattle) == 0 {
|
||||
out.ended_at = Some(frame);
|
||||
break;
|
||||
}
|
||||
out.battle_frames += 1;
|
||||
}
|
||||
out.potions_left = potions(&mut run.gb);
|
||||
eprintln!("row 63, pressing {prefer:?} whenever dealt: {out:?}");
|
||||
out
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue