File: examples/companions/text-adventures/zmachine.js (955 lines)
// A small Z-machine interpreter (versions 3, 4, 5, 7 and 8), no dependencies.
//
// It is built for a turn-based web server, not for a terminal:
// - run() executes until the game wants input, then returns the text it printed.
// - sendLine() / sendKey() hand over the player's input and keep running.
// - snapshot() / ZMachine.restore() turn the whole machine state into JSON, so the
// server can keep nothing in memory between requests.
//
// Screen model: the lower window becomes plain text. The upper window (status line,
// quote boxes) is kept as a small character grid that the server reads separately.
// Not supported: version 6 graphics, sound, timed input, mouse, menus.
//
// Spec: https://inform-fiction.org/zmachine/standards/z1point1/index.html
const A0 = 'abcdefghijklmnopqrstuvwxyz';
const A1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const A2 = ' \n0123456789.,!?_#\'"/\\-:()'; // index 0 = 10-bit escape, 1 = newline
// ZSCII 155..223, the default Unicode translation table (spec 3.8.5.3).
const DEFAULT_EXTRA = 'aouAOU???eiyEIaeiouyAEIOUYaeiouAEIOUaeiouAEIOUaA??anoANO??cC?????????';
const MAX_STEPS = 20_000_000; // per run(); protects the server from a looping game
export class ZError extends Error {}
const s16 = (v) => (v & 0x8000 ? (v & 0xffff) - 0x10000 : v & 0xffff);
const u16 = (v) => v & 0xffff;