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

forked from benjivers/val

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

Keyboard shortcuts