# TBG (J) — CPU AI: planner, controller, power use (exact spec) Scope: everything needed to reimplement the COM opponent faithfully. [C] = confirmed in Mesen (bit-exact replay or direct observation), [I] = read from code only. **The spec is executable:** `re/tools/ai_ref.py` is a literal Python transliteration of the planner (81:D9BA … 81:E46B) and controller (81:8A52) over a memory model, validated against the real game: - planner: **411/411** logged COM decisions reproduced exactly, *including the whole $019D–$01FB workspace* (7 capture runs, all branches except pattern set 4; Select/Mahi/panic paths forced via pokes). [C] - controller: **21 653/21 674** logged frames (4 runs, difficulty 0–3) predict the exact pad word; all 21 misses are frames where P1 took a piece earlier in the same frame (P1 runs before P2 in the battle loop 81:A548), i.e. a snapshot-timing artefact, not a spec gap. [C] ``` python3 -I re/tools/ai_ref.py rom/tbg_jp.sfc re/runs/ai2/log1 re/runs/ai2/rec_d0 # re-validate python3 -I re/tools/ai_tables.py rom/tbg_jp.sfc > re/notes/ai_tables.txt # readable tables python3 -I re/tools/ai_tables.py rom/tbg_jp.sfc --cpp > ai_blob.inc # C++ byte blob ``` Captures: `re/lua/ai2_log.lua` (planner entry/exit dumps, `re/runs/ai2/log*/calls.bin`), `re/lua/ai2_rec.lua` (2 KiB WRAM per frame + COM pad log, `re/runs/ai2/rec_d{0..3}/`). ## Porting recommendation Port `Planner`/`Controller` from ai_ref.py **literally** (8-bit arithmetic, N-flag compares) against a small "ROM-layout RAM image" rebuilt each call, rather than re-deriving a clean algorithm. Reasons — the original has quirks that change decisions and are reproduced only by a memory model: 1. Pointer variables are reused between pattern variants: after a successful template match whose follow-up check fails, the next variant is read through the pointer the *result lookup* left behind (81:E15B/81:E36D/81:DF18 overwrite DP $34). Matching continues over unrelated ROM bytes. 2. 81:A338 (Mahi handling) is a player-DP routine called with the *planner* DP: it tests planner $06 (= column 6 height) and zeroes planner $24 (= rank of column 6). 3. Padding loops compare a byte with itself (81:E0D8, 81:E2DE): only one pad byte is written, then the window restarts at column 0. 4. Template reads run past their tables (observed reads 81:E40A–81:F197). 5. Fit checks index the height array with a possibly negative target column (reads land in the P1 board). Image contents needed: WRAM $0100–$01FF (scratch; planner DP = $019D), boards at $0282 (P1) / $04E2 (P2) (10×24 bytes, rows from $0296/$04F6 are the 22 playfield rows), $012A (player index of the COM: 0 = P1, 1 = P2), $0228/$0229 and $0488/$0489 (status / active power per player), $0222/$0482 (attack stocks), $016B–$016D (queue), $00D2/$00D3, the COM player's DP ($0202 or $0462 + $00..$7F), and bank $81 $E400–$F1FF (`kAiBlob`). The player boards in the image are exactly the C++ `Board` cells (row-major, top first). ## When it runs At COM spawn (P2 state 04 → 05 init, 81:B23D; only when `$DE & 2` = vs-COM) [C]: 1. `DP $1D` (entry period) = **$0C = 12 frames** for the COM (humans get DP $7C = 7). [C] 2. Difficulty `$D2` (global, options; 0–3): - 0: `$D3 = $80` (soft-drop throttle, see controller). - 1: roll `R = 82:D19C`; if R < 50: `$015A = (rng & $1F) + $50` → that piece's soft-drop delay is 80–111 frames. - 2: nothing extra. 3: `DP $7D = DP $7B = 0` (lock-delay variant parameters; effect [I]). 3. `DP $0D = 0` (rotation-direction invert, set by Reverse handling [I]). 4. Planner `81:D9BA` → target rotation `DP $24`, target column `DP $25` (board column of the piece's leftmost filled cell). [C] 5. Flags `82:D1FB` → `DP $26`. Then 81:C642 / 82:8C51 / 82:BA03 (power side effects at spawn). 6. Every frame in state 05: controller `81:8A52` writes one pad word to `$01F1`, copied to `$012D` and `$01F7` (81:B2E0) = the COM's controller input. [C] ## Planner (81:D9BA) — semantics Workspace D=$019D. Piece = `DP06 mod 7` (O L J S Z I T = 0..6); **if the COM's own Select (1F) is active, plan for I** (82:BD0C — it will press L to change the piece, see controller). 1. **Heights** `h[c]` (DP $00–$09) = 22 − empty cells above the first block in column c (rows 2..23). 2. **Sort** (81:DC02): `sh[k]` sorted heights ascending (DP $0A), `sc[k]` their columns (DP $14, stable by column), `rank[c]` (DP $1E+c) = number of columns strictly lower. 3. **Profile** DP $28..$2B = `sh[1]-sh[0], sh[2]-sh[1], …` (22 − last beyond the end). 4. If the opponent's Mahi (13) is active → skip to step 7. 5. **Special templates** (81:DE38, status bit 6 set while searching): for each variant v of the piece (count E4E9): window = ranks of 6 columns starting `sc[0] - off[v]` (pad $0A off-board); must match the 6-byte rank template; the 4-byte profile template must match DP $28..; target rot/col from E51A/E528; column must be 0..9 and pass the overflow check (81:E3E3). First hit wins. 6. **Wells** (81:DFA5): scanning columns lowest-first, a well = column with both neighbours ≥ 3 higher (walls = 22); type 0 equal depth, 1 right side lower, 2 right side higher. Needs **two** wells; the first is tried, then the second, using E77F (rotation; 63 = this piece can't fill that type) and E7A2 (column offset), plus the overflow check. 7. If ≥ 5 of columns 1–8 have height ≥ 18 → **panic search** (81:DA9F) over 4 template sets (EC1F…EC3F): accept the first candidate that fits under height 22 (81:E45C); otherwise keep the candidate with the lowest base height that passes the overflow check; if none, fall through to pattern fit. 8. **Pattern fit** (81:DB40): sets 0..4 × sorted column index k 0..9 × variant: window = heights of 5 columns from `sc[k] - win` minus `sh[k]` (FF where lower, 22−base off-board) matched against a 5-byte pattern (E7D6); target from E7E0/E7EA; must pass the Mahi check and the overflow check. A set with zero variants for this piece ends the search. 9. **Fallback** (81:DB7D): first column with rank 0, rotation 0. Template byte semantics, overflow limits and all table contents: `re/notes/ai_tables.txt`. Overflow check 81:E3E3: per piece column, `h[col] + cells(piece,rot,col)` must stay below 23 (25 if ≥ 7 columns are ≥ 20 high, 27 if ≥ 7 columns are ≥ 21 high). 81:E1B6 (also used by the controller): `$01DF` = current leftmost filled column of the falling piece in board coordinates, `$01E0` = its top row − 3 (22 if above the field). ## Controller (81:8A52) — one button per frame Pad bits: Up 0800, Down 0400, Left 0200, Right 0100, A 0080 (rot +1), B 8000 (rot −1), L 0020. In order (first match wins): 1. Unless P1 has Remocon (21) active: clear `$0145/$0147/$0151 + $012A` latches. 2. `DP26 bit0` (use power): press **Up** if affordable (81:8BCE: `DP23 == 0` and meter ≥ some level cost), else nothing. 3. Own Select (1F) active and current piece not I → **L** (also clears `$0155+$012A`). 4. **Danger** (any of columns 1–8 height > 21, from the planner's heights): for L/J/I (raw type 1, 2, 5 only) shift toward the target first; otherwise as normal. 5. Rotation ≠ target → rotate: opponent's Kaiten (14) active → may soft-drop instead (81:A0DC); target rot 3 → B, 1 → A, 0/2 → B if target column < 4 else A; `DP0D` ≠ 0 swaps A/B. 6. Column ≠ target → Right if current < target else Left. 7. Aligned (81:8B5B) → soft drop (Down), except: - `bit2` (difficulty ≥ 2) and `DP2A ≠ 13`: drop if ≥ 8 columns are ≥ 18 high or garbage is incoming, or the next piece is I; **don't drop if the piece after next is I** (lets the opponent take the next piece in the contested queue so the COM gets the I). - `bit3`: don't drop if difficulty ≥ 1, `bit4`, nothing affordable, no garbage incoming, next piece is not a crystal piece but the one after is (81:8BE4: waits so it gets the crystal). - Difficulty 0: the first `$D3` (= 128 per piece) drop-eligible frames press nothing (81:8BB9). - 81:BB2A is meant to veto dropping but always returns $FF (`LDA #$00` falls into `LDA #$FF`) — no effect. Observed [C]: all moves happen inside the 12-frame entry window (horizontal moves are then instant, one column per frame); rotations repeat every 3 frames (05 → 06 → 16 → 05; the controller runs only in 05). ## Flags DP $26 (82:D1FB, rebuilt every COM spawn) | bit | set when | used by | |---|---|---| | 0 | cast now — see below | controller step 2 | | 1 | `$D2 ≥ 2`; at `$D2 == 1` if `R ≥ 50` | Mahi/Kaiten handling (81:A338, 81:A0DC) | | 2 | `$D2 ≥ 2` | queue-aware soft drop | | 3 | `$D2 ≥ 2` and a crystal block lies in the top 3 rows of the own stack (82:D326) | crystal stall | | 4 | own centre height ≥ 10 | crystal stall | | 6 | (planner) template search in progress | blocks bit 0 | `R = 82:D19C` = `(rng&63)+(rng&31)+(rng&3)+(rng&3)` (0..100, mean ≈ 50). `H` = **centre height** (82:D159: 22 − first row with a block in columns 3–6); `Hown`/`Hopp` for the COM / its opponent. **bit0 (82:D221):** clear if meter = 0, a power is already active (`DP27 ≠ FF`) or bit 6. Set if `Hown ≥ 21`. Otherwise evaluate the predicate of the power the COM would cast now (highest affordable level, 82:D2D7 → `80:DB7B[id]`): **1** → set, **FF** → clear, **0** → continue: at `$D2 == 3` look at the opponent's castable power (82:974A): Vampire 09 → set, Mirror 1D → clear; `$D2 == 0` → clear; set only if affordable and the opponent is currently falling with an I piece (82:D1CA), else clear. **Per-power predicates** (80:DB7B; thresholds are signed byte compares). "ramp(a,b,k)" = 1 if `Hown ≥ b`, 0 if `Hown < a`, else 1 if `R < (Hown−4)·k`: | power | predicate | |---|---| | 00 Mirurun, 0E Cut, 0F Moses, 11 Stardust, 15 Yose | ramp(7, 15, 8) | | 19 Sol | ramp(5, 15, 8) | | 01 Copy | FF if Hown ≤ Hopp; 1 if Hown−Hopp ≥ 8 or R < 30; else FF | | 1B Fax | FF if Hown < Hopp; 1 if Hown−Hopp ≥ 5 or R < 30; else FF | | 27 Change | 1 if Hown−Hopp ≥ 2, else FF | | 02 Medusa | 1 if Hopp ≥ 10 or Hown ≥ 15 or R < 10 | | 03 Bomb | 1 if Hopp ≥ 15; 0 if Hopp < 4; else 1 if R < (Hopp−3)·10 | | 04 Mayakashi, 12 Reverse(≥15), 20 Nu, 28 Doubles(≥10) | 1 if Hopp ≥ 12 (Reverse 15, Doubles 10) | | 05 Pentris, 1F Select | 1 if Hopp ≥ 15 or R < 30 | | 13 Mahi, 14 Kaiten, 25 Roulette | 1 if Hopp ≥ 12 or R < 30 | | 06 Dainashi, 08 Noroi | 1 if Hopp ≥ 10 or R < 40 | | 10 Mambo | 1 if Hopp ≥ 15 or R < 40 | | 22 Hanten, 29 Dark | 1 if Hopp ≥ 15 or R < 10 | | 21 Remocon | 0 if `($DE & DP$03) ≠ 0` and `$012A ≠ 0` (quirk: DP $03 is X-position high byte); else 1 if Hopp ≥ 15 or R < 50 | | 24 Inori | 0 if Hopp < 4; 1 if Hopp ≥ 15 or R < 50 | | 1A Suritote | 1 if Hopp < 4 or R < 50 | | 07 Fly, 0B Seesaw, 2A HyperFly | 1 if Hown ≥ 10 or Hopp ≥ 15 | | 18 Press | 1 if Hown ≥ 10 or R < 30 | | 1C Shield | 1 if 7 ≤ Hown < 15 and Hopp < 15 | | 1E Heavy | 0 if Hown ≥ 15; 1 if Hopp ≥ 15 or R < 30 | | 1D Mirror | 1 if R < 50 | | 09 Vampire | 0 if the opponent's meter is 0; 1 if R < 60 | | 0A Clear | 1 if Hown ≥ 19, or (quirk) the opponent's power list indexed by its meter value (`DP2F + meter`) is Vampire | | 16 Gang | 1 if the opponent's board contains a crystal (82:D2FF) | | 17 Doton | 0 if Hown < 6; 1 if R ≥ 7·(Hown−5) or the own board contains a crystal | | 23 Nakayoshi | 0 if Hown < 6; 1 if R ≥ 5·(Hown−5) | | 26 Fever | FF if Hown ≥ 10; 1 if the current piece is I or R < 30; FF if Hopp < 18; 1 if the current piece is O; else FF | | 0C, 0D | 0 | All predicates [I] from code (disassembly: `re/runs/ai2/predicates.asm`, `re/tools/ai2_preds.py`); the bit-0 plumbing is covered by the controller replay [C]. ## Open questions - DP $7B / $7D (zeroed for the COM at difficulty 3): the lock-delay variant used during the entry period — effect not measured. - `DP $23`, `DP $2A` (== 13 disables the queue-aware drop) and `DP $0D` writers not traced. - 82:974A at difficulty 3 also inspects `DP23`; behaviour against human Mirror/Vampire not tested in play.