Split The code is public; the app answers only to the crew.

Sound, sensitivity and a scope you can reach without leaving the match #31

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/cs:scout/29-sound-sensitivity-and-a-scope-you-can-re → main 2 commits fork

  • Merged. scout/29-sound-sensitivity-and-a-scope-you-can-re was merged into main as 24bfb57.

Review

Sign in to review this change.
9 files changed +437 −39
.checkdata/game.html added +178
@@ -0,0 +1,178 @@
1 <!doctype html>
2 <html lang="en">
3 <meta charset="utf-8">
4 <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
5 <title>cs — a browser defusal shooter</title>
6 <meta name="description" content="A Counter-Strike-shaped defusal shooter that runs in the browser: WebGL2, bots, bomb rounds and an economy.">
7 <style>
8 :root { color-scheme: dark; --bg:#0b0d11; --panel:#141821; --line:#232a36; --text:#e7eaf0; --dim:#9aa4b4; --t:#e2b04a; --ct:#6fa8e8; }
9 * { box-sizing: border-box; }
10 body { margin:0; background:var(--bg); color:var(--text); font:16px/1.55 system-ui,-apple-system,Segoe UI,sans-serif; }
11 header, main { max-width: 64rem; margin: 0 auto; padding: 0 1rem; }
12 header { display:flex; align-items:baseline; gap:.75rem; padding-top:1rem; flex-wrap:wrap; }
13 h1 { font-size:1.4rem; margin:0; letter-spacing:.02em; }
14 .env { font-size:.72rem; padding:.15rem .5rem; border-radius:999px; background:#1d4ed8; color:#fff; }
15 .env.production { background:#15803d; }
16 small.commit { color:var(--dim); font-size:.75rem; }
17 #stage { position:relative; width:100%; aspect-ratio:16/9; max-height:78vh; margin:1rem auto; background:#000;
18 border:1px solid var(--line); border-radius:.6rem; overflow:hidden; touch-action:none; }
19 #scene, #hud { position:absolute; inset:0; width:100%; height:100%; display:block; }
20 #hud { pointer-events:none; }
21 .overlay { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center;
22 gap:.75rem; background:rgba(8,10,14,.82); text-align:center; padding:1rem; overflow:auto;
23 /* #stage is touch-action:none for the look drag; an overlay taller
24 than the stage still has to scroll under a thumb. */
25 touch-action:pan-y; overscroll-behavior:contain; }
26 .overlay[hidden] { display:none; }
27 .overlay h2 { margin:0; font-size:1.3rem; }
28 .overlay p { margin:.2rem 0; color:var(--dim); max-width:34rem; }
29 .row { display:flex; gap:.5rem; flex-wrap:wrap; justify-content:center; align-items:center; }
30 label { display:flex; flex-direction:column; gap:.25rem; font-size:.8rem; color:var(--dim); text-align:left; }
31 input, select { min-height:44px; padding:.5rem .7rem; font:inherit; color:var(--text);
32 background:#0f131a; border:1px solid var(--line); border-radius:.45rem; }
33 button { min-height:44px; min-width:44px; padding:.6rem 1.1rem; font:inherit; border:1px solid var(--line);
34 border-radius:.45rem; background:#1b2230; color:var(--text); cursor:pointer; }
35 button:hover:not(:disabled) { background:#27303f; }
36 button:disabled { opacity:.42; cursor:not-allowed; }
37 button.primary { background:#2563eb; border-color:#2563eb; font-weight:600; }
38 #buy .grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(11rem,1fr)); gap:.5rem; width:min(40rem,100%); }
39 #buy .hint, .overlay .hint { font-size:.78rem; }
40 #summary .score { font-size:2.2rem; line-height:1.1; color:var(--text); font-variant-numeric:tabular-nums; margin:.1rem 0; }
41 #summary h2 { font-size:1.8rem; }
42 #summary #summary-line { color:var(--text); font-size:.95rem; }
43 #fps { position:absolute; right:.5rem; bottom:.4rem; font-size:.7rem; color:#8ea; opacity:.7; pointer-events:none; }
44 /* The pad is under the view, not over it: the stage is 4:3 on a phone and the
45 HUD already owns all four of its corners, so a button on the glass would sit
46 on the radar, the health or the ammo. Aim, move and fire stay on the canvas
47 — the pad is only the discrete actions. */
48 #touch { max-width:34rem; margin:0 auto 1.5rem; display:flex; flex-direction:column; gap:.4rem;
49 touch-action:manipulation; -webkit-user-select:none; user-select:none; -webkit-touch-callout:none; }
50 #touch[hidden] { display:none; }
51 #touch.blocked { visibility:hidden; }
52 #touch .pad { display:grid; grid-template-columns:repeat(auto-fit,minmax(3.4rem,1fr)); gap:.4rem; }
53 #touch .pad.wide { grid-template-columns:1fr; }
54 #touch button { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:.05rem;
55 min-height:48px; min-width:44px; padding:.4rem .25rem; font-size:.82rem; line-height:1.15; }
56 #touch button b { color:var(--dim); font-size:.68rem; font-weight:600; }
57 #touch button.fire { background:#7f1d1d; border-color:#8f2222; font-weight:600; }
58 /* A thumb has no hover, so held has to look held — and the "on" class is put
59 there by the same handler that presses the control, since preventDefault
60 costs a touched button its :active. */
61 #touch button.on { background:#33405a; border-color:#4a5c7d; }
62 #touch button.fire.on { background:#b02626; border-color:#c33; }
63 #touch .hint { margin:0; text-align:center; color:var(--dim); font-size:.74rem; }
64 main section { margin:1.5rem 0; }
65 table { width:100%; border-collapse:collapse; font-size:.9rem; }
66 th, td { text-align:left; padding:.35rem .5rem; border-bottom:1px solid var(--line); }
67 th { color:var(--dim); font-weight:500; }
68 ul.recent { list-style:none; padding:0; margin:0; font-size:.86rem; }
69 ul.recent li { padding:.35rem 0; border-bottom:1px solid var(--line); display:flex; gap:.5rem; flex-wrap:wrap; }
70 ul.recent span, ul.recent time, .empty { color:var(--dim); }
71 kbd { background:#1b2230; border:1px solid var(--line); border-radius:.25rem; padding:0 .3rem; font-size:.82rem; }
72 footer { color:var(--dim); font-size:.8rem; padding:1rem; text-align:center; }
73 code { background:#141821; padding:.1rem .35rem; border-radius:.25rem; }
74 @media (max-width: 640px) { #stage { aspect-ratio:4/3; } h1 { font-size:1.2rem; } }
75 </style>
76 <header>
77 <h1>cs</h1>
78 <span class="env ">local</span>
79
80 </header>
81 <main>
82 <div id="stage">
83 <canvas id="scene"></canvas>
84 <canvas id="hud"></canvas>
85 <div id="fps"></div>
86 <div class="overlay" id="menu">
87 <h2>Defuse or detonate</h2>
88 <p>Five against five on <b>de_forge</b>. Bomb rounds, CS movement and economy, bots that push the sites.</p>
89 <div class="row">
90 <label>Name<input id="name" maxlength="24" placeholder="you" autocomplete="nickname"></label>
91 <label>Match<select id="length"><option value="short">Short — first to 5</option><option value="long">Competitive — first to 13</option></select></label>
92 <label>Side<select id="side"><option value="ct">Counter-Terrorists</option><option value="t">Terrorists</option></select></label>
93 <label>Sensitivity<input id="sens" type="number" min="0.2" max="12" step="0.1" value="2.2"></label>
94 </div>
95 <div class="row"><button type="button" class="primary" id="play">Play</button></div>
96 <p class="hint"><kbd>WASD</kbd> move · <kbd>Space</kbd> jump · <kbd>Ctrl</kbd> crouch · <kbd>Shift</kbd> walk ·
97 mouse to aim and fire · <kbd>R</kbd> reload · <kbd>E</kbd> plant, defuse or take a gun · <kbd>B</kbd> buy ·
98 right click or <kbd>Q</kbd> to scope · <kbd>1</kbd><kbd>2</kbd><kbd>3</kbd> guns · <kbd>Tab</kbd> scores ·
99 <kbd>Esc</kbd> pause, where sound and sensitivity live too</p>
100 <p class="hint">On a phone: the left of the view is a thumb stick, the right aims, a second
101 finger on the right fires, and the pad under the view does the rest — guns, scores, buy
102 and a menu you can leave the match from.</p>
103 </div>
104 <div class="overlay" id="pause" hidden>
105 <h2>Paused</h2>
106 <div class="row">
107 <label>Sensitivity<input id="pause-sens" type="number" min="0.2" max="12" step="0.1"></label>
108 <label>Volume<input id="volume" type="range" min="0" max="100" step="1"></label>
109 <button type="button" id="mute" aria-pressed="false">Mute</button>
110 </div>
111 <div class="row"><button type="button" class="primary" id="resume">Resume</button><button type="button" id="quit">Leave match</button></div>
112 </div>
113 <div class="overlay" id="summary" hidden>
114 <h2 id="summary-title">Match over</h2>
115 <p id="summary-detail"></p>
116 <p class="score" id="summary-score"></p>
117 <p id="summary-line"></p>
118 <div class="row">
119 <button type="button" class="primary" id="again">Play again</button>
120 <button type="button" id="summary-menu">Back to menu</button>
121 </div>
122 </div>
123 <div class="overlay" id="buy" hidden></div>
124 </div>
125
126 <div id="touch" hidden>
127 <div class="pad">
128 <button type="button" data-action="slot1"><b>1</b>rifle</button>
129 <button type="button" data-action="slot2"><b>2</b>pistol</button>
130 <button type="button" data-action="slot3"><b>3</b>knife</button>
131 <button type="button" data-action="scoreboard">scores</button>
132 <button type="button" data-action="menu">menu</button>
133 </div>
134 <div class="pad">
135 <button type="button" data-action="duck">crouch</button>
136 <button type="button" data-action="jump">jump</button>
137 <button type="button" data-action="use">use</button>
138 <button type="button" data-action="reload">reload</button>
139 <button type="button" data-action="buy">buy</button>
140 <button type="button" data-action="scope">scope</button>
141 </div>
142 <div class="pad wide">
143 <button type="button" class="fire" data-action="fire">fire</button>
144 </div>
145 <p class="hint">Left of the view is the stick, the right aims — and a second
146 finger anywhere on the right fires without moving your aim.</p>
147 </div>
148
149 <section id="stats"><h2>Leaderboard</h2>
150 <p class="empty">No matches yet. Play one and it lands here.</p>
151 <h3>Recent matches</h3>
152 <ul class="recent"><li class="empty">nothing yet</li></ul></section>
153
154 <section>
155 <h2>What this is</h2>
156 <p>A defusal shooter written for the browser: WebGL2 drawn by hand, Source-style movement
157 (friction, air acceleration, 18-unit steps, strafe jumping), CS damage with armour and
158 hitgroups, fixed spray patterns you can learn, a round clock, a bomb and the buy economy.
159 Everything you see is generated — the map, the textures, the models and the sounds — so the
160 whole game is one small download and no asset files.</p>
161 <p>The bots path to a site and plant or defuse on their own, but they do not aim by rule:
162 the fight is run by a small neural network trained with PPO against
163 12,288,000 ticks of this same simulation, in
164 12.2 minutes on 2 cores.
165 In 240 fixed duels it wins
166 72% against the scripted bots this game used to have, which win
167 42% of the same duels. Its weights are about eight kilobytes
168 of int8 inside the bundle — there is no inference server and nothing is sent anywhere. Each
169 bot's own skill still decides how fast it can turn, how steady its hands are and how long it
170 takes to react, so there is still a ladder from fodder to uncomfortable.</p>
171 <p>The match runs entirely in your browser; the leaderboard here is what your browser
172 reported about it.</p>
173 <p>The app's terminal is off.</p>
174 </section>
175 </main>
176 <footer>cs · local · state lives in this environment's own database</footer>
177 <script type="module" src="/static/app.7899a5ee1a.js"></script>
178 </html>
README.md +7 −3
@@ -78,11 +78,13 @@ wants one, but the running server never reads it.
7878 ## Playing
7979
8080 <kbd>WASD</kbd> move, <kbd>Space</kbd> jump, <kbd>Ctrl</kbd> crouch,
81 <kbd>Shift</kbd> walk, mouse aims and fires, <kbd>R</kbd> reload,
81 <kbd>Shift</kbd> walk, mouse aims and fires, the right mouse button or
82 <kbd>Q</kbd> scopes on the AWP, <kbd>R</kbd> reload,
8283 <kbd>E</kbd> plants, defuses or takes the gun you are standing on (the HUD says
8384 which gun when it is one you have to ask for), <kbd>B</kbd> opens the buy menu in the freeze
8485 time, <kbd>1</kbd>/<kbd>2</kbd>/<kbd>3</kbd> switch guns, <kbd>Tab</kbd> shows
85 the scoreboard, <kbd>Esc</kbd> pauses.
86 the scoreboard, <kbd>Esc</kbd> pauses. Pausing also opens mute, volume and
87 look sensitivity, which take effect at once and are remembered for next time.
8688
8789 On a touch screen the same actions are a pad, and the view is the aim:
8890
@@ -91,11 +93,12 @@ On a touch screen the same actions are a pad, and the view is the aim:
9193 | move | <kbd>WASD</kbd> | the left third of the view is a stick |
9294 | aim | mouse | drag anywhere on the rest of the view |
9395 | fire | mouse | **a second finger on the right of the view**, or the fire bar |
96 | scope (AWP only) | right click or <kbd>Q</kbd> | `scope`, held like the mouse |
9497 | crouch, jump, use, reload | <kbd>Ctrl</kbd> <kbd>Space</kbd> <kbd>E</kbd> <kbd>R</kbd> | the pad under the view |
9598 | guns | <kbd>1</kbd>/<kbd>2</kbd>/<kbd>3</kbd> | `1 rifle`, `2 pistol`, `3 knife` |
9699 | scoreboard | <kbd>Tab</kbd> | hold `scores` |
97100 | buy | <kbd>B</kbd> | `buy`, and `Close` when you are done |
98 | pause, leave the match | <kbd>Esc</kbd> | `menu` |
101 | pause, leave the match, or change mute/volume/sensitivity | <kbd>Esc</kbd> | `menu` |
99102
100103 Firing is a second finger rather than a button under your aiming thumb because
101104 a touch keeps the target it started on for its whole life: the finger already
@@ -133,6 +136,7 @@ with the canvas as you turn; nobody re-walks the grid to draw it.
133136 `spectate` (whose eyes you borrow when you are dead), `radar` (the blips the
134137 HUD's minimap draws, and nothing it draws them with), `summary` (the end of
135138 the match as numbers), `ears` (a sound's pan and volume, as plain data),
139 `settings` (mute, volume and sensitivity: read, validated, and never NaN),
136140 `renderer`, `hud`, `input`, `audio`, `main`.
137141 Everything except the last five is headless and tested.
138142 - `src/rl/` — training, which the game never imports: `arena` is the environment
src/client/audio.ts +62 −32
@@ -15,7 +15,10 @@ export type Audio = {
1515 pain(amount: number): void;
1616 beep(pitch: number, gain?: number): void;
1717 resume(): void;
18 muted: boolean;
18 /** Mute is silence at the one node everything goes through, not a per-sound skip. */
19 setMuted(muted: boolean): void;
20 setVolume(volume: number): void;
21 readonly muted: boolean;
1922 };
2023
2124 const TONE: Record<string, { cut: number; thump: number; length: number }> = {
@@ -26,38 +29,62 @@ const TONE: Record<string, { cut: number; thump: number; length: number }> = {
2629 knife: { cut: 4200, thump: 400, length: 0.08 },
2730 };
2831
29 export function createAudio(): Audio {
30 let ctx: AudioContext | null = null;
31 let noise: AudioBuffer | null = null;
32 let lastPain = -1;
32 type Live = { ctx: AudioContext; noise: AudioBuffer; master: GainNode };
3333
34 const ensure = (): AudioContext | null => {
35 if (ctx === null) {
34 export function createAudio(): Audio {
35 let live: Live | null = null;
36 let lastPain = -1;
37 let volume = 1;
38 let muted = false;
39
40 const applyGain = (): void => {
41 if (live !== null) live.master.gain.value = muted ? 0 : volume;
42 };
43
44 // The one node the whole of this file plays into: a volume set before the
45 // first click just waits here for `master` to exist to apply itself to.
46 const ensure = (): Live | null => {
47 if (live === null) {
3648 const Ctor = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
3749 if (Ctor === undefined) return null;
38 ctx = new Ctor();
39 noise = ctx.createBuffer(1, ctx.sampleRate * 0.5, ctx.sampleRate);
50 const ctx = new Ctor();
51 const noise = ctx.createBuffer(1, ctx.sampleRate * 0.5, ctx.sampleRate);
4052 const data = noise.getChannelData(0);
4153 for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
54 const master = ctx.createGain();
55 master.connect(ctx.destination);
56 live = { ctx, noise, master };
57 applyGain();
4258 }
43 if (ctx.state === "suspended") void ctx.resume();
44 return ctx;
59 if (live.ctx.state === "suspended") void live.ctx.resume();
60 return live;
4561 };
4662
4763 const audio: Audio = {
48 muted: false,
64 get muted() {
65 return muted;
66 },
67 setMuted(next) {
68 muted = next;
69 applyGain();
70 },
71 setVolume(next) {
72 volume = Number.isFinite(next) ? Math.min(1, Math.max(0, next)) : volume;
73 applyGain();
74 },
4975 resume: () => void ensure(),
5076 shot(weapon, at, listener, listenerYaw) {
51 if (audio.muted) return;
52 const context = ensure();
53 if (context === null || noise === null) return;
77 if (muted) return;
78 const live = ensure();
79 if (live === null) return;
80 const { ctx: context, noise, master } = live;
5481 const kind = WEAPONS[weapon]?.kind ?? "rifle";
5582 const tone = TONE[kind] ?? TONE.rifle;
5683 const { pan, volume } = ears(at, listener, listenerYaw);
5784 const now = context.currentTime;
5885 const panner = context.createStereoPanner();
5986 panner.pan.value = pan;
60 panner.connect(context.destination);
87 panner.connect(master);
6188
6289 const source = context.createBufferSource();
6390 source.buffer = noise;
@@ -85,9 +112,10 @@ export function createAudio(): Audio {
85112 },
86113 /** A footstep: a short low tap, panned and faded the same way a shot is. */
87114 step(at, listener, listenerYaw) {
88 if (audio.muted) return;
89 const context = ensure();
90 if (context === null || noise === null) return;
115 if (muted) return;
116 const live = ensure();
117 if (live === null) return;
118 const { ctx: context, noise, master } = live;
91119 const { pan, volume } = ears(at, listener, listenerYaw);
92120 const now = context.currentTime;
93121 const length = 0.09;
@@ -103,7 +131,7 @@ export function createAudio(): Audio {
103131 gain.gain.exponentialRampToValueAtTime(0.0008, now + length);
104132 const panner = context.createStereoPanner();
105133 panner.pan.value = pan;
106 source.connect(filter).connect(gain).connect(panner).connect(context.destination);
134 source.connect(filter).connect(gain).connect(panner).connect(master);
107135 source.start(now);
108136 source.stop(now + length);
109137 },
@@ -117,9 +145,10 @@ export function createAudio(): Audio {
117145 * the rest would be noise on top of a sound already playing.
118146 */
119147 pain(amount) {
120 if (audio.muted) return;
121 const context = ensure();
122 if (context === null || noise === null) return;
148 if (muted) return;
149 const live = ensure();
150 if (live === null) return;
151 const { ctx: context, noise, master } = live;
123152 const now = context.currentTime;
124153 if (now - lastPain < 0.14) return;
125154 lastPain = now;
@@ -137,7 +166,7 @@ export function createAudio(): Audio {
137166 gain.gain.setValueAtTime(0.0001, now);
138167 gain.gain.exponentialRampToValueAtTime(0.16 * hurt, now + 0.02);
139168 gain.gain.exponentialRampToValueAtTime(0.0005, now + length);
140 osc.connect(shape).connect(gain).connect(context.destination);
169 osc.connect(shape).connect(gain).connect(master);
141170 osc.start(now);
142171 osc.stop(now + length + 0.02);
143172
@@ -152,22 +181,23 @@ export function createAudio(): Audio {
152181 const breathGain = context.createGain();
153182 breathGain.gain.setValueAtTime(0.07 * hurt, now);
154183 breathGain.gain.exponentialRampToValueAtTime(0.0005, now + length * 0.8);
155 breath.connect(band).connect(breathGain).connect(context.destination);
184 breath.connect(band).connect(breathGain).connect(master);
156185 breath.start(now);
157186 breath.stop(now + length);
158187 },
159188 beep(pitch, gain = 0.06) {
160 if (audio.muted) return;
161 const context = ensure();
162 if (context === null) return;
189 if (muted) return;
190 const live = ensure();
191 if (live === null) return;
192 const { ctx: context, master } = live;
163193 const now = context.currentTime;
164194 const osc = context.createOscillator();
165195 osc.type = "square";
166196 osc.frequency.value = pitch;
167 const volume = context.createGain();
168 volume.gain.setValueAtTime(gain, now);
169 volume.gain.exponentialRampToValueAtTime(0.0005, now + 0.09);
170 osc.connect(volume).connect(context.destination);
197 const gainNode = context.createGain();
198 gainNode.gain.setValueAtTime(gain, now);
199 gainNode.gain.exponentialRampToValueAtTime(0.0005, now + 0.09);
200 osc.connect(gainNode).connect(master);
171201 osc.start(now);
172202 osc.stop(now + 0.1);
173203 },
src/client/input.test.ts +23
@@ -200,3 +200,26 @@ test("the pad's slot, scoreboard and buy buttons are the keyboard's actions", ()
200200 buttons.press("buy");
201201 expect(buys).toBe(1);
202202 });
203
204 test("scope is a touch button, held like the mouse's right button", () => {
205 const { controls } = harness();
206 const buttons = pad("scope");
207 attachButtons(buttons.root, controls);
208
209 expect(controls.inputAt(controls.take(1), 0).scope).toBe(false);
210 buttons.press("scope");
211 expect(controls.inputAt(controls.take(1), 0).scope).toBe(true); // held, not a toggle
212 expect(buttons.classes("scope")).toEqual(["on"]);
213 buttons.release("scope");
214 expect(controls.inputAt(controls.take(1), 0).scope).toBe(false);
215 expect(buttons.classes("scope")).toEqual([]);
216 });
217
218 test("Q scopes from the keyboard the same way", () => {
219 const { controls } = harness();
220 const window = globals.window as Canvas;
221 window.fire("keydown", { code: "KeyQ" });
222 expect(controls.inputAt(controls.take(1), 0).scope).toBe(true);
223 window.fire("keyup", { code: "KeyQ" });
224 expect(controls.inputAt(controls.take(1), 0).scope).toBe(false);
225 });
src/client/input.ts +1 −1
@@ -39,7 +39,7 @@ const KEY_ACTIONS: Record<string, string> = {
3939 KeyW: "forward", KeyS: "back", KeyA: "left", KeyD: "right",
4040 ArrowUp: "forward", ArrowDown: "back", ArrowLeft: "left", ArrowRight: "right",
4141 Space: "jump", ControlLeft: "duck", KeyC: "duck", ShiftLeft: "walk",
42 KeyR: "reload", KeyE: "use", KeyB: "buy", Tab: "scoreboard",
42 KeyR: "reload", KeyE: "use", KeyB: "buy", Tab: "scoreboard", KeyQ: "scope",
4343 Digit1: "slot1", Digit2: "slot2", Digit3: "slot3",
4444 };
4545
src/client/main.ts +53 −2
@@ -13,6 +13,7 @@ import { clamp, dist } from "./math.ts";
1313 import { COMPETITIVE, SHORT, type Rules } from "./match.ts";
1414 import { MAX_SCALE, nextRenderScale } from "./quality.ts";
1515 import { createRenderer, type Camera } from "./renderer.ts";
16 import { DEFAULT_SETTINGS, loadSettings, saveSettings, SENSITIVITY_MAX, SENSITIVITY_MIN } from "./settings.ts";
1617 import { nextWatched, watched } from "./spectate.ts";
1718 import { summarize, type MatchSummary } from "./summary.ts";
1819 import { buyable } from "./weapons.ts";
@@ -46,6 +47,9 @@ function boot(): void {
4647 const lengthField = $<HTMLSelectElement>("length");
4748 const sideField = $<HTMLSelectElement>("side");
4849 const sensField = $<HTMLInputElement>("sens");
50 const pauseSensField = $<HTMLInputElement>("pause-sens");
51 const volumeField = $<HTMLInputElement>("volume");
52 const muteButton = $<HTMLButtonElement>("mute");
4953
5054 const renderer = createRenderer(scene);
5155 if (renderer === null) {
@@ -54,9 +58,56 @@ function boot(): void {
5458 }
5559 const hudCtx = hudCanvas.getContext("2d") as CanvasRenderingContext2D;
5660 const audio = createAudio();
57 const controls = createControls(scene, Number(sensField.value) || 2.2);
61 let settings = loadSettings();
62 // Applied here rather than in `resume`, so a volume chosen before the first
63 // click is already in force once the context exists to hear it.
64 audio.setVolume(settings.volume);
65 audio.setMuted(settings.muted);
66 const controls = createControls(scene, settings.sensitivity);
5867 attachButtons(document, controls);
5968
69 // The menu's sensitivity field and the pause overlay's are the same number:
70 // whichever one a player moves, both show it and the game feels it at once.
71 const syncSensitivity = (value: number): void => {
72 const next = Number.isFinite(value)
73 ? Math.min(SENSITIVITY_MAX, Math.max(SENSITIVITY_MIN, value))
74 : DEFAULT_SETTINGS.sensitivity;
75 settings = { ...settings, sensitivity: next };
76 controls.sensitivity = next;
77 sensField.value = String(next);
78 pauseSensField.value = String(next);
79 saveSettings(settings);
80 };
81 const updateMuteButton = (): void => {
82 muteButton.textContent = settings.muted ? "Unmute" : "Mute";
83 muteButton.setAttribute("aria-pressed", String(settings.muted));
84 };
85 sensField.value = String(settings.sensitivity);
86 pauseSensField.value = String(settings.sensitivity);
87 volumeField.value = String(Math.round(settings.volume * 100));
88 updateMuteButton();
89
90 // "change" rather than "input": a number field mid-edit (cleared, or "0.")
91 // is not a value to clamp and snap back on every keystroke.
92 sensField.addEventListener("change", () => syncSensitivity(Number(sensField.value)));
93 pauseSensField.addEventListener("change", () => syncSensitivity(Number(pauseSensField.value)));
94 volumeField.addEventListener("input", () => {
95 const next = Math.min(1, Math.max(0, Number(volumeField.value) / 100));
96 settings = { ...settings, volume: Number.isFinite(next) ? next : settings.volume };
97 audio.setVolume(settings.volume);
98 saveSettings(settings);
99 });
100 muteButton.addEventListener("click", () => {
101 settings = { ...settings, muted: !settings.muted };
102 audio.setMuted(settings.muted);
103 updateMuteButton();
104 saveSettings(settings);
105 });
106 // The pause dialog sits over a live match: a key typed into one of its
107 // fields must never reach the window-level handler that drives the game.
108 for (const field of [pauseSensField, volumeField, muteButton])
109 field.addEventListener("keydown", (event) => event.stopPropagation());
110
60111 let world: World | null = null;
61112 let matchId = "";
62113 let running = false;
@@ -199,7 +250,7 @@ function boot(): void {
199250 matchId = crypto.randomUUID();
200251 posted = -1;
201252 watching = world.me.id;
202 controls.sensitivity = clamp(Number(sensField.value) || 2.2, 0.2, 12);
253 controls.sensitivity = settings.sensitivity;
203254 running = true;
204255 lastSound = 0;
205256 show(menu, false);
src/client/settings.test.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * `parseSettings` is the whole of the boundary: whatever a player, an old
3 * version of this file or a hand-edited localStorage entry left behind, it
4 * has to come out as numbers the game can use.
5 */
6
7 import { expect, test } from "bun:test";
8 import { DEFAULT_SETTINGS, parseSettings } from "./settings.ts";
9
10 test("nothing stored yet is the default", () => {
11 expect(parseSettings(null)).toEqual(DEFAULT_SETTINGS);
12 });
13
14 test("malformed JSON is the default", () => {
15 expect(parseSettings("not json")).toEqual(DEFAULT_SETTINGS);
16 expect(parseSettings("")).toEqual(DEFAULT_SETTINGS);
17 });
18
19 test("a JSON value that isn't an object is the default", () => {
20 expect(parseSettings("42")).toEqual(DEFAULT_SETTINGS);
21 expect(parseSettings("null")).toEqual(DEFAULT_SETTINGS);
22 expect(parseSettings('"loud"')).toEqual(DEFAULT_SETTINGS);
23 });
24
25 test("out-of-range numbers are clamped, not rejected", () => {
26 expect(parseSettings('{"volume":5,"sensitivity":9999}')).toEqual({
27 muted: false, volume: 1, sensitivity: 12,
28 });
29 expect(parseSettings('{"volume":-3,"sensitivity":-1}')).toEqual({
30 muted: false, volume: 0, sensitivity: 0.2,
31 });
32 });
33
34 test("a bad type never becomes NaN", () => {
35 expect(parseSettings('{"volume":"loud","sensitivity":null}')).toEqual(DEFAULT_SETTINGS);
36 expect(parseSettings('{"volume":"NaN","sensitivity":"3"}')).toEqual(DEFAULT_SETTINGS);
37 });
38
39 test("muted is only ever true for exactly true", () => {
40 expect(parseSettings('{"muted":true}').muted).toBe(true);
41 expect(parseSettings('{"muted":"true"}').muted).toBe(false);
42 expect(parseSettings('{"muted":1}').muted).toBe(false);
43 });
44
45 test("a whole, valid settings object round-trips", () => {
46 const stored = { muted: true, volume: 0.4, sensitivity: 3.5 };
47 expect(parseSettings(JSON.stringify(stored))).toEqual(stored);
48 });
src/client/settings.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * Settings a player can reach mid-match: mute, volume and look sensitivity.
3 * Stored in localStorage beside `cs.name`. `parseSettings` is the boundary —
4 * a missing, malformed or out-of-range value falls back to the default and
5 * never puts NaN into the game.
6 */
7
8 export type Settings = {
9 muted: boolean;
10 volume: number;
11 sensitivity: number;
12 };
13
14 export const DEFAULT_SETTINGS: Settings = { muted: false, volume: 1, sensitivity: 2.2 };
15 export const SENSITIVITY_MIN = 0.2;
16 export const SENSITIVITY_MAX = 12;
17
18 const KEY = "cs.settings";
19
20 const bounded = (value: unknown, lo: number, hi: number, fallback: number): number => {
21 const n = typeof value === "number" ? value : NaN;
22 return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : fallback;
23 };
24
25 /** Pure: whatever was in storage, in or out of shape, becomes safe settings. */
26 export function parseSettings(raw: string | null): Settings {
27 if (raw === null) return { ...DEFAULT_SETTINGS };
28 let parsed: unknown;
29 try {
30 parsed = JSON.parse(raw);
31 } catch {
32 return { ...DEFAULT_SETTINGS };
33 }
34 if (typeof parsed !== "object" || parsed === null) return { ...DEFAULT_SETTINGS };
35 const obj = parsed as Record<string, unknown>;
36 return {
37 muted: obj.muted === true,
38 volume: bounded(obj.volume, 0, 1, DEFAULT_SETTINGS.volume),
39 sensitivity: bounded(obj.sensitivity, SENSITIVITY_MIN, SENSITIVITY_MAX, DEFAULT_SETTINGS.sensitivity),
40 };
41 }
42
43 export function loadSettings(): Settings {
44 try {
45 return parseSettings(localStorage.getItem(KEY));
46 } catch {
47 return { ...DEFAULT_SETTINGS };
48 }
49 }
50
51 export function saveSettings(settings: Settings): void {
52 try {
53 localStorage.setItem(KEY, JSON.stringify(settings));
54 } catch {
55 // a private tab or a full quota is not a reason to stop playing
56 }
57 }
src/pages/game.ts +8 −1
@@ -145,13 +145,19 @@ export function gamePage(db: Database, options: PageOptions): string {
145145 <div class="row"><button type="button" class="primary" id="play">Play</button></div>
146146 <p class="hint"><kbd>WASD</kbd> move · <kbd>Space</kbd> jump · <kbd>Ctrl</kbd> crouch · <kbd>Shift</kbd> walk ·
147147 mouse to aim and fire · <kbd>R</kbd> reload · <kbd>E</kbd> plant, defuse or take a gun · <kbd>B</kbd> buy ·
148 <kbd>1</kbd><kbd>2</kbd><kbd>3</kbd> guns · <kbd>Tab</kbd> scores · <kbd>Esc</kbd> pause</p>
148 right click or <kbd>Q</kbd> to scope · <kbd>1</kbd><kbd>2</kbd><kbd>3</kbd> guns · <kbd>Tab</kbd> scores ·
149 <kbd>Esc</kbd> pause, where sound and sensitivity live too</p>
149150 <p class="hint">On a phone: the left of the view is a thumb stick, the right aims, a second
150151 finger on the right fires, and the pad under the view does the rest — guns, scores, buy
151152 and a menu you can leave the match from.</p>
152153 </div>
153154 <div class="overlay" id="pause" hidden>
154155 <h2>Paused</h2>
156 <div class="row">
157 <label>Sensitivity<input id="pause-sens" type="number" min="0.2" max="12" step="0.1"></label>
158 <label>Volume<input id="volume" type="range" min="0" max="100" step="1"></label>
159 <button type="button" id="mute" aria-pressed="false">Mute</button>
160 </div>
155161 <div class="row"><button type="button" class="primary" id="resume">Resume</button><button type="button" id="quit">Leave match</button></div>
156162 </div>
157163 <div class="overlay" id="summary" hidden>
@@ -181,6 +187,7 @@ export function gamePage(db: Database, options: PageOptions): string {
181187 <button type="button" data-action="use">use</button>
182188 <button type="button" data-action="reload">reload</button>
183189 <button type="button" data-action="buy">buy</button>
190 <button type="button" data-action="scope">scope</button>
184191 </div>
185192 <div class="pad wide">
186193 <button type="button" class="fire" data-action="fire">fire</button>

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs