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

forked from benjivers/val

workbenchthis machine
Files 00e29188271b60cb71e377df120e603f5649cfdb
553 lines · 18.8 KB · ~5.5k tok Raw History
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 { drawGun, gunSnapshot, gunTick, makeGun } from "./gun.js";
16
import { choosePrompt, REACH } from "./prompt.js";
17
import { drawScene, makeScene } from "./scene.js";
18
import { moveVector } from "./steer.js";
19
import { drawTopdown } from "./topdown.js";
20
21
const $ = (id) => document.getElementById(id);
22
const view = $("view");
23
const ctx = view.getContext("2d");
24
25
const KEY_SLOT = { KeyC: "c", KeyQ: "q", KeyE: "e", KeyX: "x" };
26
const COARSE = matchMedia("(pointer: coarse)").matches;
27
const LOOK = 0.0022; // radians per pixel of mouse travel
28
const HELP_SEEN = "val.help.seen";
29
30
let map = null;
31
let solid = () => true;
32
let snap = null;
33
let socket = null;
34
let agents = null;
35
const shown = new Map(); // smoothed positions, so 15 frames a second look like 60
36
const keys = new Set();
37
let yaw = 0; // where this person is looking, theirs to move between snapshots
38
let locked = false;
39
let firing = false;
40
let mode = COARSE ? "top" : "fp"; // a raycaster with touch look is miserable
41
let mapOpen = false;
42
let pointer = null; // aim target in canvas pixels, top-down only
43
let stick = null; // { id, ox, oy, mx, my }
44
let aimTouch = null;
45
let helpShown = false;
46
let last = performance.now();
47
48
const walk = { x: 0, y: 0 };
49
const scene = makeScene();
50
const gun = makeGun();
51
const beeper = makeBeeper();
52
53
// ------------------------------------------------------------------ socket
54
55
function connect() {
56
  const url = (location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws";
57
  socket = new WebSocket(url);
58
  socket.onopen = () => ($("conn").textContent = "live");
59
  socket.onclose = () => {
60
    $("conn").textContent = "reconnecting…";
61
    setTimeout(connect, 1500);
62
  };
63
  socket.onmessage = (event) => {
64
    const data = JSON.parse(event.data);
65
    if (data.t !== "s") return;
66
    const first = snap === null;
67
    snap = data;
68
    if (first && mode === "fp") yaw = data.me.angle;
69
    gunSnapshot(gun, data);
70
    paintHud(data);
71
    maybeHelp(data);
72
  };
73
}
74
75
const send = (message) => {
76
  if (socket && socket.readyState === 1) socket.send(JSON.stringify(message));
77
};
78
79
// ------------------------------------------------------------------- input
80
81
function setMode(next) {
82
  mode = next;
83
  $("stage").dataset.mode = next;
84
  if (next !== "fp" && document.pointerLockElement === view) document.exitPointerLock();
85
  if (snap) yaw = snap.me.angle;
86
}
87
88
addEventListener("keydown", (event) => {
89
  if (event.target instanceof HTMLInputElement) return;
90
  if (event.code === "Tab") {
91
    mapOpen = true;
92
    event.preventDefault();
93
    return;
94
  }
95
  if (event.code === "KeyH" || event.key === "?") {
96
    toggleHelp();
97
    event.preventDefault();
98
    return;
99
  }
100
  if (event.code === "KeyV") {
101
    setMode(mode === "fp" ? "top" : "fp");
102
    event.preventDefault();
103
    return;
104
  }
105
  if (event.code === "KeyB") {
106
    toggleBuy();
107
    event.preventDefault();
108
    return;
109
  }
110
  if (KEY_SLOT[event.code]) {
111
    send({ t: "i", c: KEY_SLOT[event.code] });
112
    event.preventDefault();
113
    return;
114
  }
115
  keys.add(event.code);
116
  if (["KeyW", "KeyA", "KeyS", "KeyD", "Space", "KeyF", "KeyR", "ArrowLeft", "ArrowRight"].includes(event.code))
117
    event.preventDefault();
118
});
119
addEventListener("keyup", (event) => {
120
  if (event.code === "Tab") mapOpen = false;
121
  keys.delete(event.code);
122
});
123
addEventListener("blur", () => {
124
  keys.clear();
125
  mapOpen = false;
126
  firing = false;
127
});
128
129
// Aiming is pointer lock: click the canvas to capture the mouse, move to
130
// look, Escape gives it back. The angle sent is the same angle as ever.
131
view.addEventListener("click", () => {
132
  beeper.wake();
133
  if (mode !== "fp" || locked) return;
134
  if (!view.requestPointerLock) return setMode("top"); // no lock, no first person
135
  // Asked for too soon after the last release, a browser rejects this; that
136
  // is a shrug, not an error, and the hint stays up until it takes.
137
  const asked = view.requestPointerLock();
138
  if (asked && asked.catch) asked.catch(() => {});
139
});
140
document.addEventListener("pointerlockchange", () => {
141
  locked = document.pointerLockElement === view;
142
  if (!locked) firing = false;
143
  $("stage").dataset.locked = locked ? "1" : "";
144
});
145
addEventListener("mousemove", (event) => {
146
  if (locked) yaw += event.movementX * LOOK;
147
});
148
addEventListener("mousedown", (event) => {
149
  if (locked && event.button === 0) firing = true;
150
});
151
addEventListener("mouseup", (event) => {
152
  if (locked && event.button === 0) firing = false;
153
});
154
155
// The top-down view keeps the pointer aim it always had: it is the phone
156
// control scheme, and the fallback when the first-person view is not wanted.
157
const canvasPoint = (event) => {
158
  const box = view.getBoundingClientRect();
159
  return {
160
    x: ((event.clientX - box.left) / box.width) * view.width,
161
    y: ((event.clientY - box.top) / box.height) * view.height,
162
  };
163
};
164
view.addEventListener("pointermove", (event) => {
165
  if (mode !== "top" || event.pointerType === "touch") return;
166
  pointer = canvasPoint(event);
167
});
168
view.addEventListener("pointerdown", (event) => {
169
  beeper.wake();
170
  if (mode !== "top") return;
171
  view.setPointerCapture(event.pointerId);
172
  const box = view.getBoundingClientRect();
173
  if (event.pointerType === "touch") {
174
    if (event.clientX - box.left < box.width / 2)
175
      stick = { id: event.pointerId, ox: event.clientX, oy: event.clientY, mx: 0, my: 0 };
176
    else {
177
      aimTouch = { id: event.pointerId, ...canvasPoint(event) };
178
      firing = true;
179
    }
180
    event.preventDefault();
181
    return;
182
  }
183
  pointer = canvasPoint(event);
184
  firing = true;
185
});
186
view.addEventListener("pointermove", (event) => {
187
  if (stick && event.pointerId === stick.id) {
188
    const dx = event.clientX - stick.ox;
189
    const dy = event.clientY - stick.oy;
190
    const len = Math.hypot(dx, dy) || 1;
191
    const reach = Math.min(len, 48) / 48;
192
    stick.mx = (dx / len) * reach;
193
    stick.my = (dy / len) * reach;
194
  }
195
  if (aimTouch && event.pointerId === aimTouch.id) Object.assign(aimTouch, canvasPoint(event));
196
});
197
const endPointer = (event) => {
198
  if (stick && event.pointerId === stick.id) stick = null;
199
  else if (aimTouch && event.pointerId === aimTouch.id) {
200
    aimTouch = null;
201
    firing = false;
202
  } else firing = false;
203
};
204
view.addEventListener("pointerup", endPointer);
205
view.addEventListener("pointercancel", endPointer);
206
view.addEventListener("contextmenu", (event) => event.preventDefault());
207
208
// Twenty times a second the server hears what this person is doing. In the
209
// first-person view the keys are read against the way you are facing; in the
210
// top-down view they are the compass, the way they always were.
211
setInterval(() => {
212
  if (!snap || !map) return;
213
  let ax = 0;
214
  let ay = 0;
215
  if (keys.has("KeyW")) ay -= 1;
216
  if (keys.has("KeyS")) ay += 1;
217
  if (keys.has("KeyA")) ax -= 1;
218
  if (keys.has("KeyD")) ax += 1;
219
  if (stick) {
220
    ax = stick.mx;
221
    ay = stick.my;
222
  }
223
  let mx = ax;
224
  let my = ay;
225
  let angle;
226
  if (mode === "fp") {
227
    if (keys.has("ArrowLeft")) yaw -= 0.045;
228
    if (keys.has("ArrowRight")) yaw += 0.045;
229
    angle = yaw;
230
    moveVector(ax, ay, yaw, walk);
231
    mx = walk.x;
232
    my = walk.y;
233
  } else {
234
    const aim = aimTouch || pointer;
235
    const me = worldToScreen(snap.me);
236
    angle = aim ? Math.atan2(aim.y - me.y, aim.x - me.x) : snap.me.angle;
237
    yaw = angle;
238
  }
239
  send({
240
    t: "i",
241
    mx,
242
    my,
243
    a: angle,
244
    f: firing || keys.has("Space"),
245
    u: keys.has("KeyF"),
246
    r: keys.has("KeyR"),
247
  });
248
}, 50);
249
250
// ------------------------------------------------------------------ drawing
251
252
function resize() {
253
  const box = view.getBoundingClientRect();
254
  const dpr = Math.min(devicePixelRatio || 1, 2);
255
  view.width = Math.round(box.width * dpr);
256
  view.height = Math.round(box.height * dpr);
257
}
258
addEventListener("resize", resize);
259
260
const scale = () => (map ? view.width / (map.rows[0].length * map.tile) : 1);
261
const worldToScreen = (p) => ({ x: p.x * scale(), y: p.y * scale() });
262
263
function smooth(id, x, y, angle) {
264
  const now = shown.get(id);
265
  if (!now) {
266
    const fresh = { x, y, angle };
267
    shown.set(id, fresh);
268
    return fresh;
269
  }
270
  now.x += (x - now.x) * 0.35;
271
  now.y += (y - now.y) * 0.35;
272
  const turn = ((angle - now.angle + Math.PI * 3) % (Math.PI * 2)) - Math.PI;
273
  now.angle += turn * 0.4;
274
  return now;
275
}
276
277
const look = (p) => smooth(p.id, p.x, p.y, p.angle);
278
279
function frame(now) {
280
  requestAnimationFrame(frame);
281
  const dt = Math.min(0.1, (now - last) / 1000);
282
  last = now;
283
  if (!map) return;
284
  gunTick(gun, dt);
285
  ctx.clearRect(0, 0, view.width, view.height);
286
287
  if (!snap) {
288
    drawTopdown(ctx, map, null, look, { x: 0, y: 0, w: view.width, h: view.height });
289
    return;
290
  }
291
  beeper.update(snap.spike.planted, snap.spike.fuse, now / 1000);
292
  const eye = look(snap.me);
293
  const facing = mode === "fp" ? yaw : eye.angle;
294
295
  if (mode === "fp" && !mapOpen) {
296
    drawScene(ctx, scene, { solid, tile: map.tile }, { x: eye.x, y: eye.y, angle: facing }, snap, {
297
      width: view.width,
298
      height: view.height,
299
      look,
300
    });
301
    drawGun(ctx, gun, view.width, view.height, snap);
302
    drawMinimap();
303
  } else {
304
    drawTopdown(ctx, map, snap, look, { x: 0, y: 0, w: view.width, h: view.height });
305
  }
306
307
  if (snap.me.planting > 0) bar(snap.me.planting / 4, "#e0a040", "planting");
308
  else if (snap.spike.planted && snap.spike.defuse > 0 && snap.me.side === "def")
309
    bar(snap.spike.defuse / 7, "#4fd6a0", "defusing");
310
  $("flash").style.opacity = Math.min(0.95, snap.me.blind * 0.8);
311
  $("dead").style.display = snap.me.alive ? "none" : "grid";
312
  $("aimhint").style.display = mode === "fp" && !locked && !COARSE ? "grid" : "none";
313
}
314
315
/** The same top-down drawing, small, in the corner, with you as an arrow. */
316
function drawMinimap() {
317
  const w = Math.min(view.width * 0.3, 260 * (view.width / 900));
318
  const h = (w * map.rows.length) / map.rows[0].length;
319
  const pad = 8;
320
  ctx.save();
321
  ctx.globalAlpha = 0.85;
322
  ctx.fillStyle = "#0b0d11";
323
  ctx.fillRect(pad - 2, pad - 2, w + 4, h + 4);
324
  drawTopdown(ctx, map, snap, look, { x: pad, y: pad, w, h }, { labels: false });
325
  ctx.restore();
326
  ctx.strokeStyle = "rgba(255,255,255,0.18)";
327
  ctx.lineWidth = 1;
328
  ctx.strokeRect(pad - 2, pad - 2, w + 4, h + 4);
329
}
330
331
function bar(fraction, colour, label) {
332
  const w = view.width * 0.4;
333
  const x = view.width / 2 - w / 2;
334
  const y = view.height * 0.86;
335
  ctx.fillStyle = "#0009";
336
  ctx.fillRect(x, y, w, 16);
337
  ctx.fillStyle = colour;
338
  ctx.fillRect(x, y, w * Math.min(1, fraction), 16);
339
  ctx.fillStyle = "#fff";
340
  ctx.font = "12px system-ui, sans-serif";
341
  ctx.textAlign = "center";
342
  ctx.fillText(label, view.width / 2, y + 12);
343
  ctx.textAlign = "left";
344
}
345
346
// --------------------------------------------------------------------- hud
347
348
// The buy opens itself every buy phase; closing it is remembered until the
349
// next one, so nobody has to fight the panel to watch the round start.
350
function toggleBuy() {
351
  const open = $("buy").classList.toggle("on");
352
  $("buy").dataset.closed = open ? "" : "1";
353
}
354
$("buytoggle").addEventListener("click", toggleBuy);
355
$("viewtoggle").addEventListener("click", () => setMode(mode === "fp" ? "top" : "fp"));
356
$("helptoggle").addEventListener("click", () => toggleHelp());
357
$("helpclose").addEventListener("click", () => toggleHelp(false));
358
for (const button of document.querySelectorAll("[data-buy]"))
359
  button.addEventListener("click", () => send({ t: "buy", what: button.dataset.buy }));
360
for (const button of document.querySelectorAll("[data-agent]"))
361
  button.addEventListener("click", () => send({ t: "agent", id: button.dataset.agent }));
362
363
function toggleHelp(force) {
364
  const open = force === undefined ? $("help").style.display !== "grid" : force;
365
  $("help").style.display = open ? "grid" : "none";
366
  if (!open) {
367
    helpShown = true;
368
    try {
369
      localStorage.setItem(HELP_SEEN, "1");
370
    } catch {
371
      // A browser that refuses storage still gets the card, every visit.
372
    }
373
  }
374
}
375
376
/** The first-run card, once per browser, and never over a round in progress. */
377
function maybeHelp(s) {
378
  if (helpShown) return;
379
  try {
380
    if (localStorage.getItem(HELP_SEEN) === "1") {
381
      helpShown = true;
382
      return;
383
    }
384
  } catch {
385
    /* no storage: show it and move on */
386
  }
387
  if (s.phase === "live" && s.me.alive) return;
388
  helpShown = true;
389
  $("help").style.display = "grid";
390
}
391
392
const KITS = {};
393
394
function paintHud(s) {
395
  $("clock").textContent = Math.ceil(s.phase === "live" && s.spike.planted ? s.spike.fuse : s.clock);
396
  document.querySelector("#scoreline .red").textContent = "red " + s.score.red;
397
  document.querySelector("#scoreline .blue").textContent = s.score.blue + " blue";
398
  $("phase").textContent =
399
    `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 : ""}`;
400
  $("hp").textContent = `${s.me.hp} hp${s.me.armour ? " +" + s.me.armour : ""}`;
401
  $("gun").textContent = `${s.me.weapon}${s.me.reloading ? " reloading" : " " + s.me.ammo}`;
402
  $("creds").textContent = `${s.me.credits} cr`;
403
  $("ultmeter").textContent = `ult ${s.me.ult}/${s.me.ultNeeds}`;
404
  $("buy").classList.toggle("on", s.phase === "buy" && $("buy").dataset.closed !== "1");
405
  if (s.phase !== "buy") $("buy").dataset.closed = "";
406
407
  const text = choosePrompt(s, {
408
    onSite: onSite(s.me),
409
    nearSpike: s.spike.x !== null && Math.hypot(s.spike.x - s.me.x, s.spike.y - s.me.y) < REACH,
410
  });
411
  if ($("prompt").textContent !== text) $("prompt").textContent = text;
412
413
  paintKit(s);
414
  paintBuy(s);
415
416
  const log = $("log");
417
  const lines = s.events.slice(0, 3).join("\n");
418
  if (log.dataset.text !== lines) {
419
    log.dataset.text = lines;
420
    log.replaceChildren();
421
    for (const line of s.events.slice(0, 3)) {
422
      const div = document.createElement("div");
423
      div.textContent = line;
424
      log.append(div);
425
    }
426
  }
427
428
  for (const side of ["atk", "def"]) {
429
    const body = $(side + "board");
430
    const rows = s.board.filter((p) => p.side === side).sort((a, b) => b.kills - a.kills);
431
    const key = rows.map((p) => `${p.name}${p.kills}${p.deaths}${p.alive}${p.credits}`).join();
432
    if (body.dataset.key === key) continue;
433
    body.dataset.key = key;
434
    body.replaceChildren();
435
    for (const player of rows) {
436
      const tr = document.createElement("tr");
437
      const cells = [
438
        player.name + (player.bot ? " (bot)" : "") + (player.alive ? "" : " ✕"),
439
        player.agent + (player.credits !== null ? ` · ${player.credits}cr` : ""),
440
        String(player.kills),
441
        String(player.deaths),
442
      ];
443
      for (const value of cells) {
444
        const td = document.createElement("td");
445
        td.textContent = value;
446
        tr.append(td);
447
      }
448
      if (player.id === s.me.id) tr.style.fontWeight = "700";
449
      body.append(tr);
450
    }
451
  }
452
}
453
454
/** Is this player standing where the spike arms? The grid says so. */
455
function onSite(me) {
456
  if (!map) return false;
457
  const row = map.rows[Math.floor(me.y / map.tile)];
458
  const cell = row ? row[Math.floor(me.x / map.tile)] : "";
459
  return cell === "A" || cell === "B";
460
}
461
462
const kitOf = (id) => (agents ? agents.find((a) => a.id === id) : null);
463
464
/** The four ability buttons, each saying what it does and what it has left. */
465
function paintKit(s) {
466
  const kit = $("kit");
467
  const agent = kitOf(s.me.agent);
468
  const shape =
469
    ["c", "q", "e", "x"].map((slot) => `${slot}${s.me.charges[slot]}${Math.ceil(s.me.cooldown[slot])}`).join("|") +
470
    s.me.agent +
471
    s.me.ult +
472
    (agent ? "k" : "");
473
  if (KITS.shape === shape) return;
474
  KITS.shape = shape;
475
  kit.replaceChildren();
476
  for (const slot of ["c", "q", "e", "x"]) {
477
    const ability = agent ? agent.abilities[slot] : null;
478
    const button = document.createElement("button");
479
    const ready = slot === "x" ? s.me.ult >= s.me.ultNeeds : s.me.charges[slot] > 0 && s.me.cooldown[slot] <= 0;
480
    button.disabled = !ready;
481
    button.type = "button";
482
    const count =
483
      slot === "x"
484
        ? `${s.me.ult}/${s.me.ultNeeds}`
485
        : s.me.cooldown[slot] > 0
486
          ? `${Math.ceil(s.me.cooldown[slot])}s`
487
          : s.me.charges[slot];
488
    const name = document.createElement("span");
489
    name.textContent = `${slot.toUpperCase()}${ability ? " " + ability.name : ""}`;
490
    const tally = document.createElement("b");
491
    tally.textContent = String(count);
492
    button.append(name, tally);
493
    if (ability) button.title = `${ability.name} — ${ability.text}`;
494
    button.addEventListener("click", () => send({ t: "i", c: slot }));
495
    kit.append(button);
496
  }
497
}
498
499
/** Prices on every button, greyed when you cannot afford it. */
500
function paintBuy(s) {
501
  const agent = kitOf(s.me.agent);
502
  for (const button of document.querySelectorAll("[data-buy]")) {
503
    const what = button.dataset.buy;
504
    let cost = Number(button.dataset.cost ?? 0);
505
    if ((what === "c" || what === "q") && agent) {
506
      const ability = agent.abilities[what];
507
      cost = ability.cost;
508
      button.replaceChildren();
509
      const name = document.createElement("span");
510
      name.textContent = `${what.toUpperCase()} ${ability.name}`;
511
      const price = document.createElement("b");
512
      price.textContent = `${ability.cost} · ${s.me.charges[what]}/${ability.charges}`;
513
      button.append(name, price);
514
      button.title = `${ability.text} (${ability.charges} charge${ability.charges === 1 ? "" : "s"} a round)`;
515
    }
516
    button.disabled = cost > s.me.credits;
517
  }
518
  for (const button of document.querySelectorAll("[data-agent]")) {
519
    const picked = button.dataset.agent === s.me.agent;
520
    button.style.outline = picked ? "2px solid #6fcf9f" : "";
521
  }
522
}
523
524
// ------------------------------------------------------------------- start
525
526
Promise.all([fetch("/map.json").then((r) => r.json()), fetch("/agents.json").then((r) => r.json())])
527
  .then(([mapData, kit]) => {
528
    map = mapData;
529
    agents = kit.agents;
530
    const rows = map.rows;
531
    const cols = rows[0].length;
532
    solid = (col, row) =>
533
      col < 0 || row < 0 || row >= rows.length || col >= cols || rows[row][col] === "#";
534
    $("stage").dataset.mode = mode;
535
    fillHelp();
536
    resize();
537
    connect();
538
  })
539
  .catch(() => ($("conn").textContent = "offline"));
540
541
/** The card says the round, the sides, the keys and the kit, in that order. */
542
function fillHelp() {
543
  const list = $("helpagents");
544
  if (!list || !agents) return;
545
  list.replaceChildren();
546
  for (const agent of agents) {
547
    const li = document.createElement("li");
548
    li.textContent = `${agent.name} (${agent.role}) — ${agent.blurb}`;
549
    list.append(li);
550
  }
551
}
552
553
requestAnimationFrame(frame);
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts