The Iron Keep: a top-down escape game, held-key ports, monitor HEX loader
games/keep: an original game in C for the Z-80 using the sprites - twelve rooms, guards that patrol, see along rows and columns and shoot, keys and locked doors, gold, ammunition and a crown to steal. gen.py holds the art and castle map and checks reachability; test-keep.py runs it in z80emu on a model of the board's ports, takes screenshots and has a bot play it through. keep.bas loads KEEPGAME at 8600h and CALLs it. Ports 88h/89h read keys held down (ps2_keystate), the monitor writes Intel HEX records typed at its prompt, and tools/send-hex.py sends a whole file and saves it as a memory file. Testbench covers both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
13373244e8
commit
743071cff3
19 files changed
+3544
-1306
No files matched your search
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run The Iron Keep in tools/z80emu.py on a model of the board's game ports
|
||||
(graphics, sprites, frame counter, held keys, terminal) and take screenshots.
|
||||
|
||||
python3 test-keep.py [--shots DIR] [--fuzz FRAMES]
|
||||
|
||||
The scripted run starts a game, walks east into the next room, fires, and
|
||||
checks what the status line says; --fuzz then plays random keys for a while
|
||||
and checks the program never leaves its code or wrecks the stack. Screenshots
|
||||
need pyte and Pillow (text is drawn with the board's font).
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "..", "..", "tools"))
|
||||
from z80emu import Z80 # noqa: E402
|
||||
|
||||
PAL = ["000", "A00", "0A0", "A50", "00A", "A0A", "0AA", "AAA",
|
||||
"555", "F55", "5F5", "FF5", "55F", "F5F", "5FF", "FFF"]
|
||||
PAL = [tuple(int(c, 16) * 17 for c in p) for p in PAL]
|
||||
UP, DOWN, LEFT, RIGHT, FIRE, ENTER, ESC = 1, 2, 4, 8, 16, 32, 128
|
||||
|
||||
|
||||
class Board(Z80):
|
||||
def __init__(self, mem):
|
||||
super().__init__(mem)
|
||||
self.frame = 0
|
||||
self.joy = 0
|
||||
self.gfx = bytearray(320 * 240)
|
||||
self.gxv = self.gyv = 0
|
||||
self.spr = [[0, 0, 0, 0] for _ in range(32)] # x, y, shape, ctl
|
||||
self.sel = 0
|
||||
self.xst = 0
|
||||
self.pat = bytearray(8192)
|
||||
self.pat_a = 0
|
||||
self.text = bytearray()
|
||||
self.keys_in = bytearray()
|
||||
|
||||
def io_in(self, port):
|
||||
p = port & 0xFF
|
||||
if p == 0:
|
||||
return (1 if self.keys_in else 0) | 2
|
||||
if p == 1:
|
||||
return self.keys_in.pop(0) if self.keys_in else 0
|
||||
if p == 0x78: # each read is a new frame
|
||||
self.frame += 1
|
||||
return self.frame & 0xFF
|
||||
if p == 0x88:
|
||||
return self.joy
|
||||
if p == 0x33:
|
||||
return self.gfx[self.gyv * 320 + self.gxv] if self.gxv < 320 and self.gyv < 240 else 0
|
||||
if p == 0x34:
|
||||
return 0
|
||||
return 0xFF
|
||||
|
||||
def io_out(self, port, v):
|
||||
p = port & 0xFF
|
||||
if p == 1:
|
||||
self.text.append(v)
|
||||
elif p == 0x30: self.gxv = (self.gxv & 0x100) | v
|
||||
elif p == 0x31: self.gxv = (self.gxv & 0xFF) | (v & 1) << 8
|
||||
elif p == 0x32: self.gyv = v
|
||||
elif p == 0x33:
|
||||
if self.gxv < 320 and self.gyv < 240:
|
||||
self.gfx[self.gyv * 320 + self.gxv] = v & 15
|
||||
self.gxv = (self.gxv + 1) & 0x1FF
|
||||
elif p == 0x34:
|
||||
self.gfx[:] = bytes([v & 15]) * (320 * 240)
|
||||
if not v & 0x80:
|
||||
for s in self.spr: s[3] &= ~1
|
||||
elif p == 0x70: self.sel = v & 31
|
||||
elif p == 0x71: self.xst = (self.xst & 0x100) | v
|
||||
elif p == 0x72: self.xst = (self.xst & 0xFF) | (v & 1) << 8
|
||||
elif p == 0x73: self.spr[self.sel][0], self.spr[self.sel][1] = self.xst, v
|
||||
elif p == 0x74: self.spr[self.sel][2] = v & 63
|
||||
elif p == 0x75: self.spr[self.sel][3] = v & 7
|
||||
elif p == 0x76: self.pat_a = (v & 63) * 128
|
||||
elif p == 0x77:
|
||||
self.pat[self.pat_a & 8191] = v
|
||||
self.pat_a += 1
|
||||
|
||||
def run_frames(self, n, joy=0):
|
||||
"""Run until the program has waited for n more frames (or returned)."""
|
||||
self.joy = joy
|
||||
end = self.frame + 2 * n # wait_frame reads the counter twice
|
||||
while self.frame < end and self.pc != 0:
|
||||
self.step()
|
||||
if not (0x8600 <= self.pc < self.code_end or self.pc == 0):
|
||||
raise SystemExit("PC left the program: %04X" % self.pc)
|
||||
if self.sp < 0xF000:
|
||||
raise SystemExit("stack ran into memory: SP %04X" % self.sp)
|
||||
|
||||
def screen_text(self):
|
||||
import pyte
|
||||
scr = pyte.Screen(80, 32)
|
||||
pyte.ByteStream(scr).feed(bytes(self.text))
|
||||
return scr
|
||||
|
||||
def shot(self, path, font):
|
||||
from PIL import Image
|
||||
scr = self.screen_text()
|
||||
img = Image.new("RGB", (1280, 1024))
|
||||
px = img.load()
|
||||
lay = bytearray(self.gfx)
|
||||
for s in reversed(self.spr): # sprite 0 in front
|
||||
x0, y0, shape, ctl = s
|
||||
if not ctl & 1:
|
||||
continue
|
||||
for r in range(16):
|
||||
for c in range(16):
|
||||
rr = 15 - r if ctl & 4 else r
|
||||
cc = 15 - c if ctl & 2 else c
|
||||
b = self.pat[shape * 128 + rr * 8 + cc // 2]
|
||||
col = b & 15 if cc & 1 else b >> 4
|
||||
x, y = (x0 + c) & 511, (y0 + r) & 255
|
||||
if col and x < 320 and y < 240:
|
||||
lay[y * 320 + x] = col | 16
|
||||
for y in range(1024):
|
||||
for x in range(1280):
|
||||
gx, gy = x >> 2, y >> 2
|
||||
c = lay[gy * 320 + gx] & 15 if gy < 240 else 0
|
||||
px[x, y] = PAL[c]
|
||||
names = ["black", "red", "green", "brown", "blue", "magenta", "cyan", "white"]
|
||||
for r in range(32):
|
||||
for c in range(80):
|
||||
ch = scr.buffer[r][c]
|
||||
code = ord(ch.data[0]) if ch.data else 32
|
||||
if code == 32 and ch.bg == "default":
|
||||
continue
|
||||
def colour(n, d):
|
||||
if n in names: return PAL[names.index(n)]
|
||||
if n.startswith("bright") and n[6:] in names: return PAL[names.index(n[6:]) + 8]
|
||||
try:
|
||||
v = int(n, 16); return ((v >> 16) & 255, (v >> 8) & 255, v & 255)
|
||||
except ValueError:
|
||||
return d
|
||||
fg = colour(ch.fg, PAL[10])
|
||||
bg = colour(ch.bg, None)
|
||||
for y in range(16):
|
||||
bits = font[(code if code < 256 else 63) * 16 + y]
|
||||
for x in range(8):
|
||||
on = bits & (0x80 >> x)
|
||||
for dy in (0, 1):
|
||||
for dx in (0, 1):
|
||||
X, Y = c * 16 + 2 * x + dx, r * 32 + 2 * y + dy
|
||||
if on: px[X, Y] = fg
|
||||
elif bg is not None and px[X, Y] == (0, 0, 0): px[X, Y] = bg
|
||||
img.save(path)
|
||||
|
||||
|
||||
def play_through(b, a, check, font):
|
||||
"""Walk the castle by breadth-first search over gen.py's map: both keys
|
||||
nearest the throne room, the crown behind its locked door, then the
|
||||
stairs. The bot can't be seen or hurt (it keeps inv set), so this tests
|
||||
the castle and the game's rules, not the bot's skill."""
|
||||
sys.path.insert(0, HERE)
|
||||
import gen
|
||||
from collections import deque
|
||||
sym = {}
|
||||
for line in open(os.path.join(HERE, "out", "keep.map")):
|
||||
f = line.split()
|
||||
if len(f) >= 2 and f[1].startswith("_"):
|
||||
try: sym[f[1]] = int(f[0], 16)
|
||||
except ValueError: pass
|
||||
big = gen.BIG
|
||||
W, H = len(big[0]), len(big)
|
||||
where = {ch: [(x, y) for y in range(H) for x in range(W) if big[y][x] == ch] for ch in "KCX"}
|
||||
def room_of(p): return (p[1] // 14) * 4 + p[0] // 20
|
||||
keys = sorted(where["K"], key=lambda p: room_of(p) not in (1, 7))[:2]
|
||||
targets = keys + where["C"] + where["X"][:1]
|
||||
names = ["key", "key", "crown", "stairs"]
|
||||
|
||||
def i16(addr):
|
||||
v = b.m[addr] | b.m[addr + 1] << 8
|
||||
return v - 65536 if v & 0x8000 else v
|
||||
|
||||
def path(s, g):
|
||||
prev = {s: None}
|
||||
q = deque([s])
|
||||
while q:
|
||||
p = q.popleft()
|
||||
if p == g:
|
||||
break
|
||||
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
||||
n = (p[0] + dx, p[1] + dy)
|
||||
if 0 <= n[0] < W and 0 <= n[1] < H and n not in prev and big[n[1]][n[0]] != "#":
|
||||
prev[n] = p; q.append(n)
|
||||
out = [g]
|
||||
while prev[out[-1]] is not None:
|
||||
out.append(prev[out[-1]])
|
||||
return out[::-1]
|
||||
|
||||
t = 0
|
||||
joy = 0
|
||||
for frame in range(30000):
|
||||
b.m[sym["_inv"]] = 2
|
||||
if b.m[sym["_over"]]:
|
||||
break
|
||||
px, py, room = i16(sym["_px"]), i16(sym["_py"]), b.m[sym["_room"]]
|
||||
if px % 16 == 0 and (py - 16) % 16 == 0:
|
||||
here = ((room % 4) * 20 + px // 16, (room // 4) * 14 + (py - 16) // 16)
|
||||
while t < len(targets) and here == targets[t]:
|
||||
print("bot reached the %s at frame %d" % (names[t], frame))
|
||||
t += 1
|
||||
if t == len(targets):
|
||||
joy = 0
|
||||
else:
|
||||
p = path(here, targets[t])
|
||||
n = p[1]
|
||||
joy = RIGHT if n[0] > here[0] else LEFT if n[0] < here[0] else DOWN if n[1] > here[1] else UP
|
||||
elif joy == 0: # between tiles: line up with one
|
||||
joy = LEFT if px % 16 else UP
|
||||
if frame % 2000 == 0:
|
||||
print("frame %d: room %d at %d,%d, heading for the %s" % (frame, room, px, py, names[min(t, 3)]))
|
||||
b.run_frames(1, joy)
|
||||
check("bot collected %d keys and the crown" % b.m[sym["_keys"]], b.m[sym["_crown"]] == 1)
|
||||
check("taking the crown down the stairs wins", b.m[sym["_over"]] == 1 and b.m[sym["_won"]] == 1)
|
||||
b.run_frames(80)
|
||||
check("end screen", "YOU ESCAPED WITH THE CROWN" in "\n".join(b.screen_text().display))
|
||||
if a.shots: b.shot(os.path.join(a.shots, "5-escaped.png"), font)
|
||||
b.run_frames(10, ESC)
|
||||
b.run_frames(5)
|
||||
check("Esc returns to BASIC", b.pc == 0)
|
||||
|
||||
|
||||
def load(path):
|
||||
mem = bytearray(65536)
|
||||
hi = 0
|
||||
for line in open(path):
|
||||
n, a, t = int(line[1:3], 16), int(line[3:7], 16), int(line[7:9], 16)
|
||||
if t == 0:
|
||||
mem[a:a + n] = bytes.fromhex(line[9:9 + 2 * n])
|
||||
hi = max(hi, a + n)
|
||||
return mem, hi
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--shots", help="write PNG screenshots here")
|
||||
ap.add_argument("--fuzz", type=int, default=0, help="random frames to play")
|
||||
ap.add_argument("--play", action="store_true",
|
||||
help="then let a bot play the game through: keys, door, crown, stairs")
|
||||
a = ap.parse_args()
|
||||
mem, hi = load(os.path.join(HERE, "out", "keep.ihx"))
|
||||
b = Board(mem)
|
||||
b.code_end = hi
|
||||
b.m[0] = 0x76 # HALT: where main returns to
|
||||
b.pc, b.sp = 0x8600, 0xFFF0
|
||||
b.push(0x0000)
|
||||
font = None
|
||||
if a.shots:
|
||||
os.makedirs(a.shots, exist_ok=True)
|
||||
root = os.path.join(HERE, "..", "..")
|
||||
font = [int(l.split("//")[0], 16) for l in open(os.path.join(root, "font", "font.mem"))
|
||||
if l.split("//")[0].strip()]
|
||||
errors = 0
|
||||
|
||||
def check(what, ok):
|
||||
nonlocal errors
|
||||
print(("PASS " if ok else "FAIL ") + what)
|
||||
errors += not ok
|
||||
|
||||
def status():
|
||||
return "\n".join(b.screen_text().display[:2])
|
||||
|
||||
b.run_frames(20)
|
||||
check("title screen", "T H E I R O N K E E P" in "\n".join(b.screen_text().display))
|
||||
if a.shots: b.shot(os.path.join(a.shots, "1-title.png"), font)
|
||||
b.run_frames(5, FIRE)
|
||||
b.run_frames(10)
|
||||
check("game starts in the gatehouse", "GATEHOUSE" in status() and "LIVES 3" in status())
|
||||
check("player sprite shown", b.spr[0][3] & 1 == 1)
|
||||
if a.shots: b.shot(os.path.join(a.shots, "2-gatehouse.png"), font)
|
||||
# east along the top, down to the east doorway's rows, then through it
|
||||
x0, y0 = b.spr[0][0], b.spr[0][1]
|
||||
b.run_frames(30, DOWN)
|
||||
check("moving down moves the player", b.spr[0][1] == (y0 + 60) & 255)
|
||||
b.run_frames(30, UP)
|
||||
b.run_frames(8, FIRE)
|
||||
check("a shot uses ammunition", "AMMO 9" in status())
|
||||
b.run_frames(130, RIGHT)
|
||||
check("walls stop the player", b.spr[0][0] == 290)
|
||||
b.run_frames(32, DOWN)
|
||||
b.run_frames(30, RIGHT)
|
||||
check("east doorway leads to the guard room", "GUARD ROOM" in status())
|
||||
if a.shots: b.shot(os.path.join(a.shots, "3-guardroom.png"), font)
|
||||
b.run_frames(60)
|
||||
print(status())
|
||||
if a.play:
|
||||
play_through(b, a, check, font)
|
||||
if a.fuzz:
|
||||
rnd = random.Random(1)
|
||||
j = 0
|
||||
for f in range(a.fuzz):
|
||||
if f % 10 == 0:
|
||||
j = rnd.choice([UP, DOWN, LEFT, RIGHT, UP | FIRE, DOWN | FIRE, LEFT | FIRE,
|
||||
RIGHT | FIRE, FIRE, 0, UP | LEFT, DOWN | RIGHT])
|
||||
b.run_frames(1, j)
|
||||
if b.pc == 0:
|
||||
break
|
||||
if f % 500 == 499:
|
||||
print("frame", f + 1, "-", b.screen_text().display[0].strip())
|
||||
check("random play for %d frames without a crash" % a.fuzz, True)
|
||||
if a.shots: b.shot(os.path.join(a.shots, "4-fuzz.png"), font)
|
||||
sys.exit(1 if errors else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user