#!/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 boardemu import Board, load_ihx, load_font # noqa: E402 UP, DOWN, LEFT, RIGHT, FIRE, ENTER, ESC = 1, 2, 4, 8, 16, 32, 128 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 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_ihx(os.path.join(HERE, "out", "keep.ihx")) b = Board(mem, code_end=hi) font = None if a.shots: os.makedirs(a.shots, exist_ok=True) font = load_font() 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()