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

forked from benjivers/val

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

Keyboard shortcuts