wren/val Public Public: anyone can read this; nobody can change it.

forked from benjivers/val

workbenchthis machine
Files wren/10-the-whole-thing-is-choppy-the-view-is-st
1
/**
2
 * val, in a browser. It draws what the server sends and sends what the
3
 * person does — nothing else. There is no position here the server did not
4
 * hand over, and no enemy in a snapshot the server decided you cannot see,
5
 * so a patched client learns nothing a plain one does not.
6
 *
7
 * This file is the wiring: the socket, the keys and the pointer, the HUD.
8
 * The drawing lives beside it — `scene.js` for the first-person view,
9
 * `topdown.js` for the map, `gun.js` for the crosshair, `prompt.js` for the
10
 * line of advice and `raycast.js` for the maths all of it stands on.
11
 */
12
"use strict";
13
14
import { makeBeeper } from "./beep.js";
15
import { arrive, bodyAt, feed, makeTimeline, renderTime } from "./interp.js";
16
import { BODY_R, moveSpeed } from "../src/glide.ts";
17
import { drawGun, gunSnapshot, gunTick, makeGun } from "./gun.js";
18
import { advance, anchor, holdBack, insideWall, makeLocal, project, reconcile } from "./predict.js";
19
import { choosePrompt, REACH } from "./prompt.js";
20
import { roster, rosterKey } from "./roster.js";
21
import { AGENT_COLOUR, drawScene, makeScene } from "./scene.js";
22
import { moveVector } from "./steer.js";
23
import { drawTopdown } from "./topdown.js";
24
import { aim as aimAt, makeYaw, settle, told, turn } from "./yaw.js";
25
26
const $ = (id) => document.getElementById(id);
27
const view = $("view");
28
const ctx = view.getContext("2d");
29
30
const KEY_SLOT = { KeyC: "c", KeyQ: "q", KeyE: "e", KeyX: "x" };
31
const COARSE = matchMedia("(pointer: coarse)").matches;
32
const LOOK = 0.0022; // radians per pixel of mouse travel
33
const HELP_SEEN = "val.help.seen";
34
35
let map = null;
36
let solid = () => true;
37
let world = null; // what predict.js slides against: the grid, from map.json
38
let snap = null;
39
let socket = null;
40
let agents = null;
41
// Everybody else, kept as the last few things the server said about them and
42
// drawn between those — see interp.js. `drawAt` is the moment this frame is
43
// drawing, a snapshot interval behind the present.
44
const timeline = makeTimeline();
45
let drawAt = 0;
46
const keys = new Set();
47
// Where this person is looking: the browser's between snapshots, and the
48
// server's word taken only when it is saying something we did not. See
49
// yaw.js — a snapshot that stomps this is what made looking around choppy.
50
const head = makeYaw();
51
let locked = false;
52
let firing = false;
53
let mode = COARSE ? "top" : "fp"; // a raycaster with touch look is miserable
54
let mapOpen = false;
55
let pointer = null; // aim target in canvas pixels, top-down only
56
let stick = null; // { id, ox, oy, mx, my }
57
let aimTouch = null;
58
let helpShown = false;
59
let last = performance.now();
60
let snapAt = last; // when the last snapshot landed: how stale the answer is
61
62
const walk = { x: 0, y: 0 };
63
// What this person is doing right now, read once a frame for the drawing and
64
// once every 50ms for the server. The same object either way: no allocation
65
// in a loop that runs sixty times a second.
66
const intent = { mx: 0, my: 0, angle: 0, fire: false, use: false, reload: false };
67
// Your own body, run forward from your own keys between snapshots, and the
68
// object the drawing is handed for it.
69
const local = makeLocal();
70
const drawnMe = { id: "", x: 0, y: 0, angle: 0 };
71
const scene = makeScene();
72
const gun = makeGun();
73
const beeper = makeBeeper();
74
75
// ------------------------------------------------------------------ socket
76
77
function connect() {
78
  const url = (location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws";
79
  socket = new WebSocket(url);
80
  socket.onopen = () => ($("conn").textContent = "live");
81
  socket.onclose = () => {
82
    $("conn").textContent = "reconnecting…";
83
    setTimeout(connect, 1500);
84
  };
85
  socket.onmessage = (event) => {
86
    const data = JSON.parse(event.data);
87
    if (data.t !== "s") return;
88
    snap = data;
89
    snapAt = performance.now();
90
    // Timed samples for every body in it, ours included: the drawing walks
91
    // between them rather than chasing the newest one.
92
    arrive(timeline, snapAt / 1000);
93
    feed(timeline, data.me.id, data.me, snapAt / 1000);
94
    for (const player of data.players) feed(timeline, player.id, player, snapAt / 1000);
95
    // The server's angle is taken only when it is a correction, never as the
96
    // routine echo of the angle we sent it a moment ago.
97
    settle(head, data.me, snapAt / 1000);
98
    gunSnapshot(gun, data);
99
    paintHud(data);
100
    maybeHelp(data);
101
  };
102
}
103
104
const send = (message) => {
105
  if (socket && socket.readyState === 1) socket.send(JSON.stringify(message));
106
};
107
108
// ------------------------------------------------------------------- input
109
110
/**
111
 * Swap the view. The two share one facing — whichever you leave, you keep
112
 * looking the way you were looking — so nothing here touches the angle.
113
 */
114
function setMode(next) {
115
  mode = next;
116
  $("stage").dataset.mode = next;
117
  if (next !== "fp" && document.pointerLockElement === view) document.exitPointerLock();
118
}
119
120
addEventListener("keydown", (event) => {
121
  if (event.target instanceof HTMLInputElement) return;
122
  if (event.code === "Tab") {
123
    mapOpen = true;
124
    event.preventDefault();
125
    return;
126
  }
127
  if (event.code === "KeyH" || event.key === "?") {
128
    toggleHelp();
129
    event.preventDefault();
130
    return;
131
  }
132
  if (event.code === "KeyV") {
133
    setMode(mode === "fp" ? "top" : "fp");
134
    event.preventDefault();
135
    return;
136
  }
137
  if (event.code === "KeyB") {
138
    toggleBuy();
139
    event.preventDefault();
140
    return;
141
  }
142
  if (KEY_SLOT[event.code]) {
143
    send({ t: "i", c: KEY_SLOT[event.code] });
144
    event.preventDefault();
145
    return;
146
  }
147
  keys.add(event.code);
148
  if (["KeyW", "KeyA", "KeyS", "KeyD", "Space", "KeyF", "KeyR", "ArrowLeft", "ArrowRight"].includes(event.code))
149
    event.preventDefault();
150
});
151
addEventListener("keyup", (event) => {
152
  if (event.code === "Tab") mapOpen = false;
153
  keys.delete(event.code);
154
});
155
addEventListener("blur", () => {
156
  keys.clear();
157
  mapOpen = false;
158
  firing = false;
159
});
160
161
// Aiming is pointer lock: click the canvas to capture the mouse, move to
162
// look, Escape gives it back. The angle sent is the same angle as ever.
163
view.addEventListener("click", () => {
164
  beeper.wake();
165
  if (mode !== "fp" || locked) return;
166
  if (!view.requestPointerLock) return setMode("top"); // no lock, no first person
167
  // Asked for too soon after the last release, a browser rejects this; that
168
  // is a shrug, not an error, and the hint stays up until it takes.
169
  const asked = view.requestPointerLock();
170
  if (asked && asked.catch) asked.catch(() => {});
171
});
172
document.addEventListener("pointerlockchange", () => {
173
  locked = document.pointerLockElement === view;
174
  if (!locked) firing = false;
175
  $("stage").dataset.locked = locked ? "1" : "";
176
});
177
addEventListener("mousemove", (event) => {
178
  if (locked) turn(head, event.movementX * LOOK);
179
});
180
addEventListener("mousedown", (event) => {
181
  if (locked && event.button === 0) firing = true;
182
});
183
addEventListener("mouseup", (event) => {
184
  if (locked && event.button === 0) firing = false;
185
});
186
187
// The top-down view keeps the pointer aim it always had: it is the phone
188
// control scheme, and the fallback when the first-person view is not wanted.
189
const canvasPoint = (event) => {
190
  const box = view.getBoundingClientRect();
191
  return {
192
    x: ((event.clientX - box.left) / box.width) * view.width,
193
    y: ((event.clientY - box.top) / box.height) * view.height,
194
  };
195
};
196
view.addEventListener("pointermove", (event) => {
197
  if (mode !== "top" || event.pointerType === "touch") return;
198
  pointer = canvasPoint(event);
199
});
200
view.addEventListener("pointerdown", (event) => {
201
  beeper.wake();
202
  if (mode !== "top") return;
203
  view.setPointerCapture(event.pointerId);
204
  const box = view.getBoundingClientRect();
205
  if (event.pointerType === "touch") {
206
    if (event.clientX - box.left < box.width / 2)
207
      stick = { id: event.pointerId, ox: event.clientX, oy: event.clientY, mx: 0, my: 0 };
208
    else {
209
      aimTouch = { id: event.pointerId, ...canvasPoint(event) };
210
      firing = true;
211
    }
212
    event.preventDefault();
213
    return;
214
  }
215
  pointer = canvasPoint(event);
216
  firing = true;
217
});
218
view.addEventListener("pointermove", (event) => {
219
  if (stick && event.pointerId === stick.id) {
220
    const dx = event.clientX - stick.ox;
221
    const dy = event.clientY - stick.oy;
222
    const len = Math.hypot(dx, dy) || 1;
223
    const reach = Math.min(len, 48) / 48;
224
    stick.mx = (dx / len) * reach;
225
    stick.my = (dy / len) * reach;
226
  }
227
  if (aimTouch && event.pointerId === aimTouch.id) Object.assign(aimTouch, canvasPoint(event));
228
});
229
const endPointer = (event) => {
230
  if (stick && event.pointerId === stick.id) stick = null;
231
  else if (aimTouch && event.pointerId === aimTouch.id) {
232
    aimTouch = null;
233
    firing = false;
234
  } else firing = false;
235
};
236
view.addEventListener("pointerup", endPointer);
237
view.addEventListener("pointercancel", endPointer);
238
view.addEventListener("contextmenu", (event) => event.preventDefault());
239
240
// What this person is doing, in the world's terms. In the first-person view
241
// the keys are read against the way you are facing; in the top-down view they
242
// are the compass, the way they always were.
243
function readIntent() {
244
  let ax = 0;
245
  let ay = 0;
246
  if (keys.has("KeyW")) ay -= 1;
247
  if (keys.has("KeyS")) ay += 1;
248
  if (keys.has("KeyA")) ax -= 1;
249
  if (keys.has("KeyD")) ax += 1;
250
  if (stick) {
251
    ax = stick.mx;
252
    ay = stick.my;
253
  }
254
  intent.mx = ax;
255
  intent.my = ay;
256
  if (mode === "fp") {
257
    intent.angle = head.angle;
258
    moveVector(ax, ay, head.angle, walk);
259
    intent.mx = walk.x;
260
    intent.my = walk.y;
261
  } else {
262
    const aim = aimTouch || pointer;
263
    const me = worldToScreen(drawnMe.id ? drawnMe : snap.me);
264
    // The pointer is this view's aim, and it is ours the same way the mouse
265
    // is: with no pointer yet, keep the facing rather than the stale answer.
266
    if (aim) aimAt(head, Math.atan2(aim.y - me.y, aim.x - me.x));
267
    intent.angle = head.angle;
268
  }
269
  intent.fire = firing || keys.has("Space");
270
  intent.use = keys.has("KeyF");
271
  intent.reload = keys.has("KeyR");
272
  return intent;
273
}
274
275
// Twenty times a second the server hears it. Intent only — a direction, an
276
// angle, a held key — never a position: the guess below is for drawing.
277
setInterval(() => {
278
  if (!snap || !map) return;
279
  const now = readIntent();
280
  send({ t: "i", mx: now.mx, my: now.my, a: now.angle, f: now.fire, u: now.use, r: now.reload });
281
  // What we told it, so its echo is recognisable as ours when it comes back.
282
  told(head, now.angle, performance.now() / 1000);
283
}, 50);
284
285
// ------------------------------------------------------------------ drawing
286
287
function resize() {
288
  const box = view.getBoundingClientRect();
289
  const dpr = Math.min(devicePixelRatio || 1, 2);
290
  view.width = Math.round(box.width * dpr);
291
  view.height = Math.round(box.height * dpr);
292
}
293
addEventListener("resize", resize);
294
295
const scale = () => (map ? view.width / (map.rows[0].length * map.tile) : 1);
296
const worldToScreen = (p) => ({ x: p.x * scale(), y: p.y * scale() });
297
298
/**
299
 * Everybody else is drawn at `drawAt`: between the two samples that bracket
300
 * it, so they move at the server's own speed and arrive where it put them.
301
 * You are not: your own body is the one this browser can run forward
302
 * honestly, and drawing it late is what dragged the camera backwards.
303
 */
304
const look = (p) => (predicting() && p.id === snap.me.id ? drawnMe : bodyAt(timeline, p, drawAt));
305
306
/**
307
 * Your own movement is only guessed at while the round is live and you are
308
 * alive. The buy phase pens everybody in their own spawn — a rule of the
309
 * match, not of the map — and a guess that does not know it would spend the
310
 * phase being pulled back through the door.
311
 */
312
const predicting = () => snap !== null && world !== null && snap.phase !== "buy" && snap.me.alive;
313
314
/** The server's answer, caught up to now, then this frame of your own keys. */
315
function predict(dt, now) {
316
  if (!predicting()) {
317
    local.ready = false;
318
    drawnMe.id = "";
319
    return;
320
  }
321
  const held = readIntent();
322
  const speed = moveSpeed({
323
    haste: snap.me.haste > 0,
324
    slow: snap.me.slow > 0,
325
    stopped: snap.me.planting > 0 || snap.me.defusing,
326
    heavy: snap.me.weapon === "operator",
327
  });
328
  // The snapshot is a moment old and the keys held since have not reached
329
  // it; carry it that far forward and lean the drawn body onto it.
330
  const target = project(snap.me, held.mx, held.my, speed, (now - snapAt) / 1000, world);
331
  reconcile(local, target, dt);
332
  advance(local, held.mx, held.my, speed, dt, world);
333
  holdBack(local, target, held.mx, held.my);
334
  // A lean across a corner could put the drawn body in a wall; the server's
335
  // answer is never wrong, so take it rather than draw from inside one.
336
  if (insideWall(local, world)) anchor(local, snap.me);
337
  drawnMe.id = snap.me.id;
338
  drawnMe.x = local.x;
339
  drawnMe.y = local.y;
340
  // Either view: the facing is the one this browser is holding, whether the
341
  // mouse moved it or the pointer aim did. The server hears it a moment later.
342
  drawnMe.angle = head.angle;
343
}
344
345
function frame(now) {
346
  requestAnimationFrame(frame);
347
  const dt = Math.min(0.1, (now - last) / 1000);
348
  last = now;
349
  drawAt = renderTime(timeline, now / 1000);
350
  if (!map) return;
351
  gunTick(gun, dt);
352
  ctx.clearRect(0, 0, view.width, view.height);
353
354
  if (!snap) {
355
    drawTopdown(ctx, map, null, look, { x: 0, y: 0, w: view.width, h: view.height });
356
    return;
357
  }
358
  // Turning with the arrow keys belongs to the frame, at a rate a second,
359
  // rather than to whatever the input timer happens to do.
360
  if (mode === "fp" && keys.has("ArrowLeft")) turn(head, -0.9 * dt);
361
  if (mode === "fp" && keys.has("ArrowRight")) turn(head, 0.9 * dt);
362
  predict(dt, now);
363
  beeper.update(snap.spike.planted, snap.spike.fuse, now / 1000);
364
  const eye = look(snap.me);
365
  const facing = mode === "fp" ? head.angle : eye.angle;
366
367
  if (mode === "fp" && !mapOpen) {
368
    drawScene(ctx, scene, { solid, tile: map.tile }, { x: eye.x, y: eye.y, angle: facing }, snap, {
369
      width: view.width,
370
      height: view.height,
371
      look,
372
    });
373
    drawGun(ctx, gun, view.width, view.height, snap);
374
    drawMinimap();
375
  } else {
376
    drawTopdown(ctx, map, snap, look, { x: 0, y: 0, w: view.width, h: view.height });
377
  }
378
379
  if (snap.me.planting > 0) bar(snap.me.planting / 4, "#e0a040", "planting");
380
  else if (snap.spike.planted && snap.spike.defuse > 0 && snap.me.side === "def")
381
    bar(snap.spike.defuse / 7, "#4fd6a0", "defusing");
382
  $("flash").style.opacity = Math.min(0.95, snap.me.blind * 0.8);
383
  $("dead").style.display = snap.me.alive ? "none" : "grid";
384
  $("aimhint").style.display = mode === "fp" && !locked && !COARSE ? "grid" : "none";
385
}
386
387
/** The same top-down drawing, small, in the corner, with you as an arrow. */
388
function drawMinimap() {
389
  const w = Math.min(view.width * 0.3, 260 * (view.width / 900));
390
  const h = (w * map.rows.length) / map.rows[0].length;
391
  const pad = 8;
392
  ctx.save();
393
  ctx.globalAlpha = 0.85;
394
  ctx.fillStyle = "#0b0d11";
395
  ctx.fillRect(pad - 2, pad - 2, w + 4, h + 4);
396
  drawTopdown(ctx, map, snap, look, { x: pad, y: pad, w, h }, { labels: false });
397
  ctx.restore();
398
  ctx.strokeStyle = "rgba(255,255,255,0.18)";
399
  ctx.lineWidth = 1;
400
  ctx.strokeRect(pad - 2, pad - 2, w + 4, h + 4);
401
}
402
403
function bar(fraction, colour, label) {
404
  const w = view.width * 0.4;
405
  const x = view.width / 2 - w / 2;
406
  const y = view.height * 0.86;
407
  ctx.fillStyle = "#0009";
408
  ctx.fillRect(x, y, w, 16);
409
  ctx.fillStyle = colour;
410
  ctx.fillRect(x, y, w * Math.min(1, fraction), 16);
411
  ctx.fillStyle = "#fff";
412
  ctx.font = "12px system-ui, sans-serif";
413
  ctx.textAlign = "center";
414
  ctx.fillText(label, view.width / 2, y + 12);
415
  ctx.textAlign = "left";
416
}
417
418
// --------------------------------------------------------------------- hud
419
420
// The buy opens itself every buy phase; closing it is remembered until the
421
// next one, so nobody has to fight the panel to watch the round start.
422
function toggleBuy() {
423
  const open = $("buy").classList.toggle("on");
424
  $("buy").dataset.closed = open ? "" : "1";
425
}
426
$("buytoggle").addEventListener("click", toggleBuy);
427
$("viewtoggle").addEventListener("click", () => setMode(mode === "fp" ? "top" : "fp"));
428
$("helptoggle").addEventListener("click", () => toggleHelp());
429
$("helpclose").addEventListener("click", () => toggleHelp(false));
430
for (const button of document.querySelectorAll("[data-buy]"))
431
  button.addEventListener("click", () => send({ t: "buy", what: button.dataset.buy }));
432
for (const button of document.querySelectorAll("[data-agent]"))
433
  button.addEventListener("click", () => send({ t: "agent", id: button.dataset.agent }));
434
435
function toggleHelp(force) {
436
  const open = force === undefined ? $("help").style.display !== "grid" : force;
437
  $("help").style.display = open ? "grid" : "none";
438
  if (!open) {
439
    helpShown = true;
440
    try {
441
      localStorage.setItem(HELP_SEEN, "1");
442
    } catch {
443
      // A browser that refuses storage still gets the card, every visit.
444
    }
445
  }
446
}
447
448
/** The first-run card, once per browser, and never over a round in progress. */
449
function maybeHelp(s) {
450
  if (helpShown) return;
451
  try {
452
    if (localStorage.getItem(HELP_SEEN) === "1") {
453
      helpShown = true;
454
      return;
455
    }
456
  } catch {
457
    /* no storage: show it and move on */
458
  }
459
  if (s.phase === "live" && s.me.alive) return;
460
  helpShown = true;
461
  $("help").style.display = "grid";
462
}
463
464
const KITS = {};
465
466
function paintHud(s) {
467
  $("clock").textContent = Math.ceil(s.phase === "live" && s.spike.planted ? s.spike.fuse : s.clock);
468
  document.querySelector("#scoreline .red").textContent = "red " + s.score.red;
469
  document.querySelector("#scoreline .blue").textContent = s.score.blue + " blue";
470
  $("phase").textContent =
471
    `round ${s.round} · ${s.phase === "buy" ? "buy phase" : s.phase === "live" ? (s.spike.planted ? "spike down" : "live") : s.phase === "end" ? "round over" : "match over"} · ${s.attackers} attacking · you are ${s.me.side === "atk" ? "attacking" : "defending"}${s.result ? " · " + s.result : ""}`;
472
  $("hp").textContent = `${s.me.hp} hp${s.me.armour ? " +" + s.me.armour : ""}`;
473
  $("gun").textContent = `${s.me.weapon}${s.me.reloading ? " reloading" : " " + s.me.ammo}`;
474
  $("creds").textContent = `${s.me.credits} cr`;
475
  $("ultmeter").textContent = `ult ${s.me.ult}/${s.me.ultNeeds}`;
476
  $("buy").classList.toggle("on", s.phase === "buy" && $("buy").dataset.closed !== "1");
477
  if (s.phase !== "buy") $("buy").dataset.closed = "";
478
479
  const text = choosePrompt(s, {
480
    onSite: onSite(s.me),
481
    nearSpike: s.spike.x !== null && Math.hypot(s.spike.x - s.me.x, s.spike.y - s.me.y) < REACH,
482
  });
483
  if ($("prompt").textContent !== text) $("prompt").textContent = text;
484
485
  paintKit(s);
486
  paintBuy(s);
487
  paintRoster(s);
488
  paintFeed(s);
489
490
  const log = $("log");
491
  const lines = s.events.slice(0, 3).join("\n");
492
  if (log.dataset.text !== lines) {
493
    log.dataset.text = lines;
494
    log.replaceChildren();
495
    for (const line of s.events.slice(0, 3)) {
496
      const div = document.createElement("div");
497
      div.textContent = line;
498
      log.append(div);
499
    }
500
  }
501
502
  for (const side of ["atk", "def"]) {
503
    const body = $(side + "board");
504
    const rows = s.board.filter((p) => p.side === side).sort((a, b) => b.kills - a.kills);
505
    const key = rows.map((p) => `${p.name}${p.kills}${p.deaths}${p.alive}${p.credits}`).join();
506
    if (body.dataset.key === key) continue;
507
    body.dataset.key = key;
508
    body.replaceChildren();
509
    for (const player of rows) {
510
      const tr = document.createElement("tr");
511
      const cells = [
512
        player.name + (player.bot ? " (bot)" : "") + (player.alive ? "" : " ✕"),
513
        player.agent + (player.credits !== null ? ` · ${player.credits}cr` : ""),
514
        String(player.kills),
515
        String(player.deaths),
516
      ];
517
      for (const value of cells) {
518
        const td = document.createElement("td");
519
        td.textContent = value;
520
        tr.append(td);
521
      }
522
      if (player.id === s.me.id) tr.style.fontWeight = "700";
523
      body.append(tr);
524
    }
525
  }
526
}
527
528
/** Is this player standing where the spike arms? The grid says so. */
529
function onSite(me) {
530
  if (!map) return false;
531
  const row = map.rows[Math.floor(me.y / map.tile)];
532
  const cell = row ? row[Math.floor(me.x / map.tile)] : "";
533
  return cell === "A" || cell === "B";
534
}
535
536
/**
537
 * What just happened to whom: newest first, and gone a few seconds later.
538
 * The server sends names and a gun and nothing else, so there is nothing
539
 * here to read a position out of.
540
 */
541
function paintFeed(s) {
542
  const box = $("feed");
543
  const lines = (s.feed ?? []).slice().reverse();
544
  // The age is bucketed into the key: an entry fades once on its way out
545
  // rather than rebuilding the panel every frame.
546
  const key = lines.map((l) => `${l.k}>${l.v}:${l.w}:${l.h}:${l.t > 6 ? "old" : "new"}`).join("|");
547
  if (box.dataset.key === key) return;
548
  box.dataset.key = key;
549
  box.replaceChildren();
550
  for (const line of lines) {
551
    const row = document.createElement("div");
552
    row.style.opacity = line.t > 6 ? "0.5" : "1";
553
    const killer = document.createElement("span");
554
    killer.className = "k";
555
    killer.textContent = line.k ?? "—";
556
    const victim = document.createElement("span");
557
    victim.className = "v";
558
    victim.textContent = line.v;
559
    const how = document.createElement("span");
560
    how.className = "w";
561
    how.textContent = `${line.w ? " " + line.w : " ability"}${line.h ? " ✧" : ""}`;
562
    const arrow = document.createElement("span");
563
    arrow.textContent = " ▸ ";
564
    row.append(killer, arrow, victim, how);
565
    box.append(row);
566
  }
567
}
568
569
/**
570
 * Your team, always on screen: five slots, health, and struck through when
571
 * somebody is dead. The one place both questions — who is with me, who is
572
 * still up — are answered whether anybody is in sight or not.
573
 */
574
function paintRoster(s) {
575
  const rows = roster(s);
576
  const panel = $("roster");
577
  const key = rosterKey(rows);
578
  if (panel.dataset.key === key) return;
579
  panel.dataset.key = key;
580
  panel.replaceChildren();
581
  for (const row of rows) {
582
    const slot = document.createElement("div");
583
    slot.className = `slot${row.mine ? " mine" : ""}${row.alive ? "" : " down"}`;
584
    slot.style.borderLeftColor = AGENT_COLOUR[row.agent] || "#4a5162";
585
    const who = document.createElement("span");
586
    who.className = "who";
587
    who.textContent = row.name;
588
    const agent = document.createElement("span");
589
    agent.className = "agent";
590
    agent.textContent = row.alive ? row.agent : `${row.agent} · dead`;
591
    if (row.spike) {
592
      const spike = document.createElement("span");
593
      spike.className = "spike";
594
      spike.textContent = " spike";
595
      agent.append(spike);
596
    }
597
    const bar = document.createElement("span");
598
    bar.className = "hp";
599
    const fill = document.createElement("i");
600
    fill.style.width = `${row.hp}%`;
601
    fill.style.background = row.hp > 40 ? "#6fcf6f" : "#e0a040";
602
    bar.append(fill);
603
    slot.append(who, agent, bar);
604
    panel.append(slot);
605
  }
606
}
607
608
const kitOf = (id) => (agents ? agents.find((a) => a.id === id) : null);
609
610
/** The four ability buttons, each saying what it does and what it has left. */
611
function paintKit(s) {
612
  const kit = $("kit");
613
  const agent = kitOf(s.me.agent);
614
  const shape =
615
    ["c", "q", "e", "x"].map((slot) => `${slot}${s.me.charges[slot]}${Math.ceil(s.me.cooldown[slot])}`).join("|") +
616
    s.me.agent +
617
    s.me.ult +
618
    (agent ? "k" : "");
619
  if (KITS.shape === shape) return;
620
  KITS.shape = shape;
621
  kit.replaceChildren();
622
  for (const slot of ["c", "q", "e", "x"]) {
623
    const ability = agent ? agent.abilities[slot] : null;
624
    const button = document.createElement("button");
625
    const ready = slot === "x" ? s.me.ult >= s.me.ultNeeds : s.me.charges[slot] > 0 && s.me.cooldown[slot] <= 0;
626
    button.disabled = !ready;
627
    button.type = "button";
628
    const count =
629
      slot === "x"
630
        ? `${s.me.ult}/${s.me.ultNeeds}`
631
        : s.me.cooldown[slot] > 0
632
          ? `${Math.ceil(s.me.cooldown[slot])}s`
633
          : s.me.charges[slot];
634
    const name = document.createElement("span");
635
    name.textContent = `${slot.toUpperCase()}${ability ? " " + ability.name : ""}`;
636
    const tally = document.createElement("b");
637
    tally.textContent = String(count);
638
    button.append(name, tally);
639
    if (ability) button.title = `${ability.name} — ${ability.text}`;
640
    button.addEventListener("click", () => send({ t: "i", c: slot }));
641
    kit.append(button);
642
  }
643
}
644
645
/** Prices on every button, greyed when you cannot afford it. */
646
function paintBuy(s) {
647
  const agent = kitOf(s.me.agent);
648
  for (const button of document.querySelectorAll("[data-buy]")) {
649
    const what = button.dataset.buy;
650
    let cost = Number(button.dataset.cost ?? 0);
651
    if ((what === "c" || what === "q") && agent) {
652
      const ability = agent.abilities[what];
653
      cost = ability.cost;
654
      button.replaceChildren();
655
      const name = document.createElement("span");
656
      name.textContent = `${what.toUpperCase()} ${ability.name}`;
657
      const price = document.createElement("b");
658
      price.textContent = `${ability.cost} · ${s.me.charges[what]}/${ability.charges}`;
659
      button.append(name, price);
660
      button.title = `${ability.text} (${ability.charges} charge${ability.charges === 1 ? "" : "s"} a round)`;
661
    }
662
    button.disabled = cost > s.me.credits;
663
  }
664
  for (const button of document.querySelectorAll("[data-agent]")) {
665
    const picked = button.dataset.agent === s.me.agent;
666
    button.style.outline = picked ? "2px solid #6fcf9f" : "";
667
  }
668
}
669
670
// ------------------------------------------------------------------- start
671
672
Promise.all([fetch("/map.json").then((r) => r.json()), fetch("/agents.json").then((r) => r.json())])
673
  .then(([mapData, kit]) => {
674
    map = mapData;
675
    agents = kit.agents;
676
    const rows = map.rows;
677
    const cols = rows[0].length;
678
    solid = (col, row) =>
679
      col < 0 || row < 0 || row >= rows.length || col >= cols || rows[row][col] === "#";
680
    // The same grid the server collides against, so a guess about your own
681
    // movement lands where the server's answer is about to.
682
    world = { solid, tile: map.tile, r: BODY_R };
683
    $("stage").dataset.mode = mode;
684
    fillHelp();
685
    resize();
686
    connect();
687
  })
688
  .catch(() => ($("conn").textContent = "offline"));
689
690
/** The card says the round, the sides, the keys and the kit, in that order. */
691
function fillHelp() {
692
  const list = $("helpagents");
693
  if (!list || !agents) return;
694
  list.replaceChildren();
695
  for (const agent of agents) {
696
    const li = document.createElement("li");
697
    li.textContent = `${agent.name} (${agent.role}) — ${agent.blurb}`;
698
    list.append(li);
699
  }
700
}
701
702
requestAnimationFrame(frame);
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts