37 Companion zmachine.js (16/28)

  static restore(story, snap, opts = {}) {
    const m = new ZMachine(story, opts);
    m.load(snap);
    return m;
  }

  load(snap) {
    this.mem.set(this.story.subarray(0, this.dynamicSize));
    this.setupHeader();
    for (const [at, b64] of snap.diff) this.mem.set(Buffer.from(b64, 'base64'), at);
    this.pc = snap.pc;
    this.stack = snap.stack.slice();
    this.frames = snap.frames.map((f) => ({ ...f, locals: f.locals.slice() }));
    this.rng = snap.rng;
    this.waiting = snap.waiting;
    this.upperHeight = snap.upperHeight;
    this.upper = snap.upper.map((r) => r.split(''));
    this.window = snap.window;
    this.cursor = { ...snap.cursor };
    this.screenOn = snap.screenOn;
    this.quit = snap.quit;
    this.mem3 = [];
  }

  // ---------------------------------------------------------------- run loop

  // Runs until the game asks for input or quits.
  // Returns {output, waiting: 'line'|'key'|null, quit}.
  run() {
    if (this.quit) return this.result();
    if (this.waiting) return this.result();
    let steps = 0;
    while (!this.waiting && !this.quit) {
      if (++steps > MAX_STEPS) throw new ZError('the game ran too long without asking for input');
      this.step();
    }
    return this.result();
  }

  result() {
    const output = this.out.join('');
    this.out = [];
    return { output, waiting: this.waiting ? this.waiting.kind : null, quit: this.quit };
  }
‹ PreviousReader file (.txt)Next ›