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

forked from benjivers/val

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

Keyboard shortcuts