23 Companion zmachine.js (2/28)

export class ZMachine {
  constructor(story, opts = {}) {
    this.story = story instanceof Uint8Array ? story : new Uint8Array(story);
    this.version = this.story[0];
    if (![3, 4, 5, 7, 8].includes(this.version)) {
      throw new ZError(`Z-machine version ${this.version} is not supported`);
    }
    this.screenWidth = opts.width || 60;
    this.reset();
    this.seed(opts.seed ?? Date.now());
  }

  // ---------------------------------------------------------------- setup

  reset() {
    const keepFlags2 = this.mem ? this.mem[0x11] & 0x03 : 0;
    this.mem = new Uint8Array(this.story);
    this.view = new DataView(this.mem.buffer);
    this.dynamicSize = this.rw(0x0e);
    this.stack = [];
    this.frames = [];      // {ret, store, locals, argc, base}
    this.pc = this.rw(0x06);
    this.out = [];         // lower-window text of the current run
    this.mem3 = [];        // output stream 3 stack: {table, len}
    this.screenOn = true;  // output stream 1
    this.upperHeight = 0;
    this.upper = [];       // rows of characters
    this.window = 0;
    this.cursor = { row: 1, col: 1 };
    this.waiting = null;   // {kind:'line'|'key', ...operands}
    this.quit = false;
    this.undoState = null;
    this.setupHeader();
    this.mem[0x11] = (this.mem[0x11] & ~0x03) | keepFlags2;
    this.loadTables();
  }
‹ PreviousReader file (.txt)Next ›