Compare commits

..

No commits in common. "9f2345dba757e090a1c176a4a38abeba72141eb1" and "eecd5744e0b71e7ac9586094396136a074819e6f" have entirely different histories.

47 changed files with 150 additions and 5019 deletions

View file

@ -278,14 +278,10 @@ it reads as the cartridge's text box, not as a rail panel or an alarm:
| Phase | Layout | Reset copy | Restart copy |
|---|---|---|---|
| `countdown` | Text box over the bottom ~40% of the game, big `M:SS` to `executeAt`, the loop and how long it was stuck. The stuck loop stays visible above it | The fly is stuck in a loop! / Rewinding to the BOULDER BADGE milestone in 0:42 | … / Shaking it off in 0:42 |
| `acting` | Covers the whole 800x720 game panel, which is frozen or blank while flysim is down; a stepped progress bar | Rewinding… / Back to the BOULDER BADGE milestone | Shaking it off… / Same place, fresh start |
| `done` | Text box, 8 s after the helper's `updatedAt` | Back at the BOULDER BADGE milestone! | All shaken off! |
| `failed` | Text box, 20 s | That didn't work / Trying something else next | same |
A reset names its target by the ladder label: a place as is (`PEWTER CITY`), any other rung as
`the BOULDER BADGE milestone`, and the rung the fly is already on as `the start of MT. MOON` (the
ladder's first reset goes back to where it first reached that rung).
| `countdown` | Text box over the bottom ~40% of the game, big `M:SS` to `executeAt`, the loop and how long it was stuck. The stuck loop stays visible above it | The fly is stuck in a loop! / Rewinding to PEWTER CITY in 0:42 | … / Shaking it off in 0:42 |
| `acting` | Covers the whole 800x720 game panel, which is frozen or blank while flysim is down; a stepped progress bar | Rewinding… / Back to PEWTER CITY | Shaking it off… / Same place, fresh start |
| `done` | Text box, 8 s after the helper's `updatedAt` | Back at PEWTER CITY! | All shaken off! |
| `failed` | Text box, 20 s | That didn't work / A human will take a look | same |
**Where the notice comes from.** Not the feed: flysim is the thing being restarted. The helper
writes `/run/fly/wd/recovery-notice.json` atomically (tmp + rename); `flystage-web`

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 56 KiB

View file

@ -213,34 +213,11 @@ export function recoveryVisible(notice: RecoveryNotice, nowS: number): boolean {
}
}
/**
* Ladder rungs (`docs/design/ladder.md`) whose label is a place the fly can be "back at". The rest
* are events (BOULDER BADGE, GOT A STARTER, HM CUT) and read as "the BOULDER BADGE milestone".
*/
const PLACE_RUNGS: ReadonlySet<string> = new Set([
'PALLET TOWN', "OAK'S LAB", 'VIRIDIAN CITY', 'VIRIDIAN FOREST', 'PEWTER CITY', 'MT. MOON',
'CERULEAN CITY', 'NUGGET BRIDGE', 'VERMILION CITY', 'ROCK TUNNEL', 'LAVENDER TOWN',
'CELADON CITY', 'FUCHSIA CITY', 'CINNABAR ISLAND', 'INDIGO PLATEAU',
]);
/**
* Where a reset goes, in words: `PEWTER CITY`, `the BOULDER BADGE milestone`, and `the start of
* MT. MOON` when the target is the rung the fly is already on (the ladder's first reset: it goes
* back to where it first reached that rung). Empty without a label.
*/
export function resetTarget(notice: RecoveryNotice): string {
const label = notice.toLabel;
if (label === '') return '';
const named = PLACE_RUNGS.has(label) ? label : `the ${label} milestone`;
const same = notice.toRung !== null && notice.toRung === notice.fromRung;
return same ? `the start of ${named}` : named;
}
/** The splash at `nowS`, or null when nothing should be on screen. */
export function recoveryView(notice: RecoveryNotice | null, nowS: number): RecoveryView | null {
if (notice === null || !recoveryVisible(notice, nowS)) return null;
const reset = notice.action === 'reset';
const to = resetTarget(notice);
const to = notice.toLabel;
const base = {
id: notice.id,
phase: notice.phase,
@ -299,7 +276,7 @@ export function recoveryView(notice: RecoveryNotice | null, nowS: number): Recov
layout: 'box',
chip: 'AUTO RECOVERY',
headline: "That didn't work",
body: 'Trying something else next',
body: 'A human will take a look',
countdown: '',
loop: '',
stuck: '',

View file

@ -141,19 +141,6 @@ test('acting: covers the game while flysim is down, and gives up after a cap', (
assert.equal(view(acting, T + 60 + RECOVERY_ACTING_MAX_S + 1), null);
});
test('a rung that is not a place reads as a milestone, and the current rung as its start', () => {
const badge = notice({ toRung: 11, toLabel: 'BOULDER BADGE' });
assert.equal(view(badge, T + 18)?.body, 'Rewinding to the BOULDER BADGE milestone in');
assert.equal(view({ ...badge, phase: 'acting' }, T + 63)?.body, 'Back to the BOULDER BADGE milestone');
assert.equal(view({ ...badge, phase: 'done', updatedAt: T + 120 }, T + 120)?.headline, 'Back at the BOULDER BADGE milestone!');
const same = notice({ toRung: 12, toLabel: 'MT. MOON' });
assert.equal(view(same, T + 18)?.body, 'Rewinding to the start of MT. MOON in');
assert.equal(view({ ...same, phase: 'done', updatedAt: T + 120 }, T + 120)?.headline, 'Back at the start of MT. MOON!');
assert.equal(view({ ...same, toLabel: 'BOULDER BADGE', toRung: 12, fromRung: 12 }, T + 18)?.body,
'Rewinding to the start of the BOULDER BADGE milestone in');
});
test('done shows about 8 s, failed a little longer, then both clear', () => {
const done = notice({ phase: 'done', updatedAt: T + 120 });
assert.equal(view(done, T + 120)?.headline, 'Back at PEWTER CITY!');
@ -162,7 +149,7 @@ test('done shows about 8 s, failed a little longer, then both clear', () => {
assert.equal(view(done, T + 120 + RECOVERY_DONE_S + 1), null);
const failed = notice({ phase: 'failed', updatedAt: T + 120 });
assert.equal(view(failed, T + 125)?.body, 'Trying something else next');
assert.equal(view(failed, T + 125)?.body, 'A human will take a look');
assert.equal(view(failed, T + 120 + RECOVERY_FAILED_S + 1), null);
});

View file

@ -161,7 +161,7 @@ const RECOVERY_SHOTS = (['countdown', 'acting', 'done', 'failed'] as const).flat
action,
fromRung: 12,
fromLabel: 'MT. MOON',
...(action === 'reset' ? { toRung: 11, toLabel: 'BOULDER BADGE' } : {}),
...(action === 'reset' ? { toRung: 11, toLabel: 'PEWTER CITY' } : {}),
reason: 'unrewarded',
loop: ['GO OBJECTIVE', 'GO WARP'],
stuckSeconds: 1800,

View file

@ -995,32 +995,3 @@ 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.

View file

@ -1650,269 +1650,6 @@ Nothing is ranked or pressed for the fly: frames that were never the fly's deal
decoder, the reward catalog, the adapter version, the roles and the compatibility string are
untouched.
### 12.26 A counter the fly has a use for is dealt again, and a purchase is done when it is paid (2026-09-24, row 62)
The operator's reset to milestone 1 was to watch the shop, the Poké Balls and the catching. Eleven
and a half hours later the live fly (v0.6.2) had reached rung 12, Mt. Moon, with the Boulder Badge,
and in the whole event log had done `GO SHOP` twice (the parcel) and nothing else of it: no `BUY`,
no `THROW BALL`, no `GO HEAL`, `HEAL` or nurse's YES. It whited out in Mt. Moon again and again and
walked back from Pallet Town each time. The log records what was chosen, not what was dealt, so
the question was which. Surveyed with a new probe mode (`FLY_PROBE_CATCH=offers` in
`examples/scene_probe.rs`: the service's frame behind a uniform stub, counting per decidable frame
what is on the pad and reading the cartridge beside it) from the live checkpoint and four others.
**It was the pad**, in five places:
- **The errand was paid by a visit on which the counter could do nothing, and never came back.**
Section 13's "one visit per area per run" is paid on entering, and since row 54 by the
adapter's lifetime map ledger too. The Viridian mart is first entered for Oak's parcel, when
its clerk sells nothing; a centre entered with a full party heals nothing. From then on
`GO SHOP` and `GO HEAL` were off every pad in that area for the run, whatever the party or the
bag read. **`service_needed`** is the other half of the question, read from the cartridge each
time: a centre while the party needs rest (`party_needs_rest`, the byte `HEAL` and the nurse's
prompt already read), a mart while the bag has no ball, the wallet covers one (200) and the bag
does not hold Oak's parcel (until it is delivered the Viridian clerk's text table is the
parcel's). A ball because `THROW BALL` is the one button a purchase has to make possible, and
every Kanto mart stocks it first, within the cursor's reach. It **satisfies itself**: a heal
leaves the party full and a purchase leaves a ball, so the button leaves the pad when its job
is done. `GO SHOP` / `GO HEAL` aim at the area's building while the errand or the need holds.
- **A counter person the session had talked to or reached was retired for the session.** Inside,
with the need, the walk to the counter and `TALK` at it ignore the talked and reached ledgers
(the blocked window is kept); `TALK` at a counter is `facing_service` beside `facing_untalked`.
12.12's rule is unchanged where it applies: a rested party has no use for the nurse and `TALK`
is off.
- **`HEAL` was off the pad on the one tile it is for.** Its goals were `counter_aims`, which drops
the tile already facing the nurse -- where `GO HEAL` leaves the fly -- and retires a nurse
`GO HEAL` has reached for ten brain minutes. `HEAL`'s goals now keep that tile and read neither
ledger; the party is its satiation.
- **From a centre's door the nurse is off the screen.** A centre is entered at (3, 7) and its
nurse stands at (3, 1), six rows up, so the drawn sprites held nobody behind the counter: on the
arrival frame `HEAL`, `GO HEAL` and the counter's suppression (13.1) were all off, and the pad
was the way out. The counter person is read from the drawn and the off-screen sprites, row 58's
reading of the cartridge's own availability rule.
- **Route 4's centre, the last before Mt. Moon, was on no table.** `MT_MOON_POKECENTER` (`$44`,
Route 4's warp at (11, 5)) is on the map graph, on Route 4's west piece and in the amenity table
as Route 4's centre, so `HEAL` is dealt in it, and a hurt fly in Mt. Moon's first floor (whose
area is Route 4) has `GO HEAL` to walk out to it.
**Two limits on where a service is wanted** (the row's review, round 2). Both are the existing
rules applied to the new half of the question, and both hold for the errand too.
- **The building is the area's only from ground whose road to it stays in the area**
(`geography::route_within`). An area is counted by map id, and Route 4 is split: its east side
and Mt. Moon B1F's exit chamber are "in Route 4", but the only road from them to the centre on
the west side runs through B2F, which is in no area. So east of the mountain -- where the fly
arrives hurt -- `GO HEAL` walked down into B2F and left the pad there, while `GO OBJECTIVE`
walked back up toward Cerulean: a two-map ring by construction. The errand had the same fault
under `GO OBJECTIVE` itself (`errand_place` sent it to the centre behind the mountain). From
there Route 4's centre is not the area's; the rung is, and Cerulean's centre is one edge away
and its own area's. Every town is one piece, so nothing moved for them.
- **The room the rung is in is not left for a service.** Row 29's rule (12.5), which already
withholds the ways out while the rung's own target stands in the room untalked and unexcluded,
now withholds `GO HEAL` and `GO SHOP`'s walk out as well. A hurt party in a gym is the usual
case -- its trainers are why -- and row 58's ROM test measured it: four of six arrivals in the
Pewter Gym bounced back out, two by `GO HEAL` and one by `GO SHOP`. The errand needs no such
line: while it stands it *is* the objective. The escape hatch is the rule's own: a target no
walk reaches is excluded for the window and the service is wanted again.
**And `BUY BALL` reported `done` with nothing bought.** Pressed at the counter it ran 55 times from
the Pewter checkpoint, 55 `done`, the wallet at 1,606 throughout. After the quantity the mart
prints "POKé BALL? / That will be" and **waits for a press** (a `cont`), then prints "¥200. OK?"
and only then draws its YES/NO box; the script's one blind A after a settle was that press, and
the macro ended before the box existed. A purchase now pulses A until the box is drawn (the
general `yes_no_prompt` reading of row 56), presses YES, and is `done` when the wallet reads less
than it did: the cartridge rings the item up a few frames after the press. Either wait running
out is `blocked`.
**Measured, and what stays the fly's.** `THROW BALL` was never the pad's fault: it is off with no
ball (it cannot work) and dealt on 385 of 1,070 wild-battle frames with one, on both arms; pressed,
it catches. The live run had no ball because nothing on the pad could buy one. Survey totals, ten
twenty-minute uniform-stub runs per arm (`infra/docs/macros-traps.md` row 62): `GO HEAL` dealt
140 -> 2,300 frames, heals 2 -> 12, the whiteout map moved off Pallet Town in 2 -> 9 runs,
whiteouts 14 -> 9; `GO SHOP` dealt 101 -> 569. Whether the fly presses `TALK` at an open counter,
`CONFIRM` at the clerk's greeting and `BUY BALL` on the list is its choice; under the uniform stub
it rarely strings the four together, and with them preferred the chain buys a ball on the
cartridge (the ROM test).
Nothing ranks a button or presses for the fly: preconditions read the cartridge, and a purchase
waits for the box it answers. The decoder, the reward catalog, the adapter version, the roles and
the compatibility string are untouched.
### 12.27 An A the cartridge has not let go of is not a press, and a menu it is acting on is not a pad (2026-09-24, row 63)
Live on v0.6.2, rung 12, Mt. Moon B2F (map 61), wild battles: per ten minutes `BACK` 62, `ITEM`
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.
### 12.28 A ladder underfoot is taken by stepping off it, a ledge is a hop one way, and a way out that goes nowhere is not done (2026-09-28, row 64)
(12.26 and 12.27 are rows 62 and 63.) Live on v0.6.2/v0.6.4 at rank 12
(MT. MOON), from 2026-09-26 to 09-28: about 750 macros per ten brain minutes, all `done`, no reward
and no new ground. They were `GO OBJECTIVE` (61%) and `GO WARP`, 27 frames each. Forty-eight flysim
restarts did not clear it. A milestone reset bought a few hours before it came back.
The pulled checkpoint has the fly on **Mt. Moon B2F (5, 7)**, the ladder up to B1F's exit chamber,
which is the one road on. It reproduces the ring with the ledgers empty; nothing needs rebuilding.
- **A ladder fires at the end of a step onto it, and at no other time.** `CheckWarpsNoCollision`
runs after a step completes. A bump while standing on a warp fires only where `ExtraWarpCheck`
agrees: `IsPlayerFacingEdgeOfMap` on most tilesets, the cave's among them, and
`IsWarpTileInFrontOfPlayer` (a warp carpet in front) on the OVERWORLD, SHIP, SHIP_PORT and
PLATEAU tilesets and on Rocket Hideout B1F/B2F/B4F and Rock Tunnel 1F (12.29).
The fly had come down the ladder and was standing on it. `GO OBJECTIVE`, whose first hop is B1F's
exit chamber, and `GO WARP`, whose second tier is the same ladder, both aimed at the tile
underfoot. Both settled there for twenty frames, pressed nothing, and reported `done`. That is
12.2's trap, with no ledger in it. `GO FRONTIER` was refused `no route` once per restore and marked
the map exhausted (12.14). The mark was **correct**: every reachable tile of B2F's main piece had
been stood on, and the 439 unstood tiles are in its two other pieces. The pad never lacked a way
on. Its two ways on did nothing.
- **A walk that starts on its own step-fired warp steps off and back on.** Taking the warp this way
is what the cartridge requires. The step off goes to free ground, never onto another warp. With
nowhere free it ends `blocked`.
- **Route 4 east of the mountain had no road to Cerulean.** The ledge tile is absent from every
passable list, so the route search read a ledge as a wall in both directions. From B1F's exit the
way down is over ledges (the column at x = 62 and the rows at y = 5 and 9). So `GO OBJECTIVE`
refused `no route`, the east edge rested in the blocked ledger, and `GO FRONTIER` or `GO ITEM`
walked the fly back through the cave mouth (24, 5). It arrived on B1F (27, 3) with a pad of
`GO OBJECTIVE` and `GO OUT`, the same trap one floor up (nobs' "GO OUT / GO OBJECTIVE" of 09-26).
A stray walk over B1F (23, 3) put it back on B2F (5, 7). This is why a milestone reset only
bought hours.
- **A ledge is a hop, one way.** The decoded grid now marks `LedgeTiles`
(`data/tilesets/ledge_tiles.asm`). These count on the OVERWORLD tileset only, read from the
lower-left anchor tiles `HandleLedges` reads. The route search takes a hop from above as one press
that lands two tiles on, if the landing is ground. From below a ledge is still a wall. The flood
that 12.24's pieces are measured with is unchanged.
`HandleLedges` takes the joypad for the jump, and that reads as a scripted push-back. So the walk
holds while the cartridge carries the fly along the hop's own line. It then plans again from the
landing. Nothing is written to the push-back or blocked ledgers. A wild battle on the landing
still ends the walk.
- **The general half: a way out that does not take the fly anywhere is not `done`.** 12.2's rule is
now held by the executor for every way out instead of by each macro. A `Settle` arrival on an exit
key that leaves the fly on the same map ends `blocked`, and the exit rests in the window. If the
fly never left the tile it pressed from, row 57's refused-from-here ledger (12.21) also keeps the
button off that tile for the window. Without that, the last resort, which ignores the blocked
ledger, would re-deal the dead exit once per hold. This guarantees that **no in-place ring
persists**: at most one no-op per button per tile per window. It cannot supply knowledge the
macros lack. With it alone on base, the live ring broke (1,500 `done` in place dropped to 0 in
72,000 frames), but the fly still did not reach Cerulean.
What does *not* guarantee the fly is never stuck, and why it was not built: a repetition budget
that withholds a button after N unrewarded starts. Rows 58, 59 and 61 were rings in which every
macro *moved* the fly across a door, so no effect-based rule sees them. A budget keyed on the fly's
own choice history is a rule about the choice, not knowledge inside a macro (section 12's first
line and the ethos check). In every one of those rows it would have turned a ring into a wait or a
wander, without adding the fact that was missing. The guarantee for those rings stays outside the
fly: the watchdog, the recovery ladder, and the ROM road tests from each trap's checkpoint.
The decoder, the reward catalog, the adapter version, the roles and the compatibility string are
untouched. Nothing presses for the fly.
### 12.29 A floor whose way on is a passage is not left backwards, and a yard's one door is taken from where the fly stands (2026-09-29, row 65)
Two findings of the row-64 review, both on the road the release was about to put the live fly on.
**The merge.** Rows 62, 63 and 64 together crossed Route 4's west doors 34 times in row 59's ROM
test (bound 25; any two of them 3 to 18). The ring, traced: the fly arrives on Mt. Moon 1F's mouth
(14, 35) and `GO OUT` or `GO HEAL` takes it straight back out; on Route 4 (18, 6) `GO ROUTE` or
`GO OBJECTIVE` takes it straight back in, 70 to 80 frames a leg. `GO HEAL` (row 62, dealt on 1F
whenever the party is below full) is what brings a hurt fly back to that tile again and again,
but the leg that makes it a ring was older: `GO OUT`'s "a room has to be leavable" fallback. On
1F the exit is Route 4, ground the run has walked and not toward the rung, so the fallback dealt
it, one step from where the fly arrives. Which two rows were merged decided mostly where the
stub rotation stood when the fly arrived; the ring was there in all three. Swept over eight
rotation offsets the three-way tree crosses 24 to 44 times (three of eight over the bound).
- **A floor whose way on is a passage deals no `GO OUT` fallback** (`palette::ways`). While a
passage no ledger is resting leads toward the objective, the fly is on a floor of the road and
the way out is not the only way anywhere. It is `GO WARP`'s rule ("a floor that has its own
front door deals no staircase fallback") the other way round. The escape hatch is the blocked
window: a ladder no walk reaches rests, and the mouth is a way out again. A hurt party keeps its
way out under the button that says why, `GO HEAL`. Tiers one and two are untouched: a way out
into somewhere new, or toward the objective (an errand to the centre outside), is still dealt.
After: 2 to 7 crossings over the same eight offsets, all eight in the cave. The residual is
`GO HEAL` itself: a hurt fly on the mouth walks out toward the centre, and on Route 4 the pad has
the centre and the cave side by side. Both lead somewhere real, and which one is pressed is the
fly's (row 62's round-2 note on the same tug).
**The yard.** In the review's seed-7 survey `GO OUT` in the Cerulean badge house (`$e6`) took its
back door, (2, 0), onto Cerulean (9, 9): the door tile of a closed yard of 33 tiles whose only
way out is that door. The pad was empty from there to the end of the survey, 32,000 frames, with
`GO ROUTE` and `GO ITEM` refused `no route` whenever they came back. Reproduced with seed 99 on
the release tree, and saved there as a checkpoint. Four facts, each missing:
- **A door underfoot is the way out when nothing else of its kind can be walked to.** The exit
walks set a step-fired warp underfoot aside while any other exit is listed, reachable or not
(row 13's rule, for a fly that has just come down a staircase). Now they fall back on it after
every listed goal has failed the route search.
- **Where the tile in front is a warp carpet, the door is taken by a bump.** The back door's own
tile is no door tile, so it fires only through `ExtraWarpCheck`, and on the OVERWORLD tileset
that asks for a carpet tile in front (`data/tilesets/warp_carpet_tile_ids.asm`). Row 64's step
off and back on, sideways, was measured on the cartridge to do nothing here. The decoded grid
marks the carpets on the maps whose `ExtraWarpCheck` reads them, and a walk whose goal is a warp
underfoot presses toward one when it can (`CheckWarpsCollision`); a ladder is still stepped off.
- **Cerulean is two pieces.** Row 59's flood found the yard and left it off because the house was
not on the map graph. The house is on it now (both doors), and the yard is a piece of Cerulean
whose one neighbour is the house: from the house the road is the front door, so `GO OUT` no
longer takes the back one.
- **On a map in pieces, a way out on another piece is not a way out of here** (`path::exits`).
From the yard, every door and edge of the town was a candidate for the route search to refuse,
and each refusal rested that exit for the whole map: in a survey, the fly that got out stood
outside the front door with an empty pad for the rest of the window. A door no piece lists
(Cerulean Cave's mouth, the off-graph houses on Route 2) is not claimed either way. Route 4's
sides and Mt. Moon's chambers get the same rule.
From the yard checkpoint on the stub rotation, the base never leaves (an empty pad for 21,448 of
24,000 frames in a row); the branch is in the town on frame 266 and at the gym after. The route
survey from the same checkpoint, six seeds (1, 2, 3, 5, 7, 99) of 36,000 frames: all six leave
with no empty pad, and three win the Cascade Badge.
**And the guarantee reads where the fly stands** (the review's note on 12.28). A `Settle` on a way
out is `blocked` only while the fly is still on the tile it settled on: a warp that moves it on its
own map (the Saffron Gym's pads, Silph Co.'s) took it somewhere.
**Limit, named.** The frontier's exhausted mark (12.14) is per map. A fly in the yard that has
stood on all of it gets `GO FRONTIER` refused and the whole of Cerulean marked, for the session,
though the town's frontier is not exhausted. The yard is now reached only when the objective has
no route through the front door; a restart clears the mark.
Nothing ranks a button or presses for the fly: a fallback is withheld where a passage leads on,
a door is taken the way the cartridge takes it, and the map graph says what the ground says. 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.")
@ -1927,8 +1664,7 @@ Knowledge inside macros, never in the choice; the pad still lists buttons and th
- **`GO SHOP` / `GO HEAL`** are the errands as buttons of their own too (populations
`macro_go_shop`, `macro_go_heal`, from the same MBON/motor pool by the same rule): on the pad
when the area's mart / center is unvisited (GO SHOP also needs money), walk to its door and
in; inside, walk to the counter / nurse and face them. Since **12.26** also while the building
has a job to do: a centre for a party that needs rest, a mart for a bag with no ball.
in; inside, walk to the counter / nurse and face them.
- **Shop scene.** Buttons are purchases: `BUY POTION`, `BUY BALL`, `BUY ANTIDOTE`, `BUY REPEL`,
each bound only when the mart's stock (read from WRAM, `shop_stock` accessor, verified by
the survey method) lists it and money allows at least one; each macro buys ONE unit through
@ -1997,7 +1733,6 @@ 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 |
@ -2046,7 +1781,6 @@ 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":

View file

@ -193,7 +193,7 @@ Two identities, both registered on the provider: the **bot account** (chat send)
| `channel:manage:broadcast` | broadcaster | stream markers |
| `channel:manage:predictions` | broadcaster | predictions (later, Affiliate-gated) |
Startup asserts the actual granted scopes via `getTokenInfo` and refuses to start with a named missing scope rather than failing at the first subscription. Before that assertion, each role's stored token is made usable (added 2026-09-28): an access token expired by `obtainmentTimestamp + expiresIn`, or one `validate` rejects with 401, is refreshed once through that role's `RefreshingAuthProvider`, and every refresh is persisted under the role whose provider made it (serialized atomic writes), so both roles survive a restart even when they are one account. Only a refresh Twitch refuses (4xx) is fatal, with one line naming the role and the runbook's re-authorize step; tokens, the client secret and request URLs never reach the log. `channel.raid` needs no scope but does need a user token and a `to_broadcaster_user_id` condition.
Startup asserts the actual granted scopes via `getTokenInfo` and refuses to start with a named missing scope rather than failing at the first subscription. `channel.raid` needs no scope but does need a user token and a `to_broadcaster_user_id` condition.
## B2. Day one (pre-channel-setup)

View file

@ -891,28 +891,3 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
recovery splash counts down over the stuck loop, covers the game while it acts, and reports the
result (`apps/stage/mockups/`). Independent review: BLOCK, then fixed; round 2 approved with
the watchdog wait fixed.
- 2026-09-28 (bridge, unreleased): chat died for hours after an unrelated bridge outage outlived
both access tokens (~4 h) and the next start failed `validate` with 401 in a crash loop, with
both refresh tokens still good. Closes the v0.2.3 debt: on load, a stored token expired by its
timestamps or rejected with 401 is refreshed once through its role's provider before giving up,
and every refresh is persisted under its own role (serialized atomic 0600 writes), so both roles
survive when they are one account. Only a refresh Twitch refuses is fatal, one line pointing at
the runbook's re-authorize step; Twitch errors are logged without URLs, tokens or the secret.
- 2026-09-29 (v0.6.5, loop review, auto, plus infra/stage): the two-day Mt. Moon trap and what the
merge of its fixes surfaced. Row 64: the fly stood on B2F's exit ladder (5,7), the only road on;
GO OBJECTIVE and GO WARP both aimed at the tile underfoot and reported done without a step, and
the cartridge fires a ladder only at the end of a step onto it (1,500 of 1,500 macros from the
checkpoint, no ledger involved, so 48 restarts restored it). A walk standing on its warp now steps
off and back on; Route 4's ledges are one-way hops the route search takes (they read as walls,
so the road to Cerulean was "no route"); a way out that leaves the fly on its own map is not done
(the effect-based guarantee against in-place rings). The operator's GO WARP / GO FRONTIER
exhaustion lead was checked and refuted (GO WARP 25,554 starts; the frontier correctly spent).
Row 62 round 2 (shop, balls, nurse): no GO HEAL east of Mt. Moon, no service out of the rung's
room; Pewter buys a ball. Row 63: a confirming A waits for the cartridge's release (ITEM/BACK
with a usable Potion). Row 65: the merge of 62+63+64 failed row 59's ROM test (a Mt. Moon 1F
mouth door ring, 34 crossings) and review found a Cerulean badge-house yard stall; both fixed.
The release gate now refuses to run without FLY_ROM: the ROM suites had been passing vacuously
whenever it was unset, v0.6.4's gate included. Also: recovery timer every minute, the splash's
approved copy and STUCK from the last progress, flybridge refreshes expired tokens on load (and
redacts Twitch errors), a release deploy refuses an empty GAME_TITLE. Reviews: row 62 r2, 63,
64, 65 APPROVE-WITH-NOTES.

View file

@ -46,13 +46,6 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
[ $# -ge 1 ] || die "usage: $0 ENVFILE [RELEASE_TARBALL]"
load_env "$1"
# flybridge refuses to start on an empty GAME_TITLE, and the generated fly.env below writes the
# variable whether or not the env file sets it. It only reads the file at start, so a missing
# value surfaced as dead chat at the next reboot, a day and a deploy later (2026-09-28). A release
# with a channel therefore needs the title before anything is touched.
if [ "$ROLE" = release ] && [ -n "${TWITCH_CHANNEL:-}" ] && [ -z "${GAME_TITLE:-}" ]; then
die "TWITCH_CHANNEL is set but GAME_TITLE is empty in $1: flybridge would refuse to start. Set GAME_TITLE (infra/env/example.env)."
fi
RELEASE_TARBALL="${2:-}"
# The label this script writes into the files it GENERATES (/etc/fly/fly.env,

View file

@ -234,15 +234,6 @@ def run(now=None, sleep=time.sleep, clock=None):
state["resets"] = [at for at in state.get("resets", []) if now - at < DAY]
at = report.get("at")
# The last probe that saw progress (new places, or a higher rung than the last probe), kept across
# restarts and reboots so the stream's STUCK time counts the whole trap, not the last streak.
delta = (report.get("places") or {}).get("delta")
if type(at) is int and 0 <= now - at <= 600 and (
(type(delta) is int and delta > 0)
or (type(rank) is int and type(state.get("rank")) is int and rank > state["rank"])):
state["lastProgressAt"] = at
if type(rank) is int:
state["rank"] = rank
if (report.get("suspected") != 1 or type(at) is not int
or not 0 <= now - at <= 600 or report.get("action") != "none"):
state.pop("observedAt", None)
@ -281,8 +272,7 @@ def run(now=None, sleep=time.sleep, clock=None):
base = {"v": 1, "id": f"{now}-{action}", "action": action,
"fromRung": rank, "fromLabel": (report.get("milestone") or {}).get("label"),
"reason": report.get("reason"), "loop": (report.get("sequence") or [])[:4],
"stuckSeconds": now - state["lastProgressAt"] if state.get("lastProgressAt")
else max(0, now - observed) + 600,
"stuckSeconds": max(0, now - observed) + 600,
"announcedAt": now, "executeAt": now + COUNTDOWN}
if action == "reset":
base.update(toRung=target, toLabel=LADDER[target] if 0 <= target < len(LADDER) else None)

View file

@ -56,19 +56,7 @@ if [ -d "$flysim_dir" ]; then
# --release, not debug (Makefile's `rust:` target and the reason it gives): the flysim
# integration test that asserts the feed's 30 Hz contract only reaches ~9.5-10.4 Hz in a debug
# build, so a debug run would fail or flake that gate.
# The ROM suites (tests/rom_*.rs) return early and count as PASSED when FLY_ROM or their
# checkpoint variable is unset, so a gate run without them proves nothing about the macros.
# v0.6.4's gate ran that way. Refuse without the ROM; name every checkpoint suite skipped.
if [ -z "${FLY_ROM:-}" ] || [ ! -r "${FLY_ROM}" ]; then
die "FLY_ROM is unset or unreadable: the ROM test suites would pass without running. Export FLY_ROM and the FLY_*_CHECKPOINT variables (the operator's rom env) first."
fi
skipped=""
while IFS= read -r var; do
[ -n "${!var:-}" ] || skipped="${skipped} ${var}"
done < <(grep -rhoE 'var_os\("FLY_[A-Z0-9_]*_CHECKPOINT"\)' "$flysim_dir"/crates/*/tests/rom_*.rs \
| sed -E 's/.*"(FLY_[A-Z0-9_]*)".*/\1/' | sort -u)
[ -z "$skipped" ] || log "WARNING: ROM checkpoint suites that will pass WITHOUT running (unset):${skipped}"
log "running cargo test --workspace --release in services/flysim (FLY_ROM set)"
log "running cargo test --workspace --release in services/flysim"
(cd "$flysim_dir" && cargo test --workspace --release)
else
log "WARNING: services/flysim does not exist in this checkout — skipping cargo test --workspace"

View file

@ -1,7 +1,7 @@
# Automated loop recovery
`fly-watchdog` remains report-only. The separate `fly-loop-recover.timer` reads its
`/run/fly/wd/loop.json` every minute and unsticks a confirmed trap on its own, climbing
`/run/fly/wd/loop.json` every five minutes and unsticks a confirmed trap on its own, climbing
a ladder one step per trap that outlives the previous step:
| level | step | cost |

View file

@ -3051,322 +3051,3 @@ 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 62: the shop, the balls and the nurse, withheld
### What was live
v0.6.2, the fresh run since the operator's reset to milestone 1, about eleven and a half hours:
rung 12 (MT. MOON) with the Boulder Badge, 16 trainer wins, 86 wild wins. In the whole event log
(70,357 macro events) `GO SHOP` twice (the parcel errand), then no `BUY`, no `THROW BALL`, no
`GO HEAL`, `HEAL` or nurse's YES, 72 `TALK`. Rung 12 took 3.5 hours: the fly whited out in Mt.
Moon again and again and walked back from the south. The live checkpoint reads one Pokémon at
54/80, 508 money (every whiteout halves it), no ball, the Viridian and Pewter marts and the Mt.
Moon centre in the lifetime map ledger, the Pewter centre not, and **`wLastBlackoutMap` (`$d719`)
= `$00`, Pallet Town**: only the nurse's YES writes it (`SetLastBlackoutMap`), and the fly had never
said it.
### The survey: what the pad dealt
`FLY_PROBE_CATCH=offers` in `examples/scene_probe.rs` (new): 71,673 frames of the service's frame
behind a uniform stub, per decidable frame (a playable scene, a pad, no macro running) which
watched buttons are dealt, and the cartridge beside it. From the live checkpoint on `main`, twenty
brain minutes in Mt. Moon: `HEAL`, `GO HEAL`, `GO SHOP`, `BUY BALL`, `BUY POTION` and `THROW BALL`
on **0** of 32,178 decidable frames. From row 59's checkpoint inside the Mt. Moon centre at 10/70:
`HEAL` on 31 frames of 28,069, never in that centre. With the chain's buttons preferred (a
survey's driver), from the rung-11 Pewter checkpoint: `GO SHOP` never dealt on `main`; on the
branch before the purchase fix, `BUY BALL` 55 starts, 55 `done`, the wallet at 1,606 throughout.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 62 | section 13's errand is paid on entering, also by a visit on which the counter could do nothing (Oak's parcel at the Viridian mart, a centre entered with a full party), and with the lifetime map ledger since row 54 `GO SHOP` / `GO HEAL` never came back for the run | every town after its first visit; live, the whole run after the parcel | `go_heal_comes_back_for_a_hurt_party_after_the_errand_is_paid`, `go_shop_comes_back_while_the_bag_has_no_ball_and_the_money_covers_one`, `row62_go_shop_comes_back_with_no_ball_and_buy_ball_rings_up_a_ball` (ROM) | **fixed**: `palette::service_needed` (a centre while the party needs rest; a mart while the bag has no ball, the wallet covers one and no Oak's parcel is carried); `GO SHOP` / `GO HEAL` aim at the area's building while the errand or the need holds. Self-satisfying. `docs/design/macros.md` 12.26 |
| 62b | a counter person this session had talked to or reached is retired from `TALK` and the counter walk for the session | a second visit to a counter in one session | `a_counter_the_fly_has_a_use_for_opens_again_after_this_session_has_talked_to_it`, `a_declined_heal_writes_the_nurse_into_the_talked_ledger` | **fixed**: with the need, the walk and `TALK` (`facing_service`) ignore talked and reached; blocked kept; a rested party still has no `TALK` at the nurse (12.12) |
| 62c | `HEAL`'s goals were `counter_aims`, which drops the tile already facing the nurse and a nurse `GO HEAL` has reached (ten minutes) | at the counter, and after every `GO HEAL` | `heal_is_dealt_facing_the_nurse_and_after_go_heal_has_reached_her` | **fixed**: `HEAL`'s aims keep the facing tile and read neither ledger |
| 62d | from a centre's door (3, 7) the nurse at (3, 1) is off the screen, so the drawn sprites hold nobody behind the counter: `HEAL`, `GO HEAL` and the counter suppression off on arrival, the way out on the pad | every centre entry | `the_nurse_is_found_from_the_door_when_the_screen_does_not_draw_her` | **fixed**: the counter person is read from the drawn and the off-screen sprites (row 58's `offscreen_npcs`) |
| 62e | Route 4's centre (`$44`) was on no table: no `HEAL` in it, no errand to it | the last centre before Mt. Moon | `the_mt_moon_pokecenter_is_a_centre_and_route_4s`, `row62_heal_is_dealt_in_the_mt_moon_center_and_moves_the_whiteout_map` (ROM) | **fixed**: `MT_MOON_POKECENTER` in LINKS, Route 4's west piece and AMENITIES; Mt. Moon 1F's area is Route 4 |
| 62f | `BUY …` pressed its last A while the price line was still up: after the quantity the mart prints "That will be" and waits for a press (a `cont`), then draws the YES/NO box; the macro reported `done` with nothing bought and the box left to the next hold | every purchase | `a_purchase_answers_the_price_box_once_the_cartridge_has_drawn_it`, the three purchase tests, `row62_go_shop_…` (ROM) | **fixed**: `Step::Prompt` pulses A until the box is drawn, YES, `Step::Paid` waits for the wallet to drop; running out is `blocked` |
| 62g | `THROW BALL` | -- | -- | **not a trap**: off with no ball, dealt on 385 of 1,070 wild-battle frames with one (both arms), catches when pressed. The live run had no ball because 62/62f left no way to buy one |
| 62h | the nurse's YES is dealt only for a hurt party, so a full party passing a centre never moves `wLastBlackoutMap` | a centre visited healthy | -- | **left, operator's**: the prompt's other effect is the whiteout map, which no macro reads; 12.12 keeps the full-party ring closed. With 62/62c/62d a hurt fly heals and moves it (9 of 10 branch surveys) |
### Before and after
Ten uniform-stub surveys per arm, 71,673 frames each (twenty brain minutes), `main` `862e343` vs
branch, seeds 20260924 and 7. Checkpoints: `live` the row-62 live one (Mt. Moon 1F); `mtmoonpc`
row 59's, inside the Mt. Moon centre at 10/70; `viridian` the milestone-5 one carried to rung 8
(Viridian centre, 3,175, before the parcel); `pewter` row 59's rung-11 survey checkpoint (Pewter
gym, 1,606, no ball, errands paid); `route2ball` the 2026-09-22 rung-9 one (Route 2, one Poké Ball).
Cells are "frames dealt / starts".
| run (checkpoint-arm-seed) | decidable | HEAL dealt/started | GO HEAL dealt/started | GO SHOP dealt/started | BUY BALL dealt/started | BUY POTION dealt/started | THROW BALL dealt/started | heals | balls bought | thrown | catches | whiteouts | blackout map |
| live-base-s20260924 | 32178 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 0 | 0x00 |
| live-base-s7 | 23494 | 0/0 | 48/3 | 1/1 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| live-branch-s20260924 | 31387 | 2/0 | 541/16 | 0/0 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 0 | 0x0f |
| live-branch-s7 | 28546 | 7/0 | 405/8 | 178/6 | 0/0 | 0/0 | 0/0 | 2 | 0 | 0 | 0 | 1 | 0x02 |
| mtmoonpc-base-s20260924 | 28069 | 31/0 | 75/3 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| mtmoonpc-base-s7 | 27696 | 9/0 | 11/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| mtmoonpc-branch-s20260924 | 35812 | 4/0 | 356/9 | 0/0 | 0/0 | 0/0 | 0/0 | 2 | 0 | 0 | 0 | 1 | 0x0f |
| mtmoonpc-branch-s7 | 35128 | 25/2 | 634/7 | 0/0 | 0/0 | 0/0 | 0/0 | 2 | 0 | 0 | 0 | 0 | 0x0f |
| pewter-base-s20260924 | 35351 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| pewter-base-s7 | 33628 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| pewter-branch-s20260924 | 33541 | 1/1 | 42/3 | 72/5 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 1 | 0x02 |
| pewter-branch-s7 | 35554 | 0/0 | 30/1 | 29/2 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| route2ball-base-s20260924 | 32315 | 0/0 | 2/0 | 1/1 | 0/0 | 0/0 | 385/6 | 0 | 0 | 1 | 0 | 1 | 0x00 |
| route2ball-base-s7 | 39135 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 385/6 | 0 | 0 | 1 | 0 | 1 | 0x00 |
| route2ball-branch-s20260924 | 30993 | 41/0 | 209/6 | 38/2 | 9/0 | 9/1 | 385/6 | 1 | 0 | 1 | 0 | 1 | 0x02 |
| route2ball-branch-s7 | 32296 | 1/1 | 57/2 | 0/0 | 0/0 | 0/0 | 385/6 | 1 | 0 | 1 | 0 | 1 | 0x01 |
| viridian-base-s20260924 | 24307 | 2/1 | 2/0 | 34/2 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 3 | 0x01 |
| viridian-base-s7 | 29710 | 1/1 | 1/0 | 65/2 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 4 | 0x01 |
| viridian-branch-s20260924 | 34564 | 3/0 | 25/1 | 158/3 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 1 | 0x01 |
| viridian-branch-s7 | 30238 | 1/1 | 1/0 | 94/2 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 2 | 0x01 |
Totals, base -> branch: decidable frames 305,883 -> 328,059; `HEAL` dealt 43 -> 85; `GO HEAL`
dealt 140 -> 2,300 (starts 8 -> 53); `GO SHOP` dealt 101 -> 569 (starts 6 -> 20); heals 2 -> 12;
whiteout map off Pallet Town in 2 -> 9 runs; whiteouts 14 -> 9; `THROW BALL` identical (770 / 12,
two thrown). No ball bought under the uniform stub on either arm: the counter opens only on
`TALK`, then `CONFIRM`, then `BUY BALL`, and the stub rarely picks the three in a row. That is
the fly's choice; with the chain preferred, the branch buys (Pewter: 1,606 -> 1,406, one ball) and
`main` cannot (no `GO SHOP`, and a `BUY BALL` that ends before its box). The ROM tests fail on
`main` (`HEAL` never dealt in 3,000 frames in the Mt. Moon centre; `GO SHOP` not on Pewter's pad)
and pass on the branch (healed in 587 frames, `wLastBlackoutMap` `$0f`; one ball, 200 paid).
The live event log's choices against the pad the survey measured from the live checkpoint on
`main`: `HEAL`, `GO HEAL`, `GO SHOP`, `BUY BALL`, `BUY POTION`, `THROW BALL` dealt on 0 frames and
chosen 0 times, except `GO SHOP` (2 starts in eleven hours, both the parcel errand, dealt only
before it was paid). None of it was the fly's choice.
**Review round 2** (two blocking findings, fixed in the macros; `docs/design/macros.md` 12.26).
(1) Route 4's centre was dealt as `GO HEAL` (and as the errand under `GO OBJECTIVE`) from Route 4's
east side and B1F's exit chamber, both in Route 4's area, and the road to it runs through B2F, in
no area: the button dropped one hop in, opposite the road to Cerulean. A building is now the area's
only where the route to it stays in the area (`geography::route_within`). ROM, from the live
B2F checkpoint stepped up the ladder: the first round deals `GO HEAL` on 642 of 2,492 hurt frames
east of the mountain and walks back down into B2F; the fix deals it on none (`main` none, no row).
(2) Row 58's gym test failed on the first round (6 arrivals, 4 straight back out, by `GO HEAL` and
`GO SHOP`): a service is not wanted while the rung's own target stands in the room (row 29's rule),
and it passes (2 arrivals, 0 out, the badge won). The live Mt. Moon B2F trap at the ladder (row 64)
is not this mechanism: from its checkpoint all three arms stay on B2F for twenty brain minutes,
identically, and on `main` there is no Route 4 centre to route to.
## 2026-09-24, row 63: Mt. Moon B2F, ITEM, BACK, BACK
### What was live
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.
## 2026-09-28, row 64: Mt. Moon's far side, a ladder underfoot and three ledges down
### What was live
v0.6.2/v0.6.4 binary, adapter `pokered-unique8-v7`, macros mode, rank 12 (MT. MOON), objective
Cerulean City, from 2026-09-26 to 09-28. The watchdog flagged it as `unrewarded`: about 750 macro
decisions per ten brain minutes, all `done`, no reward, places delta 0. The 09-28 event log has
`GO OBJECTIVE` 41,990 starts, `GO WARP` 25,554, `GO FRONTIER refused` 27 (about one per restore),
and nothing else: no battle and no step. Forty-eight hourly flysim restarts did not clear it. The
milestone-12 reset of 09-26 bought hours; nobs had recorded a "GO OUT / GO OBJECTIVE" pad just
before that reset.
### Reproduction (the pulled checkpoint, hot generation 218910)
The fly is on Mt. Moon B2F (`$3d`) at (5, 7), which is warp 3, the ladder up to B1F's exit chamber
(23, 3). With the ledgers **empty** the pad is `GO OBJECTIVE`, `GO WARP`, `GO FRONTIER`:
- `objective_goals` is `Exit(Warp(3))` at (5, 7), and `ways(Passage)` is `[Warp(3)]` (tier 2,
toward the objective).
- `GO FRONTIER` is refused `no route` and the map is marked exhausted. Correctly: all 452 reachable
tiles are stood on, and the 439 unstood ones are in B2F's north and south pieces and the border.
- Per-frame trace: `GO OBJECTIVE` runs 27 frames with mask `0x00` on every one (a `Settle` arrival
on the tile underfoot) and ends `done`. The next hold does the same. Route survey on main,
20,000 frames: `GO OBJECTIVE` 205 and `GO WARP` 211 `done`, all on (5, 7).
With the ledgers rebuilt (`EXHAUSTED=1`, `STOOD=1`) the pad is `GO OBJECTIVE`, `GO WARP` from frame
0. **The coordinator's lead (`GO WARP` and `GO FRONTIER` exhausted) is refuted.** The frontier mark
is correct, and `GO WARP` is never withheld: it is dealt the whole time, at the ladder underfoot.
No ledger removes the way on. Both ways on execute as no-ops.
**Why it came back after the reset.** Off the ladder (a raw right/left step, then the drive), the
fly goes B1F exit chamber, then (27, 3), then Route 4 (24, 6). There `GO OBJECTIVE` is refused
`no route`, because every road from there to Cerulean's west edge crosses a ledge: the column at
x = 62 on rows 10-15, and the rows at y = 5 and 9. The route search read a ledge as a wall both
ways. The east edge rests, and `GO ITEM` or `GO FRONTIER` walk back into the cave mouth (24, 5).
The fly lands on B1F (27, 3), where `GO OBJECTIVE` settles in place (618 times in 30,000 frames),
or on B2F (5, 7) after a walk over (23, 3). The geometry re-creates the ring; nothing persisted.
### Fix (three commits)
1. `014d869`: a walk that starts on its own step-fired warp steps onto free ground beside it (never
another warp) and back on (`CheckWarpsNoCollision` runs only after a step).
2. `e10f48e`: `LedgeTiles` hops. The grid marks them (OVERWORLD tileset only, lower-left anchor
tiles). The route search takes a hop from above as one press that lands two tiles on. The walk
holds while `HandleLedges` carries the fly, so the hop is not written as a push-back.
3. `83e842a` (general, separable): a `Settle` on an exit key that leaves the fly on its map ends
`blocked`. From the tile it pressed from, row 57's refused-from-here ledger also holds the
button off for the window.
Ablations from the checkpoint:
- 1 alone becomes a B1F/Route 4 ring (`GO OBJECTIVE` done on Route 4 151 times, `GO ROUTE` on B1F
150).
- 3 alone breaks the in-place ring (1,500 done in place drops to 0 in 72,000 frames), but the fly
does not reach Cerulean.
- 1 + 2 reach Cerulean at frame 1,972.
### Before and after
Route survey from the live checkpoint, 72,000 frames per arm, `main` `eecd574` vs the branch:
| driver | base | branch |
| --- | --- | --- |
| prefer GO OBJECTIVE, GO WARP | rank 12, 3,290 tiles, 1,500 of 1,500 done on B2F | rank 13 CERULEAN, 3,434 tiles, Cerulean f1973 |
| uniform, seed 7 | rank 12, 3,290, 1,499/1,500 | rank 15 NUGGET BRIDGE, 3,551, Cerulean f3331 |
| uniform, seed 12345 | rank 12, 3,290, 1,499/1,500 | rank 13, 3,436, Cerulean f3041 |
| uniform, default seed | rank 12, 3,290, 1,499/1,500 | rank 13, 3,447, Cerulean f1973 |
ROM test `the_fly_takes_the_ladder_it_stands_on_and_hops_down_to_cerulean_from_mt_moons_far_side`
(`FLY_ROW64_CHECKPOINT`):
- base: 167 done in place, never leaves B2F, **fails**;
- branch: the first `GO OBJECTIVE` goes to B1F, 80 hop frames under a walk on Route 4, Cerulean at
f1972, pushed ledger empty, passes.
### Why nothing inside the fly broke it, and the general guarantee
The in-place ring wrote no ledger. `Done` records nothing, and every ledger with a window was
empty after a restore anyway. The per-macro form of 12.2's rule had no case for a warp underfoot.
Commit 3 makes the rule structural for every way out.
Rows 58, 59 and 61 were rings in which each macro crossed a door, so no effect-based rule sees
them. A repetition budget keyed on the fly's own starts was considered and not built. It is a rule
about the choice, not knowledge in a macro, and it would turn a ring into a wait or a wander
without adding the missing fact. Those rings stay guarded outside the fly: the watchdog, the
recovery ladder, and the ROM road tests.
## 2026-09-29, row 65: the release merge's Mt. Moon door ring, and the Cerulean badge house's yard
### What was found
Not live: both came from the row-64 review, before v0.6.5 shipped (`docs/design/macros.md` 12.29).
- **The merge.** On the staging tree (rows 63, 62 and 64 merged), row 59's ROM test
`the_fly_goes_into_mt_moon_from_the_live_route_4_checkpoint` crossed Route 4's west doors 34
times against a bound of 25. Any two of the three rows pass (3 to 18).
- **The yard.** The row-64 route survey, seed 7: `GO OUT` in the Cerulean badge house took its back
door onto Cerulean (9, 9). That is the door tile of a closed yard of 33 tiles. The pad stayed empty
from f40,753 to the end of the run, about 32,000 frames.
### Reproduction
- Row 59's test on the staging tree, traced: arrive on 1F's mouth (14, 35), `GO OUT` or `GO HEAL`
out, arrive on Route 4 (18, 6), `GO ROUTE` or `GO OBJECTIVE` back in. Each leg takes 70 to 80
frames, and there were 17 round trips. `GO HEAL` walks a hurt fly back to the mouth from deep in
the cave. `GO OUT`'s tier-3 fallback deals the mouth itself, because on 1F Route 4 is visited and
not toward the rung. The test's stub rotation was swept over eight offsets on the staging tree:
24 to 44 crossings, three of the eight over the bound. The count depends on where the rotation
stands when the fly arrives, and that is why the pairs passed.
- The yard came back on the staging tree with seed 99 (`FLY_PROBE_CATCH=route FLY_PROBE_RNG=99`
from `FLY_ROW64_CHECKPOINT`). It was saved at f31178, when the fly stood on the door, as
`survey-rank15-row65-yard.checkpoint` (`FLY_ROW65_YARD_CHECKPOINT`, not committed). The
per-frame trace of an underfoot fallback that used row 64's step-off shows the fly stepping
left and back right onto (9, 9). No warp fires, because the tile is no door tile and a sideways
step has no carpet in front.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 65 | `GO OUT`'s "a room has to be leavable" fallback deals the way back out of a cave floor whose road on is a ladder, one step from the arrival tile. Route 4's side walks straight back in | Mt. Moon 1F's mouth. `GO HEAL` (row 62) brings a hurt fly back to it | `a_floor_whose_way_on_is_a_passage_deals_no_go_out_back_the_way_it_came`, row 59's ROM test on the merged tree | **fixed**: no tier-3 `GO OUT` while an unrested passage leads toward the objective |
| 65b | the exit walks set a step-fired door underfoot aside while any other exit is listed, reachable or not | a closed yard whose one door the fly stands on | `a_door_underfoot_is_taken_when_no_other_way_out_can_be_walked_to`, `row65_the_fly_leaves_the_cerulean_badge_houses_back_yard` | **fixed**: fall back on it once every listed goal has failed the route search |
| 65c | a warp whose own tile is no door fires only through `ExtraWarpCheck`. On the OVERWORLD tileset that needs a warp carpet in front, so row 64's sideways step-off does nothing | the badge house's back door | `a_door_underfoot_that_fires_on_a_bump_is_bumped_and_not_stepped_off`, `a_warp_carpet_in_front_is_marked_where_extra_warp_check_reads_it` | **fixed**: the grid marks carpets on the maps whose check reads them. A walk takes a warp underfoot by bumping toward one when it can |
| 65d | Cerulean was one node while its ground is two pieces. The badge house was off the graph, so its two doors were one door to `GO OUT`, the nearest | the house entered by either door | `cerulean_is_a_town_and_a_yard_and_the_badge_houses_back_door_is_the_yards` | **fixed**: the house on `LINKS`, and the yard as a `SPLIT` piece |
| 65e | on a split map, the other pieces' doors and edges are candidates. Each `no route` refusal from the small piece rests that exit for the whole map | out of the yard, the town's exits resting: an empty pad outside the front door for the rest of the window (survey, seed 3) | `a_way_out_on_another_piece_of_a_split_map_is_not_a_way_out_of_this_one` | **fixed**: `path::exits` keeps the fly's own piece. A door no piece lists is not claimed |
| 65f | the 12.28 guarantee read the tile the walk settled on, so a same-map teleport would read as a way out that did not fire | the Saffron Gym's pads, Silph Co. (not reached) | `a_same_map_teleport_is_somewhere_the_way_out_took_the_fly` | **fixed**: `blocked` only while the fly still stands where it settled |
| 65g | the frontier's exhausted mark is per map, so a fly that has covered the yard marks all of Cerulean | the yard, after the fly has stood on all of it | -- | **left, named**: the yard is now reached only when the objective has no route through the front door, and a restart clears the mark |
| 65h | a hurt fly on 1F's mouth has `GO HEAL` out, and on Route 4 has `GO HEAL` and the cave side by side | row 62's service while the party is below full | -- | **left, the fly's**: both lead somewhere real (row 62 round 2, the same tug) |
### Before and after
Row 59's ROM test on the stub rotation, over eight rotation offsets (0, 5, 11, 17, 23, 29, 37, 41):
| tree | crossings | pass |
| --- | --- | --- |
| staging `release/v0.6.5` `19d295d` | 34 28 24 24 44 24 24 24 | 5 of 8 |
| row 65, road rule off (piece filter on) | 10 19 19 23 21 25 19 27 | 6 of 8 |
| row 65, piece filter off (road rule on) | 4 4 18 13 6 4 8 8 | 8 of 8 |
| row 65 | 2 4 4 4 4 4 7 5 | 8 of 8 |
At offset 0, which is the test as it ships, the result is 34 before and 2 after. Every run reached
Mt. Moon.
The same checkpoint on the uniform route survey (72,000 frames, seeds 7, 11, 12345, 99) gives base
20, 8, 19, 20 against branch 14, 16, 5, 6. The branch's remaining crossings are row 65h.
`row65_the_fly_leaves_the_cerulean_badge_houses_back_yard` (`FLY_ROW65_YARD_CHECKPOINT`, 24,000
frames, stub rotation):
- staging: never leaves the yard, with an empty pad for 21,448 frames running. **Fails.**
- branch: in the town at f266, then the gym, Pallet after a whiteout and on. The pad is never empty
in the yard. **Passes.**
Each of 65b through 65e alone lets this rotation out of the yard, so the ROM test does not separate
them; the unit mutants do. The route survey from the yard checkpoint (six seeds, 36,000 frames)
gives these results:
- **staging**: every seed is back on the door by f2,560, through the house and out of its back door
again, with an empty pad from there to the end of the run.
- **65b and 65c, no split**: a house-and-yard door ring, `GO ROUTE` bumping in and `GO OUT` taking
the back door out, hundreds of times.
- **65b to 65d**: out, but seed 3 then stands outside the front door with an empty pad for the rest
of the window (65e).
- **branch**: all six leave with no empty pad, and three win the Cascade Badge.

View file

@ -193,8 +193,6 @@ ssh the host pct exec <release-ctid> -- curl -s 127.0.0.1:7410/metrics | grep fl
| Repeating `FATAL:` + `transport_limit` for more than ~10 min | Something else is holding this account's websocket transports (a second bridge, a dev box, a stale `tools/mock-twitch.sh`) | Find and stop the other client. `GET https://api.twitch.tv/helix/eventsub/subscriptions` with the broadcaster token lists them; delete the strays. |
| Repeating `FATAL:` + `create failure ... missing scope` | The token lost a scope (re-authorized with the wrong `--role`, or Twitch revoked it) | Re-run `tools/authorize.mts` — see "Rotate the bot token" below. The bridge will NOT recover from this on its own; restarting cannot add a scope. |
| Repeating `FATAL:` + `revoked (authorization_revoked)` | The channel or the user revoked the app | Re-authorize. Same as above. |
| Repeating `FATAL: Twitch refused to refresh the <role> token ... (HTTP 400 "Invalid refresh token")` at startup | That role's refresh token is revoked or invalid (password change, app disconnected, re-authorized elsewhere) | Re-authorize that `--role` — "Rotate the bot token" below. Restarting cannot help; systemd keeps retrying every 15 s with one refresh request per role until the file is fixed. |
| `the stored <role> access token has expired; refreshing it` or `rejected the stored <role> access token (401); refreshing it once`, then a normal start | The bridge was down longer than an access token lives (~4 h), or Twitch invalidated it early | Nothing: it refreshed and persisted the new token itself. |
| One `FATAL:` then a quiet, `chatSubscriptionHealthy: true` bridge | It healed. | Nothing. Note it in the status log if it was during a stream. |
| `active (running)`, `chatSubscriptionHealthy: false`, and NO `FATAL:` line after more than 2 min | The watchdog itself is not running — an old bundle | Check `/opt/fly/current/bridge/index.js` is from a release that has it, then `systemctl restart flybridge`. |
@ -205,30 +203,13 @@ unit, so chat can never take the fly down.
## Rotate the bot token (flybridge)
Access tokens live about 4 h; refresh tokens until revoked. The bridge refreshes on its own:
at runtime through `RefreshingAuthProvider`, and ON LOAD (`prepareStartupTokens` in
`services/bridge/src/auth.ts`) — a stored access token that has expired, or that Twitch's
validate endpoint rejects with 401, is refreshed with its refresh token before the bridge gives
up, for both roles, and each refreshed token is written back to `/var/lib/flybridge/tokens.json`
under its own role (tmp file + rename, mode 0600), also when the bot and the broadcaster are one
account. So an outage longer than an access token's life no longer needs a hand refresh
(2026-09-28: it used to crash-loop on 401 at `validate`).
Re-authorizing is needed only when the journal says
`flybridge: FATAL: Twitch refused to refresh the <role> token for user <id> (HTTP 400 "Invalid refresh token")`,
or a scope is missing (the table in "Chat dead" above). Then, on the operator box:
1. `npx tsx tools/authorize.mts --role <role> --tokens-file <local copy of tokens.json>`
(`services/bridge`, `docs/design/stage-bridge.md` section B1). It rewrites only that role's
entry and keeps the other.
2. Push the file to the release container as `/var/lib/flybridge/tokens.json`, owned by the
service user, mode 0600 (it is a secret; never in a release artifact or in git).
3. `systemctl restart flybridge` and read the journal for the startup notice line.
Never paste a token or the client secret into a log, a ticket or chat: the bridge itself prints
neither (Twitch errors are logged by status and message only, URLs redacted). The `twitch-app`
credential (client id/secret) only needs rotating if the app itself is compromised; follow the
same `06-secrets.sh` pattern as the stream key.
Not yet applicable until flybridge exists and is wired up (P3, `docs/design/infra.md`
section 7). Once it is: re-run `tools/authorize.mts` (`docs/design/stage-bridge.md`
section B1) on the operator box to get a fresh refresh token, which
`RefreshingAuthProvider`'s `onRefresh` persists to `/var/lib/fly/bridge/tokens.json`
automatically from then on — a one-time manual step, not a recurring one. The
`twitch-app` credential (client id/secret) only needs rotating if the app itself is
compromised; follow the same `06-secrets.sh` pattern as the stream key.
## Restore a checkpoint locally

View file

@ -240,18 +240,6 @@ class RecoveryTests(unittest.TestCase):
with patch.object(recover.subprocess, "run", return_value=recover.subprocess.CompletedProcess([], 1, "12", "")):
self.assertEqual(RESTORABLE_RUNGS(), set())
def test_stuck_time_counts_from_the_last_progress_across_restarts(self):
self.report(at=T0 - 7200, suspected=0, places={"uniqueLocations": 10, "delta": 4})
recover.run(T0 - 7195)
recover.write_json(recover.STATE, dict(json.loads(recover.STATE.read_text()), vetoes=0))
self.confirm(T0)
self.assertEqual(json.loads(recover.NOTICE.read_text())["stuckSeconds"], 7505)
self.assertEqual(json.loads(recover.STATE.read_text())["lastProgressAt"], T0 - 7200)
def test_stuck_time_falls_back_to_the_streak_without_a_progress_mark(self):
self.confirm(T0)
self.assertEqual(json.loads(recover.NOTICE.read_text())["stuckSeconds"], 305 + 600)
def test_history_records_every_step(self):
self.confirm(T0)
lines = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]

View file

@ -2,12 +2,9 @@
Description=Check for repeated macro loops after watchdog probes
[Timer]
# Every minute: a run only reads /run/fly/wd/loop.json unless a step is due, and the ladder's
# state ignores a probe it has already seen. On a 5-minute cadence the timer's phase can sit just
# before each loop probe (live, 2026-09-28: one second), costing ~5 minutes per confirmation.
OnBootSec=2min
OnUnitActiveSec=1min
AccuracySec=5s
OnBootSec=7min
OnUnitActiveSec=5min
AccuracySec=10s
Unit=fly-loop-recover.service
[Install]

View file

@ -2,18 +2,14 @@
* Loads `tokens.json` (written by `tools/authorize.mts`) and builds the `RefreshingAuthProvider`
* with both identities registered (`docs/design/stage-bridge.md` B1): the bot account (chat) and
* the broadcaster account (redemptions, predictions, follows). Persists refreshed tokens back to
* the same file, atomically, 0600 — for BOTH roles, including when they are one account.
*
* On load, a stored access token that has expired, or that Twitch's validate endpoint rejects with
* 401, is refreshed with its refresh token before anything gives up (`prepareStartupTokens`). Only
* a refresh that Twitch itself refuses is fatal, with one line pointing at the runbook.
* the same file, atomically, 0600.
*/
import { readFile } from 'node:fs/promises';
import type { AccessToken, AccessTokenMaybeWithUserId, AccessTokenWithUserId, AuthProvider } from '@twurple/auth';
import { accessTokenIsExpired, getTokenInfo, InvalidTokenError, RefreshingAuthProvider } from '@twurple/auth';
import type { AccessTokenMaybeWithUserId, AccessTokenWithUserId, AuthProvider } from '@twurple/auth';
import { RefreshingAuthProvider } from '@twurple/auth';
import { getTokenInfo } from '@twurple/auth';
import { atomicWriteJson } from './atomic-file';
import type { BridgeConfig } from './config';
import { safeErrorMessage } from './redact';
import { assertRequiredScopes, type GrantedScopes } from './scopes';
/** One stored OAuth token, shaped like `@twurple/auth`'s `AccessToken` plus the user id. */
@ -31,9 +27,6 @@ export interface TokensFile {
broadcaster: StoredToken;
}
export type TokenRole = keyof TokensFile;
const ROLES: readonly TokenRole[] = ['bot', 'broadcaster'];
export async function loadTokensFile(path: string): Promise<TokensFile> {
let raw: string;
try {
@ -55,8 +48,6 @@ export interface AuthSetup {
botAuthProvider: RefreshingAuthProvider;
/** Carries the broadcaster token only: follows, raids, Channel Points. */
broadcasterAuthProvider: RefreshingAuthProvider;
/** Where every refresh, by either role, is persisted; `flush()` waits for the writes. */
tokenStore: TokenStore;
botUserId: string;
broadcasterUserId: string;
/** True when one Twitch account holds both roles — see the comment on `buildAuthProvider`. */
@ -82,7 +73,7 @@ export interface AuthSetup {
* second call silently REPLACED the first. The surviving token was the broadcaster's, which holds
* `channel:bot`/`moderator:read:followers`/`channel:*:redemptions` and none of
* `user:read:chat`/`user:write:chat`/`user:bot`. The startup scope assertion still passed, because
* the startup scope assertion called `getTokenInfo` on each stored token separately and never asked the
* `assertStartupScopes` calls `getTokenInfo` on each stored token separately and never asks the
* provider what it would actually hand out; the failure landed later, on the first chat send and
* on the `channel.chat.message` subscription, as a missing-scope error.
*
@ -92,29 +83,23 @@ export interface AuthSetup {
* is authorized by the token of the user it names.
*/
export function buildAuthProvider(config: Pick<BridgeConfig, 'twitchClientId' | 'twitchClientSecret' | 'tokensFile'>, tokens: TokensFile): AuthSetup {
const tokenStore = new TokenStore(config.tokensFile, tokens);
// The ROLE is fixed per provider, so a refresh is persisted under the role whose provider did
// it. This replaced guessing the role from the refreshed token's scope set, which is all a
// single shared callback could go on when both roles are one account.
const newProvider = (role: TokenRole): RefreshingAuthProvider => {
const newProvider = (): RefreshingAuthProvider => {
const provider = new RefreshingAuthProvider({
clientId: config.twitchClientId,
clientSecret: config.twitchClientSecret,
});
provider.onRefresh((userId, newTokenData) => {
tokenStore.update(role, userId, newTokenData);
});
provider.onRefreshFailure((userId, error) => {
console.error(runtimeRefreshFailureLine(role, userId, error));
void persistRefreshedToken(config.tokensFile, tokens, userId, newTokenData).catch((cause: unknown) => {
console.error(`flybridge: failed to persist refreshed token for ${userId}: ${String(cause)}`);
});
});
return provider;
};
const botAuthProvider = newProvider('bot');
const botAuthProvider = newProvider();
botAuthProvider.addUser(tokens.bot.userId, toAccessToken(tokens.bot), ['chat']);
const broadcasterAuthProvider = newProvider('broadcaster');
const broadcasterAuthProvider = newProvider();
broadcasterAuthProvider.addUser(tokens.broadcaster.userId, toAccessToken(tokens.broadcaster), ['broadcaster']);
const sameAccount = tokens.bot.userId === tokens.broadcaster.userId;
@ -122,7 +107,6 @@ export function buildAuthProvider(config: Pick<BridgeConfig, 'twitchClientId' |
return {
botAuthProvider,
broadcasterAuthProvider,
tokenStore,
botUserId: tokens.bot.userId,
broadcasterUserId: tokens.broadcaster.userId,
sameAccount,
@ -213,7 +197,13 @@ export function createRoleRoutingAuthProvider(options: RoleRoutingAuthProviderOp
};
}
function toAccessToken(token: StoredToken): AccessToken {
function toAccessToken(token: StoredToken): {
accessToken: string;
refreshToken: string | null;
scope: string[];
expiresIn: number | null;
obtainmentTimestamp: number;
} {
return {
accessToken: token.accessToken,
refreshToken: token.refreshToken,
@ -224,246 +214,59 @@ function toAccessToken(token: StoredToken): AccessToken {
}
/**
* The in-memory copy of `tokens.json` and its only writer at runtime.
* Persist a refreshed token back into `tokens.json`.
*
* Every refresh, by either role, lands here keyed by ROLE (never by user id — when both roles are
* one account the id says nothing, and writing the broadcaster token over the `bot` entry would
* destroy the chat scopes on disk). Writes are serialized, and each writes the WHOLE current
* state, so two refreshes that land together (both roles refreshed on load) cannot race each
* other's renames and leave one role's new token unpersisted — the v0.2.3 incident, where only the
* bot role's fresher token reached disk and the next start failed on the broadcaster's.
* The role is identified by the token's SCOPE SET, not by its user id: when both roles are the
* same account (the `<twitch-channel>` case) the id says nothing, and writing the refreshed
* broadcaster token over the `bot` entry would destroy the chat scopes on disk — a corruption that
* survives a restart, unlike the in-memory collision `buildAuthProvider` describes. Scopes are
* preserved exactly across a refresh, so they are a reliable discriminator.
*/
export class TokenStore {
private chain: Promise<void> = Promise.resolve();
private lastError: unknown = null;
constructor(
private readonly path: string,
private readonly tokens: TokensFile,
) {}
/** The current (possibly refreshed) token for a role. */
get(role: TokenRole): StoredToken {
return this.tokens[role];
}
update(role: TokenRole, userId: string, token: AccessToken): void {
this.tokens[role] = {
userId,
accessToken: token.accessToken,
refreshToken: token.refreshToken ?? this.tokens[role].refreshToken,
// twurple turns a refresh response without `scope` into []; never let that wipe the scopes
// the role routing and the startup assertion read from disk.
scope: token.scope.length > 0 ? token.scope : this.tokens[role].scope,
expiresIn: token.expiresIn,
obtainmentTimestamp: token.obtainmentTimestamp,
};
this.chain = this.chain.then(async () => {
try {
await atomicWriteJson(this.path, this.tokens);
} catch (cause) {
this.lastError = cause;
console.error(`flybridge: failed to persist the refreshed ${role} token to ${this.path}: ${safeErrorMessage(cause)}`);
}
});
}
/** Resolves once every queued write has finished; rejects if any of them failed. */
async flush(): Promise<void> {
await this.chain;
if (this.lastError !== null) {
const cause = this.lastError;
this.lastError = null;
throw new Error(`could not persist refreshed tokens to ${this.path}: ${safeErrorMessage(cause)}`);
}
}
}
const REAUTHORIZE_HINT =
'Restarting will not fix this: re-authorize that role with tools/authorize.mts, see ' +
'infra/docs/runbook.md "Rotate the bot token".';
/**
* `@twurple/api-call`'s `HttpStatusCodeError`, recognised by shape: that package is only a
* transitive dependency here, and the esbuild bundle would inline a second copy of it, against
* which `instanceof` never matches the one `@twurple/auth` (external) throws.
*/
interface TwitchHttpError extends Error {
statusCode: number;
body: string;
}
function isTwitchHttpError(error: unknown): error is TwitchHttpError {
return (
error instanceof Error &&
error.name === 'HttpStatusCodeError' &&
typeof (error as Partial<TwitchHttpError>).statusCode === 'number'
);
}
/** Status code and Twitch's own message, never the URL (which carries the secret and the token). */
function describeTwitchError(error: unknown): string {
if (isTwitchHttpError(error)) {
let message = '';
try {
const body = JSON.parse(String(error.body)) as { message?: unknown };
if (typeof body.message === 'string') message = body.message;
} catch {
// not JSON: say nothing more than the status
}
return `HTTP ${String(error.statusCode)}${message ? ` "${message}"` : ''}`;
}
return safeErrorMessage(error);
}
/** Twitch answered the refresh grant itself with a 4xx: the refresh token is dead. */
function isRefreshRefusal(error: unknown): boolean {
return isTwitchHttpError(error) && error.statusCode >= 400 && error.statusCode < 500;
}
function refreshFailureLine(role: TokenRole, userId: string, error: unknown): string {
return (
`flybridge: FATAL: Twitch refused to refresh the ${role} token for user ${userId} ` +
`(${describeTwitchError(error)}): the refresh token is revoked or invalid. ${REAUTHORIZE_HINT}`
);
}
/** What `onRefreshFailure` logs, at startup (before the FATAL line) and at runtime alike. */
function runtimeRefreshFailureLine(role: TokenRole, userId: string, error: unknown): string {
const base = `flybridge: refreshing the ${role} token for user ${userId} failed (${describeTwitchError(error)})`;
return isRefreshRefusal(error)
? `${base}; Twitch calls as ${role} will fail until it is re-authorized (infra/docs/runbook.md "Rotate the bot token")`
: base;
}
/**
* A stored token that could not be brought back to life on load. Its message is the whole log line
* and carries no token, secret or URL, so the entrypoint prints it as-is. `reauthorize` is true
* when Twitch refused the refresh (restarting cannot help); false for a transient failure (network,
* 5xx), which the next start retries.
*/
export class StartupTokenError extends Error {
constructor(
message: string,
readonly reauthorize: boolean,
) {
super(message);
this.name = 'StartupTokenError';
}
}
export interface PrepareStartupTokensOptions {
/** Informational lines; defaults to `console.log`. */
log?: (line: string) => void;
}
/**
* Make both stored tokens usable before the bridge does anything else, and return the scopes
* Twitch reports for each (for `assertRequiredScopes`).
*
* Per role, at most ONE refresh request:
* - expired on disk (obtainmentTimestamp + expiresIn, twurple's one-minute grace) → the role's
* `RefreshingAuthProvider` refreshes it inside `getAccessTokenForUser`, before any validate;
* - otherwise validate it; a 401 → `refreshAccessTokenForUser` once, then validate the new token.
* Every refresh goes through the role's provider, so `onRefresh` persists it under that role, and
* the writes are flushed before this returns. A refresh Twitch refuses (4xx: revoked or invalid
* refresh token) is fatal with a pointer to the runbook; twurple then also caches the failure, so
* nothing in this process asks again. Both roles are attempted before failing, so one start names
* every dead role.
*
* This replaces validating the stored access tokens first, which crash-looped the bridge on 401
* whenever it had been down longer than an access token lives (~4 h), even though both refresh
* tokens were still good (v0.2.3 and 2026-09-28).
*/
export async function prepareStartupTokens(
config: Pick<BridgeConfig, 'twitchClientId'>,
setup: Pick<AuthSetup, 'botAuthProvider' | 'broadcasterAuthProvider' | 'botUserId' | 'broadcasterUserId' | 'tokenStore'>,
options: PrepareStartupTokensOptions = {},
): Promise<GrantedScopes> {
const log = options.log ?? ((line: string) => console.log(line));
const roles = {
bot: { provider: setup.botAuthProvider, userId: setup.botUserId },
broadcaster: { provider: setup.broadcasterAuthProvider, userId: setup.broadcasterUserId },
};
const granted: Partial<GrantedScopes> = {};
const failures: StartupTokenError[] = [];
for (const role of ROLES) {
const { provider, userId } = roles[role];
const fail = (error: unknown, what: string): StartupTokenError =>
isRefreshRefusal(error)
? new StartupTokenError(refreshFailureLine(role, userId, error), true)
: new StartupTokenError(
`flybridge: FATAL: ${what} for the ${role} token (user ${userId}) failed: ${describeTwitchError(error)}`,
false,
);
try {
const expiredOnDisk = accessTokenIsExpired(setup.tokenStore.get(role));
if (expiredOnDisk) log(`flybridge: the stored ${role} access token has expired; refreshing it before validating`);
const stored = await provider.getAccessTokenForUser(userId).catch((error: unknown) => {
throw fail(error, 'refreshing the expired stored token');
});
if (stored === null) throw new StartupTokenError(`flybridge: FATAL: no ${role} token was registered`, false);
// Nothing was spent on validate yet: twurple refreshed an expired token before returning it.
let token: AccessToken = stored;
let info;
try {
info = await getTokenInfo(token.accessToken, config.twitchClientId);
} catch (error) {
if (!(error instanceof InvalidTokenError)) throw fail(error, 'validating');
if (expiredOnDisk) {
// It was refreshed a moment ago and Twitch still says 401: a second refresh would only
// repeat the first.
throw new StartupTokenError(
`flybridge: FATAL: the freshly refreshed ${role} token for user ${userId} was rejected (401). ${REAUTHORIZE_HINT}`,
true,
);
}
log(`flybridge: Twitch rejected the stored ${role} access token (401); refreshing it once`);
token = await provider.refreshAccessTokenForUser(userId).catch((refreshError: unknown) => {
throw fail(refreshError, 'refreshing the rejected token');
});
info = await getTokenInfo(token.accessToken, config.twitchClientId).catch((again: unknown) => {
throw again instanceof InvalidTokenError
? new StartupTokenError(
`flybridge: FATAL: the freshly refreshed ${role} token for user ${userId} was also rejected (401). ${REAUTHORIZE_HINT}`,
true,
)
: fail(again, 'validating the refreshed token');
});
}
granted[role] = info.scopes;
} catch (error) {
if (error instanceof StartupTokenError) failures.push(error);
else throw error;
}
}
// Persist what did refresh even if the other role is dead: its new token is still good.
await setup.tokenStore.flush();
if (failures.length > 0) {
throw new StartupTokenError(
failures.map((f) => f.message).join('\n'),
failures.some((f) => f.reauthorize),
async function persistRefreshedToken(
tokensFilePath: string,
tokens: TokensFile,
userId: string,
newToken: { accessToken: string; refreshToken: string | null; scope: string[]; expiresIn: number | null; obtainmentTimestamp: number },
): Promise<void> {
const key = roleForRefreshedToken(tokens, userId, newToken.scope);
if (!key) {
console.error(
`flybridge: refreshed token for ${userId} matches neither stored role by scope set; not persisting`,
);
return;
}
return granted as GrantedScopes;
tokens[key] = { userId, ...newToken };
await atomicWriteJson(tokensFilePath, tokens);
}
function roleForRefreshedToken(
tokens: TokensFile,
userId: string,
scope: readonly string[],
): keyof TokensFile | null {
const sameSet = (a: readonly string[], b: readonly string[]): boolean =>
a.length === b.length && [...a].sort().join(' ') === [...b].sort().join(' ');
if (sameSet(tokens.bot.scope, scope)) return 'bot';
if (sameSet(tokens.broadcaster.scope, scope)) return 'broadcaster';
// Different accounts: the id is unambiguous, so fall back to it.
if (tokens.bot.userId !== tokens.broadcaster.userId) {
return tokens.bot.userId === userId ? 'bot' : 'broadcaster';
}
return null;
}
/**
* Startup token check (`docs/design/stage-bridge.md` B1): refresh-before-give-up on both stored
* tokens (`prepareStartupTokens`), then refuse to start with a named missing scope rather than
* failing at the first subscription.
* Startup scope assertion via `getTokenInfo` (`docs/design/stage-bridge.md` B1): refuses to
* start with a named missing scope rather than failing at the first subscription.
*/
export async function assertStartupScopes(
config: Pick<BridgeConfig, 'twitchClientId' | 'featureRedemptions' | 'featurePredictions'>,
setup: Parameters<typeof prepareStartupTokens>[1],
options: PrepareStartupTokensOptions = {},
tokens: TokensFile,
): Promise<void> {
const granted = await prepareStartupTokens(config, setup, options);
const [botInfo, broadcasterInfo] = await Promise.all([
getTokenInfo(tokens.bot.accessToken, config.twitchClientId),
getTokenInfo(tokens.broadcaster.accessToken, config.twitchClientId),
]);
const granted: GrantedScopes = { bot: botInfo.scopes, broadcaster: broadcasterInfo.scopes };
assertRequiredScopes(config, granted);
}

View file

@ -40,7 +40,6 @@ import { HealthState, Metrics } from './health';
import type { ExplainerPoster } from './explainer';
import type { OnscreenChat } from './onscreen-chat';
import type { ChatSubscriptionHealth } from './subscription-health';
import { safeErrorMessage } from './redact';
import { isWebsocketTransportLimitError } from './subscription-health';
/** What one created subscription looks like from here: an id, which is all this module uses. */
@ -245,7 +244,7 @@ export function startEventSub(deps: EventSubDeps): EventSubListeners {
connected.set(listener, false);
publishConnected();
deps.metrics.increment('flybridge_eventsub_reconnects_total');
if (error) console.error(`flybridge: EventSub ${which} socket for ${userId} disconnected: ${safeErrorMessage(error)}`);
if (error) console.error(`flybridge: EventSub ${which} socket for ${userId} disconnected: ${error.message}`);
if (carriesChat) {
// twurple marks every subscription for this user dropped and re-creates them on the next
// `session_welcome`. Arm the grace timer here: if the re-create never lands (the 429
@ -281,7 +280,7 @@ export function startEventSub(deps: EventSubDeps): EventSubListeners {
});
listener.onSubscriptionCreateFailure((subscription, error) => {
console.error(`flybridge: EventSub subscription create failure for ${subscription.id}: ${safeErrorMessage(error)}`);
console.error(`flybridge: EventSub subscription create failure for ${subscription.id}: ${error.message}`);
deps.metrics.increment('flybridge_eventsub_subscription_create_failures_total');
if (isWebsocketTransportLimitError(error)) {
deps.metrics.increment('flybridge_eventsub_transport_limit_total');

View file

@ -5,7 +5,7 @@
import { realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { ApiClient } from '@twurple/api';
import { assertStartupScopes, buildAuthProvider, loadTokensFile, StartupTokenError } from './auth';
import { assertStartupScopes, buildAuthProvider, loadTokensFile } from './auth';
import { createSend, TwurpleChatSender } from './chat';
import { loadConfig } from './config';
import { startEventSub } from './eventsub';
@ -23,7 +23,6 @@ import {
RedemptionManager,
TwurpleRedemptionApi,
} from './redemptions';
import { safeErrorText } from './redact';
import { HttpSimClient } from './sim';
const EXPLAINER_TICK_MS = 60_000;
@ -32,11 +31,7 @@ const SUGAR_REWARD_TITLE = 'Sugar';
async function main(): Promise<void> {
const config = loadConfig();
const tokens = await loadTokensFile(config.tokensFile);
const auth = buildAuthProvider(config, tokens);
// Refreshes an expired or 401-rejected stored token (either role) BEFORE giving up, persists
// it, then asserts scopes. Validating first crash-looped the bridge after any outage longer
// than an access token's ~4 h life (src/auth.ts, `prepareStartupTokens`).
await assertStartupScopes(config, auth);
await assertStartupScopes(config, tokens);
const {
botAuthProvider,
@ -45,7 +40,7 @@ async function main(): Promise<void> {
broadcasterUserId,
sameAccount,
sharedEventSubAuthProvider,
} = auth;
} = buildAuthProvider(config, tokens);
// One client per identity. See `buildAuthProvider` in src/auth.ts: a single provider holding both
// tokens loses one of them whenever the two roles are the same Twitch account.
const botApiClient = new ApiClient({ authProvider: botAuthProvider });
@ -255,10 +250,7 @@ const isMainModule = (() => {
if (isMainModule) {
main().catch((error: unknown) => {
// A StartupTokenError's message is the whole, secret-free line (and names the runbook step).
// Anything else may be a twurple HttpStatusCodeError, whose message carries the request URL —
// for the refresh grant that is the client secret and refresh token — so it is redacted.
console.error(error instanceof StartupTokenError ? error.message : safeErrorText(error));
console.error(error);
process.exit(1);
});
}

View file

@ -1,27 +0,0 @@
/**
* Keeps OAuth secrets out of the journal.
*
* `@twurple/api-call`'s `HttpStatusCodeError` puts the FULL request URL, query string included, in
* its message — and twurple sends the refresh grant as a query string, so a failed refresh throws
* an error whose message carries `client_secret=` and `refresh_token=` in clear. Anything that
* prints a Twitch error (the entrypoint's last-resort handler, the EventSub failure lines, a failed
* token persist) goes through here first.
*/
import { inspect } from 'node:util';
const SECRET_PARAMS = /\b(client_secret|refresh_token|access_token|code|token)=([^&\s"']+)/g;
const AUTH_HEADER = /\b(OAuth|Bearer)\s+[A-Za-z0-9._~+/-]{8,}/g;
export function redactSecrets(text: string): string {
return text.replace(SECRET_PARAMS, '$1=<redacted>').replace(AUTH_HEADER, '$1 <redacted>');
}
/** One printable, secret-free description of anything thrown (stack and `cause` chain included). */
export function safeErrorText(error: unknown): string {
return redactSecrets(error instanceof Error ? inspect(error) : String(error));
}
/** Like `safeErrorText`, but only the message: for one-line log entries. */
export function safeErrorMessage(error: unknown): string {
return redactSecrets(error instanceof Error ? error.message : String(error));
}

View file

@ -1,339 +0,0 @@
/**
* Refresh-before-give-up on load (`prepareStartupTokens` / `assertStartupScopes` in
* `src/auth.ts`), against a mock of Twitch's two OAuth endpoints (`/oauth2/validate`,
* `/oauth2/token` refresh grant) installed as `globalThis.fetch`, which is what
* `@twurple/api-call` calls.
*
* The incident: the bridge was down longer than an access token lives (~4 h), both stored access
* tokens expired, and the next start validated them first, got 401 and crash-looped under
* Restart=always — with both refresh tokens still good.
*/
import assert from 'node:assert/strict';
import { mkdtemp, readdir, readFile, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import {
assertStartupScopes,
buildAuthProvider,
loadTokensFile,
prepareStartupTokens,
StartupTokenError,
type StoredToken,
type TokensFile,
} from '../src/auth';
const CLIENT_ID = 'test-client-id';
const CLIENT_SECRET = 'test-client-secret-DO-NOT-LOG';
const BOT_SCOPES = ['user:read:chat', 'user:write:chat', 'user:bot'];
const BROADCASTER_SCOPES = ['channel:bot', 'moderator:read:followers'];
const FOUR_HOURS_S = 14_400;
interface MockTwitch {
validateCalls: string[];
refreshCalls: string[];
restore: () => void;
}
/**
* Twitch's id endpoints. `valid` maps a live access token to its owner and scopes; `refreshable`
* maps a live refresh token to the same. A refresh mints `<refreshToken>-fresh-<n>` and makes it
* valid; an unknown refresh token gets Twitch's real answer, 400 "Invalid refresh token".
*/
function mockTwitch(
valid: Map<string, { userId: string; scopes: string[] }>,
refreshable: Map<string, { userId: string; scopes: string[] }>,
): MockTwitch {
const original = globalThis.fetch;
const validateCalls: string[] = [];
const refreshCalls: string[] = [];
let minted = 0;
const json = (status: number, body: unknown): Response =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
assert.equal(url.host, 'id.twitch.tv', `unexpected request to ${url.host}`);
if (url.pathname === '/oauth2/validate') {
const auth = new Headers(init?.headers).get('Authorization') ?? '';
const token = auth.replace(/^OAuth /, '');
validateCalls.push(token);
const owner = valid.get(token);
if (!owner) return json(401, { status: 401, message: 'invalid access token' });
return json(200, {
client_id: CLIENT_ID,
login: 'someone',
user_id: owner.userId,
scopes: owner.scopes,
expires_in: FOUR_HOURS_S,
});
}
if (url.pathname === '/oauth2/token' && url.searchParams.get('grant_type') === 'refresh_token') {
assert.equal(url.searchParams.get('client_secret'), CLIENT_SECRET);
const refreshToken = url.searchParams.get('refresh_token') ?? '';
refreshCalls.push(refreshToken);
const owner = refreshable.get(refreshToken);
if (!owner) return json(400, { status: 400, message: 'Invalid refresh token' });
minted += 1;
const accessToken = `${refreshToken}-fresh-${String(minted)}`;
valid.set(accessToken, owner);
return json(200, {
access_token: accessToken,
refresh_token: refreshToken,
scope: owner.scopes,
expires_in: FOUR_HOURS_S,
token_type: 'bearer',
});
}
throw new Error(`mock Twitch: unhandled ${url.pathname}`);
}) as typeof fetch;
return { validateCalls, refreshCalls, restore: () => (globalThis.fetch = original) };
}
function stored(userId: string, name: string, scope: string[], obtainedMsAgo: number): StoredToken {
return {
userId,
accessToken: `access-${name}`,
refreshToken: `refresh-${name}`,
scope,
expiresIn: FOUR_HOURS_S,
obtainmentTimestamp: Date.now() - obtainedMsAgo,
};
}
const EXPIRED = 6 * 3600_000; // down for six hours
const FRESH = 60_000;
async function writeTokens(tokens: TokensFile): Promise<string> {
const dir = await mkdtemp(join(tmpdir(), 'flybridge-refresh-'));
const path = join(dir, 'tokens.json');
await writeFile(path, JSON.stringify(tokens), { mode: 0o600 });
return path;
}
const CONFIG_BASE = {
twitchClientId: CLIENT_ID,
twitchClientSecret: CLIENT_SECRET,
featureRedemptions: false,
featurePredictions: false,
};
async function start(path: string, lines: string[] = []) {
const config = { ...CONFIG_BASE, tokensFile: path };
const setup = buildAuthProvider(config, await loadTokensFile(path));
await assertStartupScopes(config, setup, { log: (line) => lines.push(line) });
return setup;
}
void test('expired-on-disk tokens for both roles are refreshed (not validated first) and the bridge starts', async () => {
const path = await writeTokens({
bot: stored('111', 'bot', BOT_SCOPES, EXPIRED),
broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, EXPIRED),
});
const twitch = mockTwitch(
new Map(), // neither stored access token is valid any more
new Map([
['refresh-bot', { userId: '111', scopes: BOT_SCOPES }],
['refresh-caster', { userId: '222', scopes: BROADCASTER_SCOPES }],
]),
);
try {
const lines: string[] = [];
await start(path, lines);
assert.deepEqual(twitch.refreshCalls, ['refresh-bot', 'refresh-caster']);
// Only the refreshed tokens were ever sent to validate: no 401 was spent on the stale ones.
assert.deepEqual(twitch.validateCalls, ['refresh-bot-fresh-1', 'refresh-caster-fresh-2']);
assert.ok(lines.some((l) => l.includes('stored bot access token has expired')));
const onDisk = JSON.parse(await readFile(path, 'utf8')) as TokensFile;
assert.equal(onDisk.bot.accessToken, 'refresh-bot-fresh-1');
assert.equal(onDisk.broadcaster.accessToken, 'refresh-caster-fresh-2');
assert.ok(Date.now() - onDisk.bot.obtainmentTimestamp < 60_000);
} finally {
twitch.restore();
}
});
void test('a 401 on validate of an unexpired token triggers exactly one refresh, then succeeds', async () => {
const path = await writeTokens({
bot: stored('111', 'bot', BOT_SCOPES, FRESH),
broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, FRESH),
});
const twitch = mockTwitch(
// The broadcaster's access token is fine; the bot's was invalidated early (e.g. superseded).
new Map([['access-caster', { userId: '222', scopes: BROADCASTER_SCOPES }]]),
new Map([
['refresh-bot', { userId: '111', scopes: BOT_SCOPES }],
['refresh-caster', { userId: '222', scopes: BROADCASTER_SCOPES }],
]),
);
try {
const lines: string[] = [];
await start(path, lines);
assert.deepEqual(twitch.refreshCalls, ['refresh-bot'], 'one refresh, for the rejected role only');
assert.deepEqual(twitch.validateCalls, ['access-bot', 'refresh-bot-fresh-1', 'access-caster']);
assert.ok(lines.some((l) => l.includes('rejected the stored bot access token (401)')));
const onDisk = JSON.parse(await readFile(path, 'utf8')) as TokensFile;
assert.equal(onDisk.bot.accessToken, 'refresh-bot-fresh-1');
assert.equal(onDisk.broadcaster.accessToken, 'access-caster', 'untouched role is left as it was');
} finally {
twitch.restore();
}
});
void test('a revoked refresh token is fatal with the runbook pointer, one attempt, and no secret in the message', async () => {
const path = await writeTokens({
bot: stored('111', 'bot', BOT_SCOPES, EXPIRED),
broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, EXPIRED),
});
const twitch = mockTwitch(
new Map(),
// Broadcaster's refresh token still works; the bot's was revoked.
new Map([['refresh-caster', { userId: '222', scopes: BROADCASTER_SCOPES }]]),
);
const errors: string[] = [];
const originalError = console.error;
console.error = (...args: unknown[]) => errors.push(args.map(String).join(' '));
try {
const error = await start(path).then(
() => assert.fail('startup should have failed'),
(e: unknown) => e,
);
assert.ok(error instanceof StartupTokenError);
assert.equal(error.reauthorize, true);
assert.match(error.message, /FATAL: Twitch refused to refresh the bot token for user 111 \(HTTP 400 "Invalid refresh token"\)/);
assert.match(error.message, /tools\/authorize\.mts/);
assert.match(error.message, /infra\/docs\/runbook\.md "Rotate the bot token"/);
assert.doesNotMatch(error.message, /broadcaster token/, 'the healthy role is not blamed');
// No retry storm: one refresh request per role, and nothing validated with the dead bot token.
assert.deepEqual(twitch.refreshCalls, ['refresh-bot', 'refresh-caster']);
assert.deepEqual(twitch.validateCalls, ['refresh-caster-fresh-1']);
// Nothing printed may carry a token or the client secret.
for (const text of [error.message, ...errors]) {
assert.doesNotMatch(text, /DO-NOT-LOG|refresh-bot|refresh-caster|client_secret=(?!<redacted>)/, text);
}
// The role that did refresh is still persisted.
const onDisk = JSON.parse(await readFile(path, 'utf8')) as TokensFile;
assert.equal(onDisk.broadcaster.accessToken, 'refresh-caster-fresh-1');
assert.equal(onDisk.bot.accessToken, 'access-bot');
} finally {
console.error = originalError;
twitch.restore();
}
});
void test('a refreshed token that validate still rejects is fatal without a second refresh', async () => {
const path = await writeTokens({
bot: stored('111', 'bot', BOT_SCOPES, FRESH),
broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, FRESH),
});
const valid = new Map([['access-caster', { userId: '222', scopes: BROADCASTER_SCOPES }]]);
const twitch = mockTwitch(valid, new Map([['refresh-bot', { userId: '111', scopes: BOT_SCOPES }]]));
// Make every freshly minted bot token invalid as soon as it is minted.
const mintingFetch = globalThis.fetch;
globalThis.fetch = (async (...args: Parameters<typeof fetch>) => {
const response = await mintingFetch(...args);
for (const key of [...valid.keys()]) if (key.startsWith('refresh-bot-fresh')) valid.delete(key);
return response;
}) as typeof fetch;
try {
const error = await start(path).then(
() => assert.fail('startup should have failed'),
(e: unknown) => e,
);
assert.ok(error instanceof StartupTokenError);
assert.match(error.message, /freshly refreshed bot token .* rejected \(401\)/);
assert.deepEqual(twitch.refreshCalls, ['refresh-bot']);
} finally {
twitch.restore();
}
});
void test('both roles on ONE account: each refresh is persisted under its own role, scopes intact', async () => {
const path = await writeTokens({
bot: stored('333', 'bot', BOT_SCOPES, EXPIRED),
broadcaster: stored('333', 'caster', BROADCASTER_SCOPES, EXPIRED),
});
const twitch = mockTwitch(
new Map(),
new Map([
['refresh-bot', { userId: '333', scopes: BOT_SCOPES }],
['refresh-caster', { userId: '333', scopes: BROADCASTER_SCOPES }],
]),
);
try {
const setup = await start(path);
assert.equal(setup.sameAccount, true);
const onDisk = JSON.parse(await readFile(path, 'utf8')) as TokensFile;
assert.equal(onDisk.bot.userId, '333');
assert.equal(onDisk.broadcaster.userId, '333');
assert.equal(onDisk.bot.accessToken, 'refresh-bot-fresh-1');
assert.deepEqual(onDisk.bot.scope, BOT_SCOPES);
assert.equal(onDisk.broadcaster.accessToken, 'refresh-caster-fresh-2');
assert.deepEqual(onDisk.broadcaster.scope, BROADCASTER_SCOPES);
// A later runtime refresh of one role must not
// clobber the other role's entry.
twitch.refreshCalls.length = 0;
await setup.broadcasterAuthProvider.refreshAccessTokenForUser('333');
await setup.tokenStore.flush();
const after = JSON.parse(await readFile(path, 'utf8')) as TokensFile;
assert.equal(after.bot.accessToken, 'refresh-bot-fresh-1');
assert.equal(after.broadcaster.accessToken, 'refresh-caster-fresh-3');
} finally {
twitch.restore();
}
});
void test('tokens.json is rewritten atomically at mode 0600 with no temp file left behind', async () => {
const path = await writeTokens({
bot: stored('111', 'bot', BOT_SCOPES, EXPIRED),
broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, EXPIRED),
});
const before = await stat(path);
const twitch = mockTwitch(
new Map(),
new Map([
['refresh-bot', { userId: '111', scopes: BOT_SCOPES }],
['refresh-caster', { userId: '222', scopes: BROADCASTER_SCOPES }],
]),
);
try {
await start(path);
const after = await stat(path);
assert.equal(after.mode & 0o777, 0o600);
// A rename puts a new inode in place; an in-place rewrite would keep the old one.
assert.notEqual(after.ino, before.ino);
const dir = join(path, '..');
assert.deepEqual(await readdir(dir), ['tokens.json']);
} finally {
twitch.restore();
}
});
void test('a transient failure (Twitch 5xx on refresh) is fatal for this start but not a re-authorize', async () => {
const path = await writeTokens({
bot: stored('111', 'bot', BOT_SCOPES, EXPIRED),
broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, FRESH),
});
const original = globalThis.fetch;
globalThis.fetch = (async () =>
new Response('upstream sad', { status: 503, headers: { 'Content-Type': 'text/plain' } })) as typeof fetch;
try {
const config = { ...CONFIG_BASE, tokensFile: path };
const setup = buildAuthProvider(config, await loadTokensFile(path));
const error = await prepareStartupTokens(config, setup, { log: () => undefined }).then(
() => assert.fail('should fail'),
(e: unknown) => e,
);
assert.ok(error instanceof StartupTokenError);
assert.equal(error.reauthorize, false);
assert.match(error.message, /HTTP 503/);
assert.doesNotMatch(error.message, /DO-NOT-LOG|refresh-bot/);
} finally {
globalThis.fetch = original;
}
});

View file

@ -1,22 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { redactSecrets, safeErrorText } from '../src/redact';
void test('redactSecrets strips OAuth secrets from a twurple HttpStatusCodeError-shaped message', () => {
const message =
'Encountered HTTP status code 400: Bad Request\n\nURL: token?grant_type=refresh_token&client_id=abc' +
'&client_secret=s3cr3t&refresh_token=r3fr3sh\nMethod: POST';
const out = redactSecrets(message);
assert.doesNotMatch(out, /s3cr3t|r3fr3sh/);
assert.match(out, /client_secret=<redacted>&refresh_token=<redacted>/);
assert.match(out, /client_id=abc/, 'the client id is not a secret and stays readable');
});
void test('redactSecrets strips Authorization header values', () => {
assert.equal(redactSecrets('Authorization: OAuth abcdef0123456789'), 'Authorization: OAuth <redacted>');
});
void test('safeErrorText redacts the cause chain too', () => {
const error = new Error('outer', { cause: new Error('URL: token?client_secret=s3cr3t') });
assert.doesNotMatch(safeErrorText(error), /s3cr3t/);
});

View file

@ -430,35 +430,6 @@ 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);

View file

@ -56,10 +56,6 @@ pub mod item {
pub const POTION: u8 = 20;
/// `$1e`.
pub const REPEL: u8 = 30;
/// `$46`. The Viridian clerk's parcel for Oak: while the bag holds it, that counter has
/// nothing to sell (`scripts/ViridianMart.asm` keeps the parcel's text table until
/// `EVENT_OAK_GOT_PARCEL`).
pub const OAKS_PARCEL: u8 = 0x46;
}
/// Mart prices at the pinned pokered commit, for section 3's "if money allows".
@ -392,26 +388,6 @@ 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

View file

@ -25,7 +25,7 @@ use crate::adapter::MemoryReader;
use crate::emulator::buttons;
use super::cartridge::{
ExitId, FACINGS, ListKind, MacroState, TalkTarget, TargetKey, Tile, battle_entry, button, item,
FACINGS, ListKind, MacroState, TalkTarget, TargetKey, Tile, battle_entry, button, item,
opposite,
};
use super::geography::Amenity;
@ -120,16 +120,6 @@ const SETTLE_FRAMES: u32 = 20;
/// because a battle spends whole seconds animating, and a wait presses nothing.
const CURSOR_WAIT: u32 = 180;
/// Frames a purchase waits for the mart's YES/NO box before it gives up ([`Step::Prompt`]).
///
/// The price line is two dozen characters either side of one press, at the cartridge's text
/// speed; six brain seconds is twice what the Pewter counter took.
const PROMPT_WAIT: u32 = 360;
/// Frames between the presses [`Step::Prompt`] makes while the price line is up: one
/// [`PRESS_HOLD`] of A, then released, so the press is a new one each time.
const PROMPT_PULSE: u32 = 40;
/// Extra presses a cursor navigation may spend beyond twice the length of its list, to cover a
/// press the game swallows while a menu is still drawing.
const CURSOR_SLACK: u8 = 6;
@ -353,23 +343,6 @@ enum Step {
/// the presses happened and the conversation may simply have been about something else -- so
/// it reports `Next` and the close press still happens.
Rested { waited: u32 },
/// Advance the price line until the mart's YES/NO box is drawn ([`MacroState::yes_no_prompt`]),
/// then move on to the press that answers it; `Blocked` if the box never comes.
///
/// A purchase's last answer (row 62). After the quantity the mart prints "POKe BALL? / That
/// will be" and **waits for a press** -- the line is a `cont`, with the blinking arrow -- and
/// only after it prints "200. OK?" and draws the box. The script's one blind A after a settle
/// was that press, so the box came up after the macro had reported `done`: 55 `BUY BALL`
/// starts on the cartridge, 55 `done`, the wallet at 1,606 throughout, and the box left to
/// whatever the pad dealt next. So this pulses A every [`PROMPT_PULSE`] frames while no box
/// is drawn -- a press on a line still printing only prints it faster -- and reads the box
/// the way `HEAL` reads the party. `before` is the wallet when the purchase began: if it has
/// dropped, a pulse already answered the box and the purchase is rung up.
Prompt { waited: u32, before: u32 },
/// Press nothing until the wallet reads less than `before`, which is the purchase rung up;
/// `Blocked` if it never does. The cartridge adds the item and takes the money a few frames
/// after the YES, so a purchase is `done` when the wallet says so and not when the press is.
Paid { waited: u32, before: u32 },
}
/// Progress through one A* walk.
@ -449,36 +422,6 @@ struct Walk {
/// without this the same tile is aimed at once per hold for ever, which is what a ledge, a
/// tile-pair rule or a person on the far side of it looks like.
stalled: bool,
/// The ledge hop the held press is making, as the tile it was pressed from and its direction.
///
/// Row 64. The route search takes a ledge the one way the cartridge does
/// ([`path::route_avoiding`]), and the cartridge's way is to take the joypad: `HandleLedges`
/// sets `wJoyIgnore` and simulates the two tiles of the jump, so the scene reads
/// [`Scene::Unknown`] for the length of it. Without this the walk ended on that scene change
/// like any other, `scripted` and all, and [`MacroMachine::observe_push`] wrote a hop the walk
/// asked for as a push-back: the tile walled for the session and the target rested for the
/// window. Set when the press begins, cleared when the fly has moved.
hop: Option<(Tile, Facing)>,
/// The warp this walk began standing on, while it has not yet stepped off it.
///
/// Row 64, Mt. Moon, two days. A ladder, a cave mouth, a staircase -- every warp whose exit
/// has no press -- fires at the end of a *step onto it* (`CheckWarpsNoCollision`, run after a
/// step completes), and nothing else fires it: a press into the wall beside it warps only at
/// a map's edge (`ExtraWarpCheck`, `IsPlayerFacingEdgeOfMap` off the overworld). A fly that
/// arrived on B2F's exit ladder by coming down it is standing on the one way on, and
/// `GO OBJECTIVE` and `GO WARP` both aimed at the tile underfoot, settled on it, and reported
/// `done` without a press -- section 12.2's trap, with no ledger in it for a restart to clear.
/// So a walk that starts on its own step-fired warp takes it the way the cartridge does: one
/// step onto free ground beside it, and the step back.
step_off: Option<Tile>,
/// Whether the walk settled on a way out and the map did not change: the exit did not take it.
///
/// The general half of row 64 (section 12.2's rule, held by the executor instead of by each
/// macro): a way out's whole promise is a different map, so a `Settle` arrival on one that
/// leaves the fly on this map has not arrived anywhere. It ends `Blocked` -- the exit rests in
/// the window -- and, when the fly never left the tile it pressed from,
/// [`MacroMachine::unfired_here`] keeps the button off this tile for the window too.
unfired: bool,
}
/// Progress through one cursor navigation.
@ -911,13 +854,6 @@ impl MacroMachine {
// ended every walk north this way, `Done` with nothing recorded, once per hold for eight
// hours.
let now = class(state.scene());
// A ledge the walk pressed into is the cartridge carrying the fly where the walk asked it
// to go, not the world moving on under it ([`Walk::hop`]): the walk waits it out and
// re-plans from the landing.
if now != started_in && !spans.contains(&now) && self.hopping(state) {
self.active.as_mut()?.frames += 1;
return Some(buttons::NONE);
}
if now != started_in && !spans.contains(&now) {
let pushed = state.scripted() || self.moved_away(state);
let at = pushed.then(|| state.player()).flatten();
@ -944,9 +880,6 @@ impl MacroMachine {
Decided::End(outcome) => {
let pushed = state.scripted();
let at = pushed.then(|| state.player()).flatten();
if outcome == MacroAbort::Blocked {
self.unfired_here(state);
}
return self.finish(outcome, true, pushed, at);
}
Decided::Pop => {
@ -1059,44 +992,6 @@ impl MacroMachine {
self.pending_push_calm = 0;
}
/// A way out that did not fire, pressed from the tile the fly is still standing on: the button
/// is not dealt again from here for the window (row 57's ledger, [`Walk::unfired`]).
///
/// The blocked entry alone rests the exit for every list but a last resort, and a last resort
/// ignores the blocked ledger by design -- so on a map with nothing else on it the same button
/// would be dealt at the same dead exit once per hold, which is the ring this is here to end.
/// A pad with nothing left that can run is empty and the fly waits, section 13.1's answer.
fn unfired_here(&mut self, state: &mut dyn MacroState) {
let Some(active) = self.active.as_ref() else { return };
let Some(Step::Walk(walk)) = active.plan.front() else { return };
if !walk.unfired {
return;
}
let Some(player) = state.player() else { return };
let here = Tile::new(player.x, player.y);
if player.map == walk.map && active.from == Some(here) {
self.refused_at = Some((player.map, active.kind.slot(), here));
}
}
/// Whether the running walk is mid-hop: it pressed into a ledge ([`Walk::hop`]), the
/// cartridge has the joypad with no text up, and the fly is on the hop's own line -- the tile
/// it pressed from, the ledge, or the landing -- on the walk's own map. A wild battle on the
/// landing is a battle, and ends the walk as a scene change always has.
fn hopping(&self, state: &mut dyn MacroState) -> bool {
let Some(active) = self.active.as_ref() else { return false };
let Some(Step::Walk(walk)) = active.plan.front() else { return false };
let Some((from, facing)) = walk.hop else { return false };
if state.scene() != Scene::Unknown || !state.scripted() || state.text_open() {
return false;
}
let Some(player) = state.player() else { return false };
let at = Tile::new(player.x, player.y);
let over = from.step(facing);
let landing = over.and_then(|tile| tile.step(facing));
player.map == walk.map && (at == from || Some(at) == over || Some(at) == landing)
}
/// Whether the fly is standing somewhere other than where the running macro began.
///
/// The other half of "the game moved the fly": a script can finish its push-back inside the
@ -1567,32 +1462,6 @@ fn advance(step: &mut Step, state: &mut dyn MacroState) -> Progress {
Progress::Hold(buttons::NONE)
}
}
Step::Paid { waited, before } => {
if state.money() < *before {
Progress::Next
} else if *waited >= PROMPT_WAIT {
Progress::Blocked
} else {
*waited += 1;
Progress::Hold(buttons::NONE)
}
}
Step::Prompt { waited, before } => {
if state.money() < *before {
Progress::Finished
} else if state.yes_no_prompt() {
Progress::Next
} else if *waited >= PROMPT_WAIT {
Progress::Blocked
} else {
*waited += 1;
if *waited % PROMPT_PULSE < PRESS_HOLD {
Progress::Hold(buttons::A)
} else {
Progress::Hold(buttons::NONE)
}
}
}
}
}
@ -1638,13 +1507,6 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress {
walk.held += 1;
if walk.held <= SETTLE_FRAMES {
Progress::Hold(buttons::NONE)
} else if settled_on_a_way_out(walk) && walk.arrived == Some(here) {
// Still on this map (the top of this function ends the walk on any other),
// and still on the tile it settled on: the way out did not take the fly
// anywhere ([`Walk::unfired`]). A warp that moves the fly on its own map --
// the Saffron Gym's pads, Silph Co.'s -- has taken it somewhere (row 65).
walk.unfired = true;
Progress::Blocked
} else {
arrived(walk.continues)
}
@ -1693,12 +1555,10 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress {
if let Some((facing, from)) = walk.holding {
if here != from {
// Moved: this tile is done and the failure run is broken. The plan's head is spent,
// and the next one steps from where the player now stands -- two tiles on, after a
// ledge ([`Walk::hop`]).
// and the next one steps from where the player now stands.
walk.plan.pop_front();
walk.expect = Some(here);
walk.holding = None;
walk.hop = None;
walk.held = 0;
walk.failures = 0;
walk.gap = STEP_GAP;
@ -1718,7 +1578,6 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress {
walk.plan.clear();
walk.expect = None;
walk.holding = None;
walk.hop = None;
walk.held = 0;
walk.gap = STEP_GAP;
walk.failures += 1;
@ -1729,15 +1588,8 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress {
};
}
// Off the warp it began on: from here the way back onto it is an ordinary step, and the
// step is what fires it ([`Walk::step_off`]).
if walk.step_off.is_some_and(|tile| tile != here) {
walk.step_off = None;
}
// Plan, or re-plan.
if walk.step_off.is_none()
&& let Some(goal) = walk.goals.iter().find(|goal| goal.tile == here)
{
if let Some(goal) = walk.goals.iter().find(|goal| goal.tile == here) {
walk.arrival = Some(goal.arrival);
walk.arrived = Some(here);
walk.plan.clear();
@ -1752,11 +1604,7 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress {
// walkable window that has moved with the player, which is the oscillation [`Walk::plan`]
// documents; the plan is only remade when the ground has said something new.
if walk.plan.is_empty() || walk.expect != Some(here) {
let tiles: Vec<Tile> = if walk.step_off.is_some() {
beside(state, here)
} else {
walk.goals.iter().map(|goal| goal.tile).collect()
};
let tiles: Vec<Tile> = walk.goals.iter().map(|goal| goal.tile).collect();
let Some(Route { steps, .. }) = path::route_avoiding(state, &tiles, &walk.refused) else {
return Progress::Blocked;
};
@ -1771,35 +1619,9 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress {
};
walk.holding = Some((first, here));
walk.held = 1;
walk.hop = state
.map_grid()
.is_some_and(|grid| grid.map() == walk.map && grid.hops(here.x, here.y, first))
.then_some((here, first));
Progress::Hold(button(first))
}
/// Whether the goal the walk is settling on is a way out: an exit key, whose promise is a map
/// change. A tile the objective names is not one -- standing on it is the point.
fn settled_on_a_way_out(walk: &Walk) -> bool {
walk.arrived.is_some_and(|tile| {
walk.goals
.iter()
.any(|goal| goal.tile == tile && matches!(goal.key, Some(TargetKey::Exit(_))))
})
}
/// The tiles one step from `here` that are not themselves warps: where a walk standing on a warp
/// it has to fire steps to first ([`Walk::step_off`]). Stepping onto another warp would fire that
/// one instead. Which of them is ground is the route search's answer, as it is for every goal.
fn beside(state: &mut dyn MacroState, here: Tile) -> Vec<Tile> {
let warps: Vec<Tile> = state.warps().iter().map(|warp| Tile::new(warp.x, warp.y)).collect();
FACINGS
.iter()
.filter_map(|facing| here.step(*facing))
.filter(|tile| !warps.contains(tile))
.collect()
}
/// The extra scene classes a macro is allowed to run through ([`Active::spans`]).
///
/// One row, and the empty slice everywhere else. `HEAL` walks in the overworld and finishes in a
@ -1903,22 +1725,6 @@ 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);
@ -1984,31 +1790,18 @@ fn script(
MacroKind::GoWarp => Way::Passage,
_ => Way::Route,
};
let (goals, mut underfoot) = exit_goals(state, way);
let goals = exit_goals(state, way);
unreachable.extend(goal_keys(&goals));
// A last resort that preferred the way toward the objective, and the route search
// cannot reach it: the rest of the last resort, nearest reachable first (row 57).
let mut walked = walk_to(state, goals);
if walked.is_none() {
let rest = super::palette::last_resort_wide(state, way);
underfoot.extend(underfoot_warps(state, &rest));
let wide = goals_of(state, rest);
if !wide.is_empty() {
walked = walk_to(state, wide);
let walked = match walk_to(state, goals) {
Some(walked) => Some(walked),
None => {
let rest = super::palette::last_resort_wide(state, way);
let wide = goals_of(state, rest);
if wide.is_empty() { None } else { walk_to(state, wide) }
}
}
// **The door underfoot, when no other way of this kind can be walked to** (row 65).
// [`goals_of`] sets a step-fired warp underfoot aside while any other exit is listed,
// reachable or not, so a fly standing on the one door out of a closed yard -- the
// Cerulean badge house's back door, whose yard has no other exit -- refused
// `no route` at every other exit and never took the one it stood on: the pad emptied
// for as long as the survey ran. Only here, after every listed goal has failed the
// route search: it is the step off and back on that row 64 taught the walk
// ([`Walk::step_off`]), and the executor's own rule still ends it `blocked` if the
// map does not change.
if walked.is_none() && !underfoot.is_empty() {
walked = walk_to(state, underfoot);
}
};
let (walk, target) = walked?;
aimed = target;
vec![Step::Walk(walk)]
@ -2345,35 +2138,6 @@ fn walk_then(
.or(nearest);
let here = Tile::new(player.x, player.y);
let budget = walk_budget(route.steps.len());
// Standing on the goal already, and the goal is a warp that fires by itself: the arrival
// would settle where the warp has plainly not fired ([`Walk::step_off`]).
let mut step_off = route
.goal
.and_then(|index| goals.get(index))
.filter(|goal| {
route.steps.is_empty()
&& goal.tile == here
&& goal.arrival == Arrival::Settle
&& matches!(goal.key, Some(TargetKey::Exit(ExitId::Warp(_))))
})
.map(|goal| goal.tile);
// ...unless the cartridge takes it by a bump from where the fly stands (row 65): a warp whose
// own tile is no door, with a warp carpet in front one way, fires on a press that way
// (`CheckWarpsCollision`, [`super::state::MapGrid::carpet_press`]) and on no step back onto it
// made any other way. The Cerulean badge house's back door is one: stepped off sideways and
// back on, it did nothing.
let mut goals = goals;
if step_off.is_some()
&& let Some(bump) = state
.map_grid()
.filter(|grid| grid.map() == map)
.and_then(|grid| grid.carpet_press(here.x, here.y))
{
step_off = None;
for goal in goals.iter_mut().filter(|goal| goal.tile == here && goal.arrival == Arrival::Settle) {
goal.arrival = Arrival::Leave(bump);
}
}
Some((
Walk {
goals,
@ -2393,9 +2157,6 @@ fn walk_then(
best_distance: distance,
continues,
stalled: false,
hop: None,
step_off,
unfired: false,
},
target,
))
@ -2429,30 +2190,9 @@ fn one_target(goals: &[Goal]) -> Option<TargetKey> {
/// by itself has plainly not fired, so it is not an exit to walk to — which is the state the fly
/// is in the moment it comes down a staircase and lands on the warp tile. A doormat underfoot is
/// different: its press is the point, so it stays.
///
/// The second list is the step-fired warps underfoot that [`goals_of`] set aside, for the exit
/// script to fall back on when nothing in the first can be walked to (row 65).
fn exit_goals(state: &mut dyn MacroState, way: Way) -> (Vec<Goal>, Vec<Goal>) {
fn exit_goals(state: &mut dyn MacroState, way: Way) -> Vec<Goal> {
let exits = ways(state, way);
let underfoot = underfoot_warps(state, &exits);
(goals_of(state, exits), underfoot)
}
/// The step-fired warps of `exits` the fly is standing on, as goals: what [`goals_of`] sets aside
/// while another exit is listed, for the exit script to fall back on when none of those can be
/// walked to (row 65).
///
/// [`walk_then`] takes it the way the cartridge does from where the fly stands: a bump toward a
/// warp carpet where there is one, row 64's step off and back on otherwise.
fn underfoot_warps(state: &mut dyn MacroState, exits: &[Exit]) -> Vec<Goal> {
let Some(here) = state.player().map(|player| Tile::new(player.x, player.y)) else {
return Vec::new();
};
exits
.iter()
.filter(|exit| exit.tile == here && exit.press.is_none() && matches!(exit.id, ExitId::Warp(_)))
.map(|exit| Goal { tile: exit.tile, arrival: Arrival::Settle, key: Some(TargetKey::Exit(exit.id)) })
.collect()
goals_of(state, exits)
}
/// [`exit_goals`] over a list of exits the caller already has.
@ -2544,7 +2284,6 @@ fn approach(state: &mut dyn MacroState, targets: &[(Tile, TalkTarget)]) -> Vec<G
/// script works both from a freshly opened counter and from the buy list.
fn shop_plan(state: &mut dyn MacroState, want: u8) -> Option<Vec<Step>> {
let index = stock_index(state, want)?;
let before = state.money();
let mut steps = Vec::new();
if shop_screen(state)? == ShopScreen::BuySellQuit {
// BUY is the counter menu's first entry.
@ -2553,12 +2292,10 @@ fn shop_plan(state: &mut dyn MacroState, want: u8) -> Option<Vec<Step>> {
}
steps.push(cursor(index, true));
steps.push(settle());
// The quantity prompt opens on one, and the price confirmation opens on YES -- once it is
// drawn, which is after the price has finished printing (row 62).
// The quantity prompt opens on one, and the price confirmation opens on YES.
steps.push(press(buttons::A));
steps.push(Step::Prompt { waited: 0, before });
steps.push(settle());
steps.push(press(buttons::A));
steps.push(Step::Paid { waited: 0, before });
Some(steps)
}

View file

@ -160,19 +160,9 @@ const LINKS: &[(u8, u8)] = &[
(maps::MT_MOON_1F, maps::MT_MOON_B1F),
(maps::MT_MOON_B1F, maps::MT_MOON_B2F),
(maps::MT_MOON_B1F, maps::ROUTE_4),
// Route 4's own Pokémon Center, the door at (11, 5) on the cave mouth's side (row 62). On the
// graph because it is an amenity ([`AMENITIES`]): a centre with no row here is one no errand
// can walk to and no `HEAL` is dealt in.
(maps::MT_MOON_POKECENTER, maps::ROUTE_4),
(maps::CERULEAN_GYM, maps::CERULEAN_CITY),
(maps::CERULEAN_MART, maps::CERULEAN_CITY),
(maps::CERULEAN_POKECENTER, maps::CERULEAN_CITY),
// The badge house (row 65): no rung place needs a route through it, but its back door at
// (9, 9) is the only way into or out of a closed yard, so without it on the graph Cerulean is
// one piece and the house's two doors are the same door to every `GO OUT` -- the nearest one,
// which from the back door's arrival is the back door. Which piece each door opens onto is
// [`SPLIT`]'s business.
(maps::CERULEAN_BADGE_HOUSE, maps::CERULEAN_CITY),
(maps::ROCK_TUNNEL_1F, maps::ROUTE_10),
(maps::INDIGO_PLATEAU_LOBBY, maps::INDIGO_PLATEAU),
];
@ -248,11 +238,6 @@ const B2F_MAIN: u8 = 0;
const B2F_NORTH: u8 = 1;
const B2F_SOUTH: u8 = 2;
/// Cerulean City's town, and the closed yard behind the badge house.
const CERULEAN_TOWN: u8 = 0;
#[cfg(test)]
const CERULEAN_YARD: u8 = 1;
/// Every map whose ground is in pieces, with each piece's doors and neighbours.
///
/// Every row is measured from the disassembly at the pinned commit: the map's blocks, its
@ -273,12 +258,6 @@ const CERULEAN_YARD: u8 = 1;
/// to dead ends on B2F.
/// - **`MT_MOON_B2F`** (row 59): the fossil floor, one large piece with the two ladders the road
/// uses, and two small pieces under the dead-end ladders.
/// - **`CERULEAN_CITY`** (row 65): the town, and a closed yard of 33 tiles behind the badge house
/// whose one way out is the house's back door at (9, 9). Row 59's flood found it and left it
/// off because the house was not on the graph; the fly found it in a survey and stood in it with
/// an empty pad for 32,000 frames. The flood's third piece -- a strip of the west edge beside
/// Cerulean Cave's mouth, reached over water -- has no door on the graph and stays unlisted, so
/// the Route 4 edge and the cave are the town's as before.
const SPLIT: &[Split] = &[
Split {
map: maps::ROUTE_2,
@ -304,17 +283,13 @@ const SPLIT: &[Split] = &[
pieces: &[
Piece {
doors: &[(0, 11, 5), (1, 18, 5)],
next: &[
Region::whole(maps::ROUTE_3),
Region::whole(maps::MT_MOON_POKECENTER),
Region::whole(maps::MT_MOON_1F),
],
next: &[Region::whole(maps::ROUTE_3), Region::whole(maps::MT_MOON_1F)],
},
Piece {
doors: &[(2, 24, 5)],
next: &[
Region::piece(maps::MT_MOON_B1F, B1F_EXIT),
Region::piece(maps::CERULEAN_CITY, CERULEAN_TOWN),
Region::whole(maps::CERULEAN_CITY),
],
},
],
@ -372,65 +347,12 @@ const SPLIT: &[Split] = &[
},
],
},
Split {
map: maps::CERULEAN_CITY,
pieces: &[
Piece {
doors: &[
(0, 27, 11),
(1, 13, 15),
(2, 19, 17),
(3, 30, 19),
(4, 13, 25),
(5, 25, 25),
(7, 27, 9),
(8, 9, 11),
],
next: &[
Region::whole(maps::ROUTE_24),
Region::whole(maps::ROUTE_5),
Region::piece(maps::ROUTE_4, EAST_SIDE),
Region::whole(maps::ROUTE_9),
Region::whole(maps::CERULEAN_POKECENTER),
Region::whole(maps::CERULEAN_GYM),
Region::whole(maps::CERULEAN_MART),
Region::whole(maps::CERULEAN_BADGE_HOUSE),
],
},
Piece { doors: &[(9, 9, 9)], next: &[Region::whole(maps::CERULEAN_BADGE_HOUSE)] },
],
},
];
fn split_of(map: u8) -> Option<&'static Split> {
SPLIT.iter().find(|split| split.map == map)
}
/// Whether `map`'s ground is in pieces ([`SPLIT`] has a row for it).
pub fn is_split(map: u8) -> bool {
split_of(map).is_some()
}
/// Whether warp `index` of `from`'s map stands on the piece `from` (row 65).
///
/// A warp another piece lists is on ground no walk from here reaches, so it is not a way out of
/// here: from the Cerulean yard the town's eight doors, and from the town the yard's. A warp no
/// piece lists -- a door off the graph -- is not claimed either way and stays a way out.
pub fn warp_on(from: Region, index: u8) -> bool {
let Some(split) = split_of(from.map) else { return true };
pieces(split)
.find(|(_, piece)| piece.doors.iter().any(|(door, _, _)| *door == index))
.is_none_or(|(part, _)| part == from.part)
}
/// Whether the edge of `from`'s map onto `to` is stepped off the piece `from` (row 65): the piece
/// lists `to` among what is one step from it, or no piece does.
pub fn edge_on(from: Region, to: u8) -> bool {
let Some(split) = split_of(from.map) else { return true };
let mut owners = pieces(split).filter(|(_, piece)| piece.next.iter().any(|next| next.map == to)).peekable();
owners.peek().is_none() || owners.any(|(part, _)| part == from.part)
}
/// The pieces of a split map with their numbers, which are their [`Region::part`]s.
fn pieces(split: &'static Split) -> impl Iterator<Item = (u8, &'static Piece)> {
split.pieces.iter().enumerate().filter_map(|(part, piece)| Some((u8::try_from(part).ok()?, piece)))
@ -705,9 +627,6 @@ const AMENITIES: &[(u8, Amenity, u8)] = &[
(maps::VIRIDIAN_CITY, Amenity::Center, maps::VIRIDIAN_POKECENTER),
(maps::PEWTER_CITY, Amenity::Mart, maps::PEWTER_MART),
(maps::PEWTER_CITY, Amenity::Center, maps::PEWTER_POKECENTER),
// Route 4 has no mart, and its centre is the last one before Mt. Moon (row 62): the one the
// cave's first floor is an area with, since Mt. Moon's mouths open onto Route 4.
(maps::ROUTE_4, Amenity::Center, maps::MT_MOON_POKECENTER),
(maps::CERULEAN_CITY, Amenity::Mart, maps::CERULEAN_MART),
(maps::CERULEAN_CITY, Amenity::Center, maps::CERULEAN_POKECENTER),
];
@ -735,32 +654,6 @@ pub fn amenity_of(area: u8, kind: Amenity) -> Option<u8> {
.map(|(_, _, map)| *map)
}
/// Whether the route [`next_step`] walks from `from` to the map `to` stays inside `area` on every
/// hop, which is what makes `to` *this area's* building from where the fly stands.
///
/// An area is counted by map id ([`area_of`]), and a split map's pieces can be in one area while
/// the ground between them is not: Route 4's east side, and Mt. Moon B1F's exit chamber, are "in
/// Route 4" and its centre is on the west side, through B2F, which is in no area at all (row 62,
/// review round 2). A walk that has to leave the area to reach the building is not the area's
/// errand from here -- it is the mountain crossed backwards, and the first hop off the area drops
/// the button that started it. `true` when `from` is already on `to`; `false` when no route is
/// known.
pub fn route_within(from: Region, to: u8, area: u8) -> bool {
let mut here = from;
// A shortest route never revisits a piece, so it is at most as long as the table is big.
for _ in 0..=LINKS.len() + CONNECTIONS.len() {
if here.map == to {
return true;
}
let Some(hop) = next_step(here, to) else { return false };
if hop.map != to && area_of(hop.map) != Some(area) {
return false;
}
here = hop;
}
false
}
/// Which kind of amenity `map` *is*, when it is one.
///
/// The reverse lookup, and what tells the fly it is standing in a mart rather than in a house: the
@ -944,33 +837,6 @@ mod tests {
}
}
#[test]
fn cerulean_is_a_town_and_a_yard_and_the_badge_houses_back_door_is_the_yards() {
// Row 65. The yard behind the badge house is 33 tiles with one way out, the house's back
// door at (9, 9) (Cerulean's warp 9). From the house the road to anywhere is the front
// door, which opens on the town; from the yard it is the house.
let yard = Region::piece(maps::CERULEAN_CITY, CERULEAN_YARD);
let town = Region::piece(maps::CERULEAN_CITY, CERULEAN_TOWN);
assert_eq!(town, Region::whole(maps::CERULEAN_CITY), "the town is the piece every old row names");
assert_eq!(region_at(maps::CERULEAN_CITY, 9, 9), yard);
assert_eq!(region_at(maps::CERULEAN_CITY, 9, 12), town);
assert_eq!(arrival_by_warp(maps::CERULEAN_CITY, 9), Some(yard), "the back door lands in the yard");
assert_eq!(arrival_by_warp(maps::CERULEAN_CITY, 8), Some(town), "the front door in the town");
let house = Region::whole(maps::CERULEAN_BADGE_HOUSE);
assert_eq!(next_step(house, maps::CERULEAN_GYM), Some(town));
assert_eq!(next_step(yard, maps::CERULEAN_GYM), Some(house));
assert_eq!(hops(yard, maps::CERULEAN_GYM), Some(3));
assert_eq!(arrival_by_edge(maps::CERULEAN_CITY, maps::ROUTE_4), Some(town));
// What is on which piece, for the exit list (`path::exits`).
assert!(warp_on(yard, 9) && !warp_on(yard, 8) && !warp_on(town, 9) && warp_on(town, 8));
assert!(warp_on(yard, 6) && warp_on(town, 6), "the cave's mouth is no piece's door");
assert!(!edge_on(yard, maps::ROUTE_24) && edge_on(town, maps::ROUTE_24));
assert!(warp_on(Region::whole(maps::PEWTER_CITY), 3), "an unsplit map claims nothing");
// Route 4's sides, which row 59 split, answer the same question.
let west = Region::piece(maps::ROUTE_4, WEST_SIDE);
assert!(warp_on(west, 1) && !warp_on(west, 2) && !edge_on(west, maps::CERULEAN_CITY));
}
#[test]
fn the_road_from_pewter_to_cerulean_is_through_mt_moon_one_chamber_at_a_time() {
// Row 59. Every step of the road, as the pieces the fly stands in, measured from the
@ -1224,32 +1090,6 @@ mod tests {
assert_eq!(amenity_at(maps::VIRIDIAN_CITY), None);
}
#[test]
fn route_4s_centre_is_the_areas_only_from_the_mountains_west_side() {
// Row 62, review round 2: Route 4's east side and B1F's exit chamber are in Route 4's
// area, and the only road from them to its centre is through B2F, which is in none.
let centre = maps::MT_MOON_POKECENTER;
let area = maps::ROUTE_4;
assert_eq!(next_step(Region::piece(maps::ROUTE_4, EAST_SIDE), centre).map(|hop| hop.map), Some(maps::MT_MOON_B1F));
assert_eq!(next_step(Region::piece(maps::MT_MOON_B1F, B1F_EXIT), centre).map(|hop| hop.map), Some(maps::MT_MOON_B2F));
assert_eq!(area_of(maps::MT_MOON_B2F), None, "the fossil floor opens on no outdoor map");
assert!(!route_within(Region::piece(maps::ROUTE_4, EAST_SIDE), centre, area));
assert!(!route_within(Region::piece(maps::MT_MOON_B1F, B1F_EXIT), centre, area));
// The west side, the first floor and the three chambers a first-floor ladder reaches.
assert!(route_within(Region::piece(maps::ROUTE_4, WEST_SIDE), centre, area));
assert!(route_within(Region::whole(maps::MT_MOON_1F), centre, area));
for chamber in [B1F_WEST, B1F_MIDDLE, B1F_SOUTH] {
assert!(route_within(Region::piece(maps::MT_MOON_B1F, chamber), centre, area), "{chamber}");
}
assert!(route_within(Region::whole(centre), centre, area), "already there");
// A town is one piece, so every building off it is within: nothing moved for them.
for (town, kind) in [(maps::VIRIDIAN_CITY, Amenity::Mart), (maps::PEWTER_CITY, Amenity::Center)] {
let building = amenity_of(town, kind).unwrap();
assert!(route_within(Region::whole(town), building, town));
assert!(route_within(Region::whole(maps::PEWTER_GYM), maps::PEWTER_POKECENTER, maps::PEWTER_CITY));
}
}
#[test]
fn every_amenity_is_on_the_map_graph() {
// A building with no `LINKS` row is one `GO OBJECTIVE` and `GO SHOP` could never route to,

View file

@ -11,7 +11,7 @@
use super::cartridge::{
CHEAPEST_PURCHASE, FACINGS, MART_CURSOR_ROWS, opposite,
ExitId, ListKind, Listing, MacroState, Objective, PARTY_CAPACITY, PURCHASES, TalkTarget,
TargetKey, Tile, item, outdoors, price,
TargetKey, Tile, item, outdoors,
};
use crate::adapter::PlaceKind;
@ -547,16 +547,6 @@ 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
@ -637,13 +627,7 @@ pub fn precondition(kind: MacroKind, state: &mut dyn MacroState) -> bool {
// object with a purpose, not a person to chat with: with the party already full her whole
// conversation is forty-six text frames that end where they began, which is section
// 12.2's trap at conversation scale (section 12.12).
// ...and, since row 62, at a counter the fly has a use for however many times this
// session has already talked to it ([`facing_service`]): a clerk or a nurse is a service,
// and the talked ledger answers "is there anything left to say", which for a service is
// the party's HP or the bag's balls rather than the last conversation.
MacroKind::Talk => {
(facing_untalked(state) || facing_service(state)) && !rested_nurse(state)
}
MacroKind::Talk => facing_untalked(state) && !rested_nurse(state),
// The start menu opens from anywhere, and that is exactly why `MENU` is on no pad:
// "the precondition is satisfied wherever the fly stands" is section 12.2's trap, and a
// macro whose whole effect is a screen its own scene's `BACK` closes again is 12.10's
@ -674,13 +658,7 @@ 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(),
// ...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)
}
MacroKind::Item => hurt(state) && potion_slot(state).is_some(),
// 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.
@ -893,7 +871,7 @@ pub fn errand(state: &mut dyn MacroState, kind: Amenity) -> Option<u8> {
if kind == Amenity::Mart && state.money() < CHEAPEST_PURCHASE {
return None;
}
let map = amenity_in_reach(state, area, kind)?;
let map = geography::amenity_of(area, kind)?;
// **A building this run has already been inside is an errand already discharged.** The session
// ledger above is the errand's own record and it is the one that can be missing: it is written
// from the frame the fly stands on the building's map, so a restore starts with it empty and
@ -995,16 +973,9 @@ pub fn stock_index(state: &mut dyn MacroState, item: u8) -> Option<u8> {
pub fn amenity_goals(state: &mut dyn MacroState, kind: Amenity) -> Vec<Aim> {
let Some(here) = state.player().map(|player| player.map) else { return Vec::new() };
if geography::amenity_at(here) == Some(kind) {
// **A counter the fly has a use for is not retired by the last visit** (row 62). The
// reached and talked ledgers answer "is this job done", and for a service the answer is
// the party or the bag, not the ledger: a nurse reached an hour ago with a party that has
// since been beaten is a job to do again.
if service_needed(state, kind) {
return service_aims(state, kind);
}
return counter_aims(state, counter_sprite(kind));
}
match amenity_wanted(state, kind) {
match errand(state, kind) {
Some(map) => {
let here = state.player().map(|player| Tile::new(player.x, player.y));
goals_toward(state, map)
@ -1032,123 +1003,7 @@ pub fn heal_goals(state: &mut dyn MacroState) -> Vec<Aim> {
if geography::amenity_at(here) != Some(Amenity::Center) {
return Vec::new();
}
// **Neither the reached nor the talked ledger, and the counter the fly already faces is
// somewhere to heal from** (row 62). `HEAL` is only dealt while the party needs it, and that
// is its whole satiation: a completed heal leaves a party that reads full. Through
// [`counter_aims`] the button was off the pad on the one tile it is for -- facing the nurse,
// which is where `GO HEAL` leaves the fly, and for ten brain minutes after `GO HEAL` had
// reached her. Only the blocked window is kept: a counter no walk can reach is still that.
person_aims(state, poke_sprite::NURSE, Ledgers::BlockedOnly, true)
}
/// Whether the building of `kind` has something to do for the fly right now: the party needs the
/// nurse, or the bag has no ball the wallet could buy one of (row 62).
///
/// The errand (section 13) is "visit each area's building once per run", and it is paid on
/// entering -- by a visit on which the counter could do nothing, too: the Viridian mart is entered
/// first for Oak's parcel, when its clerk sells nothing, and a centre entered with a full party
/// heals nothing. Once paid it was never offered again, whatever the party or the bag read. This
/// is the other half of the same question, read from the cartridge each time it is asked, and
/// **it satisfies itself**: a heal leaves the party full and a purchase leaves a ball in the bag,
/// so the button leaves the pad the moment the job is done.
///
/// - **Centre**: [`party_needs_rest`], the same byte `HEAL` and the nurse's prompt read.
/// - **Mart**: no ball in the bag, and the money for one. A ball because `THROW BALL` is the one
/// button in the vocabulary that a purchase has to make possible -- with no ball it is never
/// dealt (section 12.9) -- and every mart in Kanto stocks it as its first row
/// (`data/items/marts.asm`), inside the cursor's reach ([`stock_index`]). And not while the bag
/// holds Oak's parcel: until it is delivered the Viridian clerk's text table is the parcel's,
/// and his counter sells nothing (`scripts/ViridianMart.asm`).
pub fn service_needed(state: &mut dyn MacroState, kind: Amenity) -> bool {
match kind {
Amenity::Center => party_needs_rest(state),
Amenity::Mart => {
let bag = state.bag();
state.money() >= price::POKE_BALL
&& !bag.iter().any(|stack| item::BALLS.contains(&stack.id) && stack.count > 0)
&& !bag.iter().any(|stack| stack.id == item::OAKS_PARCEL)
}
}
}
/// The map `GO SHOP` or `GO HEAL` walks toward from elsewhere in the area, or `None`.
///
/// The errand while it stands ([`errand`]), and otherwise the area's building of that kind while
/// it has something to do ([`service_needed`]). Nothing here ranks the building above anything
/// else on the pad: it is what the button aims at, and the fly chooses the button.
pub fn amenity_wanted(state: &mut dyn MacroState, kind: Amenity) -> Option<u8> {
if let Some(map) = errand(state, kind) {
return Some(map);
}
if !service_needed(state, kind) {
return None;
}
// **The room the rung is in is not left for a service** (row 62, review round 2). The same
// rule row 29 gave the ways out ([`exit_tiers`]) and row 58 measured in the Pewter Gym: while
// the thing that earns the rung stands on this map untalked and unexcluded, nothing walks the
// fly out of the room. A hurt party in a gym is the common case -- its trainers are why -- and
// `GO HEAL` / `GO SHOP` from the gym's floor were four of its six doormat bounces. The errand
// above needs no such line: while it stands it *is* the objective, so the rung's target is not
// on this map. The escape hatch is the rule's own: a target no walk reaches is excluded for
// the window, `objective_targets` empties, and the service is wanted again.
if !objective_targets(state).is_empty() {
return None;
}
let area = area_here(state)?;
amenity_in_reach(state, area, kind)
}
/// `area`'s building of `kind`, when the route to it from the piece of ground the fly stands on
/// stays inside the area ([`geography::route_within`]).
///
/// Row 62's review, round 2: Route 4's centre is on the mountain's west side, and Route 4's east
/// side and Mt. Moon B1F's exit chamber are in Route 4's area too -- but the only road from them
/// to that door runs through B2F, which is in no area, so the button that started the walk left
/// the pad one hop in, opposite `GO OBJECTIVE`'s road to Cerulean. From there the centre is not
/// this area's building; Cerulean's is one edge away, and it is its own area's.
fn amenity_in_reach(state: &mut dyn MacroState, area: u8, kind: Amenity) -> Option<u8> {
let map = geography::amenity_of(area, kind)?;
let from = region_here(state)?;
geography::route_within(from, map, area).then_some(map)
}
/// Inside a building with a job to do: the tiles to face its counter person from, whatever the
/// ledgers say, and nothing once the fly already faces them -- that is `TALK`'s tile, and a walk
/// that settles where it started is section 12.2's trap.
fn service_aims(state: &mut dyn MacroState, kind: Amenity) -> Vec<Aim> {
if facing_counter_person(state, kind) {
return Vec::new();
}
person_aims(state, counter_sprite(kind), Ledgers::BlockedOnly, false)
}
/// Whether the fly stands facing the clerk or the nurse of the building of `kind` it is in.
fn facing_counter_person(state: &mut dyn MacroState, kind: Amenity) -> bool {
let inside = state.player().is_some_and(|player| geography::amenity_at(player.map) == Some(kind));
let Some(TalkTarget::Sprite(slot)) = facing_target(state) else { return false };
inside
&& state
.npcs()
.iter()
.any(|npc| npc.slot == slot && npc.picture == counter_sprite(kind))
}
/// Whether the fly faces a counter whose service it has a use for: `TALK`'s second reason (row
/// 62). The press that opens a mart's counter or a nurse's conversation, dealt whatever the talked
/// ledger says, while [`service_needed`] holds.
pub fn facing_service(state: &mut dyn MacroState) -> bool {
Amenity::ALL
.into_iter()
.any(|kind| facing_counter_person(state, kind) && service_needed(state, kind))
}
/// Which of the target ledgers [`person_aims`] respects.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Ledgers {
/// Talked, reached and blocked: a person whose conversation is a job done once.
All,
/// Blocked alone: a service, whose job is done when the cartridge says so.
BlockedOnly,
counter_aims(state, poke_sprite::NURSE)
}
/// The picture id of the person who stands behind `kind`'s counter.
@ -1184,29 +1039,10 @@ pub mod poke_sprite {
/// Nearest first by Manhattan distance, ties by tile, which is `approach`'s own rule. Whether any
/// of the tiles is *reachable* is the route search's answer, not this one's.
pub fn counter_aims(state: &mut dyn MacroState, picture: u8) -> Vec<Aim> {
person_aims(state, picture, Ledgers::All, false)
}
/// [`counter_aims`] with the ledgers it respects, and whether the tile the fly already faces
/// the person from stays in the list (`HEAL`'s walk may be no steps at all).
fn person_aims(
state: &mut dyn MacroState,
picture: u8,
ledgers: Ledgers,
keep_facing: bool,
) -> Vec<Aim> {
let Some(player) = state.player() else { return Vec::new() };
let here = Tile::new(player.x, player.y);
// **Drawn or not** (row 62). A centre is entered at (3, 7) and its nurse stands at (3, 1), six
// rows up and off the top of the screen, so from the doormat the drawn sprites held nobody
// behind the counter: `HEAL` was off the pad, `GO HEAL` had nobody to walk to and the
// counter's suppression was released, all on the frame the fly walked in -- measured in the
// Pewter centre, where the pad on arrival was the way out. Row 58's reading of the sprites the
// cartridge keeps off the screen is the same table, so the counter person is found from the
// door.
let mut everyone = state.npcs();
everyone.extend(state.offscreen_npcs());
let mut people: Vec<(u32, Tile, u8)> = everyone
let mut people: Vec<(u32, Tile, u8)> = state
.npcs()
.iter()
.filter(|npc| npc.picture == picture)
.map(|npc| (Tile::new(npc.x, npc.y).distance(here), Tile::new(npc.x, npc.y), npc.slot))
@ -1219,11 +1055,10 @@ fn person_aims(
// already been stood in front of, or already talked to, is a job done. Without them
// `amenity_goals` never empties, `GO SHOP` never leaves the pad inside the building, and the
// suppression in [`ways`] would keep the fly in there for ever.
let retired = match ledgers {
Ledgers::All => state.talked(target) || state.reached(TargetKey::Thing(target)),
Ledgers::BlockedOnly => false,
};
if retired || state.blocked(TargetKey::Thing(target)) {
if state.talked(target)
|| state.reached(TargetKey::Thing(target))
|| state.blocked(TargetKey::Thing(target))
{
return Vec::new();
}
let key = Some(TargetKey::Thing(target));
@ -1261,9 +1096,7 @@ fn person_aims(
// The tile the fly is already standing on facing the right way is not somewhere to walk to:
// that is `TALK`'s state, and the same exclusion `untalked` makes (row 4).
let ahead = Tile::new(player.x, player.y).step(player.facing);
if !keep_facing {
aims.retain(|aim| aim.tile != here || Some(tile) != ahead);
}
aims.retain(|aim| aim.tile != here || Some(tile) != ahead);
aims
}
@ -1371,16 +1204,6 @@ pub fn ways(state: &mut dyn MacroState, way: Way) -> Vec<Exit> {
Way::Exit => {
if all.is_empty() {
last_resort(state, way)
} else if on_the_road(state) {
// **A floor whose way on is a passage is not a room to be stuck in** (row 65). The
// fallback is for a room with no other way anywhere; on Mt. Moon's first floor the
// road to Cerulean is a ladder, and the cave's mouth -- ground the run has walked,
// away from the rung -- was `GO OUT`'s nearest, one step from the tile the fly
// arrives on. `GO ROUTE` / `GO OBJECTIVE` on Route 4's side walk it straight back
// in: with row 62's `GO HEAL` bringing a hurt fly back to that tile, the review's
// three-way merge crossed Route 4's west doors 34 times in twenty minutes. This is
// `GO WARP`'s rule below, the other way round.
Vec::new()
} else {
all
}
@ -1415,14 +1238,6 @@ pub fn ways(state: &mut dyn MacroState, way: Way) -> Vec<Exit> {
}
}
/// Whether a passage no ledger is resting leads toward the objective: the fly is on a floor of the
/// road, and the way on is inside (row 65, [`ways`]). The blocked window is the escape hatch, as it
/// is for every suppression: a passage no walk reaches rests, and the way out is a candidate again.
fn on_the_road(state: &mut dyn MacroState) -> bool {
let passages = unexcluded_exits(state, Way::Passage);
!passages.is_empty() && !toward_objective(state, &passages).is_empty()
}
/// Every way out of this kind, ignoring the ledgers, when the map offers nothing else at all.
///
/// Section 13.1's never-empty rule, and since section 12.11 it is what the rule *rests* on: the
@ -2170,14 +1985,8 @@ 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];
return !any_useful || useful[0] || entry.is_none_or(|entry| entry.pp == 0);
}
let Some(entry) = entry else { return false };
if entry.pp > 0 {

View file

@ -143,12 +143,11 @@ pub enum Way {
/// A *directed* wall, which is the only shape that fits what the game encodes. Two of its rules
/// are invisible to the collision table [`super::state::walkable`] reads:
///
/// - **ledges.** `HandleLedges` (`engine/overworld/ledges.asm`) matches a triple of facing, the
/// tile the player stands on and the tile in front against `LedgeTiles`, and hops the player
/// *two* tiles that way. The ledge tile itself is absent from every tileset's passable list, so
/// the predicate calls it [`Walkable::No`] from both sides. With the decoded grid the search
/// takes the hop the one way the cartridge does (row 64, [`route_avoiding`]); without one, or
/// from the side below, it is a wall the walk declines to plan through.
/// - **ledges.** `HandleLedges` (`home/overworld.asm`) matches a triple of facing, the tile the
/// player stands on and the tile in front against `LedgeTiles`, and hops the player *two* tiles
/// that way. The ledge tile itself is absent from every tileset's passable list, so the
/// predicate already calls it [`Walkable::No`] and the search never plans through one in either
/// direction — a hop is a move the walk declines to use rather than one it gets wrong.
/// - **tile-pair collisions.** `TilePairCollisionsLand` and `...Water`
/// (`data/tilesets/tile_pair_collisions.asm`) refuse a step *between* two tiles that are each
/// passable on their own — the water/land boundary, a forest's tree line, a gym's floor edge.
@ -255,36 +254,6 @@ pub fn route_avoiding(
open.push(Reverse((step_cost + heuristic(next), step_cost, next)));
}
}
// **A ledge is a step the cartridge takes one way** (row 64). The ledge tile reads
// [`Walkable::No`] and the loop above never plans onto it, which is right from below and
// wrong from above: pressed into from its top side the cartridge hops the fly over it and
// lands it two tiles on. Before this, Route 4 east of Mt. Moon had no road to Cerulean at
// all -- the way down is three ledges -- so `GO OBJECTIVE` refused `no route` on the
// mountain's far side and the fly walked back into the cave. One press, one plan entry;
// the executor holds the walk while the cartridge carries the fly over.
if let Some(grid) = grid {
for facing in super::cartridge::FACINGS {
if !grid.hops(tile.x, tile.y, facing) || refused.contains(&(tile, facing)) {
continue;
}
let Some(landing) = tile.step(facing).and_then(|over| over.step(facing)) else {
continue;
};
if landing.x >= size.width || landing.y >= size.height {
continue;
}
if state.pushed_tile(landing.x, landing.y)
|| !grid.walkable(landing.x, landing.y).is_walkable()
{
continue;
}
let step_cost = cost + 2;
if best.get(&landing).is_none_or(|(known, _, _)| step_cost < *known) {
best.insert(landing, (step_cost, tile, facing));
open.push(Reverse((step_cost + heuristic(landing), step_cost, landing)));
}
}
}
}
// Nothing reachable is a goal. Walk to whatever gets closest, so the predicate's window has
@ -431,20 +400,9 @@ pub fn exits(state: &mut dyn MacroState) -> Vec<Exit> {
let grid = state.map_grid();
let grid = grid.as_deref();
let here_outdoors = outdoors(player.map);
// **On a map in pieces, a way out on another piece is not a way out of here** (row 65,
// section 12.24's pieces). From the Cerulean yard every one of the town's doors and edges was
// a candidate the route search refused, and each refusal rested that exit for the whole map --
// so a fly that got out of the yard found the town's ways out resting (a survey: an empty pad
// outside the badge house's front door for the rest of the window). A warp no piece lists is
// not claimed either way ([`geography::warp_on`]).
let piece = geography::is_split(player.map)
.then(|| geography::region_on(player.map, player.x, player.y, grid));
let mut out = Vec::new();
for (index, warp) in state.warps().iter().enumerate() {
let Ok(id) = u8::try_from(index) else { continue };
if piece.is_some_and(|piece| !geography::warp_on(piece, id)) {
continue;
}
let tile = Tile::new(warp.x, warp.y);
// Section 9.1's classification, from the destination map id and nothing else. Outdoors
// every warp is a door into somewhere new, which is a route; indoors the destination
@ -481,11 +439,6 @@ pub fn exits(state: &mut dyn MacroState) -> Vec<Exit> {
// the cartridge does not normally do -- it is still a way out of the building.
let way = if here_outdoors { Way::Route } else { Way::Exit };
let into = geography::connected(player.map, edge);
if let (Some(piece), Some(to)) = (piece, into)
&& !geography::edge_on(piece, to)
{
continue;
}
for tile in edge_tiles(facing, size.width, size.height) {
// Not `== Yes`: without a grid the walkable predicate's window is the screen, so the
// far edge of an outdoor map reads `Unknown` from anywhere but next to it, and

View file

@ -421,13 +421,7 @@ impl Walkable {
/// - **directed walls**: one step out of one tile in one direction that the cartridge refuses
/// although both tiles are passable. Pokered has two such rules and the tile-pair lists are the
/// one that can be read ahead of time; a ledge is already [`Walkable::No`] in the collision
/// list, and a person in the way is the sprite list's answer, not the ground's;
/// - **ledge hops** (row 64): the one step the collision list calls a wall that the cartridge
/// *does* take, one way, two tiles at a time -- `HandleLedges` matching the facing, the tile
/// stood on and the ledge tile in front against `LedgeTiles`
/// ([`crate::pokemon_red::mapgrid::LEDGE_TILES`]). A hop is a fact about the tables, like a
/// wall, and only [`super::path::route_avoiding`] reads it: [`MapGrid::reachable`] keeps the
/// ground as the collision list draws it, which is what a map's pieces are measured on.
/// list, and a person in the way is the sprite list's answer, not the ground's.
///
/// Nothing here is a fact about the run: no ledger, no visit, no target. Those stay where they
/// are, session state in the executor layer.
@ -443,12 +437,6 @@ pub struct MapGrid {
/// Row-major bitmask of the directions a step out of this tile is refused in
/// ([`MapGrid::wall`]).
walls: Vec<u8>,
/// Row-major bitmask of the directions a press out of this tile hops a ledge in
/// ([`MapGrid::ledge`]), landing two tiles that way.
hops: Vec<u8>,
/// Row-major bitmask of the directions whose tile in front is a warp carpet
/// ([`MapGrid::carpet`]): from a warp on this tile, a bump that way warps (row 65).
carpets: Vec<u8>,
}
impl MapGrid {
@ -462,8 +450,6 @@ impl MapGrid {
tiles: vec![Walkable::Unknown; cells],
ids: vec![None; cells],
walls: vec![0; cells],
hops: vec![0; cells],
carpets: vec![0; cells],
}
}
@ -500,40 +486,6 @@ impl MapGrid {
}
}
/// Record that a press out of `(x, y)` in `facing` hops the ledge in front, two tiles.
pub fn ledge(&mut self, x: u8, y: u8, facing: Facing) {
if let Some(index) = self.index(x, y) {
self.hops[index] |= wall_bit(facing);
}
}
/// Whether a press out of `(x, y)` in `facing` is a ledge hop ([`MapGrid::ledge`]).
pub fn hops(&self, x: u8, y: u8, facing: Facing) -> bool {
self.index(x, y).is_some_and(|index| self.hops[index] & wall_bit(facing) != 0)
}
/// Record that the tile in front of `(x, y)` in `facing` is a warp carpet
/// (`data/tilesets/warp_carpet_tile_ids.asm`), on a map whose `ExtraWarpCheck` reads it.
pub fn carpet(&mut self, x: u8, y: u8, facing: Facing) {
if let Some(index) = self.index(x, y) {
self.carpets[index] |= wall_bit(facing);
}
}
/// The direction a fly standing on a warp at `(x, y)` presses to take it by bumping, when the
/// cartridge would: the tile in front that way is a warp carpet ([`MapGrid::carpet`]).
///
/// Row 65. A warp whose own tile is not a door fires only through `ExtraWarpCheck`: at the end
/// of a step onto it with the direction still held, or on a bump while standing on it
/// (`CheckWarpsCollision`), and on the OVERWORLD tileset both ask `IsWarpTileInFrontOfPlayer`.
/// Down first, the order pokered lists the carpets in.
pub fn carpet_press(&self, x: u8, y: u8) -> Option<Facing> {
let bits = self.index(x, y).map_or(0, |index| self.carpets[index]);
[Facing::Down, Facing::Up, Facing::Left, Facing::Right]
.into_iter()
.find(|facing| bits & wall_bit(*facing) != 0)
}
/// Whether the player could stand on this tile. Off the map is [`Walkable::No`], which is the
/// window predicate's own answer for it.
pub fn walkable(&self, x: u8, y: u8) -> Walkable {

View file

@ -19,16 +19,16 @@ use crate::emulator::buttons;
use super::cartridge::{
BLOCKED_MINUTES_DEFAULT, CHEAPEST_PURCHASE, Edge, ExitId, FACINGS, LAST_MAP, MacroState, Objective,
PURCHASES, TalkTarget, TargetKey, TargetLedger, Targets, Tile, battle_entry, button, item, price,
TalkTarget, TargetKey, TargetLedger, Targets, Tile, battle_entry, button, item, price,
};
use super::geography::{self, Amenity};
use super::geography::Amenity;
use super::executor::{
FRAME_CAP, FRAMES_PER_PLANNED_TILE, MacroAbort, MacroMachine, MacroRefused, Refusal,
WALK_FRAME_CEILING, walk_budget,
};
use super::palette::{
MacroId, MacroKind, Palette, SLOTS, amenity_goals, amenity_wanted, answer_key, errand, facing_nurse,
healthiest_other, heal_goals, inside_center, nurse_prompt, rested_nurse, service_needed,
MacroId, MacroKind, Palette, SLOTS, amenity_goals, answer_key, errand, facing_nurse,
healthiest_other, heal_goals, nurse_prompt, rested_nurse,
listing, losing, move_slot_bound, objective_goals, party_needs_rest, party_rested,
poke_sprite, precondition, throw_slot, untalked_objects, untalked_people, ways,
};
@ -168,14 +168,6 @@ 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
@ -194,37 +186,8 @@ struct World {
/// beside a cursor the game never clears, and what the palette asks is only "is a choice
/// open" (section 12.12).
prompt: bool,
/// A mart's price confirmation (row 62): after this many more A presses in the shop the price
/// line starts printing, and the YES/NO box is drawn this many frames later. `None`: the fake
/// draws no price box at all, which is what it did before row 62.
price_after: Option<(u8, u32)>,
/// The frame the price box is drawn on, once the presses above have been made.
price_at: Option<u32>,
/// Purchases the fake mart has rung up: an A on its drawn price box.
bought: u32,
/// Whether the cartridge is driving the player right now ([`MacroState::scripted`]).
scripted: bool,
/// Ledges, as the tile a press hops from and its direction (row 64). Empty everywhere but the
/// tests about them, and with it empty the world has no decoded grid, as before.
ledges: Vec<(Tile, Facing)>,
/// A hop the cartridge is carrying the player through: frames left, the ledge tile, the
/// landing. `HandleLedges` takes the joypad for the length of it, so the scene reads
/// `Unknown` and the world is scripted.
hop: Option<(u32, Tile, Tile)>,
/// Warps a step onto does not fire: the "turns out to need some other press" of
/// [`path::exits`]'s `outward`, for the executor's rule about a way out that did not take the
/// fly anywhere.
duds: BTreeSet<Tile>,
/// Warp carpets, as the tile a bump is made from and its direction (row 65): standing on a
/// warp there, a press that way into ground the fly cannot enter fires it
/// (`CheckWarpsCollision`). With it non-empty the world has a decoded grid.
carpets: Vec<(Tile, Facing)>,
/// Same-map teleports, as the pad and where it puts the player (row 65): the Saffron Gym's
/// pads and Silph Co.'s move the fly on its own map a few frames after it stands on one, with
/// no scene change.
teleports: Vec<(Tile, Tile)>,
/// Frames the player has stood on a teleport pad.
on_pad: u32,
/// A frame at which the cartridge takes the joypad, which is what the Viridian gate does.
scripted_at: Option<u32>,
/// Every completed pulse, in order.
@ -297,23 +260,11 @@ 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,
prompt: false,
price_after: None,
price_at: None,
bought: 0,
scripted: false,
ledges: Vec::new(),
hop: None,
duds: BTreeSet::new(),
carpets: Vec::new(),
teleports: Vec::new(),
on_pad: 0,
scripted_at: None,
pulses: Vec::new(),
held: 0,
@ -442,23 +393,6 @@ impl World {
fn frame(&mut self, mask: u8) {
self.frames += 1;
// A ledge hop in flight: the cartridge's own joypad states, whatever is pressed.
if let Some((left, over, landing)) = self.hop {
let left = left.saturating_sub(1);
if left == 8 {
self.player = over;
}
if left == 0 {
self.player = landing;
self.scene = Scene::Overworld;
self.scripted = false;
self.hop = None;
} else {
self.hop = Some((left, over, landing));
}
self.previous = mask;
return;
}
if let Some((at, next)) = self.pending
&& self.frames >= at
{
@ -488,26 +422,10 @@ impl World {
}
self.heal_at = None;
}
if let Some(at) = self.price_at
&& self.frames >= at
{
self.prompt = true;
self.price_at = None;
}
if mask == buttons::NONE && self.previous != buttons::NONE {
self.pulses.push(self.previous);
self.on_pulse(self.previous);
}
match self.teleports.iter().find(|(pad, _)| *pad == self.player).copied() {
Some((_, to)) => {
self.on_pad += 1;
if self.on_pad >= 8 {
self.player = to;
self.on_pad = 0;
}
}
None => self.on_pad = 0,
}
if self.scene == Scene::Overworld {
match direction_of(mask) {
Some(facing) => {
@ -550,32 +468,9 @@ 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 && self.scene == Scene::Shop {
if self.prompt {
// YES on the drawn price box: the one press that rings a purchase up, and the
// wallet pays for the item the list's cursor is on.
self.prompt = false;
self.bought += 1;
let item = self.stock.get(usize::from(self.cursor)).copied();
let price = PURCHASES.iter().find(|(id, _)| Some(*id) == item).map_or(0, |(_, p)| *p);
self.money = self.money.saturating_sub(price);
} else if let Some((left, print)) = self.price_after {
if left <= 1 {
self.price_after = None;
self.price_at = Some(self.frames + print);
} else {
self.price_after = Some((left - 1, print));
}
}
}
if mask == buttons::A
&& let Some(next) = self.opens.pop_front()
{
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 {
@ -642,23 +537,7 @@ impl World {
return;
}
let next = Tile::new(x as u8, y as u8);
// `HandleLedges`: the press over a ledge takes the joypad and hops two tiles.
if self.ledges.contains(&(self.player, facing))
&& let Some(landing) = next.step(facing)
{
self.scene = Scene::Unknown;
self.scripted = true;
self.hop = Some((16, next, landing));
return;
}
if self.walkable(next.x, next.y) != Walkable::Yes {
// A bump while standing on a warp, toward a carpet: `CheckWarpsCollision` (row 65).
if self.carpets.contains(&(self.player, facing))
&& let Some(warp) =
self.warps.iter().find(|warp| warp.x == self.player.x && warp.y == self.player.y)
{
self.map = warp.destination_map;
}
return;
}
self.player = next;
@ -667,9 +546,6 @@ impl World {
else {
return;
};
if self.duds.contains(&next) {
return;
}
// An interior warp fires on the step onto it; a doormat only when the step onto it is the
// same direction the step off the map would be.
match outward(next, self.size.height) {
@ -820,21 +696,13 @@ impl MacroState for World {
/// A drawn box is what the reading rests on, so a prompt cannot be open with no box open:
/// `pokemon_red::state::yes_no_prompt` gates on `wFontLoaded` before it looks at the tiles.
fn yes_no_prompt(&mut self) -> bool {
self.prompt && matches!(self.scene, Scene::Dialog | Scene::Shop)
self.prompt && self.scene == Scene::Dialog
}
fn move_without_effect(&mut self, id: u8) -> bool {
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()
}
@ -882,28 +750,6 @@ impl MacroState for World {
fn objective(&mut self) -> Option<Objective> {
self.objective
}
/// The decoded grid, only for a world with ledges in it (row 64): the same walls the window
/// reads, plus the hops. Every other fixture keeps answering from the window, as before.
fn map_grid(&mut self) -> Option<std::sync::Arc<super::state::MapGrid>> {
if self.ledges.is_empty() && self.carpets.is_empty() {
return None;
}
let mut grid = super::state::MapGrid::new(self.map, self.size.width, self.size.height);
for y in 0..self.size.height {
for x in 0..self.size.width {
let wall = self.walls.contains(&Tile::new(x, y));
grid.set(x, y, if wall { 0x60 } else { 0x01 }, if wall { Walkable::No } else { Walkable::Yes });
}
}
for (tile, facing) in &self.ledges {
grid.ledge(tile.x, tile.y, *facing);
}
for (tile, facing) in &self.carpets {
grid.carpet(tile.x, tile.y, *facing);
}
Some(std::sync::Arc::new(grid))
}
}
fn direction_of(mask: u8) -> Option<Facing> {
@ -1002,10 +848,6 @@ fn settle(machine: &mut MacroMachine, world: &mut World) {
assert_eq!(map, world.map);
world.pushes.insert(tile);
}
// `PokemonPalette::record_talk` drains this after every finish, not only after a refusal.
if let Some((map, slot, tile)) = machine.take_refused() {
world.targets.record_refused(map, slot, tile);
}
if let Some((map, target)) = machine.take_talked() {
assert_eq!(map, world.map);
world.talked.insert(target);
@ -2468,95 +2310,6 @@ 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();
@ -2564,8 +2317,6 @@ fn buy_potion_takes_buy_then_the_item_then_confirms_twice() {
world.list = List::Shop(ShopScreen::BuySellQuit);
world.cursor_max = 2;
world.stock = vec![item::POKE_BALL, item::POTION];
// BUY, the item, the quantity, then the press the price line's `cont` waits for (row 62).
world.price_after = Some((4, 40));
world.money = 1000;
world.b_to_close = u8::MAX;
// A on BUY opens the priced stock list.
@ -2579,11 +2330,10 @@ fn buy_potion_takes_buy_then_the_item_then_confirms_twice() {
assert_eq!(world.cursor, 1, "the potion is the second thing the mart stocks");
assert_eq!(
world.pulses.iter().filter(|mask| **mask == buttons::A).count(),
5,
"BUY, the item, the quantity, the price line and the YES: {:?}",
4,
"BUY, the item, the quantity and the price: {:?}",
world.pulses
);
assert_eq!(world.bought, 1, "and the price box was answered once it was drawn");
}
#[test]
@ -2595,14 +2345,12 @@ fn buy_ball_skips_the_counter_menu_when_the_buy_list_is_already_up() {
world.stock = vec![item::POKE_BALL, item::POTION];
world.money = 1000;
world.b_to_close = u8::MAX;
world.price_after = Some((3, 40));
assert_eq!(run(&mut world, MacroKind::BuyBall).unwrap(), MacroAbort::Done);
assert_eq!(world.bought, 1);
assert_eq!(world.cursor, 0);
assert_eq!(
world.pulses.iter().filter(|mask| **mask == buttons::A).count(),
4,
"the item, the quantity, the price line and the YES: {:?}",
3,
"the item, the quantity and the price: {:?}",
world.pulses
);
}
@ -4398,11 +4146,9 @@ fn go_shop_and_go_heal_are_on_the_pad_while_their_errand_stands() {
assert!(on_the_pad(&mut world, MacroKind::GoHeal));
// Paid, and the button leaves the pad -- which is section 12's "a precondition failure means
// the button is not on the pad", and what makes the errand impossible to loop on. Since row
// 62 that holds while neither building has a job to do: a ball in the bag and a full party.
// the button is not on the pad", and what makes the errand impossible to loop on.
world.areas.insert((Amenity::Mart, maps::VIRIDIAN_CITY));
world.areas.insert((Amenity::Center, maps::VIRIDIAN_CITY));
world.bag = vec![(item::POKE_BALL, 3)];
assert!(!on_the_pad(&mut world, MacroKind::GoShop));
assert!(!on_the_pad(&mut world, MacroKind::GoHeal));
@ -4668,7 +4414,6 @@ fn a_purchase_navigates_by_the_items_place_in_the_stock_list() {
world.cursor_max = 3;
world.stock = vec![item::POKE_BALL, item::ANTIDOTE, 15, 12];
world.money = 3_000;
world.price_after = Some((3, 40));
assert_eq!(run(&mut world, MacroKind::BuyAntidote).unwrap(), MacroAbort::Done);
assert_eq!(world.cursor, 1, "the Antidote's own index");
assert_eq!(world.pulses.last(), Some(&buttons::A), "the price confirmation");
@ -5563,15 +5308,11 @@ fn a_declined_heal_writes_the_nurse_into_the_talked_ledger() {
assert_eq!(run(&mut center, MacroKind::No).unwrap(), MacroAbort::Done);
assert!(center.talked.contains(&TalkTarget::Sprite(1)), "the nurse: {:?}", center.talked);
// So `TALK` is off the pad there while the party stays full: the ledger is the record that
// this run has had her conversation, and a full party has nothing to ask her for.
// So `TALK` is off the pad there even if the party is hurt later: the ledger is the record
// that this run has had her conversation.
center.scene = Scene::Overworld;
assert!(!precondition(MacroKind::Talk, &mut center));
// Row 62: hurt again later, and she is a service with a job to do. The talked ledger said
// "never again" for the session, which was the whole Mt. Moon run's one nurse.
center.mons[0].hp = 4;
assert!(precondition(MacroKind::Talk, &mut center), "a hurt party has a use for her");
assert!(!precondition(MacroKind::Talk, &mut center));
}
#[test]
@ -5746,531 +5487,3 @@ fn a_trainer_walking_up_teaches_the_ledgers_nothing() {
assert!(!world.targets.blocked(world.map, north), "a challenge is not the road refusing");
assert!(world.pushes.is_empty(), "and the ground is as walkable as it was");
}
// ---------------------------------------------------------------------------------------------
// Row 62: a service the fly has a use for is not withheld by the ledger that paid its errand
// ---------------------------------------------------------------------------------------------
#[test]
fn go_heal_comes_back_for_a_hurt_party_after_the_errand_is_paid() {
// The live run of 2026-09-24: the fly entered the Viridian centre once with a full party,
// which paid the errand for the run, and was never offered `GO HEAL` in Viridian again --
// eleven hours, no heal anywhere, and every whiteout sent it back to Pallet Town.
let mut world = viridian();
world.areas.insert((Amenity::Center, maps::VIRIDIAN_CITY));
world.seen_maps.insert(maps::VIRIDIAN_POKECENTER);
assert_eq!(errand(&mut world, Amenity::Center), None, "the errand is paid");
assert!(!on_the_pad(&mut world, MacroKind::GoHeal), "full party: nothing to go for");
world.mons[0].hp = 7;
assert!(on_the_pad(&mut world, MacroKind::GoHeal), "hurt: the centre has a job to do");
assert_eq!(
amenity_goals(&mut world, Amenity::Center).iter().map(|aim| aim.tile).collect::<Vec<_>>(),
vec![Tile::new(6, 1)],
"the centre's door"
);
// A status counts as the nurse's job too, and a route with no centre has none to go to.
world.mons[0].hp = 20;
world.mons[0].status = Status::Poison;
assert!(on_the_pad(&mut world, MacroKind::GoHeal));
world.map = maps::ROUTE_1;
assert!(!on_the_pad(&mut world, MacroKind::GoHeal), "no centre in this area");
}
#[test]
fn go_shop_comes_back_while_the_bag_has_no_ball_and_the_money_covers_one() {
// The Viridian mart is entered first for Oak's parcel, when its clerk sells nothing, and that
// visit paid the errand for the run: `GO SHOP` was never dealt in Viridian again, `BUY BALL`
// never, `THROW BALL` never (live: GO SHOP 2 starts in eleven hours, both on the parcel).
let mut world = viridian();
world.areas.insert((Amenity::Mart, maps::VIRIDIAN_CITY));
world.seen_maps.insert(maps::VIRIDIAN_MART);
assert_eq!(errand(&mut world, Amenity::Mart), None, "the errand is paid");
assert!(on_the_pad(&mut world, MacroKind::GoShop), "no ball and 3000 to buy one with");
// A ball in the bag: nothing to go for.
world.bag = vec![(item::POTION, 1), (item::POKE_BALL, 1)];
assert!(!on_the_pad(&mut world, MacroKind::GoShop));
// Thrown, and it is back.
world.bag = vec![(item::POTION, 1)];
assert!(on_the_pad(&mut world, MacroKind::GoShop));
// Under a ball's price: nothing it could buy the ball with.
world.money = price::POKE_BALL - 1;
assert!(!on_the_pad(&mut world, MacroKind::GoShop));
world.money = price::POKE_BALL;
assert!(on_the_pad(&mut world, MacroKind::GoShop));
// Carrying Oak's parcel the Viridian counter sells nothing (`scripts/ViridianMart.asm`).
world.bag = vec![(item::OAKS_PARCEL, 1)];
assert!(!on_the_pad(&mut world, MacroKind::GoShop), "the parcel's text table, no counter");
}
#[test]
fn heal_is_dealt_facing_the_nurse_and_after_go_heal_has_reached_her() {
// Row 62. `HEAL`'s goals were `counter_aims`, which drops the tile the fly already faces her
// from and retires a nurse `GO HEAL` has reached for ten brain minutes: so `HEAL` was off the
// pad on the one tile it is for, and for ten minutes after the walk that put the fly there.
let mut center = World::center();
center.player = Tile::new(3, 3);
center.facing = Facing::Up;
center.mons[0].hp = 5;
assert!(facing_nurse(&mut center));
assert!(on_the_pad(&mut center, MacroKind::Heal), "facing her with a hurt party");
let nurse = TargetKey::Thing(TalkTarget::Sprite(1));
center.targets.record_reached(center.map, nurse);
center.talked.insert(TalkTarget::Sprite(1));
assert!(on_the_pad(&mut center, MacroKind::Heal), "reached and talked: still her job");
assert!(on_the_pad(&mut center, MacroKind::Talk), "and the press that opens her box");
// It runs from where it stands: no walk, the talk, the YES, and a party that reads full.
center.switch = Some((40, Scene::Dialog));
center.heal_at = Some(80);
assert_eq!(run(&mut center, MacroKind::Heal).unwrap(), MacroAbort::Done);
assert_eq!(center.player, Tile::new(3, 3));
assert!(party_rested(&mut center));
center.scene = Scene::Overworld;
assert!(!on_the_pad(&mut center, MacroKind::Heal), "full: the button leaves the pad");
assert!(!on_the_pad(&mut center, MacroKind::Talk), "and so does the nurse's conversation");
// The blocked window is kept: a counter no walk reaches is still that.
center.mons[0].hp = 5;
center.targets.record_blocked(center.map, nurse);
assert!(!on_the_pad(&mut center, MacroKind::Heal));
}
#[test]
fn a_counter_the_fly_has_a_use_for_opens_again_after_this_session_has_talked_to_it() {
// The clerk talked once this session (the parcel, or a visit that bought nothing) was out of
// `TALK`'s reach for the rest of it, and `GO SHOP` inside had nobody to walk to: the counter
// could not be opened again, so `BUY BALL` could not be dealt again.
let mut mart = World::mart();
mart.talked.insert(TalkTarget::Sprite(1));
mart.targets.record_reached(mart.map, TargetKey::Thing(TalkTarget::Sprite(1)));
assert!(service_needed(&mut mart, Amenity::Mart));
assert!(on_the_pad(&mut mart, MacroKind::GoShop), "walk to the clerk: {:?}", pad_of(&mut mart));
// At the counter, facing him: the walk is done and the press that opens it is dealt.
mart.player = Tile::new(2, 5);
mart.facing = Facing::Left;
assert!(!on_the_pad(&mut mart, MacroKind::GoShop), "already there");
assert!(on_the_pad(&mut mart, MacroKind::Talk), "open the counter again");
// With a ball in the bag the ledgers answer as they always did.
mart.bag = vec![(item::POKE_BALL, 2)];
assert!(!on_the_pad(&mut mart, MacroKind::Talk));
mart.player = Tile::new(3, 6);
assert!(!on_the_pad(&mut mart, MacroKind::GoShop));
}
#[test]
fn the_mt_moon_pokecenter_is_a_centre_and_route_4s() {
// Route 4's centre, the last before Mt. Moon, was on no table: `HEAL` was never dealt in it and
// the nurse's prompt was nobody's. Live: the fly stood in it at 10/70 (the row 59 checkpoint)
// and walked back out.
assert_eq!(geography::amenity_at(maps::MT_MOON_POKECENTER), Some(Amenity::Center));
assert_eq!(geography::area_of(maps::MT_MOON_POKECENTER), Some(maps::ROUTE_4));
assert_eq!(geography::amenity_of(maps::ROUTE_4, Amenity::Center), Some(maps::MT_MOON_POKECENTER));
assert_eq!(geography::amenity_of(maps::ROUTE_4, Amenity::Mart), None, "Route 4 has no mart");
// The cave's first floor opens onto Route 4, so a hurt fly inside it has a centre to go to.
assert_eq!(geography::area_of(maps::MT_MOON_1F), Some(maps::ROUTE_4));
let mut center = World::center();
center.map = maps::MT_MOON_POKECENTER;
center.player = Tile::new(3, 3);
center.facing = Facing::Up;
center.mons[0].hp = 10;
assert!(inside_center(&mut center));
assert!(on_the_pad(&mut center, MacroKind::Heal));
}
#[test]
fn the_nurse_is_found_from_the_door_when_the_screen_does_not_draw_her() {
// Row 62, measured in the Pewter centre: the fly arrives at (3, 7) and the nurse at (3, 1) is
// six rows up, off the top of the screen, so the drawn sprites hold nobody behind the
// counter. The pad on arrival was the way out: no `HEAL`, no `GO HEAL`, and the counter's
// suppression released.
let mut center = World::center();
center.player = Tile::new(3, 7);
center.mons[0].hp = 6;
center.offscreen = std::mem::take(&mut center.npcs);
assert!(
heal_goals(&mut center).iter().any(|aim| aim.tile == Tile::new(3, 3)),
"over the counter: {:?}",
heal_goals(&mut center)
);
assert!(on_the_pad(&mut center, MacroKind::Heal));
assert!(!on_the_pad(&mut center, MacroKind::GoOut), "the counter is still unfaced");
}
#[test]
fn a_purchase_answers_the_price_box_once_the_cartridge_has_drawn_it() {
// Row 62, from the rung-11 checkpoint in the Pewter mart: the price line "POKe BALL? That will
// be 200. OK?" prints at text speed after the quantity is chosen, and only then is the YES/NO
// box drawn. The script's last A came one settle after the quantity's and landed on the text
// while it was still printing, so `BUY BALL` reported `done` with nothing bought -- 55 starts,
// 55 `done`, the wallet at 1,606 throughout -- and the box it had not answered was left to
// whatever the pad dealt next.
let mut world = World::room();
world.scene = Scene::Shop;
world.list = List::Shop(ShopScreen::Buying);
world.cursor_max = 3;
world.stock = vec![item::POKE_BALL, item::POTION, 29, item::ANTIDOTE];
world.money = 1_606;
world.b_to_close = u8::MAX;
// Measured: the line waits for a press after "That will be", and the box is drawn after
// the rest of it prints. The fake draws it three presses after the item's: the item, the
// quantity, and the press that the `cont` waits for.
world.price_after = Some((3, 30));
assert_eq!(run(&mut world, MacroKind::BuyBall).unwrap(), MacroAbort::Done);
assert_eq!(world.bought, 1, "YES on the drawn box: {:?}", world.pulses);
assert!(!world.prompt, "and the box is answered, not left up");
// A box that never comes is not a purchase: `blocked`, and nothing answered.
let mut world = World::room();
world.scene = Scene::Shop;
world.list = List::Shop(ShopScreen::Buying);
world.cursor_max = 3;
world.stock = vec![item::POKE_BALL];
world.money = 1_606;
world.b_to_close = u8::MAX;
assert_eq!(run(&mut world, MacroKind::BuyBall).unwrap(), MacroAbort::Blocked);
assert_eq!(world.bought, 0);
}
// ---------------------------------------------------------------------------------------------
// Row 62, review round 2: a service is not dealt off the area's ground, nor out of the rung's room
// ---------------------------------------------------------------------------------------------
/// A hurt fly with no ball and money for one, on `map` at `(x, y)`, the rung in Cerulean.
fn hurt_on(map: u8, x: u8, y: u8) -> World {
let mut world = World::room().at(x, y);
world.map = map;
world.size = MapSize { width: 40, height: 36 };
world.warps = Vec::new();
world.mons[0].hp = 7;
world.money = 1_000;
world.objective = Some(Objective {
map: maps::CERULEAN_CITY,
tile: None,
warp: None,
edge: None,
target: None,
});
world
}
#[test]
fn east_of_mt_moon_route_4s_centre_is_not_the_areas_errand_or_service() {
// B1: Route 4's east side (where the fly comes out of the mountain, hurt) and B1F's exit
// chamber are "in Route 4", and the centre is on the west side through B2F, which is in no
// area. The pad dealt `GO HEAL` there, its walk took it into B2F, and it left the pad one hop
// in, opposite `GO OBJECTIVE`'s road back up: a two-map ring by construction.
for (map, x, y, place) in [
(maps::ROUTE_4, 30, 10, "Route 4 east"),
(maps::MT_MOON_B1F, 26, 4, "B1F exit chamber"),
] {
let mut world = hurt_on(map, x, y);
assert!(party_needs_rest(&mut world));
assert_eq!(errand(&mut world, Amenity::Center), None, "{place}: not the area's errand from here");
assert_eq!(amenity_wanted(&mut world, Amenity::Center), None, "{place}: nor its service");
assert!(amenity_goals(&mut world, Amenity::Center).is_empty(), "{place}");
assert!(!on_the_pad(&mut world, MacroKind::GoHeal), "{place}: GO HEAL is off the pad");
assert_eq!(
super::palette::objective_place(&mut world).map(|place| place.map),
Some(maps::CERULEAN_CITY),
"{place}: GO OBJECTIVE is the rung, not the centre behind the mountain"
);
}
// West of the mountain, and on the first floor, it is the area's centre as it was.
let mut world = hurt_on(maps::ROUTE_4, 12, 8);
world.warps = vec![Warp { x: 11, y: 5, destination_warp: 0, destination_map: maps::MT_MOON_POKECENTER }];
assert_eq!(amenity_wanted(&mut world, Amenity::Center), Some(maps::MT_MOON_POKECENTER));
assert!(on_the_pad(&mut world, MacroKind::GoHeal), "the door is a few tiles away");
let mut world = hurt_on(maps::MT_MOON_1F, 14, 20);
assert_eq!(amenity_wanted(&mut world, Amenity::Center), Some(maps::MT_MOON_POKECENTER));
}
#[test]
fn a_service_does_not_walk_the_fly_out_of_the_rungs_room() {
// B2, row 58's ROM test on the branch: in the Pewter Gym with BROCK up the room, a hurt party
// and an empty bag put `GO HEAL` and `GO SHOP` on the pad, and both walked out of the door the
// fly had just come in by -- four of six arrivals bounced. Row 29's rule is the ways out's and
// is now the services' too.
let mut world = pewter_gym_doormat();
world.mons[0].hp = 7;
world.money = 1_000;
world.bag = Vec::new();
assert!(service_needed(&mut world, Amenity::Center));
assert!(service_needed(&mut world, Amenity::Mart));
assert!(!super::palette::objective_targets(&mut world).is_empty(), "BROCK is in the room");
assert_eq!(amenity_wanted(&mut world, Amenity::Center), None);
assert_eq!(amenity_wanted(&mut world, Amenity::Mart), None);
assert!(!on_the_pad(&mut world, MacroKind::GoHeal));
assert!(!on_the_pad(&mut world, MacroKind::GoShop));
assert!(on_the_pad(&mut world, MacroKind::GoObjective), "the walk to him is still there");
// The rule's own escape hatch: with the room's people talked to (or excluded), the services
// are wanted again and the centre is Pewter's.
for slot in [1, 2] {
world.talked.insert(TalkTarget::Sprite(slot));
}
assert!(super::palette::objective_targets(&mut world).is_empty());
assert_eq!(amenity_wanted(&mut world, Amenity::Center), Some(maps::PEWTER_POKECENTER));
assert_eq!(amenity_wanted(&mut world, Amenity::Mart), Some(maps::PEWTER_MART));
}
#[test]
fn a_walk_that_starts_on_the_ladder_it_wants_steps_off_and_back_on_to_take_it() {
// Row 64, Mt. Moon B2F (5, 7): the fly came down the ladder and is standing on it, and the
// ladder is the one way on. The cartridge fires a ladder at the end of a step onto it and at
// no other time, so a walk that "arrives" on the tile it is already standing on and settles
// there presses nothing, reports `done` and changes nothing -- `GO OBJECTIVE` and `GO WARP`,
// 27 frames each, for two days. The walk takes it the way the cartridge does: a step onto
// free ground beside it and the step back.
for kind in [MacroKind::GoWarp, MacroKind::GoObjective] {
let mut world = World::room().at(3, 3);
world.warps = vec![Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x26 }];
if kind == MacroKind::GoObjective {
world.objective = Some(Objective { map: 0x26, tile: None, warp: None, edge: None, target: None });
}
assert_eq!(run(&mut world, kind), Ok(MacroAbort::Done), "{}", kind.name());
assert_eq!(world.map, 0x26, "{} took the ladder it was standing on", kind.name());
assert!(!world.pulses.is_empty(), "{} pressed something to take it", kind.name());
}
}
#[test]
fn a_walk_off_its_ladder_does_not_step_onto_another_warp() {
// Stepping onto a warp is what fires it, so the step off the one underfoot goes to plain
// ground. With the only free side another ladder there is nowhere to step off to, and the
// walk ends `blocked` -- its exit rests in the window -- rather than taking the other ladder.
let mut world = World::room().at(3, 3).wall(&[(3, 2), (2, 3), (3, 4)]);
world.warps = vec![
Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x26 },
Warp { x: 4, y: 3, destination_warp: 0, destination_map: 0x27 },
];
world.seen_maps = BTreeSet::from([0x27]);
// Only one side is free and it is the other ladder: nowhere to step off to without firing it.
assert_eq!(run(&mut world, MacroKind::GoWarp), Ok(MacroAbort::Blocked));
assert_eq!(world.map, 0x25, "the other ladder was not taken for this one");
}
#[test]
fn a_ledge_the_walk_presses_into_is_hopped_and_is_not_a_push_back() {
// Row 64, Route 4 east of Mt. Moon: Cerulean is three ledges down from the cave's exit, and a
// ledge read as a wall both ways, so `GO OBJECTIVE` refused `no route` there. The route search
// takes a hop the one way the cartridge does, and the walk waits while the cartridge carries
// the fly over -- `HandleLedges` takes the joypad for it, which is the same reading as a
// scripted push-back, and a push-back walls the tile for the session.
let mut world = World::room().at(3, 1);
world.map = 0x0f;
// Route 4's centre (row 62) is seen, so its errand does not come ahead of the goal.
world.seen_maps.insert(maps::MT_MOON_POKECENTER);
for x in 0..8 {
world.walls.insert(Tile::new(x, 3));
world.ledges.push((Tile::new(x, 2), Facing::Down));
}
let goal = Tile::new(3, 6);
world.objective = Some(Objective { map: 0x0f, tile: Some(goal), warp: None, edge: None, target: None });
let mut machine = MacroMachine::new(0x1234_5678);
assert_eq!(run_with(&mut machine, &mut world, MacroKind::GoObjective), Ok(MacroAbort::Done));
assert_eq!(world.player, goal, "over the ledge and on to the goal in one walk");
hand_back(&mut machine, &mut world);
assert!(world.pushes.is_empty(), "the hop the walk asked for walled nothing: {:?}", world.pushes);
assert!(!world.targets.blocked(world.map, TargetKey::Tile(goal)), "nor rested the goal");
// From below, the ledge is a wall: nothing plans up it.
let mut below = World::room().at(3, 6);
below.map = 0x0f;
below.seen_maps.insert(maps::MT_MOON_POKECENTER);
for x in 0..8 {
below.walls.insert(Tile::new(x, 3));
below.ledges.push((Tile::new(x, 2), Facing::Down));
}
below.objective =
Some(Objective { map: 0x0f, tile: Some(Tile::new(3, 1)), warp: None, edge: None, target: None });
assert!(run(&mut below, MacroKind::GoObjective).is_err(), "a ledge is not climbed");
assert_eq!(below.player, Tile::new(3, 6));
}
#[test]
fn a_way_out_that_does_not_take_the_fly_anywhere_is_not_done() {
// The general half of row 64 (section 12.2's rule, held by the executor): a way out's promise
// is another map, so settling on one that leaves the fly on this map is not an arrival. Live,
// `GO OBJECTIVE` and `GO WARP` reported that `done` ~750 times per ten brain minutes on one
// tile for two days. Here the warp does not fire at all, whatever the walk does.
let mut world = World::room().at(1, 1);
world.warps = vec![Warp { x: 5, y: 5, destination_warp: 0, destination_map: 0x26 }];
world.duds = BTreeSet::from([Tile::new(5, 5)]);
let mut machine = MacroMachine::new(0x1234_5678);
assert_eq!(run_with(&mut machine, &mut world, MacroKind::GoWarp), Ok(MacroAbort::Blocked));
assert_eq!((world.map, world.player), (0x25, Tile::new(5, 5)), "walked to it; it did not fire");
let exit = TargetKey::Exit(ExitId::Warp(0));
assert!(world.targets.blocked(world.map, exit), "the dead exit rests in the window");
// Walked to from elsewhere, so the button is not held against the tile it now stands on:
// a different tile is a different press.
assert!(!world.targets.refused(world.map, MacroKind::GoWarp.slot(), world.player));
}
#[test]
fn a_way_out_pressed_from_where_it_does_not_fire_is_not_dealt_again_from_there() {
// Standing on it: step off, step back on, nothing. The blocked entry rests the exit for every
// list but a last resort, and the last resort ignores the blocked ledger by design, so on a
// map with nothing else on it the same button would be dealt at the same dead exit once per
// hold. Row 57's ledger ends that: not from this tile, for the window.
let mut world = World::room().at(3, 3);
world.warps = vec![Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x26 }];
world.duds = BTreeSet::from([Tile::new(3, 3)]);
world.seen_maps = BTreeSet::from([0x26]);
world.stood = (0..8).flat_map(|y| (0..8).map(move |x| Tile::new(x, y))).collect();
let mut machine = MacroMachine::new(0x1234_5678);
// Nothing else on this map: the last resort is what deals `GO WARP` here.
assert!(pick_opt(&mut world, MacroKind::GoWarp), "the last resort deals the only way out");
assert_eq!(run_with(&mut machine, &mut world, MacroKind::GoWarp), Ok(MacroAbort::Blocked));
assert_eq!((world.map, world.player), (0x25, Tile::new(3, 3)));
assert!(world.targets.refused(world.map, MacroKind::GoWarp.slot(), world.player));
assert!(!pick_opt(&mut world, MacroKind::GoWarp), "not dealt again from the tile it failed on");
}
/// Whether `kind` is on the pad the world's scene deals now.
fn pick_opt(world: &mut World, kind: MacroKind) -> bool {
let scene = world.scene();
Palette::for_scene(scene, world).slots.iter().any(|slot| slot.is_some_and(|spec| spec.kind == kind))
}
#[test]
fn a_door_underfoot_is_taken_when_no_other_way_out_can_be_walked_to() {
// Row 65, the Cerulean badge house's back yard: the fly stands on the one door out of ground
// walled off from every other exit. The exit walks set a step-fired door underfoot aside while
// any other exit is listed, reachable or not, so `GO OUT` refused `no route` at the far door
// for as long as it was dealt and never took the one underfoot. It now falls back on it, the
// way row 64 taught the walk to take a ladder: a step off and the step back on.
let mut world = World::room().at(3, 3).wall(&[(5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7)]);
world.warps = vec![
Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x00 },
Warp { x: 7, y: 3, destination_warp: 1, destination_map: 0x00 },
];
assert_eq!(run(&mut world, MacroKind::GoOut), Ok(MacroAbort::Done));
assert_eq!(world.map, 0x00, "the door underfoot was taken");
assert!(!world.pulses.is_empty(), "by a step off it and back on");
// With the other door reachable, it is still the one walked to: the fallback is a fallback.
let mut open = World::room().at(3, 3);
open.warps = world.warps.clone();
open.warps[1].destination_map = 0x01;
assert_eq!(run(&mut open, MacroKind::GoOut), Ok(MacroAbort::Done));
assert_eq!(open.map, 0x01, "the reachable door, not the one underfoot");
}
#[test]
fn a_door_underfoot_that_fires_on_a_bump_is_bumped_and_not_stepped_off() {
// The same yard, measured on the cartridge: the back door's tile is no door tile, so a step
// back onto it sideways fires nothing (`duds`), and the cartridge takes it on a bump toward
// the house -- a warp carpet in front, `CheckWarpsCollision` for a player standing on a warp.
let wall: Vec<(u8, u8)> = (0..8).map(|y| (5, y)).chain([(3, 4)]).collect();
let mut world = World::room().at(3, 3).wall(&wall);
world.warps = vec![
Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x00 },
Warp { x: 7, y: 3, destination_warp: 1, destination_map: 0x00 },
];
world.duds = BTreeSet::from([Tile::new(3, 3)]);
world.carpets = vec![(Tile::new(3, 3), Facing::Down)];
assert_eq!(run(&mut world, MacroKind::GoOut), Ok(MacroAbort::Done));
assert_eq!(world.map, 0x00, "the bump took the door");
assert!(world.pulses.iter().all(|mask| *mask == buttons::DOWN), "a press down and nothing else");
// The row-64 step off alone is what this tile does not answer: with no carpet it ends
// `blocked`, the executor's rule for a way out that went nowhere.
let mut stepped = World::room().at(3, 3).wall(&wall);
stepped.warps = world.warps.clone();
stepped.duds = world.duds.clone();
assert_eq!(run(&mut stepped, MacroKind::GoOut), Ok(MacroAbort::Blocked));
assert_eq!(stepped.map, 0x25);
}
#[test]
fn a_floor_whose_way_on_is_a_passage_deals_no_go_out_back_the_way_it_came() {
// Row 65, Mt. Moon 1F: the objective is Cerulean, the road is the ladder at (5, 5) into B1F's
// west chamber, and the cave mouth leads back onto Route 4, where the run has been. `GO OUT`'s
// "a room has to be leavable" fallback dealt the mouth anyway, one step from the tile the fly
// arrives on, and Route 4's `GO ROUTE` walked straight back in.
let mut world = World::room().at(3, 6);
world.map = maps::MT_MOON_1F;
world.size = MapSize { width: 8, height: 8 };
world.warps = vec![
Warp { x: 3, y: 7, destination_warp: 1, destination_map: maps::ROUTE_4 },
Warp { x: 5, y: 2, destination_warp: 0, destination_map: maps::MT_MOON_B1F },
];
// The centre beside the mouth has been visited, so it is no errand: the objective is the rung.
world.seen_maps = BTreeSet::from([maps::ROUTE_4, maps::MT_MOON_B1F, maps::MT_MOON_POKECENTER]);
world.objective = Some(Objective { map: maps::CERULEAN_CITY, tile: None, warp: None, edge: None, target: None });
assert!(ways(&mut world, Way::Exit).is_empty(), "no way out: the road is the ladder");
assert!(!on_the_pad(&mut world, MacroKind::GoOut));
assert!(on_the_pad(&mut world, MacroKind::GoWarp), "the ladder is the way on");
// The escape hatch every suppression has: a ladder no walk reaches rests in the window, and
// the mouth is a way out again.
world.targets.record_blocked(maps::MT_MOON_1F, TargetKey::Exit(ExitId::Warp(1)));
assert_eq!(ways(&mut world, Way::Exit).len(), 1);
assert!(on_the_pad(&mut world, MacroKind::GoOut));
// And a party that needs the nurse still has its way out, under the button that says why.
let mut hurt = World::room().at(3, 6);
hurt.map = maps::MT_MOON_1F;
hurt.warps = world.warps.clone();
hurt.seen_maps = world.seen_maps.clone();
hurt.objective = world.objective;
hurt.mons = vec![mon(0, 5, 20, &[(33, 30)])];
assert!(!on_the_pad(&mut hurt, MacroKind::GoOut));
assert!(on_the_pad(&mut hurt, MacroKind::GoHeal), "GO HEAL walks out to the centre");
}
#[test]
fn a_way_out_on_another_piece_of_a_split_map_is_not_a_way_out_of_this_one() {
// Row 65, Cerulean City's yard behind the badge house. Every door and edge of the town was a
// way out of the yard for the route search to refuse, and each refusal rested that exit for
// the whole map: out of the yard at last, the fly found the town's exits, the gym's door
// among them, resting. On a split map the exits are the fly's own piece's.
let mut world = World::room().at(9, 9);
world.map = maps::CERULEAN_CITY;
world.size = MapSize { width: 40, height: 36 };
world.connections = Connections { north: true, south: true, east: true, west: true };
world.warps = [(27, 11), (13, 15), (19, 17), (30, 19), (13, 25), (25, 25), (4, 11), (27, 9), (9, 11), (9, 9)]
.iter()
.map(|(x, y)| Warp { x: *x, y: *y, destination_warp: 0, destination_map: 0x40 })
.collect();
let exits = path::exits(&mut world);
let ids: Vec<ExitId> = exits.iter().map(|exit| exit.id).collect();
assert!(ids.contains(&ExitId::Warp(9)), "the back door is the yard's");
assert!(ids.contains(&ExitId::Warp(6)), "the cave's mouth is no piece's, and not claimed");
assert!(!ids.contains(&ExitId::Warp(8)), "the front door is the town's: {ids:?}");
assert!(!ids.iter().any(|id| matches!(id, ExitId::Edge(_))), "the town's edges: {ids:?}");
// From the town it is the other way round.
world.player = Tile::new(9, 12);
let ids: Vec<ExitId> = path::exits(&mut world).iter().map(|exit| exit.id).collect();
assert!(ids.contains(&ExitId::Warp(8)) && !ids.contains(&ExitId::Warp(9)), "{ids:?}");
assert!(ids.iter().any(|id| matches!(id, ExitId::Edge(_))), "{ids:?}");
}
#[test]
fn a_same_map_teleport_is_somewhere_the_way_out_took_the_fly() {
// Row 65, the row-64 review's note: the executor's guarantee (a way out that leaves the fly on
// its map is not done) read the tile the walk settled on, so a warp that moves the fly on its
// own map -- the Saffron Gym's pads, Silph Co.'s -- would read as one that did not fire. The
// fly has gone somewhere when it no longer stands where it settled.
let mut world = World::room().at(3, 3);
world.warps = vec![Warp { x: 3, y: 5, destination_warp: 0, destination_map: 0x25 }];
world.duds = BTreeSet::from([Tile::new(3, 5)]);
world.teleports = vec![(Tile::new(3, 5), Tile::new(6, 1))];
assert_eq!(run(&mut world, MacroKind::GoWarp), Ok(MacroAbort::Done));
assert_eq!((world.map, world.player), (0x25, Tile::new(6, 1)), "moved by the pad");
// A pad that does nothing is still the guarantee's case.
let mut dead = World::room().at(3, 3);
dead.warps = world.warps.clone();
dead.duds = world.duds.clone();
assert_eq!(run(&mut dead, MacroKind::GoWarp), Ok(MacroAbort::Blocked));
}

View file

@ -36,8 +36,6 @@ struct Ground {
npcs: Vec<Npc>,
/// Whether the whole map is decoded, or only the window can answer.
decoded: bool,
/// Ledges, as the tile a press hops from and its direction, as the grid records them (row 64).
ledges: Vec<(Tile, Facing)>,
}
impl Ground {
@ -54,7 +52,6 @@ impl Ground {
connections: Connections::default(),
npcs: Vec::new(),
decoded: true,
ledges: Vec::new(),
}
}
@ -208,9 +205,6 @@ impl MacroState for Ground {
for (tile, facing) in &self.pair_walls {
grid.wall(tile.x, tile.y, *facing);
}
for (tile, facing) in &self.ledges {
grid.ledge(tile.x, tile.y, *facing);
}
Some(Arc::new(grid))
}
@ -348,32 +342,3 @@ fn a_connection_on_the_far_edge_is_a_goal_and_the_walls_along_it_are_not() {
.count();
assert_eq!(count, 20);
}
#[test]
fn a_ledge_is_one_press_down_and_a_wall_up() {
// Row 64: Route 4 east of Mt. Moon, where every road to Cerulean is a ledge down. A row of
// ledge tiles across the map, which the collision list calls a wall.
let mut ground = Ground::new(12, 10, (5, 1));
for x in 0..12 {
ground.walls.insert(Tile::new(x, 4));
ground.ledges.push((Tile::new(x, 3), Facing::Down));
}
let below = Tile::new(5, 8);
let route = path::route(&mut ground, &[below]).expect("a route down");
assert_eq!(route.goal, Some(0), "the goal itself, over the ledge");
// Two steps to the ledge's edge, one press that hops two tiles, three steps on.
assert_eq!(route.steps, vec![Facing::Down; 6]);
// Up is a wall: the search gets as close as it can and reaches nothing.
ground.player = below;
let route = path::route(&mut ground, &[Tile::new(5, 1)]);
assert!(route.as_ref().is_none_or(|route| route.goal.is_none()), "a ledge is not climbed: {route:?}");
// And without the decoded grid there is nothing to read a ledge from: a wall, as before.
let mut blind = Ground::new(12, 10, (5, 1));
for x in 0..12 {
blind.walls.insert(Tile::new(x, 4));
}
let route = path::route(&mut blind, &[below]);
assert!(route.as_ref().is_none_or(|route| route.goal.is_none()), "no hop without a ledge: {route:?}");
}

View file

@ -29,8 +29,6 @@
//! What it does **not** model is what it did not model before: sprites standing on ground (the
//! sprite list answers that, and [`super::macros::path::frontier`] reads it), warps that fire on
//! the step onto them, and scripts that push the fly off a tile (a session ledger answers that).
//! Ledges it has modelled since row 64 ([`LEDGE_TILES`]): a wall in the collision list, and a hop
//! the route search may take the one way the cartridge takes it.
use std::sync::Arc;
@ -78,37 +76,8 @@ const ANCHOR_ROW: usize = 1;
/// Tileset ids the tile-pair lists name (`constants/tileset_constants.asm`, counted in the order
/// that file declares them: OVERWORLD 0 … FOREST 3 … CAVERN 17).
pub mod tileset {
pub const OVERWORLD: u8 = 0;
pub const FOREST: u8 = 3;
pub const SHIP: u8 = 13;
pub const SHIP_PORT: u8 = 14;
pub const CAVERN: u8 = 17;
pub const PLATEAU: u8 = 23;
}
/// `WarpTileListPointers` at the pinned pokered commit (`data/tilesets/warp_carpet_tile_ids.asm`):
/// per facing, the tile ids in front of the player that `IsWarpTileInFrontOfPlayer` answers yes
/// to.
pub const WARP_CARPET_TILES: [(Facing, &[u8]); 4] = [
(Facing::Down, &[0x01, 0x12, 0x17, 0x3d, 0x04, 0x18, 0x33]),
(Facing::Up, &[0x01, 0x5c]),
(Facing::Left, &[0x1a, 0x4b]),
(Facing::Right, &[0x0f, 0x4e]),
];
/// Whether `ExtraWarpCheck` asks `IsWarpTileInFrontOfPlayer` on this map (`home/overworld.asm`):
/// the OVERWORLD, SHIP, SHIP_PORT and PLATEAU tilesets and four maps by id, except the S.S. Anne's
/// 3F, which asks `IsPlayerFacingEdgeOfMap` like every other map.
fn carpets_apply(tileset: u8, map: u8) -> bool {
const SS_ANNE_3F: u8 = 0x61;
const ROCKET_HIDEOUT_B1F: u8 = 0xc7;
const ROCKET_HIDEOUT_B2F: u8 = 0xc8;
const ROCKET_HIDEOUT_B4F: u8 = 0xca;
if map == SS_ANNE_3F {
return false;
}
matches!(map, ROCKET_HIDEOUT_B1F | ROCKET_HIDEOUT_B2F | ROCKET_HIDEOUT_B4F | super::maps::ROCK_TUNNEL_1F)
|| matches!(tileset, tileset::OVERWORLD | tileset::SHIP | tileset::SHIP_PORT | tileset::PLATEAU)
}
/// `TilePairCollisionsLand` at the pinned pokered commit, as `(tileset, one tile, the other)`.
@ -141,31 +110,6 @@ pub const TILE_PAIRS_LAND: [(u8, u8, u8); 11] = [
(tileset::FOREST, 0x5f, 0x2e),
];
/// `LedgeTiles` at the pinned pokered commit, as `(facing, the tile stood on, the ledge tile)`.
///
/// `data/tilesets/ledge_tiles.asm`, read by `HandleLedges` (`engine/overworld/ledges.asm`) on the
/// OVERWORLD tileset only (`wCurMapTileset` is 0 or it returns): when the player faces one of
/// these ledge tiles from one of these tiles with that direction held, the cartridge takes the
/// joypad and hops the player **two** tiles that way. Both tiles are the ones
/// `_GetTileAndCoordsInFrontOfPlayer` reads -- screen `(8, 9)` for the player's own and `(8, 11)`,
/// `(8, 7)`, `(6, 9)` or `(10, 9)` for the one in front -- which is the lower-left corner of each
/// map tile's quadrant, the same corner [`ANCHOR_ROW`] decodes. The input column of the table is
/// the facing again, so it is not repeated.
///
/// The ledge tile is absent from every passable list, which is why a ledge read as a wall in both
/// directions before row 64 and why nothing east of Mt. Moon could be walked to from its exit:
/// Route 4's road down to Cerulean is three ledges, and every one of them faces away from the cave.
pub const LEDGE_TILES: [(Facing, u8, u8); 8] = [
(Facing::Down, 0x2c, 0x37),
(Facing::Down, 0x39, 0x36),
(Facing::Down, 0x39, 0x37),
(Facing::Left, 0x2c, 0x27),
(Facing::Left, 0x39, 0x27),
(Facing::Right, 0x2c, 0x0d),
(Facing::Right, 0x2c, 0x1d),
(Facing::Right, 0x39, 0x0d),
];
/// The tileset's two tables, as the decoder needs them.
///
/// Gathered by [`super::state::map_grid`] from WRAM and ROM; separate from the decoding so that
@ -234,61 +178,9 @@ pub fn decode(map: u8, width_blocks: u8, height_blocks: u8, blocks: &[u8], tiles
}
}
add_pair_walls(&mut grid, tiles.id);
add_ledge_hops(&mut grid, tiles.id);
add_warp_carpets(&mut grid, tiles.id, map);
grid
}
/// Mark, for every tile, the directions whose tile in front is a warp carpet ([`WARP_CARPET_TILES`]),
/// on a map whose `ExtraWarpCheck` reads them ([`carpets_apply`]). Only a warp's own tile ever
/// asks ([`MapGrid::carpet_press`], row 65).
fn add_warp_carpets(grid: &mut MapGrid, tileset: u8, map: u8) {
if !carpets_apply(tileset, map) {
return;
}
for y in 0..grid.height() {
for x in 0..grid.width() {
for (facing, carpets) in WARP_CARPET_TILES {
let (dx, dy) = facing.delta();
let (Some(nx), Some(ny)) = (checked_step(x, dx), checked_step(y, dy)) else { continue };
if grid.tile_id(nx, ny).is_some_and(|tile| carpets.contains(&tile)) {
grid.carpet(x, y, facing);
}
}
}
}
}
/// Mark every ledge the loaded tileset has as a hop out of the tile in front of it ([`LEDGE_TILES`]).
///
/// Only where the cartridge would take it: the OVERWORLD tileset, a ledge tile in front, and a
/// landing two tiles away that is still on the map. Whether the landing is ground is the route
/// search's question, as it is for every step.
fn add_ledge_hops(grid: &mut MapGrid, tileset: u8) {
if tileset != tileset::OVERWORLD {
return;
}
for y in 0..grid.height() {
for x in 0..grid.width() {
let Some(here) = grid.tile_id(x, y) else { continue };
for (facing, stood, ledge) in LEDGE_TILES {
if here != stood {
continue;
}
let (dx, dy) = facing.delta();
let (Some(nx), Some(ny)) = (checked_step(x, dx), checked_step(y, dy)) else { continue };
let (Some(lx), Some(ly)) = (checked_step(nx, dx), checked_step(ny, dy)) else { continue };
if lx >= grid.width() || ly >= grid.height() {
continue;
}
if grid.tile_id(nx, ny) == Some(ledge) {
grid.ledge(x, y, facing);
}
}
}
}
}
/// Turn every tile-pair collision the loaded tileset has into two directed walls.
fn add_pair_walls(grid: &mut MapGrid, tileset: u8) {
let pairs: Vec<(u8, u8)> = TILE_PAIRS_LAND

View file

@ -162,75 +162,3 @@ fn the_cache_holds_one_map_and_drops_it_on_arrival_somewhere_else() {
assert_eq!(grids.held(), Some(4));
assert!(grids.get(3, 4, 4).is_none());
}
#[test]
fn a_ledge_is_a_hop_from_above_on_the_overworld_tileset_only() {
// `LedgeTiles`: facing down from `$2C` onto `$37` hops two tiles down. Row 64, Route 4.
let mut grid = MapGrid::new(0x0f, 2, 5);
for y in 0..5 {
grid.set(0, y, 0x2c, Walkable::Yes);
}
grid.set(1, 0, 0x2c, Walkable::Yes);
grid.set(1, 1, 0x37, Walkable::No);
grid.set(1, 2, 0x2c, Walkable::Yes);
grid.set(1, 3, 0x2c, Walkable::Yes);
grid.set(1, 4, 0x2c, Walkable::Yes);
add_ledge_hops(&mut grid, tileset::OVERWORLD);
assert!(grid.hops(1, 0, Facing::Down), "down over the ledge from above");
assert!(!grid.hops(1, 2, Facing::Up), "never up it from below");
assert!(!grid.hops(0, 0, Facing::Down), "plain ground is not a ledge");
assert!(!grid.hops(1, 0, Facing::Right), "only the direction the table names");
// `HandleLedges` returns at once on any other tileset.
let mut plain = MapGrid::new(0x3d, 2, 5);
for y in 0..5 {
plain.set(1, y, grid.tile_id(1, y).unwrap_or(0), grid.walkable(1, y));
}
add_ledge_hops(&mut plain, tileset::CAVERN);
assert!(!plain.hops(1, 0, Facing::Down), "no ledges in a cave");
// A ledge whose landing would be off the map is not a hop the table can promise.
let mut edge = MapGrid::new(0x0f, 1, 2);
edge.set(0, 0, 0x2c, Walkable::Yes);
edge.set(0, 1, 0x37, Walkable::No);
add_ledge_hops(&mut edge, tileset::OVERWORLD);
assert!(!edge.hops(0, 0, Facing::Down));
}
#[test]
fn a_warp_carpet_in_front_is_marked_where_extra_warp_check_reads_it() {
// Row 65, the Cerulean badge house's back door: a warp whose own tile is no door, with a
// carpet tile in front of it facing down (`$12`, `warp_carpet_tile_ids.asm`). The bump that
// way is how the cartridge takes it from where the fly stands.
let mut grid = MapGrid::new(0x03, 1, 3);
grid.set(0, 0, 0x2c, Walkable::Yes);
grid.set(0, 1, 0x2c, Walkable::Yes);
grid.set(0, 2, 0x12, Walkable::No);
add_warp_carpets(&mut grid, tileset::OVERWORLD, 0x03);
assert_eq!(grid.carpet_press(0, 1), Some(Facing::Down), "a bump down, into the carpet");
assert_eq!(grid.carpet_press(0, 0), None, "two tiles off is not in front");
// A carpet id is only a carpet in the facing pokered lists it under: `$12` is a down carpet.
let mut up = MapGrid::new(0x03, 1, 2);
up.set(0, 0, 0x12, Walkable::No);
up.set(0, 1, 0x2c, Walkable::Yes);
add_warp_carpets(&mut up, tileset::OVERWORLD, 0x03);
assert_eq!(up.carpet_press(0, 1), None);
// A cave asks `IsPlayerFacingEdgeOfMap` instead, and so does the S.S. Anne's 3F on SHIP.
let mut cave = MapGrid::new(0x3b, 1, 3);
for y in 0..3 {
cave.set(0, y, grid.tile_id(0, y).unwrap_or(0), grid.walkable(0, y));
}
add_warp_carpets(&mut cave, tileset::CAVERN, 0x3b);
assert_eq!(cave.carpet_press(0, 1), None, "no carpets in a cave");
let mut rock_tunnel = cave.clone();
add_warp_carpets(&mut rock_tunnel, tileset::CAVERN, super::super::maps::ROCK_TUNNEL_1F);
assert_eq!(rock_tunnel.carpet_press(0, 1), Some(Facing::Down), "Rock Tunnel 1F is named");
let mut ship = MapGrid::new(0x61, 1, 3);
for y in 0..3 {
ship.set(0, y, grid.tile_id(0, y).unwrap_or(0), grid.walkable(0, y));
}
add_warp_carpets(&mut ship, tileset::SHIP, 0x61);
assert_eq!(ship.carpet_press(0, 1), None, "the S.S. Anne's 3F asks the edge");
}

View file

@ -86,13 +86,5 @@ pub const MT_MOON_B2F: u8 = 0x3d;
pub const CERULEAN_POKECENTER: u8 = 0x40;
pub const CERULEAN_GYM: u8 = 0x41;
pub const CERULEAN_MART: u8 = 0x43;
/// Route 4's Pokémon Center, the one beside Mt. Moon's mouth: the id straight after
/// `CERULEAN_MART` `$43`, and confirmed by the cartridge rather than by counting -- Route 4's warp
/// table names `$44` at (11, 5) (`tests/rom_macros_mode.rs`, row 59's door survey).
pub const MT_MOON_POKECENTER: u8 = 0x44;
pub const ROCK_TUNNEL_1F: u8 = 0x52;
pub const INDIGO_PLATEAU_LOBBY: u8 = 0xae;
/// The house beside Cerulean's west road whose back door is the one way into the closed yard at
/// (9, 9) (row 65). Confirmed by the cartridge rather than by counting: Cerulean City's warp table
/// names `$e6` at (9, 11) and at (9, 9), read from the yard's own survey checkpoint.
pub const CERULEAN_BADGE_HOUSE: u8 = 0xe6;

View file

@ -43,13 +43,6 @@ 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;
@ -292,47 +285,6 @@ 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 {
@ -834,147 +786,6 @@ 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
@ -2163,14 +1974,6 @@ 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).
///

View file

@ -1253,115 +1253,3 @@ 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");
}

View file

@ -1276,36 +1276,3 @@ 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);
}

View file

@ -30,12 +30,6 @@
//! | `FLY_TRAP_CHECKPOINT` | `FLY_MACRO_CHECKPOINT` | the `FLYSIM01` checkpoint to start from |
//! | `FLY_PROBE_FRAMES` | 200000 | frames to drive before giving up |
//! | `FLY_PROBE_STUCK` | 600 | consecutive frames in one non-overworld scene that count as stuck |
//!
//! `FLY_PROBE_CATCH=offers` (row 62) is a different drive: twenty brain minutes of the service's
//! frame behind a uniform stub, counting on every decidable frame which of the shop, centre and
//! ball buttons are on the pad, and reading the cartridge beside it (heals, purchases, throws,
//! catches, whiteouts, `wLastBlackoutMap`). `FLY_PROBE_RNG`, `FLY_PROBE_PREFER`, `FLY_PROBE_PADS`
//! and `FLY_PROBE_TRACE_MACRO` are documented on `offers_survey`.
use std::collections::BTreeMap;
@ -1608,15 +1602,6 @@ fn route_survey(
let (pushed, frontiers) = macros.fences();
println!("- pushed tiles (no window): {pushed:?}");
println!("- frontier marks (no window): {frontiers:?}");
// `FLY_PROBE_SAVE` without `FLY_PROBE_SAVE_RANK` writes the caught frame itself (row 65: the
// Cerulean yard, reached by the survey and by nothing else). The ledgers stay behind, as they
// do in every checkpoint.
if save_rank.is_none()
&& let Some(path) = std::env::var_os("FLY_PROBE_SAVE")
{
let bytes = save_state(checkpoint, gb, adapter, frame, &path);
println!("- saved the caught frame to `{}` ({bytes} bytes)", std::path::Path::new(&path).display());
}
let ledger = AdapterLedger(&*adapter);
macros.inspect(gb, &ledger, |state: &mut dyn MacroState| {
let player = state.player().expect("a loaded map");
@ -1718,303 +1703,6 @@ fn route_survey(
});
}
/// Row 62's offer survey: which of the shop, the centre and the ball buttons the pad deals, on how
/// many frames, under which preconditions, and what comes of the ones that are pressed.
///
/// `FLY_PROBE_CATCH=offers`. The live run bought nothing, threw nothing and healed nowhere for
/// eleven hours, and the event log records only what was chosen, so the question is what was
/// *dealt*. This drives the service's own frame (`flysim::frame::LegacyFrame`) with the macro layer
/// behind a uniform stub: once per hold one of the scene's bound channels is made hot, chosen
/// uniformly (a survey's driver, never the fly's; nothing in the crate reads it). Every frame on
/// which the fly could decide -- a playable scene, a non-empty pad, no macro running -- counts which
/// watched buttons are on the pad; the cartridge is read beside it for what those buttons change.
///
/// `FLY_PROBE_FRAMES` (default twenty brain minutes) bounds the drive, `FLY_PROBE_RNG` changes the
/// choices, `FLY_PROBE_PREFER` names buttons pressed whenever dealt, `FLY_PROBE_PADS=1` prints
/// every pad change and every macro event (and, in a centre with a hurt party and no `HEAL`,
/// the sprites and the ground the nurse's aims are read from), and `FLY_PROBE_TRACE_MACRO=<NAME>`
/// prints every frame of that macro's first three runs with the screen as text
/// (`FLY_PROBE_TRACE_SCREEN=all` on every frame rather than on each press).
#[allow(clippy::too_many_lines)]
fn offers_survey(
gb: &mut Emulator,
adapter: &mut PokemonRedReward,
ms: &mut f64,
layer: &mut flysim::macros::MacroLayer,
decoder: &mut PopulationDecoder,
hold_ms: f64,
) {
use flybrain_gb::pokemon_red::macros::cartridge::MacroState;
use flybrain_gb::pokemon_red::macros::geography::{self, Amenity};
use flybrain_gb::pokemon_red::macros::palette;
const WATCH: [&str; 12] = [
"HEAL", "GO HEAL", "GO SHOP", "BUY BALL", "BUY POTION", "THROW BALL", "YES", "NO", "TALK",
"ITEM", "LEAVE", "CONFIRM",
];
const POKE_BALL: u8 = 0x04;
const CENTERS: [u8; 11] = [0x29, 0x3a, 0x40, 0x44, 0x51, 0x59, 0x85, 0x8d, 0x9a, 0xab, 0xb6];
const MARTS: [u8; 3] = [0x2a, 0x38, 0x43];
let blackout = |gb: &mut Emulator| gb.read8(0xd719);
let balls = |gb: &mut Emulator| {
state::bag(gb).iter().filter(|item| item.id == POKE_BALL).map(|item| u32::from(item.count)).sum::<u32>()
};
let snapshot = |gb: &mut Emulator, adapter: &PokemonRedReward, label: &str| {
let party = state::party(gb);
let hp: Vec<String> =
party.mons.iter().map(|mon| format!("{}/{} {:?}", mon.hp, mon.max_hp, mon.status)).collect();
let bag: Vec<(u8, u8)> = state::bag(gb).iter().map(|item| (item.id, item.count)).collect();
let money = state::money(gb);
let last = blackout(gb);
let player = state::player(gb);
let ledger = AdapterLedger(adapter);
let mut poke = flybrain_gb::pokemon_red::state::PokeState::with_ledger(gb, &ledger);
let st: &mut dyn MacroState = &mut poke;
println!("\n## {label}\n");
println!("- player {player:?}, area {:?}, rank {}", palette::area_here(st), adapter.progress().rank);
println!("- party {hp:?}; needs rest {}", palette::party_needs_rest(st));
println!("- money {money}, bag {bag:?}");
println!("- wLastBlackoutMap ($d719) = {last:#04x}");
let centers: Vec<(String, bool)> =
CENTERS.iter().map(|map| (format!("{map:#04x}"), st.map_visited(*map))).collect();
let marts: Vec<(String, bool)> =
MARTS.iter().map(|map| (format!("{map:#04x}"), st.map_visited(*map))).collect();
println!("- centres visited (lifetime): {centers:?}");
println!("- marts visited (lifetime): {marts:?}");
println!(
"- errand here: mart {:?}, centre {:?}; amenity at map {:?}",
palette::errand(st, Amenity::Mart),
palette::errand(st, Amenity::Center),
player.and_then(|player| geography::amenity_at(player.map))
);
};
snapshot(gb, adapter, "Before the drive");
let budget = env_usize("FLY_PROBE_FRAMES", 71_673);
let mut rng = env_usize("FLY_PROBE_RNG", 20_260_924) as u32 | 1;
let prefer: Vec<String> = std::env::var("FLY_PROBE_PREFER")
.map(|value| value.split(',').map(|name| name.trim().to_string()).collect())
.unwrap_or_default();
// `FLY_PROBE_PADS=1` prints every pad the fly could decide on, when it changes.
let pads = std::env::var("FLY_PROBE_PADS").is_ok_and(|value| value == "1");
let trace_macro = std::env::var("FLY_PROBE_TRACE_MACRO").ok();
let mut traced = 0u32;
let mut tracing_macro = false;
let mut last_mask = 0u32;
let mut last_pad: Vec<String> = Vec::new();
let mut legacy = flysim::frame::LegacyFrame::new();
let mut hot: Option<String> = None;
let mut hot_until = 0.0f64;
let mut next_pick = *ms;
// (button) -> [decidable frames on the pad, starts, done, other outcomes]
let mut tally: BTreeMap<&str, [u64; 4]> = WATCH.iter().map(|name| (*name, [0u64; 4])).collect();
let mut decidable = 0u64;
let mut context: BTreeMap<String, u64> = BTreeMap::new();
let mut starts: BTreeMap<String, u64> = BTreeMap::new();
let mut log: Vec<String> = Vec::new();
let mut last_balls = balls(gb);
let mut last_money = state::money(gb);
let mut last_blackout = blackout(gb);
let mut last_map = state::player(gb).map(|player| player.map);
let mut was_wiped = false;
let mut was_full = true;
let mut counts: BTreeMap<&str, u64> = BTreeMap::new();
let mut maps_seen: BTreeMap<u8, u64> = BTreeMap::new();
for frame in 0..budget {
let bound = layer.bound_channels();
if *ms >= next_pick && !bound.is_empty() && layer.running().is_none() {
rng ^= rng << 13;
rng ^= rng >> 17;
rng ^= rng << 5;
// `FLY_PROBE_PREFER=BUY BALL,THROW BALL` presses those whenever they are dealt, first
// one first: to see what a button does once pressed, not how often the fly would.
let preferred = prefer.iter().map(|name| format!("macro_{}", name.to_lowercase().replace(' ', "_"))).find(|channel| bound.contains(channel));
hot = Some(preferred.unwrap_or_else(|| bound[rng as usize % bound.len()].clone()));
hot_until = *ms + BURST_MS;
next_pick = *ms + hold_ms;
}
if *ms >= hot_until {
hot = None;
}
let active = decoder.decode_bound(&rates(hot.as_deref()), *ms, false, None, Some(&bound));
// What the fly could have pressed on this frame, before the layer acts on it.
let names: Vec<String> = layer.feed_palette().into_iter().map(|slot| slot.name).collect();
let free = layer.running().is_none() && !names.is_empty();
if pads && free && names != last_pad {
println!(
" f{frame:<6} {:?} {} pad {names:?}",
state::player(gb).map(|p| (p.map, p.x, p.y, p.facing)),
layer.scene_name()
);
last_pad = names.clone();
let party_hurt = state::party(gb).mons.iter().any(|mon| mon.hp < mon.max_hp);
if party_hurt
&& state::player(gb).is_some_and(|p| CENTERS.contains(&p.map))
&& !names.iter().any(|name| name == "HEAL")
{
let ledger = AdapterLedger(&*adapter);
let mut poke = flybrain_gb::pokemon_red::state::PokeState::with_ledger(gb, &ledger);
let st: &mut dyn MacroState = &mut poke;
println!(" npcs {:?}", st.npcs());
println!(" heal_goals {:?}", palette::heal_goals(st));
let size = st.map_size();
println!(" size {size:?}");
if let Some(size) = size {
for y in 0..size.height {
let row: String = (0..size.width)
.map(|x| match st.walkable(x, y) {
flybrain_gb::pokemon_red::macros::state::Walkable::Yes => if st.counter_tile(x, y) { 'c' } else { '.' },
flybrain_gb::pokemon_red::macros::state::Walkable::No => if st.counter_tile(x, y) { 'C' } else { '#' },
flybrain_gb::pokemon_red::macros::state::Walkable::Unknown => '?',
})
.collect();
println!(" y{y:2} {row}");
}
}
}
}
if free {
decidable += 1;
for name in &names {
if let Some(entry) = tally.get_mut(name.as_str()) {
entry[0] += 1;
}
}
}
let executed = legacy.execute(Some(layer), &active, 0, *ms, gb, adapter);
// `FLY_PROBE_TRACE_MACRO=BUY BALL` prints every frame of that macro's first three runs:
// the mask, the scene, the counter's screen, the cursor and the wallet.
if let Some(want) = trace_macro.as_deref()
&& layer.running() == Some(want)
&& traced < 3
{
let shop = state::shop(gb);
let cur = state::cursor(gb);
println!(
" {want} f{frame} mask {:#04x} scene {} shop {:?} cursor {}/{} top ({},{}) money {} text {:?}",
executed.mask,
layer.scene_name(),
shop.map(|shop| shop.screen),
cur.current,
cur.max,
cur.top_x,
cur.top_y,
state::money(gb),
state::text_box(gb)
);
if executed.mask != last_mask || std::env::var("FLY_PROBE_TRACE_SCREEN").is_ok_and(|v| v == "all") {
for line in screen_text(gb) {
println!(" | {line}");
}
}
last_mask = executed.mask;
tracing_macro = true;
} else if tracing_macro {
tracing_macro = false;
traced += 1;
}
for event in &executed.events {
if pads {
println!(" f{frame:<6} event {} hot {hot:?}", event.label());
}
let key = match event.outcome { None => 1, Some(flysim::snapshot::MacroOutcome::Done) => 2, Some(_) => 3 };
if let Some(entry) = tally.get_mut(event.name) {
entry[key] += 1;
}
if event.outcome.is_none() {
*starts.entry(event.name.to_string()).or_default() += 1;
}
}
*ms += MS_PER_FRAME;
let evaluated = legacy.stub_advance(Some(layer), gb, adapter, *ms).expect("a frame should complete");
for reward in &evaluated.rewards {
if reward.label.contains("CAUGHT") || reward.label.contains("CATCH") { log.push(format!("f{frame} {}: {}", reward.kind, reward.label)); }
if reward.kind == "catch" {
*counts.entry("catches").or_default() += 1;
log.push(format!("f{frame} catch: {}", reward.label));
}
}
// The cartridge beside the pad.
let party = state::party(gb);
let player = state::player(gb);
let map = player.map(|player| player.map);
if let Some(map) = map {
*maps_seen.entry(map).or_default() += 1;
}
let wiped = !party.mons.is_empty() && party.mons.iter().all(|mon| mon.hp == 0);
let full = party.mons.iter().all(|mon| mon.hp == mon.max_hp && matches!(mon.status, flybrain_gb::pokemon_red::macros::state::Status::Healthy));
if wiped && !was_wiped {
*counts.entry("whiteouts").or_default() += 1;
log.push(format!("f{frame} whiteout on map {map:?}"));
}
if full && !was_full && !wiped && map.is_some_and(|map| CENTERS.contains(&map)) {
*counts.entry("heals at a nurse").or_default() += 1;
log.push(format!("f{frame} healed at a nurse on map {map:?}"));
}
was_wiped = wiped;
was_full = full;
let now_balls = balls(gb);
if now_balls > last_balls {
*counts.entry("balls bought").or_default() += u64::from(now_balls - last_balls);
log.push(format!("f{frame} balls {last_balls} -> {now_balls}"));
} else if now_balls < last_balls {
*counts.entry("balls thrown").or_default() += u64::from(last_balls - now_balls);
log.push(format!("f{frame} balls {last_balls} -> {now_balls}"));
}
last_balls = now_balls;
let money = state::money(gb);
if money < last_money && map.is_some_and(|map| MARTS.contains(&map)) {
*counts.entry("spent at a mart").or_default() += u64::from(last_money - money);
log.push(format!("f{frame} money {last_money} -> {money} on map {map:?}"));
}
last_money = money;
let now_blackout = blackout(gb);
if now_blackout != last_blackout {
log.push(format!("f{frame} wLastBlackoutMap {last_blackout:#04x} -> {now_blackout:#04x}"));
last_blackout = now_blackout;
}
if map != last_map {
if map.is_some_and(|map| CENTERS.contains(&map) || MARTS.contains(&map)) {
log.push(format!("f{frame} entered {map:?} (party full {full}, money {money})"));
}
last_map = map;
}
if free {
let inside = match map {
Some(map) if CENTERS.contains(&map) => "in a centre",
Some(map) if MARTS.contains(&map) => "in a mart",
_ => "elsewhere",
};
let hurt = if full { "full" } else { "hurt" };
let scene = layer.scene_name();
*context.entry(format!("{scene} {inside} party {hurt}")).or_default() += 1;
if scene == "battle" && state::party(gb).active.is_some() {
let ball = if balls(gb) == 0 { "0 balls" } else { ">0 balls" };
let kind = match gb.read8(ram::wIsInBattle) { 1 => "wild", 2 => "trainer", _ => "other" };
*context.entry(format!("battle {kind} {ball}")).or_default() += 1;
}
}
}
println!("\n## Offers over {budget} frames ({:.1} brain minutes), {decidable} decidable\n", budget as f64 * MS_PER_FRAME / 60_000.0);
println!("| button | frames on the pad | share of decidable | starts | done | other |");
println!("| --- | ---: | ---: | ---: | ---: | ---: |");
for (name, [offered, started, done, other]) in &tally {
println!(
"| {name} | {offered} | {:.2}% | {started} | {done} | {other} |",
if decidable == 0 { 0.0 } else { *offered as f64 * 100.0 / decidable as f64 }
);
}
println!("\n- decidable frames by context: {context:?}");
println!("- all starts: {starts:?}");
println!("- counts: {counts:?}");
println!("- frames per map: {maps_seen:?}");
println!("\n### Events\n");
for line in log.iter().take(200) {
println!("- {line}");
}
snapshot(gb, adapter, "After the drive");
}
/// How the candidate readings of "a two-option box is up" separate the frames of a survey.
///
/// Three columns, because three things could say it and only a measurement says which: the
@ -2099,14 +1787,6 @@ 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);
@ -2150,12 +1830,6 @@ fn main() {
return;
}
// Row 62's offer survey: which shop, centre and ball buttons are dealt, frame by frame.
if std::env::var("FLY_PROBE_CATCH").is_ok_and(|value| value == "offers") {
offers_survey(&mut gb, &mut adapter, &mut ms, &mut layer, &mut decoder, hold_ms);
return;
}
// Row 57's pad survey: earn the session's ledgers from the checkpoint with the real palette,
// and read the frame the pad comes down to one refusing button on.
if std::env::var("FLY_PROBE_CATCH").is_ok_and(|value| value == "route") {
@ -2474,348 +2148,3 @@ 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}");
}
}

View file

@ -702,8 +702,13 @@ impl Run {
flybrain_gb::pokemon_red::state::money(&mut self.gb)
}
/// How many of `item` the bag holds, summed over its stacks: what row 62's purchase is
/// measured by.
/// How many of `item` the bag holds, summed over its stacks.
///
/// Kept unused for now: the purchase the section-13 test would have counted with it is
/// unit-proven rather than ROM-proven (see `go_shop_enters_the_mart_once_and_walks_to_its_counter`
/// and rows 35 and 36 of `infra/docs/macros-traps.md`), and deleting the reader would mean
/// writing it again with the fix.
#[allow(dead_code)]
fn bag_count(&mut self, item: u8) -> u32 {
flybrain_gb::pokemon_red::state::bag(&mut self.gb)
.iter()
@ -773,10 +778,8 @@ 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. 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) {
// (the v0.2.4 deadlock fix), so counting it would measure the wrong thing.
if self.own_turn() {
self.move_button_on_battle_pad |=
bound.iter().any(|channel| channel.starts_with("macro_move_"));
let dealt = bound.len();
@ -3803,754 +3806,3 @@ 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
}
/// `wLastBlackoutMap`, `$d719` at the pinned commit (`ram/wram.asm`, the byte after
/// `wBoulderSpriteIndex`): the map a whiteout returns the player to, written by the nurse's YES
/// (`SetLastBlackoutMap`) and by nothing else a walk can reach. Read by this test only; the macros
/// never read it.
const W_LAST_BLACKOUT_MAP: u16 = 0xd719;
const POKE_BALL: u8 = 0x04;
/// The live checkpoint from inside the Mt. Moon Pokémon Center with a hurt party, or `None`.
fn row62_center_checkpoint() -> Option<flysim::store::Checkpoint> {
std::env::var_os("FLY_ROW62_CENTER_CHECKPOINT").map(|path| {
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope")
})
}
/// The rung-11 Pewter checkpoint, errands paid, money and no ball, or `None`.
fn row62_mart_checkpoint() -> Option<flysim::store::Checkpoint> {
std::env::var_os("FLY_ROW62_MART_CHECKPOINT").map(|path| {
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope")
})
}
/// Row 62: in Route 4's Pokémon Center with a hurt party, `HEAL` is on the pad and heals, and the
/// cartridge's whiteout map becomes Route 4.
///
/// **What was live** (2026-09-24, v0.6.2, rung 12 MT. MOON, 3.5 hours on the rung): in eleven
/// hours of the fresh run no `HEAL`, no `GO HEAL` after the first visit, no nurse's YES, so
/// `wLastBlackoutMap` stayed Pallet Town and every whiteout in Mt. Moon walked the fly back from
/// Pallet. This centre was on no table: `HEAL` is dealt by the map id and the map id was not
/// there. The checkpoint is row 59's, taken with the fly in this centre at 10 of 70 HP.
///
/// ```sh
/// FLY_ROM=/path/to/pokemon-red.gb \
/// FLY_ROW62_CENTER_CHECKPOINT=.local/checkpoints/release-rank12-mtmoon-center.checkpoint \
/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row62
/// ```
#[test]
fn row62_heal_is_dealt_in_the_mt_moon_center_and_moves_the_whiteout_map() {
let rom = skip_without_rom!();
let Some(checkpoint) = row62_center_checkpoint() else {
eprintln!("skipped: no FLY_ROW62_CENTER_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.map(), MT_MOON_POKECENTER, "the checkpoint is Route 4's centre");
assert!(!run.party_rested(), "and the party is hurt");
assert_eq!(run.gb.read_wram(W_LAST_BLACKOUT_MAP), 0x00, "whiteouts go to Pallet Town");
// `HEAL` on the pad inside the centre. On the base it is never there: the map id is on no
// table, so the rotation walks the fly back out.
run.force_hot = Some("macro_heal");
let mut heal_dealt = false;
run.drive_until("HEAL on the centre's pad", 3_000, |run| {
heal_dealt |= run.map() == MT_MOON_POKECENTER
&& run.layer.bound_channels().iter().any(|channel| channel == "macro_heal");
heal_dealt
});
run.drive_until("the party reads back full", 3_000, |run| run.party_rested());
assert_eq!(run.map(), MT_MOON_POKECENTER, "healed where it stood");
assert_eq!(
u32::from(run.gb.read_wram(W_LAST_BLACKOUT_MAP)),
ROUTE_4,
"the nurse's YES wrote Route 4 as the whiteout map"
);
// Full now, so the button leaves the pad rather than being pressed again (12.12).
for _ in 0..120 {
run.frame();
}
assert!(
!run.layer.bound_channels().iter().any(|channel| channel == "macro_heal"),
"a rested party is no reason to rest: {:?}",
run.layer.bound_channels()
);
}
/// Row 62: from Pewter City with both errands paid, 1,606 in the wallet and no ball, `GO SHOP` is
/// on the pad, and the counter it leads to sells the fly a ball.
///
/// **What was live**: `GO SHOP` twice in eleven hours, both on the parcel; `BUY BALL` never;
/// `THROW BALL` never. Three things stood between the fly and a ball, all measured from this
/// checkpoint: the errand was paid by the first visit and never offered again; a clerk this
/// session had talked to was out of `TALK`'s reach; and `BUY BALL` pressed its last A while the
/// price line was still printing, so it reported `done` with nothing bought (55 of 55 on the
/// cartridge, the wallet unchanged). The drive here leans on one button at a time, in order; it
/// says nothing about which the fly would press.
///
/// ```sh
/// FLY_ROM=/path/to/pokemon-red.gb \
/// FLY_ROW62_MART_CHECKPOINT=.local/checkpoints/survey-rank11-pewter.checkpoint \
/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row62
/// ```
#[test]
fn row62_go_shop_comes_back_with_no_ball_and_buy_ball_rings_up_a_ball() {
use flybrain_gb::pokemon_red::macros::PokemonPalette;
use flybrain_gb::{MacroPalette, Outcome, Started};
let rom = skip_without_rom!();
let Some(checkpoint) = row62_mart_checkpoint() else {
eprintln!("skipped: no FLY_ROW62_MART_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.bag_count(POKE_BALL), 0, "no ball at the checkpoint");
let money = run.money();
assert!(money >= 200, "and the money for one: {money}");
// The palette driven directly, one choice per hold: the chain's buttons whenever they are
// dealt, in this order, and otherwise the first button on the pad. A survey's driver, never
// the fly's -- the claim is about what the pad deals and what the buttons do.
let order = ["BUY BALL", "CONFIRM", "TALK", "GO SHOP"];
let hold_frames = 48u32;
let mut palette = PokemonPalette::new(SEED);
let mut running: Option<&'static str> = None;
let mut since_decision = hold_frames;
let mut ms = run.ms;
let mut go_shop_on_the_first_pad = None;
let mut entered_the_mart = None;
let mut buy_done_without_a_ball = 0u32;
let mut buy_done_with_a_ball = 0u32;
for frame in 0..30_000u32 {
palette.clock(ms);
let observed = {
let ledger = AdapterLedger(&run.adapter);
palette.observe(&mut run.gb, &ledger)
};
if go_shop_on_the_first_pad.is_none() && !observed.bindings.is_empty() {
go_shop_on_the_first_pad =
Some(observed.bindings.iter().any(|binding| binding.name == "GO SHOP"));
}
let mut mask = 0u8;
{
let ledger = AdapterLedger(&run.adapter);
if running.is_some() {
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = None,
}
} else if since_decision >= hold_frames && !observed.bindings.is_empty() {
since_decision = 0;
let binding = order
.iter()
.find_map(|want| observed.bindings.iter().find(|binding| binding.name == *want))
.unwrap_or(&observed.bindings[0]);
if let Started::Running(name) = palette.start(binding.slot, &mut run.gb, &ledger) {
running = Some(name);
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = None,
}
}
}
}
if let Some((name, outcome)) = palette.take_finished()
&& name == "BUY BALL"
&& outcome == Outcome::Done
{
if run.bag_count(POKE_BALL) == 0 {
buy_done_without_a_ball += 1;
} else {
buy_done_with_a_ball += 1;
}
}
since_decision += 1;
run.gb.set_buttons(mask);
run.gb.run_frame().expect("a frame should complete");
ms += MS_PER_FRAME;
run.adapter.sample(&mut run.gb, ms);
if entered_the_mart.is_none() && run.map() == PEWTER_MART {
entered_the_mart = Some(frame);
}
if run.bag_count(POKE_BALL) > 0 && running.is_none() {
break;
}
}
eprintln!(
"GO SHOP on the first pad {go_shop_on_the_first_pad:?}, into the mart at \
{entered_the_mart:?}, BUY BALL done with a ball {buy_done_with_a_ball} / without \
{buy_done_without_a_ball}, balls {}, money {} -> {}",
run.bag_count(POKE_BALL),
money,
run.money()
);
// The errand is paid (the adapter's map ledger has the mart), so on the base `GO SHOP` is on
// no pad in Pewter at all.
assert_eq!(go_shop_on_the_first_pad, Some(true), "`GO SHOP` with no ball and 1,606");
assert!(entered_the_mart.is_some(), "`GO SHOP` walked into the Pewter mart");
assert_eq!(buy_done_without_a_ball, 0, "a `BUY BALL` reported done with nothing bought");
assert_eq!(run.bag_count(POKE_BALL), 1, "one ball, one press");
assert_eq!(run.money(), money - 200, "and the wallet paid for it");
// With a ball in the bag the mart has nothing to do for the fly.
let still = {
let ledger = AdapterLedger(&run.adapter);
palette.observe(&mut run.gb, &ledger)
};
assert!(
!still.bindings.iter().any(|binding| binding.name == "GO SHOP"),
"a ball in the bag: {:?}",
still.bindings.iter().map(|binding| binding.name).collect::<Vec<_>>()
);
}
/// A checkpoint from Mt. Moon B2F standing on the ladder up to B1F's exit chamber (rank 12, the
/// party hurt), or `None`.
fn row62_east_checkpoint() -> Option<flysim::store::Checkpoint> {
std::env::var_os("FLY_ROW62_EAST_CHECKPOINT").map(|path| {
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope")
})
}
/// Row 62, review round 2: east of Mt. Moon, `GO HEAL` is not dealt to walk a hurt fly back into
/// the mountain.
///
/// **The fault** (review of the row's first round): Route 4's centre is on the mountain's west
/// side, and Route 4's east side and B1F's exit chamber are in Route 4's area too. The only road
/// from them to that door runs through B2F, which is in no area, so `GO HEAL` walked the fly down
/// into B2F and left the pad there, while `GO OBJECTIVE` walked it back up toward Cerulean: a
/// two-map ring by construction, and a hurt fly is exactly the one that comes out of the mountain.
///
/// The checkpoint is the live one from B2F standing on the exit chamber's ladder at (5, 7)
/// (v0.6.4, rank 12, 28 of 85 HP). The test's own setup steps the player off the ladder and back
/// on through the joypad, which takes it up into the exit chamber; from there it drives the stub
/// rotation with `GO OBJECTIVE` leaned on, the road out. The claim is about the pad only: on the
/// exit chamber and on Route 4's east side, with the party hurt, `GO HEAL` is never dealt. `main`
/// passes it too -- it has no row for Route 4's centre at all.
///
/// ```sh
/// FLY_ROM=/path/to/pokemon-red.gb \
/// FLY_ROW62_EAST_CHECKPOINT=.local/checkpoints/release-rank12-mtmoon-b2f-ladder.checkpoint \
/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row62_east
/// ```
#[test]
fn row62_east_of_mt_moon_go_heal_is_not_dealt_back_into_the_mountain() {
use flybrain_gb::emulator::buttons;
use flybrain_gb::pokemon_red::macros::geography::{self, Region};
const MT_MOON_B1F: u8 = 0x3c;
const MT_MOON_B2F: u8 = 0x3d;
let rom = skip_without_rom!();
let Some(checkpoint) = row62_east_checkpoint() else {
eprintln!("skipped: no FLY_ROW62_EAST_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert!(run.adapter.progress().rank >= 12, "the checkpoint is on the Mt. Moon rung");
assert!(!run.party_rested(), "and the party is hurt");
let at = |run: &mut Run| {
flybrain_gb::pokemon_red::state::player(&mut run.gb).map(|p| (p.map, p.x, p.y))
};
assert_eq!(at(&mut run), Some((MT_MOON_B2F, 5, 7)), "on the ladder up to the exit chamber");
// Setup, not the fly: off the ladder to the right and back onto it, which climbs it.
for mask in [buttons::RIGHT, buttons::NONE, buttons::LEFT, buttons::NONE] {
for _ in 0..24 {
run.gb.set_buttons(mask);
run.gb.run_frame().expect("a frame");
}
}
for _ in 0..240 {
if at(&mut run).is_some_and(|(map, _, _)| map == MT_MOON_B1F) {
break;
}
run.gb.set_buttons(buttons::NONE);
run.gb.run_frame().expect("a frame");
}
assert_eq!(at(&mut run).map(|(map, _, _)| map), Some(MT_MOON_B1F), "up the ladder");
let east = |run: &mut Run| {
let Some((map, x, y)) = at(run) else { return false };
let grid = flybrain_gb::pokemon_red::state::map_grid(&mut run.gb).ok();
let region = geography::region_on(map, x, y, grid.as_ref());
region == Region::piece(MT_MOON_B1F, 0) || region == Region::piece(0x0f, 1)
};
let mut east_frames = 0u32;
let mut on_route_4 = 0u32;
let mut go_heal_east = 0u32;
let mut first: Option<(u32, (u8, u8, u8))> = None;
run.force_hot = Some("macro_go_objective");
for frame in 0..12_000u32 {
run.frame();
if !east(&mut run) || run.party_rested() {
continue;
}
east_frames += 1;
if run.map() == ROUTE_4 {
on_route_4 += 1;
}
if run.layer.bound_channels().iter().any(|channel| channel == "macro_go_heal") {
go_heal_east += 1;
if let Some(here) = at(&mut run) {
first.get_or_insert((frame, here));
}
}
}
eprintln!(
"{:.1} brain minutes: hurt east of the mountain {east_frames} frames ({on_route_4} on Route 4), \
GO HEAL dealt on {go_heal_east} (first {first:?}), rank {}, route {:?}, macros {:?}",
run.ms / 60_000.0,
run.adapter.progress().rank,
run.route,
run.started
);
assert!(east_frames > 0, "the fly was never hurt on the exit chamber: {:?}", run.route);
assert_eq!(go_heal_east, 0, "GO HEAL dealt east of the mountain, first at {first:?}");
}
fn row64_checkpoint() -> Option<flysim::store::Checkpoint> {
std::env::var_os("FLY_ROW64_CHECKPOINT").map(|path| {
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope")
})
}
/// Mt. Moon's far side, from the checkpoint pulled during the two-day ring.
///
/// **What was live** (2026-09-26 to 09-28, v0.6.2/v0.6.4, rank 12 MT. MOON, the objective Cerulean
/// City): about 750 macros per ten brain minutes, every one `done`, no reward, no new ground --
/// `GO OBJECTIVE` and `GO WARP`, 27 frames each. Forty-eight hourly flysim restarts did not clear
/// it and a milestone reset bought hours (`infra/docs/macros-traps.md` row 64). The fly stands on
/// B2F (5, 7), the ladder up to B1F's exit chamber, which is the one road on. Two things stacked:
///
/// - a warp whose exit has no press fires at the end of a **step onto it**
/// (`CheckWarpsNoCollision`), and both buttons aimed at the tile underfoot, settled on it and
/// reported `done` without a press -- section 12.2's trap with no ledger in it, so a restore
/// restores it;
/// - off the ladder, the road reaches Route 4's east side, where Cerulean is three **ledges** down.
/// The route search read a ledge as a wall both ways, so `GO OBJECTIVE` refused `no route`, the
/// edge rested in the blocked ledger, and the other walks took the fly back into the cave --
/// onto B1F's exit (27, 3), the same trap one floor up.
///
/// The driver is the real palette with the live brain's measured favourites pressed whenever they
/// are dealt (`GO OBJECTIVE`, then `GO WARP`) and one xorshift choice per hold otherwise: a harness
/// choice, not the fly's. On the base it never leaves (5, 7). The claims:
///
/// - **the first `GO OBJECTIVE`, started on the ladder, takes it**: the map has changed when it ends;
/// - **the fly hops a ledge on Route 4** under a walk (`wMovementFlags` bit 6 with a macro running),
/// and **no tile enters the pushed ledger on the way down**: a hop the walk asked for is not a push-back;
/// - **the fly reaches Cerulean City** inside the budget.
///
/// ```sh
/// FLY_ROM=/path/to/pokemon-red.gb \
/// FLY_ROW64_CHECKPOINT=<the rank-12 checkpoint pulled during the ring, under .local/checkpoints> \
/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture mt_moons_far_side
/// ```
#[test]
fn the_fly_takes_the_ladder_it_stands_on_and_hops_down_to_cerulean_from_mt_moons_far_side() {
use flybrain_gb::pokemon_red::macros::PokemonPalette;
use flybrain_gb::pokemon_red::state;
use flybrain_gb::{MacroPalette, MemoryReader, Outcome, Started};
const MT_MOON_B2F: u8 = 0x3d;
const ROUTE_4: u8 = 0x0f;
const CERULEAN: u8 = 0x03;
const LEDGE_OR_FISHING: u8 = 1 << 6;
let rom = skip_without_rom!();
let Some(checkpoint) = row64_checkpoint() else {
eprintln!("skipped: no FLY_ROW64_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
let start = state::player(&mut run.gb).expect("a loaded map");
assert_eq!((start.map, start.x, start.y), (MT_MOON_B2F, 5, 7), "the checkpoint is on B2F's exit ladder");
let budget = 8_000u32;
let hold_frames = 48u32;
let mut palette = PokemonPalette::new(SEED);
let mut rng = 20_260_928u32 | 1;
let mut running = false;
let mut since_decision = hold_frames;
let mut ms = run.ms;
let mut arrivals: Vec<(u32, u8)> = Vec::new();
let mut last = None;
let mut first_objective: Option<(u8, u8)> = None;
let mut first_started_on: Option<u8> = None;
let mut hop_frames = 0u32;
let mut done_in_place = 0u32;
// The pushed ledger as it stood when the fly first arrived in Cerulean City: the road from the
// ladder over the ledges.
let mut pushed_on_the_way: Option<String> = None;
let mut walled = false;
for frame in 0..budget {
palette.clock(ms);
let observed = {
let ledger = AdapterLedger(&run.adapter);
palette.observe(&mut run.gb, &ledger)
};
let before = state::player(&mut run.gb).map(|player| (player.map, player.x, player.y));
let mut mask = 0u8;
{
let ledger = AdapterLedger(&run.adapter);
if running {
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = false,
}
} else if since_decision >= hold_frames && !observed.bindings.is_empty() {
since_decision = 0;
rng ^= rng << 13;
rng ^= rng >> 17;
rng ^= rng << 5;
let binding = ["GO OBJECTIVE", "GO WARP"]
.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) {
if first_started_on.is_none() && binding.name == "GO OBJECTIVE" {
first_started_on = before.map(|(map, _, _)| map);
}
running = true;
match palette.step(&mut run.gb, &ledger) {
Some(held) => mask = held,
None => running = false,
}
}
}
}
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((name, outcome)) = palette.take_finished() {
let after = state::player(&mut run.gb).map(|player| player.map);
if name == "GO OBJECTIVE" && first_objective.is_none() {
first_objective = first_started_on.zip(after);
}
if matches!(outcome, Outcome::Done)
&& matches!(name, "GO OBJECTIVE" | "GO WARP")
&& after == Some(MT_MOON_B2F)
&& state::player(&mut run.gb).is_some_and(|player| (player.x, player.y) == (5, 7))
{
done_in_place += 1;
}
}
if running
&& state::player(&mut run.gb).is_some_and(|player| player.map == ROUTE_4)
&& run.gb.read8(flybrain_gb::pokemon_red::symbols::ram::wMovementFlags) & LEDGE_OR_FISHING != 0
{
hop_frames += 1;
}
if let Some(player) = state::player(&mut run.gb)
&& last != Some(player.map)
{
last = Some(player.map);
arrivals.push((frame, player.map));
if player.map == CERULEAN && pushed_on_the_way.is_none() {
pushed_on_the_way = Some(format!("{:?}", palette.fences().0));
walled = !palette.fences().0.is_empty();
}
}
}
let cerulean = arrivals.iter().find(|(_, map)| *map == CERULEAN).map(|(frame, _)| *frame);
let route_4_pushed = pushed_on_the_way.unwrap_or_else(|| format!("{:?}", palette.fences().0));
eprintln!(
"{:.1} brain minutes: first GO OBJECTIVE {first_objective:?}, done on the ladder in place \
{done_in_place}, hop frames under a walk on Route 4 {hop_frames}, Cerulean City at \
{cerulean:?}, pushed on the way {route_4_pushed}, rank {}, arrivals {arrivals:?}",
(ms - run.ms) / 60_000.0,
run.adapter.progress().rank,
);
assert_eq!(done_in_place, 0, "a walk reported done on the ladder it had not taken");
let (from, to) = first_objective.expect("GO OBJECTIVE was never started and finished");
assert_eq!(from, MT_MOON_B2F, "the first GO OBJECTIVE started on B2F's ladder");
assert_ne!(to, MT_MOON_B2F, "the first GO OBJECTIVE ended where it began: {arrivals:?}");
assert!(hop_frames > 0, "no ledge was hopped under a walk on Route 4: {arrivals:?}");
assert!(!walled, "a tile was walled on the way down to Cerulean City: {route_4_pushed}");
assert!(cerulean.is_some(), "the fly never reached Cerulean City: {arrivals:?}");
}
const CERULEAN_CITY: u32 = 0x03;
const CERULEAN_BADGE_HOUSE: u32 = 0xe6;
/// A checkpoint in the closed yard behind Cerulean's badge house, standing on its back door, or
/// `None` to skip.
///
/// Row 65's is the route survey's own (`examples/scene_probe.rs`, `FLY_PROBE_CATCH=route
/// FLY_PROBE_RNG=99` from `FLY_ROW64_CHECKPOINT`, written with `FLY_PROBE_CATCH_FRAME=31170
/// FLY_PROBE_SAVE`): the first free frame after `GO OUT` in the badge house took its back door.
fn row65_yard_checkpoint() -> Option<flysim::store::Checkpoint> {
std::env::var_os("FLY_ROW65_YARD_CHECKPOINT").map(|path| {
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope")
})
}
/// Row 65: out of the Cerulean badge house's back yard, whose one way out is the door underfoot.
///
/// **What the row-64 review found** (its own survey, seed 7, and the same from seed 99 on the
/// release tree): `GO OUT` in the badge house (`$e6`) took the back door at (2, 0), which leaves
/// the fly on Cerulean (9, 9), the door tile of a yard of 33 tiles whose only exit is that door.
/// From then on the pad was empty for as long as the survey ran (about 32,000 frames), with
/// `GO ROUTE` and `GO ITEM` refused `no route` whenever they came back. Three things stacked:
///
/// - the exit walks set a step-fired door underfoot aside whenever any other exit was listed,
/// reachable or not, so the one door that could be taken never was;
/// - the door is no door tile: it fires on a bump toward the house (a warp carpet in front), and
/// row 64's step off and back on does nothing on it;
/// - Cerulean was one piece on the map graph, so every door and edge of the town was a way out of
/// the yard for the route search to refuse, and the house's two doors were one door to `GO OUT`.
///
/// The claims, none of them about which button the fly presses, over the stub rotation: the fly
/// **leaves the yard** for the town, and **no run of overworld frames in the yard deals an empty
/// pad** for as long as ten seconds.
///
/// ```sh
/// FLY_ROM=/path/to/pokemon-red.gb \
/// FLY_ROW65_YARD_CHECKPOINT=.local/checkpoints/survey-rank15-row65-yard.checkpoint \
/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row65
/// ```
#[test]
fn row65_the_fly_leaves_the_cerulean_badge_houses_back_yard() {
let rom = skip_without_rom!();
let Some(checkpoint) = row65_yard_checkpoint() else {
eprintln!("skipped: no FLY_ROW65_YARD_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.map(), CERULEAN_CITY, "the checkpoint is in Cerulean City");
assert_eq!(run.tile(), (9, 9), "on the badge house's back door");
// The yard, as the cartridge's own ground says: every tile a walk from the door reaches. Read
// here rather than from the map graph, so the base (which has no piece for it) is measured by
// the same ruler.
let grid = flybrain_gb::pokemon_red::state::map_grid(&mut run.gb).expect("Cerulean's grid decodes");
let yard = grid.reachable(9, 9);
assert!(!yard.contains(9, 12), "the town outside the front door is not the yard's");
let in_yard = |run: &mut Run| run.map() == CERULEAN_CITY && {
let (x, y) = run.tile();
yard.contains(x, y)
};
let mut left: Option<(u32, u32)> = None;
let mut empty = 0u32;
let mut worst_empty = 0u32;
let mut into_the_house = 0u32;
let mut previous = run.map();
for frame in 0..24_000u32 {
run.frame();
let map = run.map();
if map == CERULEAN_BADGE_HOUSE && previous == CERULEAN_CITY {
into_the_house += 1;
}
previous = map;
let yard_now = in_yard(&mut run);
// On a frame the pad is dealt for: a warp's tear holds the new map with the old tile.
if left.is_none()
&& !yard_now
&& map != CERULEAN_BADGE_HOUSE
&& map != u32::MAX
&& run.layer.scene_name() == "overworld"
{
left = Some((frame, map));
}
if yard_now && run.layer.scene_name() == "overworld" && run.layer.bound_channels().is_empty() {
empty += 1;
worst_empty = worst_empty.max(empty);
} else {
empty = 0;
}
}
eprintln!(
"{:.1} brain minutes: out of the yard at {left:?}, into the badge house {into_the_house} \
times, longest empty pad in the yard {worst_empty} frames, rank {}, route {:?}, macros {:?}",
run.ms / 60_000.0,
run.adapter.progress().rank,
run.route,
run.started
);
assert!(worst_empty < 600, "an empty pad in the yard for {worst_empty} frames: {:?}", run.started);
assert!(left.is_some(), "the fly never left the yard: {:?} {:?}", run.route, run.started);
}