File size: 13,525 Bytes
c04dd6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Browser app shell shared by every game: boss select, human play loop, and the agent-facing API (window.BossBench).
// Game-specific content comes from the manifest BB.GAME = {id, title, roster: [{id, name, arch}], defaultCase}
// (games/<game>/game.js); the page (games/<game>/index.html) supplies the DOM and the controls help.
(function (g) {
  var BB = g.BB, doc = g.document;
  var GAME = BB.GAME || {}, ROSTER = GAME.roster || Object.keys(BB.CASES).sort().map(function (id) { return { id: id, name: BB.CASES[id].title, arch: '' }; });
  var $ = function (id) { return doc.getElementById(id); };
  var canvas = $('view'), R = new BB.Renderer(canvas), input = new BB.Input(g);
  input.bindMouse(canvas);
  input.enabled = false;
  var sel = { id: GAME.defaultCase || ROSTER.filter(function (b) { return BB.CASES[b.id]; })[0].id, d: 0.5, seed: 0 };
  var game = null;     // {case, subs, packets, acc, hold, paused, done}
  var mode = 'select';

  // ---------- select screen ----------
  var grid = $('grid');
  ROSTER.forEach(function (b) { b.playable = !!BB.CASES[b.id]; });
  ROSTER.forEach(function (b) {
    var el = doc.createElement('button');
    el.className = 'card' + (b.id === sel.id ? ' on' : '') + (b.playable ? '' : ' locked');
    el.setAttribute('aria-pressed', String(b.id === sel.id));
    el.innerHTML = '<div class="nm"></div><div class="ar"></div><div class="tag"></div>';
    el.querySelector('.nm').textContent = b.name;
    el.querySelector('.ar').textContent = b.arch;
    el.querySelector('.tag').textContent = b.playable ? 'PLAYABLE' : 'LOCKED';
    el.dataset.id = b.id;
    if (!b.playable) { el.disabled = true; el.title = 'Not implemented: planned 2D scene'; }
    el.addEventListener('click', function () {
      if (!b.playable) return;
      sel.id = b.id;
      [].forEach.call(grid.children, function (c) { c.classList.toggle('on', c.dataset.id === b.id); c.setAttribute('aria-pressed', String(c.dataset.id === b.id)); });
      skillTable(); preview = new BB.Case(sel.id); preview.reset(3, 0.5); R.juice.reset();
    });
    grid.appendChild(el);
  });
  function setD(d) {
    sel.d = Math.round(d * 100) / 100; $('dslider').value = sel.d; $('dval').textContent = sel.d.toFixed(2);
    [].forEach.call(doc.querySelectorAll('[data-d]'), function (b) { b.classList.toggle('on', +b.dataset.d === sel.d); });
  }
  // Public difficulty = three tiers (2026-11-02). When the game declares BB.GAME.tiers, the page's preset
  // buttons are rebuilt from that declaration so the page and bossbench.make_policy_env(tier=...) agree.
  if (GAME.tiers) {
    var presets = doc.querySelectorAll('[data-d]'), names = { easy: 'Easy', normal: 'Normal', hard: 'Hard' };
    if (presets.length) {
      var host = presets[0].parentNode, cls = presets[0].className.replace(/\bon\b/, '').trim();
      [].forEach.call(presets, function (b) { b.parentNode.removeChild(b); });
      ['easy', 'normal', 'hard'].forEach(function (t) {
        var b = doc.createElement('button'); b.className = cls; b.dataset.d = String(GAME.tiers[t]); b.dataset.tier = t;
        b.textContent = names[t] + ' ' + GAME.tiers[t]; host.appendChild(b);
      });
    }
    sel.d = GAME.tiers.normal;
  }
  [].forEach.call(doc.querySelectorAll('[data-d]'), function (b) { b.addEventListener('click', function () { setD(+b.dataset.d); }); });
  if (GAME.tiers) setD(GAME.tiers.normal);
  $('dslider').addEventListener('input', function () { setD(+this.value); });
  $('start').addEventListener('click', function () { sel.seed = (+$('seed').value) >>> 0; start(); });
  // Standard live scripted demo (BB.GAME.scripted): the same trusted controller the harness drives through
  // bossbench.make_policy_env; packets are recorded exactly like a human run.
  if (typeof GAME.scripted === 'function' && !$('scripted-start')) {
    var scriptedButton = doc.createElement('button');
    scriptedButton.id = 'scripted-start'; scriptedButton.type = 'button';
    scriptedButton.className = $('start').className; scriptedButton.textContent = 'Scripted Demo';
    scriptedButton.title = 'Reference script controller: reads internal state and is only for demos and replays, not model performance';
    $('start').insertAdjacentElement('afterend', scriptedButton);
    scriptedButton.addEventListener('click', function () { sel.seed = (+$('seed').value) >>> 0; start(true); });
  }
  $('again').addEventListener('click', function () { start(); });
  $('back').addEventListener('click', toSelect);
  function skillTable() {
    var ul = $('skilllist'), def = BB.CASES[sel.id], spec = new def.Boss().spec;
    ul.textContent = ''; doc.querySelector('#skills h3').textContent = 'Move list:' + def.title;
    spec.moves.forEach(function (m) {
      var li = doc.createElement('li');
      var local = GAME.skillText && GAME.skillText[sel.id] && GAME.skillText[sel.id][m.name];
      li.textContent = local || m.name + ': ' + m.cue + (m.punish ? '  →  ' + m.punish : '');
      ul.appendChild(li);
    });
  }
  skillTable();

  function start(auto) {
    var options = typeof GAME.resetOptions === 'function' ? GAME.resetOptions() : {};
    var c = new BB.Case(sel.id); c.reset(sel.seed, sel.d, options);
    R.juice.reset();
    game = { c: c, options: options, subs: [], packets: [], acc: 0, hold: 0, paused: false, keys: {}, mouse: [0, 0, 0], t0: performance.now(),
             auto: !!auto, autoPacket: null };
    mode = 'play';
    input.clear(); input.enabled = !auto;
    if ($('play-actions')) $('play-actions').classList.remove('hidden');
    if ($('pausepanel')) $('pausepanel').classList.add('hidden');
    if ($('pause')) $('pause').textContent = 'Pause';
    $('select').classList.add('hidden'); $('result').classList.add('hidden'); $('pausehint').classList.remove('hidden');
    canvas.focus && canvas.focus();
  }
  function toSelect() {
    mode = 'select'; game = null;
    input.clear(); input.enabled = false;
    if ($('play-actions')) $('play-actions').classList.add('hidden');
    if ($('pausepanel')) $('pausepanel').classList.add('hidden');
    $('result').classList.add('hidden'); $('select').classList.remove('hidden'); $('pausehint').classList.add('hidden');
  }
  function finish() {
    mode = 'result';
    input.clear(); input.enabled = false;
    if ($('play-actions')) $('play-actions').classList.add('hidden');
    var c = game.c, v = c.verifier();
    var messages = GAME.results || {win: 'VICTORY', loss: 'DEFEATED', timeout: 'TIME UP'};
    $('rtitle').textContent = messages[v.outcome];
    $('rtitle').style.color = v.outcome === 'win' ? 'var(--gold)' : (GAME.results ? '#c63061' : '#ff8a7a');
    $('rsub').textContent = 'Boss damage ' + Math.round(v.boss_damage * 100) + '%  ·  time: ' + v.seconds.toFixed(1) + ' s  ·  remaining health: ' + v.player_hp;
    $('rjson').textContent = 'verifier = ' + JSON.stringify(v) + '\npackets recorded = ' + game.packets.length;
    $('result').classList.remove('hidden'); $('pausehint').classList.add('hidden');
    g.BossBench.lastRun = { case: sel.id, seed: sel.seed, d: sel.d, packets: game.packets.slice(), verifier: v, final_hash: BB.hashState(c) };
    if (GAME.rules) g.BossBench.lastRun.rules = GAME.rules;
    if (typeof GAME.resetOptions === 'function') g.BossBench.lastRun.options = game.options;
  }
  function pause() {
    if (mode !== 'play') return;
    game.paused = !game.paused; input.clear(); input.enabled = !game.paused;
    if ($('pausepanel')) $('pausepanel').classList.toggle('hidden', !game.paused);
    if ($('pause')) $('pause').textContent = game.paused ? 'Resume' : 'Pause';
  }
  if ($('pause')) $('pause').addEventListener('click', pause);
  if ($('resume')) $('resume').addEventListener('click', pause);
  if ($('quit')) $('quit').addEventListener('click', toSelect);
  if ($('download')) $('download').addEventListener('click', function () {
    if (!g.BossBench.lastRun) return;
    var url = URL.createObjectURL(new Blob([JSON.stringify(g.BossBench.lastRun, null, 2)], {type: 'application/json'}));
    var a = doc.createElement('a'); a.href = url; a.download = GAME.id + '-replay.json'; a.click();
    setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
  });
  g.addEventListener('keydown', function (e) {
    if (e.repeat) return;
    if (mode === 'play' && (e.code === 'Escape' || e.code === 'KeyP')) { pause(); e.preventDefault(); }
    else if (mode === 'result' && e.code === 'KeyR') start();
    else if (mode === 'result' && e.code === 'Escape') toSelect();
    else if (mode === 'select' && e.code === 'Enter') $('start').click();
    if (mode === 'play' && game.paused && e.code === 'KeyQ') toSelect();
  });
  g.addEventListener('blur', function () { if (mode === 'play' && !game.paused) pause(); });

  // ---------- human loop: fixed 60 Hz ticks; input sampled once per 33 ms sub-step (= packet K(j)) ----------
  var last = performance.now(), idleT = 0;
  var preview = new BB.Case(sel.id); preview.reset(3, 0.5);
  function frame(now) {
    var dt = Math.min(0.1, (now - last) / 1000); last = now;
    if (mode === 'play' && !game.paused) {
      var c = game.c;
      if (game.hold > 0) game.hold -= dt;           // hit-stop: wall-clock pause, the tick sequence is unchanged
      else {
        game.acc += dt;
        while (game.acc >= BB.DT && !c.result) {
          if (!game.auto && typeof c.body.mouse === 'function') {
            // Aim is sampled once per packet: live play and packet replay distribute the same integer delta.
            if (c.t % (BB.SUBSTEPS * BB.TICKS_PER_SUB) === 0) {
              game.packetMouse = [0, 0, 0];
              if (input.pointer && typeof c.body.pointerDelta === 'function') game.packetMouse = c.body.pointerDelta(input.pointer, BB.VIEW);
              game.mouse = game.packetMouse.map(function (v) { return v / (BB.SUBSTEPS * BB.TICKS_PER_SUB); });
            }
          }
          if (game.auto && c.t % (BB.SUBSTEPS * BB.TICKS_PER_SUB) === 0) {
            game.autoPacket = BB.parsePacket(BB.scriptedPacket(c));
            game.packetMouse = game.autoPacket.mouse.slice();
            game.mouse = game.packetMouse.map(function (v) { return v / (BB.SUBSTEPS * BB.TICKS_PER_SUB); });
          }
          if (c.t % BB.TICKS_PER_SUB === 0) {
            game.keys = game.auto ? game.autoPacket.subs[(c.t % (BB.SUBSTEPS * BB.TICKS_PER_SUB)) / BB.TICKS_PER_SUB] : input.sample();
            game.subs.push(game.keys);
            if (game.subs.length === BB.SUBSTEPS) { game.packets.push(BB.formatPacket(game.subs, game.packetMouse)); game.subs = []; }
          }
          c.tick(game.keys, game.mouse); game.acc -= BB.DT;
        }
      }
      R.draw(c, c.t / BB.FPS, game.paused ? 'PAUSED' : '');
      var hs = R.juice.takeHitstop(); if (hs > 0) { game.hold = Math.max(game.hold, hs); game.acc = 0; }
      if (c.result) { if (game.subs.length) game.packets.push(BB.formatPacket(game.subs.concat([{}, {}, {}, {}, {}, {}]).slice(0, 6), game.packetMouse)); finish(); }
    } else if (mode === 'play') {
      R.draw(game.c, game.c.t / BB.FPS, 'PAUSED  (Esc Resume · Q Exit)');
    } else if (mode === 'select') {
      idleT += dt;                                   // attract mode behind the menu: boss alone, no player input
      while (idleT >= BB.DT) { preview.tick({}); idleT -= BB.DT; if (preview.result) { preview.reset(preview.seed + 1, 0.5); R.juice.reset(); } }
      R.draw(preview, preview.t / BB.FPS, '');
    }
    g.__bb_ready = true;
    g.requestAnimationFrame(frame);
  }
  g.requestAnimationFrame(frame);

  // ---------- agent-facing API (proposal 4.4) ----------
  // env = BossBench.make('2d/needle_warden', {obs_mode:'rgb'|'symbolic', time_mode:'paused'|'virtual_rt'|'wallclock_rt', latency})
  // r = env.reset(seed, {difficulty});  r = env.step('<|action_start|> 0 0 0 ; D ; D ; D,Space ; ; J ; J <|action_end|>')
  // rgb obs = PNG data URL of the 854x480 frame, rendered on a private canvas (deterministic: shake uses sim time).
  function rgbRenderer() {
    var cv = doc.createElement('canvas'), rr = new BB.Renderer(cv);
    return function (c) { rr.draw(c, c.t / BB.FPS, ''); return cv.toDataURL('image/png'); };
  }
  g.BossBench = {
    game: GAME.id, cases: ROSTER,
    make: function (id, opts) {
      opts = Object.assign({ obs_mode: 'rgb' }, opts || {});
      if (opts.obs_mode === 'rgb' && !opts.renderer) opts.renderer = rgbRenderer();
      return BB.make(id, opts);
    },
    NOOP: BB.NOOP, parsePacket: BB.parsePacket, formatPacket: BB.formatPacket,
    // show an env's case on the main canvas (for watching an agent play)
    watch: function (env, label) {
      mode = 'watch'; input.clear(); input.enabled = false;
      sel.id = env.case.id;
      [].forEach.call(grid.children, function (card) { card.classList.toggle('on', card.dataset.id === sel.id); card.setAttribute('aria-pressed', String(card.dataset.id === sel.id)); });
      skillTable();
      $('select').classList.add('hidden'); $('result').classList.add('hidden'); $('pausehint').classList.add('hidden');
      if ($('play-actions')) $('play-actions').classList.add('hidden'); if ($('pausepanel')) $('pausepanel').classList.add('hidden');
      R.juice.reset(); this._watched = env; this._watchLabel = label || 'AGENT'; R.draw(env.case, env.case.t / BB.FPS, this._watchLabel);
    },
    takeHitstop: function () { return R.juice.takeHitstop(); },
    redraw: function () { if (this._watched) R.draw(this._watched.case, this._watched.case.t / BB.FPS, this._watchLabel || 'AGENT'); },
    lastRun: null
  };
})(window);