36 Companion zmachine.js (15/28)

  sendKey(key) {
    const w = this.waiting;
    if (!w) throw new ZError('the game is not waiting for input');
    this.waiting = null;
    const ch = [...key][0] || '\n';
    const z = /^(enter|return)$/i.test(key) ? 13 : this.charToZscii(ch);
    if (w.kind === 'line') {
      // A key for a line prompt: just send it as a one-character line.
      this.waiting = w;
      return this.sendLine(ch === '\n' ? '' : ch);
    }
    this.writeVar(w.store, z);
    return this.run();
  }

  // ---------------------------------------------------------------- state

  snapshot() {
    // Dynamic memory, stored as a diff against the story file (much smaller).
    const diff = [];
    for (let i = 0; i < this.dynamicSize; i++) {
      if (this.mem[i] !== this.story[i]) {
        let j = i;
        while (j < this.dynamicSize && this.mem[j] !== this.story[j]) j++;
        diff.push([i, Buffer.from(this.mem.subarray(i, j)).toString('base64')]);
        i = j;
      }
    }
    return {
      v: 1,
      diff,
      pc: this.pc,
      stack: this.stack.slice(),
      frames: this.frames.map((f) => ({ ...f, locals: f.locals.slice() })),
      rng: this.rng,
      waiting: this.waiting,
      upperHeight: this.upperHeight,
      upper: this.upper.map((r) => Array.from({ length: r.length }, (_, i) => r[i] || ' ').join('')),
      window: this.window,
      cursor: { ...this.cursor },
      screenOn: this.screenOn,
      quit: this.quit,
    };
  }
‹ PreviousReader file (.txt)Next ›