Files

837 lines
30 KiB
Python

#!/usr/bin/env python3
"""Reference implementation of the TBG CPU-AI planner (81:D9BA .. 81:E46B).
Literal transliteration of the 65816 code with a memory model, so that the original's
quirks (pointer variables clobbered between pattern variants, a planner-DP/player-DP mixup
in the Mahi check, padding loops that compare a byte with itself) are reproduced exactly.
Read this file as the spec; re/notes/ai_detail.md explains the semantics.
Memory model: `wram` is the low 8 KiB of WRAM (bank $00/$81 mirror), `rom` the LoROM image.
All planner code runs with DBR=$81, so indirect reads (`ptr),Y`) of addresses < $2000 hit WRAM
and addresses >= $8000 hit bank-$81 ROM.
usage: ai_ref.py ROM DIR [DIR...]
DIR with calls.bin (re/lua/ai2_log.lua) -> planner validation (full workspace compare)
DIR with rec.bin+pad.txt (re/lua/ai2_rec.lua) -> controller validation (pad word per frame)
"""
import sys
PLAN_D = 0x019D # planner direct page
class Trap(Exception):
"""The original would hang here (BRA to self): an internal assertion."""
class Planner:
def __init__(self, rom, wram):
self.rom = rom
self.w = bytearray(wram) # $0000-$1FFF
self.D = 0 # current direct page
self.rom_reads = []
self.path = []
# ---- memory -------------------------------------------------------------------------
def rd(self, a): # DBR = $81 data read
a &= 0xFFFF
if a < 0x2000:
return self.w[a]
if a >= 0x8000:
self.rom_reads.append(a)
return self.rom[0x8000 * 1 + (a - 0x8000)] # bank $81 -> file offset 0x8000..
raise ValueError(f"read of ${a:04X} (I/O)")
def wr(self, a, v):
a &= 0xFFFF
if a >= 0x2000:
raise ValueError(f"write to ${a:04X}")
self.w[a] = v & 0xFF
def romw(self, a): # 16-bit read in bank 81
return self.rd(a) | (self.rd(a + 1) << 8)
def dp(self, o):
return self.w[(self.D + o) & 0xFFFF]
def sdp(self, o, v):
self.w[(self.D + o) & 0xFFFF] = v & 0xFF
def dpw(self, o):
return self.dp(o) | (self.dp(o + 1) << 8)
def sdpw(self, o, v):
self.sdp(o, v)
self.sdp(o + 1, v >> 8)
def abs_(self, a):
return self.w[a]
def sabs(self, a, v):
self.w[a] = v & 0xFF
@staticmethod
def neg(v): # N flag of an 8-bit result
return bool(v & 0x80)
# ---- small helpers ---------------------------------------------------------------------
def addp(self, o, n): # INC $o (16-bit pointer) n times
self.sdpw(o, (self.dpw(o) + n) & 0xFFFF)
def div10(self, a): # 81:813E with $11C=10: $11A=a/10, $11E=a%10
self.sabs(0x11A, a // 10)
self.sabs(0x11E, a % 10)
self.sabs(0x11C, 10)
def mul10(self, a): # 81:8193 (8-bit)
t = (a << 1) & 0xFF
self.sabs(0x11A, t)
return ((t << 2) + t) & 0xFF
# ---- player-context predicates (D = player DP) ---------------------------------------
def opp_power(self): # 81:A153 input
return self.abs_(0x229) if self.abs_(0x12A) else self.abs_(0x489)
def own_power(self): # 82:BCF5 input
return self.abs_(0x489) if self.abs_(0x12A) else self.abs_(0x229)
def own_status(self):
return self.abs_(0x488) if self.abs_(0x12A) else self.abs_(0x228)
def a153(self): # opponent has Mahi (13) active
return 1 if self.opp_power() == 0x13 else 0
def a338(self): # called with the PLANNER direct page (original bug: reads planner $06/$24)
if not self.a153():
return 0
if not (self.own_status() & 0x02):
return 0
t = self.dp(0x06)
if t == 0x00 or t == 0x07:
self.sdp(0x24, 0)
return 0
return 0xFF if self.dp(0x24) else 0
# ---- planner ----------------------------------------------------------------------------
def run(self, player_d):
"""81:D9BA. player_d = $0202 or $0462 (the D value at the call)."""
self.D = player_d
# 81:E22C
t = self.dp(0x06)
self.sabs(0x1F4, t)
self.sabs(0x1DA, t - 7 if t >= 7 else t)
if self.own_power() == 0x1F: # 82:BD0C: own Select active -> plan for an I piece
self.sabs(0x1DA, 5)
self.D = PLAN_D
self.sdpw(0x32, 0x04F6 if self.abs_(0x12A) else 0x0296)
self.heights() # 81:DBB9
self.sort() # 81:DC02
self.sabs(0x114, 0)
self.profile() # 81:DC59
handled = False
if self.a153():
self.path.append('mahi')
if self.own_power() == 0x1F:
self.path.append('select')
if not self.a153():
st = 0x488 if self.abs_(0x12A) else 0x228
self.sabs(st, self.abs_(st) | 0x40)
self.special() # 81:DE38
if self.dp(0x56) == 0:
handled = True
self.path.append('special')
else:
self.sabs(st, self.abs_(st) & 0xBF)
self.wells() # 81:DFA5
if self.dp(0x56) == 0:
handled = True
self.path.append('wells')
if not handled:
y = sum(1 for x in range(1, 9) if self.dp(x) >= 0x12)
if y < 5:
self.pattern() # 81:DB40
else:
self.panic() # 81:DA9F
if self.neg(self.abs_(0x1DD)):
self.pattern()
self.D = player_d
self.sdp(0x25, self.abs_(0x1DD))
self.sdp(0x24, self.abs_(0x1DC))
self.e1b6()
def heights(self): # 81:DBB9: DP $00..$09 = 22 - empty cells above the first block
y = 0
self.sabs(0x10D, 0)
for x in range(10):
self.sabs(0x10C, 0)
while True:
if self.rd(self.dpw(0x32) + y) != 0:
break
self.sabs(0x10C, self.abs_(0x10C) + 1)
if self.abs_(0x10C) == 0x16:
break
y = (self.mul10(self.abs_(0x10C)) + self.abs_(0x10D)) & 0xFF
self.sdp(x, 0x16 - self.abs_(0x10C))
self.sabs(0x10D, self.abs_(0x10D) + 1)
y = self.abs_(0x10D)
def sort(self): # 81:DC02: DP $0A.. sorted heights, $14.. their columns, $1E+col = rank
self.sabs(0x1D1, 0xA7); self.sabs(0x1D2, 0x01)
self.sabs(0x1D3, 0xB1); self.sabs(0x1D4, 0x01)
self.sabs(0x108, 0); self.sabs(0x109, 0); self.sabs(0x11C, 0)
y = 0
x = 0
while True:
if self.dp(x) == self.abs_(0x108):
self.sabs(0x11C, self.abs_(0x11C) + 1)
self.wr(self.dpw(0x34) + y, self.dp(x))
self.wr(self.dpw(0x36) + y, x)
self.sdp(0x1E + x, self.abs_(0x109))
y += 1
if y == 10:
return
x += 1
if x == 10:
self.sabs(0x108, self.abs_(0x108) + 1)
self.sabs(0x109, self.abs_(0x11C))
x = 0
def profile(self): # 81:DC59: DP $28..$2B = deltas of sorted heights from index $114
x = self.abs_(0x114)
y = 0
while True:
prev = self.dp(0x0A + x)
self.sabs(0x108, prev)
x += 1
if x == 10:
self.sdp(0x28 + y, 0x16 - prev)
y += 1
while y != 4:
self.sdp(0x28 + y, 0x16)
y += 1
return
self.sdp(0x28 + y, self.dp(0x0A + x) - prev)
y += 1
if y == 4:
return
# pattern element test shared by DE38 / E0E9 / E2EF. kind: 'rank' (DE38/E0E9) or 'panic' (E2EF)
def elem_ok(self, a, m, kind):
if self.neg(a):
if kind == 'eq_neg': # E0E9: negative pattern bytes must match exactly
return a == m
if kind == 'panic': # E2EF: (-m) >= (-a), signed
n = (-a) & 0xFF
return not self.neg(((-m) & 0xFF) - n)
# DE38: A = $FF-(a-1) = -a; ok unless (A - m) negative
self.sabs(0x108, a - 1)
v = (0xFF - self.abs_(0x108)) & 0xFF
return not self.neg(v - m)
if a == 0x63:
return True
if not self.neg(a - 0x0A): # a >= 10: "at least a/10"
self.div10(a)
return not self.neg(m - self.abs_(0x11A))
return a == m
def dcb4(self): # 81:DCB4: $1C9.. = ranks of 6 columns from sorted[0]-offset (pad $0A)
self.sabs(0x10A, self.dp(0x38)); self.sabs(0x10B, self.dp(0x39))
x2 = self.dp(0x3D) * 2
self.sdpw(0x38, self.romw(0xE4F0 + x2))
yv = self.dp(0x3C)
a = (self.dp(0x14) - self.rd(self.dpw(0x38) + yv)) & 0xFF
if self.neg(a):
n = (self.rd(self.dpw(0x38) + yv) - self.dp(0x14)) & 0xFF
self.sabs(0x108, n); self.sabs(0x109, 0)
y = 0
while True:
self.wr(self.dpw(0x36) + y, 0x0A)
y += 1
if y >= 7:
raise Trap('DD0B')
if y == n:
break
x = 0
else:
x, y = a, 0
while True:
self.wr(self.dpw(0x36) + y, self.dp(0x1E + x))
y += 1
if y == 6:
break
x += 1
if x >= 10:
while True:
self.wr(self.dpw(0x36) + y, 0x0A)
y += 1
if y >= 7:
raise Trap('DD21')
if y == 6:
break
break
self.sdpw(0x38, self.abs_(0x10A) | (self.abs_(0x10B) << 8))
def special(self): # 81:DE38: per-piece rank+profile templates
x1 = self.dp(0x3D)
self.sabs(0x10C, self.rd(0xE4E9 + x1))
self.sdp(0x3C, 0)
x2 = x1 * 2
self.sdpw(0x34, self.romw(0xE4FE + x2))
self.sdpw(0x36, 0x01C9)
self.sdpw(0x38, self.romw(0xE50C + x2))
self.sdpw(0x3A, 0x01C5)
while True:
self.dcb4()
ok = all(self.elem_ok(self.rd(self.dpw(0x34) + y), self.rd(self.dpw(0x36) + y), 'de38')
for y in range(6))
if ok:
ok = all(self.elem_ok(self.rd(self.dpw(0x38) + y), self.rd(self.dpw(0x3A) + y), 'de38')
for y in range(4))
if ok:
# 81:DF18 (clobbers $34)
self.sdpw(0x34, self.romw(0xE528 + x2))
self.sdp(0x3E, self.rd(self.dpw(0x34) + self.dp(0x3C)))
self.sdpw(0x34, self.romw(0xE51A + x2))
self.sdp(0x3F, self.rd(self.dpw(0x34) + self.dp(0x3C)))
self.sdp(0x40, self.dp(0x14) - self.dp(0x3E))
self.sdp(0x41, self.dp(0x0A))
a = self.dp(0x40)
if not self.neg(a) and self.neg(a - 0x0A) and self.e3e3() == 0:
self.sdp(0x56, 0)
return
self.addp(0x34, 6)
self.addp(0x38, 4)
self.sdp(0x3C, self.dp(0x3C) + 1)
self.sabs(0x10C, self.abs_(0x10C) - 1)
if self.abs_(0x10C) == 0:
self.sdp(0x56, 0xFF)
return
def df3f(self): # 81:DF3F: is column $114 a well (both sides >= 3 higher)?
x = self.abs_(0x114)
h = self.dp(x)
self.sabs(0x108, h)
left = 0x16 if x == 0 else self.dp(x - 1)
a = (left - h) & 0xFF
if self.neg(a):
self.sdp(0x56, 0xFF); return
self.sdp(0x28, a)
if self.neg(a - 3):
self.sdp(0x56, 0xFF); return
right = 0x16 if x >= 9 else self.dp(x + 1)
b = (right - h) & 0xFF
if self.neg(b):
self.sdp(0x56, 0xFF); return
self.sdp(0x29, b)
if self.neg(b - 3):
self.sdp(0x56, 0xFF); return
if b == self.dp(0x28):
self.sdp(0x56, 0)
elif self.neg(b - self.dp(0x28)):
self.sdp(0x56, 1)
else:
self.sdp(0x56, 2)
def wells(self): # 81:DFA5: needs two wells among the columns (scanned lowest-first)
self.sabs(0x10C, 2)
for x in range(10):
self.sabs(0x114, self.dp(0x14 + x))
self.df3f()
if self.neg(self.dp(0x56)):
continue
self.sabs(0x10C, self.abs_(0x10C) - 1)
if self.abs_(0x10C) == 0:
break
self.sabs(0x10D, x)
self.sdp(0x3F, self.dp(0x56))
else:
self.sdp(0x56, 0xFF)
return
self.sabs(0x108, x)
self.sabs(0x109, self.dp(0x56))
self.sabs(0x10C, 2)
while True:
x2 = self.dp(0x3D) * 2
self.sdpw(0x34, self.romw(0xE77F + x2))
y = self.dp(0x3F)
a = self.rd(self.dpw(0x34) + y)
if a != 0x63:
self.sdp(0x3F, a)
self.sdpw(0x34, self.romw(0xE7A2 + x2))
self.sdp(0x3E, self.rd(self.dpw(0x34) + y))
xi = self.abs_(0x10D)
self.sdp(0x40, self.dp(0x14 + xi) - self.dp(0x3E))
self.sdp(0x41, self.dp(0x0A + xi))
self.sdp(0x56, self.e3e3())
return
self.sabs(0x10D, self.abs_(0x108))
self.sdp(0x3F, self.abs_(0x109))
self.sabs(0x10C, self.abs_(0x10C) - 1)
if self.abs_(0x10C) == 0:
self.sdp(0x56, 0xFF)
return
def e3c8(self):
x2 = self.dp(0x3D) * 2
self.sdpw(0x34, (self.romw(0xE46B + x2) + ((self.dp(0x3F) << 2) & 0xFF)) & 0xFFFF)
def fit_check(self, limit): # 81:E42E
self.sabs(0x108, limit)
x = self.dp(0x40)
for y in range(4):
a = self.rd(self.dpw(0x34) + y)
if a == 0:
return 0
a = (a + self.dp(x)) & 0xFF
if not self.neg(a - limit):
return 0xFF
if y == 3:
return 0
x += 1
if x == 10:
return 0
return 0
def e3e3(self): # stack would overflow? limit $17, $19 or $1B depending on how full the field is
self.sabs(0x109, 0)
self.e3c8()
if sum(1 for x in range(10) if not self.neg(self.dp(x) - 0x15)) >= 7:
lim = 0x1B
elif sum(1 for x in range(10) if not self.neg(self.dp(x) - 0x14)) >= 7:
lim = 0x19
else:
lim = 0x17
return self.fit_check(lim)
def e45c(self):
self.sabs(0x109, 0)
self.e3c8()
return self.fit_check(0x16)
def e03c(self): # 81:E03C: $1C9.. = heights of 5 columns from sorted[$45]-offset, minus base
xi = self.dp(0x45)
base = self.dp(0x0A + xi)
self.sabs(0x108, base)
self.sdpw(0x3A, self.romw(0xE7CC + self.dp(0x44) * 2))
self.sdpw(0x38, self.romw(self.dpw(0x3A) + self.dp(0x3D) * 2))
a = (self.dp(0x14 + xi) - self.rd(self.dpw(0x38) + self.dp(0x3C))) & 0xFF
if self.neg(a):
self.sabs(0x109, self.dp(0x14 + xi))
self.sabs(0x109, self.rd(self.dpw(0x38) + self.dp(0x3C)) - self.abs_(0x109))
self.wr(self.dpw(0x36) + 0, 0x16 - base)
x, y = 0, 1 # original's "LDA $109 / CMP $109" always takes the exit after one pad
else:
x, y = a, 0
while True:
v = (self.dp(x) - base) & 0xFF
if self.neg(v):
v = 0xFF
self.wr(self.dpw(0x36) + y, v)
x += 1
if x >= 10:
while True:
y += 1
if y >= 6:
raise Trap('E097')
self.wr(self.dpw(0x36) + y, 0x16 - base)
if y >= 4:
return
y += 1
if y == 5:
return
def e0e9(self): # 81:E0E9: match pattern set $44 variant $3C against the profile
if self.dp(0x3C) == 0:
self.sdpw(0x3A, self.romw(0xE7D6 + self.dp(0x44) * 2))
self.sdpw(0x34, self.romw(self.dpw(0x3A) + self.dp(0x3D) * 2))
self.sdpw(0x36, 0x01C9)
self.e03c()
for y in range(5):
a = self.rd(self.dpw(0x34) + y)
m = self.rd(self.dpw(0x36) + y)
if not self.elem_ok(a, m, 'eq_neg'):
self.addp(0x34, 5)
self.sdp(0x56, 0xFF)
return
# 81:E15B
x2 = self.dp(0x44) * 2
y2 = self.dp(0x3D) * 2
self.sdpw(0x3A, self.romw(0xE7EA + x2))
self.sdpw(0x34, self.romw(self.dpw(0x3A) + y2))
self.sdp(0x3E, self.rd(self.dpw(0x34) + self.dp(0x3C)))
self.sdpw(0x3A, self.romw(0xE7E0 + x2))
self.sdpw(0x34, self.romw(self.dpw(0x3A) + y2))
self.sdp(0x3F, self.rd(self.dpw(0x34) + self.dp(0x3C)))
xi = self.dp(0x45)
self.sdp(0x40, self.dp(0x14 + xi) - self.dp(0x3E))
self.sdp(0x41, self.dp(0x0A + xi))
self.sdp(0x56, 0)
def count_variants(self, table): # 81:DB26 / 81:DA8F
self.sdpw(0x34, self.romw(table + self.dp(0x44) * 2))
self.sabs(0x10C, self.rd(self.dpw(0x34) + self.dp(0x3D)))
return self.abs_(0x10C)
def pattern(self): # 81:DB40
self.sdp(0x44, 0); self.sdp(0x45, 0); self.sdp(0x3C, 0)
while True:
if self.count_variants(0xE7C2) == 0:
break
while True:
self.e0e9()
if self.dp(0x56) == 0 and self.a338() == 0 and self.e3e3() == 0:
self.path.append(f'pattern set{self.dp(0x44)}')
return
self.sdp(0x3C, self.dp(0x3C) + 1)
if self.dp(0x3C) != self.abs_(0x10C):
continue
self.sdp(0x3C, 0)
self.sdp(0x45, self.dp(0x45) + 1)
if self.dp(0x45) != 10:
continue
break
self.sdp(0x3C, 0); self.sdp(0x45, 0)
self.sdp(0x44, self.dp(0x44) + 1)
if self.dp(0x44) == 5:
break
# 81:DB7D fallback: first column with rank 0, rotation 0
self.path.append('fallback')
x = 0
while x < 10 and self.dp(0x1E + x) != 0:
x += 1
self.sdp(0x40, x)
self.sdp(0x3F, 0)
def e242(self): # 81:E242: like E03C but negatives -> $FF/$FE, off-board -> $63
xi = self.dp(0x45)
base = self.dp(0x0A + xi)
self.sabs(0x108, base)
self.sdpw(0x3A, self.romw(0xEC27 + self.dp(0x44) * 2))
self.sdpw(0x38, self.romw(self.dpw(0x3A) + self.dp(0x3D) * 2))
a = (self.dp(0x14 + xi) - self.rd(self.dpw(0x38) + self.dp(0x3C))) & 0xFF
if self.neg(a):
self.sabs(0x109, self.dp(0x14 + xi))
self.sabs(0x109, self.rd(self.dpw(0x38) + self.dp(0x3C)) - self.abs_(0x109))
self.wr(self.dpw(0x36) + 0, 0x63)
x, y = 0, 1
else:
x, y = a, 0
while True:
v = (self.dp(x) - base) & 0xFF
if self.neg(v):
v = 0xFF if v == 0xFF else 0xFE
self.wr(self.dpw(0x36) + y, v)
x += 1
if x >= 10:
while True:
y += 1
if y >= 6:
raise Trap('E29D')
self.wr(self.dpw(0x36) + y, 0x63)
if y >= 4:
return
y += 1
if y == 5:
return
def e2ef(self): # 81:E2EF: panic-search pattern match
if self.dp(0x3C) == 0:
self.sdpw(0x3A, self.romw(0xEC2F + self.dp(0x44) * 2))
self.sdpw(0x34, self.romw(self.dpw(0x3A) + self.dp(0x3D) * 2))
self.sdpw(0x36, 0x01C9)
self.e242()
for y in range(5):
a = self.rd(self.dpw(0x34) + y)
m = self.rd(self.dpw(0x36) + y)
if not self.elem_ok(a, m, 'panic'):
self.addp(0x34, 5)
self.sdp(0x56, 0xFF)
return
# 81:E36D
x2 = self.dp(0x44) * 2
y2 = self.dp(0x3D) * 2
self.sdpw(0x3A, self.romw(0xEC3F + x2))
self.sdpw(0x34, self.romw(self.dpw(0x3A) + y2))
self.sdp(0x3E, self.rd(self.dpw(0x34) + self.dp(0x3C)))
self.sdpw(0x3A, self.romw(0xEC37 + x2))
self.sdpw(0x34, self.romw(self.dpw(0x3A) + y2))
self.sdp(0x3F, self.rd(self.dpw(0x34) + self.dp(0x3C)))
xi = self.dp(0x45)
self.sdp(0x40, self.dp(0x14 + xi) - self.dp(0x3E))
self.sdp(0x41, self.dp(0x0A + xi))
self.sdp(0x56, 0)
def panic(self): # 81:DA9F
self.sdp(0x44, 0); self.sdp(0x45, 0); self.sdp(0x3C, 0)
self.sabs(0x1F9, 0xFF); self.sabs(0x1FA, 0x16)
while True:
if self.count_variants(0xEC1F) != 0:
while True:
self.e2ef()
a = self.dp(0x40)
if (self.dp(0x56) == 0 and not self.neg(a) and self.neg(a - 0x0A)
and self.a338() == 0 and self.e3e3() == 0):
if self.e45c() == 0:
self.path.append('panic-fit')
return
a41 = self.dp(0x41)
if a41 <= self.abs_(0x1FA) or self.neg(self.abs_(0x1F9)):
self.sabs(0x1F9, self.dp(0x40))
self.sabs(0x1FA, a41)
self.sabs(0x1FB, self.dp(0x3F))
if not self.neg(self.abs_(0x10C) - 0x0F):
raise Trap('DAF3')
self.sdp(0x3C, self.dp(0x3C) + 1)
if self.dp(0x3C) != self.abs_(0x10C):
continue
self.sdp(0x3C, 0)
self.sdp(0x45, self.dp(0x45) + 1)
if self.dp(0x45) != 10:
continue
break
self.sdp(0x3C, 0); self.sdp(0x45, 0)
self.sdp(0x44, self.dp(0x44) + 1)
if self.neg(self.dp(0x44) - 4):
continue
self.sdp(0x40, self.abs_(0x1F9))
self.sdp(0x3F, self.abs_(0x1FB))
self.path.append('panic-best' if not self.neg(self.abs_(0x1F9)) else 'panic-none')
return
def e1b6(self): # 81:E1B6 (player DP): leftmost occupied column / top row of the current shape
self.sabs(0x108, 0x12 if self.abs_(0x12A) else 0x04)
ptr = self.dpw(0x00) # shape pointer (bank 81)
c10d, c10c = 0, 0
y = 0
while True:
if self.rd(ptr + y) != 0:
break
c10c += 1
if c10c == 4:
c10d += 1
y = c10d
if y == 4:
break
c10c = 0
continue
y = ((c10c << 2) + c10d) & 0xFF
self.sabs(0x10C, c10c); self.sabs(0x10D, c10d)
self.sabs(0x1DF, c10d + self.dp(0x08) - self.abs_(0x108))
r = ((c10c & 0x0C) >> 2) + self.dp(0x09)
self.sabs(0x1E0, 0x16 if self.neg(r - 3) else r - 3)
def parse_calls(path):
data = open(path + '/calls.bin', 'rb').read()
calls, i, cur = [], 0, None
while i < len(data):
tag = data[i:i + 4]; i += 4
if tag == b'ENTR':
cur = {'entry': data[i:i + 0x800]}; i += 0x800
elif tag == b'EXIT':
cur['exit'] = data[i:i + 0x100]; i += 0x100
elif tag == b'E1B6':
cur['e1b6'] = data[i:i + 0x100]; i += 0x100
calls.append(cur)
else:
raise ValueError(tag)
return calls
def validate(rom, dirs):
total = ok = 0
from collections import Counter
paths = Counter()
for d in dirs:
for n, c in enumerate(parse_calls(d)):
if 'e1b6' not in c:
continue
total += 1
entry = bytearray(0x2000)
entry[:0x800] = c['entry']
p = Planner(rom, entry)
player_d = 0x0462 if entry[0x12A] else 0x0202
err = None
try:
p.run(player_d)
except Exception as e: # noqa
err = repr(e)
want = c['e1b6']
got = p.w[0x100:0x200]
# compare the workspace $019D..$01FB plus results; ignore $0100-$019C (other scratch)
diffs = [hex(0x100 + k) for k in range(0x9D, 0xFC) if want[k] != got[k]]
res_w = (want[0xDD], want[0xDC])
res_g = (got[0xDD], got[0xDC])
paths[' > '.join(p.path)] += 1
good = err is None and res_w == res_g and not diffs
ok += good
if not good:
print(f'{d} #{n + 1}: want col,rot={res_w} got={res_g} err={err} ws_diffs={diffs[:12]}')
for k, v in paths.most_common():
print(f' {v:5d} {k}')
print(f'{ok}/{total} planner calls reproduced exactly')
return ok, total
class Controller(Planner):
"""81:8A52: one virtual-pad word per frame for the COM player (D = player DP), stored in $1F1.
Runs every frame the COM is in state 05. Button bits: Up 0800, Down 0400, Left 0200, Right 0100,
A 0080 (rot+1), B 8000 (rot-1), L 0020."""
def own_status_dp(self):
return self.dp(0x26)
def can_cast(self): # 81:8BCE: $23 == 0 and meter >= some level cost (signed compares)
if self.dp(0x23) != 0:
return 0
for x in (3, 2, 1, 0):
if not self.neg(self.dp(0x1F) - self.dp(0x2B + x)):
return 1
return 0
def opp_kaiten(self): # 81:A071
return 1 if self.opp_power() == 0x14 else 0
def kaiten_hold(self): # 81:A0DC
return 1 if (self.opp_kaiten() and (self.dp(0x26) & 0x02) and not self.can_cast()) else 0
def select_press(self): # 82:BD18: own Select active and current piece is not I -> press L
if self.own_power() != 0x1F:
return 0
if self.dp(0x06) in (0x05, 0x0C):
return 0
self.sabs(0x155 + self.abs_(0x12A), 0)
return 1
def drop_throttle(self): # 81:8BB9: difficulty 0 waits $D3 frames (set to $80 at spawn)
if self.abs_(0xD2) == 0 and self.abs_(0xD3) != 0:
self.sabs(0xD3, self.abs_(0xD3) - 1)
return 0
return 1
def incoming(self):
return self.abs_(0x482) if self.abs_(0x12A) == 0 else self.abs_(0x222)
def stall_for_crystal(self): # 81:8BE4: 0 = hold off soft-dropping
if self.neg(self.abs_(0xD2) - 1) or not (self.dp(0x26) & 0x10) or self.can_cast() or self.incoming():
return 1
if not self.neg(self.abs_(0x16B) - 7):
return 1
if not self.neg(self.abs_(0x16C) - 7):
return 0
return 1
def run(self, player_d):
self.D = player_d
pad = 0
if self.abs_(0x229) != 0x21: # P1 not using Remocon: clear the per-player latches
x = self.abs_(0x12A)
for a in (0x145, 0x147, 0x151):
self.sabs(a + x, 0)
if self.dp(0x26) & 0x01:
return 0x0800 if self.can_cast() else 0
if self.select_press():
return 0x0020
danger = any(self.abs_(0x19D + x) > 0x15 for x in range(1, 9))
if danger:
return self.danger_path()
return self.normal_path()
def move_or_drop(self): # 81:8AB4
self.e1b6()
cur, tgt = self.abs_(0x1DF), self.dp(0x25)
if cur == tgt:
return self.aligned()
return 0x0100 if self.neg(cur - tgt) else 0x0200
def normal_path(self): # 81:8AAE
if self.dp(0x24) != self.dp(0x07):
return self.rotate()
return self.move_or_drop()
def rotate(self): # 81:8AEA
if self.opp_kaiten():
if not self.kaiten_hold():
return self.soft_drop()
r = self.dp(0x24)
if r == 3:
use_b = True
elif r == 1:
use_b = False
else:
use_b = self.neg(self.dp(0x25) - 4)
if self.dp(0x0D): # reversed controls: swap A/B
use_b = not use_b
return 0x8000 if use_b else 0x0080
def soft_drop(self): # 81:8ADD
return 0x0400 if self.drop_throttle() else 0
def try_drop(self): # 81:8AD1 (81:BB2A always returns $FF in the original: a missing branch)
if self.kaiten_hold():
return 0
return self.soft_drop()
def aligned(self): # 81:8B5B
if (self.dp(0x26) & 0x04) and self.dp(0x2A) != 0x13:
tall = sum(1 for x in range(10) if not self.neg(self.abs_(0x19D + x) - 0x12))
if tall >= 8 or self.incoming():
return self.try_drop()
if self.abs_(0x16B) in (0x05, 0x0C):
return self.try_drop()
if self.abs_(0x16C) in (0x05, 0x0C):
return 0
if (self.dp(0x26) & 0x08) and self.stall_for_crystal() == 0:
return 0
return self.try_drop()
def danger_path(self): # 81:8B2A: L/J/I shift before rotating
self.e1b6()
cur, tgt = self.abs_(0x1DF), self.dp(0x25)
if cur != tgt and self.dp(0x06) in (1, 2, 5):
return 0x0100 if self.neg(cur - tgt) else 0x0200
if self.dp(0x24) != self.dp(0x07):
return self.rotate()
return self.move_or_drop()
def validate_controller(rom, d):
"""Replay ai2_rec.lua recordings: predict each logged COM pad word from the previous frame's WRAM."""
W = 0x800
rec = open(d + '/rec.bin', 'rb').read()
n = len(rec) // W
from collections import Counter
bad, ok, miss = 0, 0, Counter()
for line in open(d + '/pad.txt'):
f, v = line.split()
if v == 'PLAN':
continue
f, v = int(f), int(v, 16)
if f < 1 or f > n:
continue
w = bytearray(0x2000)
w[:W] = rec[(f - 1) * W:f * W]
c = Controller(rom, w)
try:
got = c.run(0x0462)
except Exception as e: # noqa
got = -1
if got == v:
ok += 1
else:
bad += 1
miss[(v, got)] += 1
print(f'{d}: controller {ok}/{ok + bad} frames match; mismatches (logged, predicted): {miss.most_common(6)}')
if __name__ == '__main__':
import os
rom = open(sys.argv[1], 'rb').read()
pdirs = [d for d in sys.argv[2:] if os.path.exists(d + '/calls.bin')]
if pdirs:
validate(rom, pdirs)
for d in sys.argv[2:]:
if os.path.exists(d + '/rec.bin'):
validate_controller(rom, d)