/** * val, in a browser. It draws what the server sends and sends what the * person does — nothing else. There is no position here the server did not * hand over, and no enemy in a snapshot the server decided you cannot see, * so a patched client learns nothing a plain one does not. * * This file is the wiring: the socket, the keys and the pointer, the HUD. * The drawing lives beside it — `scene.js` for the first-person view, * `topdown.js` for the map, `gun.js` for the crosshair, `prompt.js` for the * line of advice and `raycast.js` for the maths all of it stands on. */ "use strict"; import { makeBeeper } from "./beep.js"; import { drawGun, gunSnapshot, gunTick, makeGun } from "./gun.js"; import { choosePrompt, REACH } from "./prompt.js"; import { roster, rosterKey } from "./roster.js"; import { AGENT_COLOUR, drawScene, makeScene } from "./scene.js"; import { moveVector } from "./steer.js"; import { drawTopdown } from "./topdown.js"; const $ = (id) => document.getElementById(id); const view = $("view"); const ctx = view.getContext("2d"); const KEY_SLOT = { KeyC: "c", KeyQ: "q", KeyE: "e", KeyX: "x" }; const COARSE = matchMedia("(pointer: coarse)").matches; const LOOK = 0.0022; // radians per pixel of mouse travel const HELP_SEEN = "val.help.seen"; let map = null; let solid = () => true; let snap = null; let socket = null; let agents = null; const shown = new Map(); // smoothed positions, so 15 frames a second look like 60 const keys = new Set(); let yaw = 0; // where this person is looking, theirs to move between snapshots let locked = false; let firing = false; let mode = COARSE ? "top" : "fp"; // a raycaster with touch look is miserable let mapOpen = false; let pointer = null; // aim target in canvas pixels, top-down only let stick = null; // { id, ox, oy, mx, my } let aimTouch = null; let helpShown = false; let last = performance.now(); const walk = { x: 0, y: 0 }; const scene = makeScene(); const gun = makeGun(); const beeper = makeBeeper(); // ------------------------------------------------------------------ socket function connect() { const url = (location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws"; socket = new WebSocket(url); socket.onopen = () => ($("conn").textContent = "live"); socket.onclose = () => { $("conn").textContent = "reconnecting…"; setTimeout(connect, 1500); }; socket.onmessage = (event) => { const data = JSON.parse(event.data); if (data.t !== "s") return; const first = snap === null; snap = data; if (first && mode === "fp") yaw = data.me.angle; gunSnapshot(gun, data); paintHud(data); maybeHelp(data); }; } const send = (message) => { if (socket && socket.readyState === 1) socket.send(JSON.stringify(message)); }; // ------------------------------------------------------------------- input function setMode(next) { mode = next; $("stage").dataset.mode = next; if (next !== "fp" && document.pointerLockElement === view) document.exitPointerLock(); if (snap) yaw = snap.me.angle; } addEventListener("keydown", (event) => { if (event.target instanceof HTMLInputElement) return; if (event.code === "Tab") { mapOpen = true; event.preventDefault(); return; } if (event.code === "KeyH" || event.key === "?") { toggleHelp(); event.preventDefault(); return; } if (event.code === "KeyV") { setMode(mode === "fp" ? "top" : "fp"); event.preventDefault(); return; } if (event.code === "KeyB") { toggleBuy(); event.preventDefault(); return; } if (KEY_SLOT[event.code]) { send({ t: "i", c: KEY_SLOT[event.code] }); event.preventDefault(); return; } keys.add(event.code); if (["KeyW", "KeyA", "KeyS", "KeyD", "Space", "KeyF", "KeyR", "ArrowLeft", "ArrowRight"].includes(event.code)) event.preventDefault(); }); addEventListener("keyup", (event) => { if (event.code === "Tab") mapOpen = false; keys.delete(event.code); }); addEventListener("blur", () => { keys.clear(); mapOpen = false; firing = false; }); // Aiming is pointer lock: click the canvas to capture the mouse, move to // look, Escape gives it back. The angle sent is the same angle as ever. view.addEventListener("click", () => { beeper.wake(); if (mode !== "fp" || locked) return; if (!view.requestPointerLock) return setMode("top"); // no lock, no first person // Asked for too soon after the last release, a browser rejects this; that // is a shrug, not an error, and the hint stays up until it takes. const asked = view.requestPointerLock(); if (asked && asked.catch) asked.catch(() => {}); }); document.addEventListener("pointerlockchange", () => { locked = document.pointerLockElement === view; if (!locked) firing = false; $("stage").dataset.locked = locked ? "1" : ""; }); addEventListener("mousemove", (event) => { if (locked) yaw += event.movementX * LOOK; }); addEventListener("mousedown", (event) => { if (locked && event.button === 0) firing = true; }); addEventListener("mouseup", (event) => { if (locked && event.button === 0) firing = false; }); // The top-down view keeps the pointer aim it always had: it is the phone // control scheme, and the fallback when the first-person view is not wanted. const canvasPoint = (event) => { const box = view.getBoundingClientRect(); return { x: ((event.clientX - box.left) / box.width) * view.width, y: ((event.clientY - box.top) / box.height) * view.height, }; }; view.addEventListener("pointermove", (event) => { if (mode !== "top" || event.pointerType === "touch") return; pointer = canvasPoint(event); }); view.addEventListener("pointerdown", (event) => { beeper.wake(); if (mode !== "top") return; view.setPointerCapture(event.pointerId); const box = view.getBoundingClientRect(); if (event.pointerType === "touch") { if (event.clientX - box.left < box.width / 2) stick = { id: event.pointerId, ox: event.clientX, oy: event.clientY, mx: 0, my: 0 }; else { aimTouch = { id: event.pointerId, ...canvasPoint(event) }; firing = true; } event.preventDefault(); return; } pointer = canvasPoint(event); firing = true; }); view.addEventListener("pointermove", (event) => { if (stick && event.pointerId === stick.id) { const dx = event.clientX - stick.ox; const dy = event.clientY - stick.oy; const len = Math.hypot(dx, dy) || 1; const reach = Math.min(len, 48) / 48; stick.mx = (dx / len) * reach; stick.my = (dy / len) * reach; } if (aimTouch && event.pointerId === aimTouch.id) Object.assign(aimTouch, canvasPoint(event)); }); const endPointer = (event) => { if (stick && event.pointerId === stick.id) stick = null; else if (aimTouch && event.pointerId === aimTouch.id) { aimTouch = null; firing = false; } else firing = false; }; view.addEventListener("pointerup", endPointer); view.addEventListener("pointercancel", endPointer); view.addEventListener("contextmenu", (event) => event.preventDefault()); // Twenty times a second the server hears what this person is doing. In the // first-person view the keys are read against the way you are facing; in the // top-down view they are the compass, the way they always were. setInterval(() => { if (!snap || !map) return; let ax = 0; let ay = 0; if (keys.has("KeyW")) ay -= 1; if (keys.has("KeyS")) ay += 1; if (keys.has("KeyA")) ax -= 1; if (keys.has("KeyD")) ax += 1; if (stick) { ax = stick.mx; ay = stick.my; } let mx = ax; let my = ay; let angle; if (mode === "fp") { if (keys.has("ArrowLeft")) yaw -= 0.045; if (keys.has("ArrowRight")) yaw += 0.045; angle = yaw; moveVector(ax, ay, yaw, walk); mx = walk.x; my = walk.y; } else { const aim = aimTouch || pointer; const me = worldToScreen(snap.me); angle = aim ? Math.atan2(aim.y - me.y, aim.x - me.x) : snap.me.angle; yaw = angle; } send({ t: "i", mx, my, a: angle, f: firing || keys.has("Space"), u: keys.has("KeyF"), r: keys.has("KeyR"), }); }, 50); // ------------------------------------------------------------------ drawing function resize() { const box = view.getBoundingClientRect(); const dpr = Math.min(devicePixelRatio || 1, 2); view.width = Math.round(box.width * dpr); view.height = Math.round(box.height * dpr); } addEventListener("resize", resize); const scale = () => (map ? view.width / (map.rows[0].length * map.tile) : 1); const worldToScreen = (p) => ({ x: p.x * scale(), y: p.y * scale() }); function smooth(id, x, y, angle) { const now = shown.get(id); if (!now) { const fresh = { x, y, angle }; shown.set(id, fresh); return fresh; } now.x += (x - now.x) * 0.35; now.y += (y - now.y) * 0.35; const turn = ((angle - now.angle + Math.PI * 3) % (Math.PI * 2)) - Math.PI; now.angle += turn * 0.4; return now; } const look = (p) => smooth(p.id, p.x, p.y, p.angle); function frame(now) { requestAnimationFrame(frame); const dt = Math.min(0.1, (now - last) / 1000); last = now; if (!map) return; gunTick(gun, dt); ctx.clearRect(0, 0, view.width, view.height); if (!snap) { drawTopdown(ctx, map, null, look, { x: 0, y: 0, w: view.width, h: view.height }); return; } beeper.update(snap.spike.planted, snap.spike.fuse, now / 1000); const eye = look(snap.me); const facing = mode === "fp" ? yaw : eye.angle; if (mode === "fp" && !mapOpen) { drawScene(ctx, scene, { solid, tile: map.tile }, { x: eye.x, y: eye.y, angle: facing }, snap, { width: view.width, height: view.height, look, }); drawGun(ctx, gun, view.width, view.height, snap); drawMinimap(); } else { drawTopdown(ctx, map, snap, look, { x: 0, y: 0, w: view.width, h: view.height }); } if (snap.me.planting > 0) bar(snap.me.planting / 4, "#e0a040", "planting"); else if (snap.spike.planted && snap.spike.defuse > 0 && snap.me.side === "def") bar(snap.spike.defuse / 7, "#4fd6a0", "defusing"); $("flash").style.opacity = Math.min(0.95, snap.me.blind * 0.8); $("dead").style.display = snap.me.alive ? "none" : "grid"; $("aimhint").style.display = mode === "fp" && !locked && !COARSE ? "grid" : "none"; } /** The same top-down drawing, small, in the corner, with you as an arrow. */ function drawMinimap() { const w = Math.min(view.width * 0.3, 260 * (view.width / 900)); const h = (w * map.rows.length) / map.rows[0].length; const pad = 8; ctx.save(); ctx.globalAlpha = 0.85; ctx.fillStyle = "#0b0d11"; ctx.fillRect(pad - 2, pad - 2, w + 4, h + 4); drawTopdown(ctx, map, snap, look, { x: pad, y: pad, w, h }, { labels: false }); ctx.restore(); ctx.strokeStyle = "rgba(255,255,255,0.18)"; ctx.lineWidth = 1; ctx.strokeRect(pad - 2, pad - 2, w + 4, h + 4); } function bar(fraction, colour, label) { const w = view.width * 0.4; const x = view.width / 2 - w / 2; const y = view.height * 0.86; ctx.fillStyle = "#0009"; ctx.fillRect(x, y, w, 16); ctx.fillStyle = colour; ctx.fillRect(x, y, w * Math.min(1, fraction), 16); ctx.fillStyle = "#fff"; ctx.font = "12px system-ui, sans-serif"; ctx.textAlign = "center"; ctx.fillText(label, view.width / 2, y + 12); ctx.textAlign = "left"; } // --------------------------------------------------------------------- hud // The buy opens itself every buy phase; closing it is remembered until the // next one, so nobody has to fight the panel to watch the round start. function toggleBuy() { const open = $("buy").classList.toggle("on"); $("buy").dataset.closed = open ? "" : "1"; } $("buytoggle").addEventListener("click", toggleBuy); $("viewtoggle").addEventListener("click", () => setMode(mode === "fp" ? "top" : "fp")); $("helptoggle").addEventListener("click", () => toggleHelp()); $("helpclose").addEventListener("click", () => toggleHelp(false)); for (const button of document.querySelectorAll("[data-buy]")) button.addEventListener("click", () => send({ t: "buy", what: button.dataset.buy })); for (const button of document.querySelectorAll("[data-agent]")) button.addEventListener("click", () => send({ t: "agent", id: button.dataset.agent })); function toggleHelp(force) { const open = force === undefined ? $("help").style.display !== "grid" : force; $("help").style.display = open ? "grid" : "none"; if (!open) { helpShown = true; try { localStorage.setItem(HELP_SEEN, "1"); } catch { // A browser that refuses storage still gets the card, every visit. } } } /** The first-run card, once per browser, and never over a round in progress. */ function maybeHelp(s) { if (helpShown) return; try { if (localStorage.getItem(HELP_SEEN) === "1") { helpShown = true; return; } } catch { /* no storage: show it and move on */ } if (s.phase === "live" && s.me.alive) return; helpShown = true; $("help").style.display = "grid"; } const KITS = {}; function paintHud(s) { $("clock").textContent = Math.ceil(s.phase === "live" && s.spike.planted ? s.spike.fuse : s.clock); document.querySelector("#scoreline .red").textContent = "red " + s.score.red; document.querySelector("#scoreline .blue").textContent = s.score.blue + " blue"; $("phase").textContent = `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 : ""}`; $("hp").textContent = `${s.me.hp} hp${s.me.armour ? " +" + s.me.armour : ""}`; $("gun").textContent = `${s.me.weapon}${s.me.reloading ? " reloading" : " " + s.me.ammo}`; $("creds").textContent = `${s.me.credits} cr`; $("ultmeter").textContent = `ult ${s.me.ult}/${s.me.ultNeeds}`; $("buy").classList.toggle("on", s.phase === "buy" && $("buy").dataset.closed !== "1"); if (s.phase !== "buy") $("buy").dataset.closed = ""; const text = choosePrompt(s, { onSite: onSite(s.me), nearSpike: s.spike.x !== null && Math.hypot(s.spike.x - s.me.x, s.spike.y - s.me.y) < REACH, }); if ($("prompt").textContent !== text) $("prompt").textContent = text; paintKit(s); paintBuy(s); paintRoster(s); const log = $("log"); const lines = s.events.slice(0, 3).join("\n"); if (log.dataset.text !== lines) { log.dataset.text = lines; log.replaceChildren(); for (const line of s.events.slice(0, 3)) { const div = document.createElement("div"); div.textContent = line; log.append(div); } } for (const side of ["atk", "def"]) { const body = $(side + "board"); const rows = s.board.filter((p) => p.side === side).sort((a, b) => b.kills - a.kills); const key = rows.map((p) => `${p.name}${p.kills}${p.deaths}${p.alive}${p.credits}`).join(); if (body.dataset.key === key) continue; body.dataset.key = key; body.replaceChildren(); for (const player of rows) { const tr = document.createElement("tr"); const cells = [ player.name + (player.bot ? " (bot)" : "") + (player.alive ? "" : " ✕"), player.agent + (player.credits !== null ? ` · ${player.credits}cr` : ""), String(player.kills), String(player.deaths), ]; for (const value of cells) { const td = document.createElement("td"); td.textContent = value; tr.append(td); } if (player.id === s.me.id) tr.style.fontWeight = "700"; body.append(tr); } } } /** Is this player standing where the spike arms? The grid says so. */ function onSite(me) { if (!map) return false; const row = map.rows[Math.floor(me.y / map.tile)]; const cell = row ? row[Math.floor(me.x / map.tile)] : ""; return cell === "A" || cell === "B"; } /** * Your team, always on screen: five slots, health, and struck through when * somebody is dead. The one place both questions — who is with me, who is * still up — are answered whether anybody is in sight or not. */ function paintRoster(s) { const rows = roster(s); const panel = $("roster"); const key = rosterKey(rows); if (panel.dataset.key === key) return; panel.dataset.key = key; panel.replaceChildren(); for (const row of rows) { const slot = document.createElement("div"); slot.className = `slot${row.mine ? " mine" : ""}${row.alive ? "" : " down"}`; slot.style.borderLeftColor = AGENT_COLOUR[row.agent] || "#4a5162"; const who = document.createElement("span"); who.className = "who"; who.textContent = row.name; const agent = document.createElement("span"); agent.className = "agent"; agent.textContent = row.alive ? row.agent : `${row.agent} · dead`; if (row.spike) { const spike = document.createElement("span"); spike.className = "spike"; spike.textContent = " spike"; agent.append(spike); } const bar = document.createElement("span"); bar.className = "hp"; const fill = document.createElement("i"); fill.style.width = `${row.hp}%`; fill.style.background = row.hp > 40 ? "#6fcf6f" : "#e0a040"; bar.append(fill); slot.append(who, agent, bar); panel.append(slot); } } const kitOf = (id) => (agents ? agents.find((a) => a.id === id) : null); /** The four ability buttons, each saying what it does and what it has left. */ function paintKit(s) { const kit = $("kit"); const agent = kitOf(s.me.agent); const shape = ["c", "q", "e", "x"].map((slot) => `${slot}${s.me.charges[slot]}${Math.ceil(s.me.cooldown[slot])}`).join("|") + s.me.agent + s.me.ult + (agent ? "k" : ""); if (KITS.shape === shape) return; KITS.shape = shape; kit.replaceChildren(); for (const slot of ["c", "q", "e", "x"]) { const ability = agent ? agent.abilities[slot] : null; const button = document.createElement("button"); const ready = slot === "x" ? s.me.ult >= s.me.ultNeeds : s.me.charges[slot] > 0 && s.me.cooldown[slot] <= 0; button.disabled = !ready; button.type = "button"; const count = slot === "x" ? `${s.me.ult}/${s.me.ultNeeds}` : s.me.cooldown[slot] > 0 ? `${Math.ceil(s.me.cooldown[slot])}s` : s.me.charges[slot]; const name = document.createElement("span"); name.textContent = `${slot.toUpperCase()}${ability ? " " + ability.name : ""}`; const tally = document.createElement("b"); tally.textContent = String(count); button.append(name, tally); if (ability) button.title = `${ability.name} — ${ability.text}`; button.addEventListener("click", () => send({ t: "i", c: slot })); kit.append(button); } } /** Prices on every button, greyed when you cannot afford it. */ function paintBuy(s) { const agent = kitOf(s.me.agent); for (const button of document.querySelectorAll("[data-buy]")) { const what = button.dataset.buy; let cost = Number(button.dataset.cost ?? 0); if ((what === "c" || what === "q") && agent) { const ability = agent.abilities[what]; cost = ability.cost; button.replaceChildren(); const name = document.createElement("span"); name.textContent = `${what.toUpperCase()} ${ability.name}`; const price = document.createElement("b"); price.textContent = `${ability.cost} · ${s.me.charges[what]}/${ability.charges}`; button.append(name, price); button.title = `${ability.text} (${ability.charges} charge${ability.charges === 1 ? "" : "s"} a round)`; } button.disabled = cost > s.me.credits; } for (const button of document.querySelectorAll("[data-agent]")) { const picked = button.dataset.agent === s.me.agent; button.style.outline = picked ? "2px solid #6fcf9f" : ""; } } // ------------------------------------------------------------------- start Promise.all([fetch("/map.json").then((r) => r.json()), fetch("/agents.json").then((r) => r.json())]) .then(([mapData, kit]) => { map = mapData; agents = kit.agents; const rows = map.rows; const cols = rows[0].length; solid = (col, row) => col < 0 || row < 0 || row >= rows.length || col >= cols || rows[row][col] === "#"; $("stage").dataset.mode = mode; fillHelp(); resize(); connect(); }) .catch(() => ($("conn").textContent = "offline")); /** The card says the round, the sides, the keys and the kit, in that order. */ function fillHelp() { const list = $("helpagents"); if (!list || !agents) return; list.replaceChildren(); for (const agent of agents) { const li = document.createElement("li"); li.textContent = `${agent.name} (${agent.role}) — ${agent.blurb}`; list.append(li); } } requestAnimationFrame(frame);