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

Death and the end of the match read right: spectate the player you are watching, and show the result #16

Merged opened this

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

Merged

vesper/cs:vesper/11-death-and-the-end-of-the-match-read-righ → main 1 commit fork

  • Merged. vesper/11-death-and-the-end-of-the-match-read-righ was merged into main as 343dfe4.

Review

Sign in to review this change.
14 files changed +573 −253
README.md +9 −1
@@ -71,6 +71,13 @@ the scoreboard, <kbd>Esc</kbd> pauses. On a touch screen the left of the view
7171 is a thumb stick, the right looks around, and the buttons along the bottom do
7272 the rest.
7373
74 When you die the camera moves to a teammate who is still up and the HUD becomes
75 theirs — their health, armour, ammo and gun, no crosshair — over a line naming
76 who killed you and with what. Clicking, or the fire key, moves on to the next
77 teammate. The round's result stays on the screen through the freeze time, and
78 when the match ends a card says who won, the final score from your side and
79 what you did, with a button to play again and one back to the menu.
80
7481 The counter in the corner of the view is the measured frame time. When a
7582 machine cannot hold 60 fps the scene is drawn into a smaller buffer — half the
7683 device pixel ratio at the worst, stepped at most twice a second, the HUD
@@ -83,7 +90,8 @@ pixels you are getting. Nothing on the page moves when it changes.
8390 `physics`, `weapons`, `combat`, `match` (the rules), `world` (the simulation),
8491 `bots`, `observe`, `action`, `policy`, `weights`, `models`, `textures`,
8592 `press` (the input latch), `quality` (the render scale the frame time buys),
86 `renderer`, `hud`, `input`, `audio`, `main`.
93 `spectate` (whose eyes you borrow when you are dead), `summary` (the end of
94 the match as numbers), `renderer`, `hud`, `input`, `audio`, `main`.
8795 Everything except the last five is headless and tested.
8896 - `src/rl/` — training, which the game never imports: `arena` is the environment
8997 (a real duel on de_forge with the round and the economy taken out), `ppo` is
src/client/hud.test.ts +89 −12
@@ -8,14 +8,18 @@
88 import { expect, test } from "bun:test";
99 import { drawHud } from "./hud.ts";
1010 import { SHORT } from "./match.ts";
11 import { createWorld, type World } from "./world.ts";
11 import { createWorld, type Player, type World } from "./world.ts";
1212
13 type Call = { name: string; args: number[] };
13 type Call = { name: string; args: number[]; text: string };
1414
1515 function recorder(): { ctx: CanvasRenderingContext2D; calls: Call[] } {
1616 const calls: Call[] = [];
1717 const log = (name: string) => (...args: unknown[]): void => {
18 calls.push({ name, args: args.filter((a) => typeof a === "number") as number[] });
18 calls.push({
19 name,
20 args: args.filter((a) => typeof a === "number") as number[],
21 text: args.filter((a) => typeof a === "string").join(" "),
22 });
1923 };
2024 const ctx = {
2125 clearRect: log("clearRect"), fillRect: log("fillRect"), rect: log("rect"),
@@ -24,7 +28,7 @@ function recorder(): { ctx: CanvasRenderingContext2D; calls: Call[] } {
2428 fillText: log("fillText"), save: log("save"), restore: log("restore"),
2529 measureText: () => ({ width: 10 }),
2630 createRadialGradient: (...args: unknown[]) => {
27 calls.push({ name: "createRadialGradient", args: args as number[] });
31 calls.push({ name: "createRadialGradient", args: args as number[], text: "" });
2832 return { addColorStop: (): void => {} };
2933 },
3034 globalAlpha: 1, lineWidth: 1, fillStyle: "", strokeStyle: "",
@@ -35,6 +39,10 @@ function recorder(): { ctx: CanvasRenderingContext2D; calls: Call[] } {
3539
3640 const W = 1280, H = 720;
3741
42 /** One frame of the HUD, drawing `view` — the person unless a spectator is watching. */
43 const draw = (into: { ctx: CanvasRenderingContext2D }, world: World, view: Player = world.me,
44 scoreboard = false): void => drawHud(into.ctx, world, view, W, H, scoreboard);
45
3846 /** Where the middle of a stroked wedge lands on the screen. */
3947 const wedgePoint = (call: Call): { x: number; y: number } => {
4048 const [x, y, r, start, end] = call.args as [number, number, number, number, number];
@@ -53,14 +61,14 @@ const hurtWorld = (yaw: number, from: [number, number, number], victim: number):
5361
5462 test("a hit from behind puts the wedge below the crosshair, one from the left on its left", () => {
5563 const behind = recorder();
56 drawHud(behind.ctx, hurtWorld(0, [-500, 0, 40], 0), W, H, false);
64 draw(behind, hurtWorld(0, [-500, 0, 40], 0));
5765 const back = behind.calls.filter((c) => c.name === "arc").map(wedgePoint);
5866 expect(back.length).toBe(1);
5967 expect(back[0].y).toBeGreaterThan(H / 2 + 20);
6068 expect(Math.abs(back[0].x - W / 2)).toBeLessThan(20);
6169
6270 const left = recorder();
63 drawHud(left.ctx, hurtWorld(0, [0, 500, 40], 0), W, H, false);
71 draw(left, hurtWorld(0, [0, 500, 40], 0));
6472 const side = left.calls.filter((c) => c.name === "arc").map(wedgePoint);
6573 expect(side.length).toBe(1);
6674 expect(side[0].x).toBeLessThan(W / 2 - 20);
@@ -71,11 +79,11 @@ test("hits stack, and damage to anyone but the player being drawn is not drawn",
7179 const two = recorder();
7280 const world = hurtWorld(0, [-500, 0, 40], 0);
7381 world.effects.push({ kind: "hurt", at: world.time, victim: 0, from: [0, -500, 40], amount: 18 });
74 drawHud(two.ctx, world, W, H, false);
82 draw(two, world);
7583 expect(two.calls.filter((c) => c.name === "arc").length).toBe(2);
7684
7785 const bot = recorder();
78 drawHud(bot.ctx, hurtWorld(0, [-500, 0, 40], 4), W, H, false);
86 draw(bot, hurtWorld(0, [-500, 0, 40], 4));
7987 expect(bot.calls.filter((c) => c.name === "arc").length).toBe(0);
8088 });
8189
@@ -83,26 +91,95 @@ test("an old hit has faded out by the time the effects list is trimmed", () => {
8391 const world = hurtWorld(0, [-500, 0, 40], 0);
8492 world.time += 1.5; // still in the list, which update keeps for two seconds
8593 const frame = recorder();
86 drawHud(frame.ctx, world, W, H, false);
94 draw(frame, world);
8795 expect(frame.calls.filter((c) => c.name === "arc").length).toBe(0);
8896 });
8997
9098 test("the hurt vignette follows health and its gradient is built once, not per frame", () => {
9199 const healthy = recorder();
92100 const world = createWorld(SHORT, "me", "ct", 5, 73);
93 drawHud(healthy.ctx, world, W, H, false);
101 draw(healthy, world);
94102 const full = (calls: Call[]): Call[] =>
95103 calls.filter((c) => c.name === "fillRect" && c.args[0] === 0 && c.args[1] === 0 && c.args[2] === W);
96104 expect(full(healthy.calls).length).toBe(0);
97105
98106 world.me.health = 20;
99107 const hurt = recorder();
100 drawHud(hurt.ctx, world, W, H, false);
108 draw(hurt, world);
101109 expect(full(hurt.calls).length).toBe(1);
102110
103111 // The second frame at the same size reuses the gradient the first one made.
104112 const again = recorder();
105 drawHud(again.ctx, world, W, H, false);
113 draw(again, world);
106114 expect(full(again.calls).length).toBe(1);
107115 expect(again.calls.filter((c) => c.name === "createRadialGradient").length).toBe(0);
108116 });
117
118 /** A world where the person is dead and one named teammate is still up. */
119 const spectatedWorld = (): World => {
120 const world = createWorld(SHORT, "me", "ct", 5, 79);
121 const mates = world.players.filter((p) => p.team === "ct" && p !== world.me);
122 for (const p of mates.slice(1)) p.alive = false;
123 world.me.alive = false;
124 world.me.health = 0;
125 world.feed.push({
126 at: world.time, killer: "Krait", killerId: 9, victim: world.me.name, victimId: world.me.id,
127 weapon: "ak47", headshot: true, killerTeam: "t",
128 });
129 return world;
130 };
131
132 test("dead, the HUD is the watched player's: their numbers, no crosshair, and who killed you", () => {
133 const world = spectatedWorld();
134 const mate = world.players.find((p) => p.alive && p.team === "ct") as Player;
135 mate.health = 64;
136 mate.money = 4321;
137 const frame = recorder();
138 draw(frame, world, mate);
139 const texts = frame.calls.filter((c) => c.name === "fillText").map((c) => c.text);
140
141 expect(texts).toContain("64"); // the watched player's health, not the corpse's zero
142 expect(texts).toContain("$4321");
143 expect(texts.join("|")).toContain(`Watching ${mate.name}`);
144 expect(texts.join("|")).toContain("Krait killed you with AK-47");
145 expect(texts.join("|")).toContain("headshot");
146 // The crosshair is four strokes out from the middle; a spectator gets none.
147 expect(frame.calls.filter((c) => c.name === "moveTo" && c.args[1] === H / 2).length).toBe(0);
148 });
149
150 test("a spectator does not inherit the dead player's hit markers", () => {
151 const world = spectatedWorld();
152 const mate = world.players.find((p) => p.alive && p.team === "ct") as Player;
153 world.effects.push({ kind: "hitmark", at: world.time, headshot: false });
154 const watching = recorder();
155 draw(watching, world, mate);
156 expect(watching.calls.filter((c) => c.name === "moveTo").length).toBe(0);
157
158 // Alive, the same effect is the marker it was drawn for.
159 const alive = createWorld(SHORT, "me", "ct", 5, 79);
160 alive.effects.push({ kind: "hitmark", at: alive.time, headshot: false });
161 const own = recorder();
162 draw(own, alive);
163 expect(own.calls.filter((c) => c.name === "moveTo").length).toBeGreaterThan(4);
164 });
165
166 test("the round result stays up through the end delay and the freeze that follows", () => {
167 const world = createWorld(SHORT, "me", "ct", 5, 83);
168 world.match.phase = "over";
169 world.messages.push({ at: world.time, text: "Counter-Terrorists win — defused the bomb" });
170 world.time += SHORT.endDelay + SHORT.freezeTime - 1; // well past the four-second fade
171 const ending = recorder();
172 draw(ending, world);
173 expect(ending.calls.some((c) => c.text.includes("defused the bomb"))).toBe(true);
174
175 world.match.phase = "freeze";
176 const freezing = recorder();
177 draw(freezing, world);
178 expect(freezing.calls.some((c) => c.text.includes("defused the bomb"))).toBe(true);
179
180 // Live again, an old line is gone: it is the round's result, not wallpaper.
181 world.match.phase = "live";
182 const live = recorder();
183 draw(live, world);
184 expect(live.calls.some((c) => c.text.includes("defused the bomb"))).toBe(false);
185 });
src/client/hud.ts +89 −50
@@ -2,10 +2,15 @@
22 * The HUD, drawn on a 2D canvas over the scene: crosshair, health, ammo, the
33 * round clock, the kill feed and the scoreboard. It reads the world and draws;
44 * it never changes anything.
5 *
6 * It is handed the player it is drawing rather than reaching for `world.me`:
7 * while the person is dead the camera is on a teammate, and the numbers under
8 * it have to be that teammate's or the HUD belongs to a corpse.
59 */
610
711 import { angleDelta, clamp } from "./math.ts";
812 import { MOVE } from "./physics.ts";
13 import { deathNotice } from "./spectate.ts";
914 import { inaccuracy, WEAPONS } from "./weapons.ts";
1015 import { currentWeapon, eyePos, useProgress, type Player, type World } from "./world.ts";
1116
@@ -17,6 +22,10 @@ const CT_COLOR = "#6fa8e8";
1722 * keeps an effect for, so the trim window stays where it is.
1823 */
1924 const HURT_FADE = 1.1;
25
26 /** How long a round message stays up when the clock is not holding it there. */
27 const MESSAGE_FADE = 4;
28
2029 const rad = Math.PI / 180;
2130
2231 // The vignette is one radial gradient per canvas size, kept between frames:
@@ -42,36 +51,38 @@ function hurtVignette(ctx: CanvasRenderingContext2D, width: number, height: numb
4251 }
4352
4453 /**
45 * The wedges around the crosshair pointing at whatever just hurt `me`, in its
54 * The wedges around the crosshair pointing at whatever just hurt `view`, in its
4655 * own yaw frame, and the red vignette that deepens as its health drops. Several
47 * hits stack: each is its own wedge, fading on its own clock.
56 * hits stack: each is its own wedge, fading on its own clock. A spectator sees
57 * neither: `hurt` effects are only ever pushed for the person, so a teammate's
58 * id matches nothing here.
4859 */
4960 function drawDamage(
5061 ctx: CanvasRenderingContext2D,
5162 world: World,
52 me: Player,
63 view: Player,
5364 width: number,
5465 height: number,
5566 ): void {
56 const low = clamp((55 - me.health) / 55, 0, 1);
57 if (me.alive && low > 0) {
67 const low = clamp((55 - view.health) / 55, 0, 1);
68 if (view.alive && low > 0) {
5869 ctx.globalAlpha = 0.65 * low * low;
5970 ctx.fillStyle = hurtVignette(ctx, width, height);
6071 ctx.fillRect(0, 0, width, height);
6172 ctx.globalAlpha = 1;
6273 }
6374
64 const eye = eyePos(me);
75 const eye = eyePos(view);
6576 const radius = Math.min(width, height) * 0.14;
6677 for (const effect of world.effects) {
67 if (effect.kind !== "hurt" || effect.victim !== me.id) continue;
78 if (effect.kind !== "hurt" || effect.victim !== view.id) continue;
6879 const age = world.time - effect.at;
6980 if (age < 0 || age > HURT_FADE) continue;
7081 const bearing = (Math.atan2(effect.from[1] - eye[1], effect.from[0] - eye[0]) * 180) / Math.PI;
7182 // Yaw grows anticlockwise, so a source to the left is a positive angle off
7283 // the view; the canvas turns clockwise from +x, so the wedge sits at minus
7384 // that angle, a quarter turn back from straight up.
74 const middle = -angleDelta(me.yaw, bearing) * rad - Math.PI / 2;
85 const middle = -angleDelta(view.yaw, bearing) * rad - Math.PI / 2;
7586 const half = (14 + clamp(effect.amount, 0, 60) * 0.2) * rad;
7687 ctx.globalAlpha = clamp(1 - age / HURT_FADE, 0, 1) * clamp(0.35 + effect.amount / 50, 0, 0.9);
7788 ctx.strokeStyle = "#ff4238";
@@ -91,27 +102,29 @@ const clock = (seconds: number): string => {
91102 export function drawHud(
92103 ctx: CanvasRenderingContext2D,
93104 world: World,
105 view: Player,
94106 width: number,
95107 height: number,
96108 showScoreboard: boolean,
97109 ): void {
98110 ctx.clearRect(0, 0, width, height);
99111 ctx.textBaseline = "alphabetic";
100 const me = world.me;
101 const weapon = currentWeapon(me);
112 const spectating = view !== world.me;
113 const over = world.match.phase === "match_over";
114 const weapon = currentWeapon(view);
102115 const pad = Math.max(12, Math.round(width * 0.02));
103116
104117 // --- being shot: where it came from, and how close to dead it left us
105 drawDamage(ctx, world, me, width, height);
118 drawDamage(ctx, world, view, width, height);
106119
107120 // --- crosshair, opening up exactly as much as the gun is inaccurate
108 if (me.alive) {
109 const speed = Math.hypot(me.vel[0], me.vel[1]);
121 if (view.alive && !spectating && !over) {
122 const speed = Math.hypot(view.vel[0], view.vel[1]);
110123 const spread = inaccuracy(weapon, {
111124 moving: clamp(speed / MOVE.maxSpeed, 0, 1),
112 inAir: !me.onGround,
113 ducking: me.duckAmount > 0.5,
114 scoped: me.scoped,
125 inAir: !view.onGround,
126 ducking: view.duckAmount > 0.5,
127 scoped: view.scoped,
115128 });
116129 const gap = 4 + spread * 14;
117130 const arm = 7;
@@ -123,29 +136,34 @@ export function drawHud(
123136 ctx.lineTo(width / 2 + dx * (gap + arm), height / 2 + dy * (gap + arm));
124137 }
125138 ctx.stroke();
126 if (me.scoped) {
127 ctx.fillStyle = "rgba(0,0,0,0.55)";
128 ctx.beginPath();
129 ctx.rect(0, 0, width, height);
130 ctx.arc(width / 2, height / 2, Math.min(width, height) * 0.36, 0, Math.PI * 2, true);
131 ctx.fill("evenodd");
132 }
139 }
140 // The scope mask belongs to the camera, not to the crosshair: a spectator
141 // watching a scoped teammate is looking down that scope's field of view.
142 if (view.alive && view.scoped) {
143 ctx.fillStyle = "rgba(0,0,0,0.55)";
144 ctx.beginPath();
145 ctx.rect(0, 0, width, height);
146 ctx.arc(width / 2, height / 2, Math.min(width, height) * 0.36, 0, Math.PI * 2, true);
147 ctx.fill("evenodd");
133148 }
134149
135 // --- hit markers
136 for (const effect of world.effects) {
137 if (effect.kind !== "hitmark") continue;
138 const age = world.time - effect.at;
139 if (age > 0.25) continue;
140 ctx.strokeStyle = effect.headshot ? "rgba(255,90,90,0.95)" : "rgba(255,255,255,0.9)";
141 ctx.lineWidth = 2;
142 const r = 9 + age * 20;
143 ctx.beginPath();
144 for (const [dx, dy] of [[1, 1], [-1, -1], [1, -1], [-1, 1]]) {
145 ctx.moveTo(width / 2 + dx * r * 0.55, height / 2 + dy * r * 0.55);
146 ctx.lineTo(width / 2 + dx * r, height / 2 + dy * r);
150 // --- hit markers, which are the person's own hits and nobody else's: a
151 // spectator never inherits the ones the corpse left behind.
152 if (!spectating && view.alive) {
153 for (const effect of world.effects) {
154 if (effect.kind !== "hitmark") continue;
155 const age = world.time - effect.at;
156 if (age > 0.25) continue;
157 ctx.strokeStyle = effect.headshot ? "rgba(255,90,90,0.95)" : "rgba(255,255,255,0.9)";
158 ctx.lineWidth = 2;
159 const r = 9 + age * 20;
160 ctx.beginPath();
161 for (const [dx, dy] of [[1, 1], [-1, -1], [1, -1], [-1, 1]]) {
162 ctx.moveTo(width / 2 + dx * r * 0.55, height / 2 + dy * r * 0.55);
163 ctx.lineTo(width / 2 + dx * r, height / 2 + dy * r);
164 }
165 ctx.stroke();
147166 }
148 ctx.stroke();
149167 }
150168
151169 const scale = clamp(width / 1280, 0.7, 1.4);
@@ -178,18 +196,18 @@ export function drawHud(
178196 // --- health, armour, money
179197 ctx.textAlign = "left";
180198 ctx.font = big;
181 ctx.fillStyle = me.health > 30 ? "#f3f5f8" : "#ff6b5b";
182 ctx.fillText(String(Math.max(0, Math.round(me.health))), pad, height - pad);
199 ctx.fillStyle = view.health > 30 ? "#f3f5f8" : "#ff6b5b";
200 ctx.fillText(String(Math.max(0, Math.round(view.health))), pad, height - pad);
183201 ctx.font = small;
184202 ctx.fillStyle = "#9fd0ff";
185203 ctx.fillText(
186 `${me.armor > 0 ? `armour ${me.armor}${me.helmet ? " + helmet" : ""}` : "no armour"}`,
204 `${view.armor > 0 ? `armour ${view.armor}${view.helmet ? " + helmet" : ""}` : "no armour"}`,
187205 pad, height - pad - Math.round(30 * scale),
188206 );
189207 ctx.fillStyle = "#7ddc8a";
190208 ctx.font = mid;
191 ctx.fillText(`$${me.money}`, pad, pad + Math.round(18 * scale));
192 if (me.team === "ct" && me.defuseKit) {
209 ctx.fillText(`$${view.money}`, pad, pad + Math.round(18 * scale));
210 if (view.team === "ct" && view.defuseKit) {
193211 ctx.fillStyle = "#9fd0ff";
194212 ctx.font = small;
195213 ctx.fillText("defuse kit", pad, pad + Math.round(38 * scale));
@@ -199,13 +217,13 @@ export function drawHud(
199217 ctx.textAlign = "right";
200218 ctx.font = big;
201219 ctx.fillStyle = "#f3f5f8";
202 const ammo = me.ammo[weapon.id];
220 const ammo = view.ammo[weapon.id];
203221 const ammoText = weapon.magazine === 0 ? "—" : `${ammo?.mag ?? 0} / ${ammo?.reserve ?? 0}`;
204222 ctx.fillText(ammoText, width - pad, height - pad);
205223 ctx.font = small;
206224 ctx.fillStyle = "#c8ccd4";
207 ctx.fillText(weapon.name + (me.hasBomb ? " · bomb" : ""), width - pad, height - pad - Math.round(30 * scale));
208 if (world.time < me.reloadUntil) {
225 ctx.fillText(weapon.name + (view.hasBomb ? " · bomb" : ""), width - pad, height - pad - Math.round(30 * scale));
226 if (world.time < view.reloadUntil) {
209227 ctx.fillStyle = "#f0c060";
210228 ctx.fillText("reloading", width - pad, height - pad - Math.round(50 * scale));
211229 }
@@ -234,9 +252,12 @@ export function drawHud(
234252 ctx.globalAlpha = 1;
235253 });
236254
237 // --- what the round is saying
255 // --- what the round is saying. The line stays up for four seconds, and a
256 // round result stays until the next round goes live: the end delay plus the
257 // freeze is long enough to read who won and why, which is the point of it.
238258 const message = world.messages[world.messages.length - 1];
239 if (message !== undefined && world.time - message.at < 4) {
259 const holding = phase === "over" || phase === "freeze" || phase === "match_over";
260 if (message !== undefined && (holding || world.time - message.at < MESSAGE_FADE)) {
240261 ctx.textAlign = "center";
241262 ctx.font = mid;
242263 ctx.fillStyle = "rgba(255,255,255,0.92)";
@@ -244,7 +265,7 @@ export function drawHud(
244265 }
245266
246267 // --- planting or defusing
247 const progress = useProgress(world, me);
268 const progress = useProgress(world, view);
248269 if (progress !== null) {
249270 const w = Math.round(260 * scale), h = Math.round(14 * scale);
250271 const x = width / 2 - w / 2, y = height * 0.62;
@@ -257,11 +278,29 @@ export function drawHud(
257278 ctx.fillText(progress.label, width / 2, y - 8 * scale);
258279 }
259280
260 if (!me.alive && world.match.phase !== "match_over") {
281 // --- dead: who killed you, and whose eyes you are borrowing until the round
282 // is over. The kill feed is where the killer comes from, so a death nobody
283 // was credited with — the bomb — simply says nothing about one.
284 if (!world.me.alive && !over) {
285 const top = height * 0.38;
261286 ctx.textAlign = "center";
262287 ctx.font = big;
263 ctx.fillStyle = "rgba(255,255,255,0.85)";
264 ctx.fillText("You are dead — watching the round out", width / 2, height * 0.4);
288 ctx.fillStyle = "rgba(255,255,255,0.88)";
289 ctx.fillText("You are dead", width / 2, top);
290 const notice = deathNotice(world, world.me);
291 if (notice !== null) {
292 ctx.font = mid;
293 ctx.fillStyle = "#ff8f86";
294 const how = `${notice.killer} killed you with ${WEAPONS[notice.weapon].name}` +
295 (notice.headshot ? " — headshot" : "");
296 ctx.fillText(how, width / 2, top + Math.round(30 * scale));
297 }
298 ctx.font = small;
299 ctx.fillStyle = "#c8ccd4";
300 ctx.fillText(
301 spectating ? `Watching ${view.name} — fire or click for the next` : "Nobody left to watch",
302 width / 2, top + Math.round(56 * scale),
303 );
265304 }
266305
267306 if (showScoreboard) drawScoreboard(ctx, world, width, height, scale);
src/client/main.ts +47 −14
@@ -13,6 +13,8 @@ import { clamp } 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 { nextWatched, watched } from "./spectate.ts";
17 import { summarize, type MatchSummary } from "./summary.ts";
1618 import { buyable } from "./weapons.ts";
1719 import {
1820 buy, canBuy, createWorld, eyePos, flinch, priceOf, update, type BuyItem, type Player, type World,
@@ -36,6 +38,7 @@ function boot(): void {
3638 const hudCanvas = $<HTMLCanvasElement>("hud");
3739 const menu = $("menu");
3840 const pause = $("pause");
41 const summaryPanel = $("summary");
3942 const buyPanel = $("buy");
4043 const touchPanel = $("touch");
4144 const stats = $("stats");
@@ -62,6 +65,7 @@ function boot(): void {
6265 let renderScale = MAX_SCALE;
6366 let scaledAt = 0;
6467 let posted = -1;
68 let watching = 0; // the id whose eyes we are borrowing while dead
6569
6670 const show = (element: HTMLElement, on: boolean): void => {
6771 element.hidden = !on;
@@ -146,6 +150,21 @@ function boot(): void {
146150 }
147151 }
148152
153 /**
154 * The end of the match, on the screen: who won, the score from your side and
155 * what you did, over the last frame the game drew. It goes up only once the
156 * result has been sent — and a post that failed still puts it up, because a
157 * leaderboard that cannot be reached is not a reason to hide the scoreline.
158 */
159 function showSummary(summary: MatchSummary): void {
160 $("summary-title").textContent = summary.headline;
161 $("summary-detail").textContent = summary.detail;
162 $("summary-score").textContent = summary.score;
163 $("summary-line").textContent = `${summary.name} — ${summary.line}`;
164 show(summaryPanel, true);
165 $("again").focus();
166 }
167
149168 function start(): void {
150169 const rules: Rules = lengthField.value === "long" ? COMPETITIVE : SHORT;
151170 const team = sideField.value === "t" ? "t" : "ct";
@@ -153,11 +172,13 @@ function boot(): void {
153172 world = createWorld(rules, name, team, 5);
154173 matchId = crypto.randomUUID();
155174 posted = -1;
175 watching = world.me.id;
156176 controls.sensitivity = clamp(Number(sensField.value) || 2.2, 0.2, 12);
157177 running = true;
158178 lastSound = 0;
159179 show(menu, false);
160180 show(pause, false);
181 show(summaryPanel, false);
161182 show(touchPanel, matchMedia("(pointer: coarse)").matches);
162183 audio.resume();
163184 void scene.requestPointerLock();
@@ -169,13 +190,18 @@ function boot(): void {
169190 show(pause, false);
170191 void scene.requestPointerLock();
171192 });
172 $("quit").addEventListener("click", () => {
193 const toMenu = (): void => {
173194 running = false;
174195 world = null;
175196 show(pause, false);
197 show(summaryPanel, false);
176198 show(menu, true);
177199 show(touchPanel, false);
178 });
200 $("play").focus();
201 };
202 $("quit").addEventListener("click", toMenu);
203 $("summary-menu").addEventListener("click", toMenu);
204 $("again").addEventListener("click", start);
179205 window.addEventListener("keydown", (event) => {
180206 if (event.code === "Escape" && !buyPanel.hidden) openBuy(false);
181207 });
@@ -183,10 +209,12 @@ function boot(): void {
183209 if (saved !== null && nameField.value === "") nameField.value = saved;
184210
185211 // --- sound and flinch for whatever happened in the ticks we just ran
186 function feelEffects(current: World): void {
212 function feelEffects(current: World, ears: Player): void {
187213 for (const effect of current.effects) {
188214 if (effect.at <= lastSound) continue;
189 if (effect.kind === "shot") audio.shot(effect.weapon, effect.pos, eyePos(current.me));
215 // Sound comes from where the camera is: while dead that is a teammate's
216 // head, not the corpse the shots are no longer near.
217 if (effect.kind === "shot") audio.shot(effect.weapon, effect.pos, eyePos(ears));
190218 else if (effect.kind === "hitmark") audio.hit(effect.headshot);
191219 else if (effect.kind === "hurt" && effect.victim === current.me.id) {
192220 flinch(current.me, effect.from, effect.amount);
@@ -196,11 +224,6 @@ function boot(): void {
196224 lastSound = current.time;
197225 }
198226
199 const spectated = (current: World): Player => {
200 if (current.me.alive) return current.me;
201 return current.players.find((p) => p.alive && p.team === current.me.team) ?? current.me;
202 };
203
204227 let last = performance.now();
205228 let accumulator = 0;
206229
@@ -227,14 +250,19 @@ function boot(): void {
227250 accumulator += elapsed;
228251 const steps = Math.min(8, Math.floor(accumulator / TICK));
229252 const pressed = controls.take(steps);
253 // A dead player's fire is nobody's trigger, so it is the spectator's: each
254 // press moves the camera on to the next teammate still alive.
255 let cycle = false;
230256 for (let step = 0; step < steps; step += 1) {
231257 const input = controls.inputAt(pressed, step);
232258 input.switchTo = switchTo;
233259 if (!buyPanel.hidden) input.fire = false;
260 if (!world.me.alive && input.fire) cycle = true;
234261 update(world, TICK, input);
235262 accumulator -= TICK;
236263 }
237 feelEffects(world);
264 watching = nextWatched(world, watching, cycle);
265 feelEffects(world, watched(world, watching));
238266
239267 // The buy window closes itself when the round goes live.
240268 if (!buyPanel.hidden && !canBuy(world, me)) openBuy(false);
@@ -245,12 +273,17 @@ function boot(): void {
245273 }
246274 if (world.match.phase === "match_over" && running) {
247275 running = false;
276 posted = played;
248277 document.exitPointerLock();
249 show(menu, true);
250 $("play").focus();
278 show(buyPanel, false);
279 show(touchPanel, false);
280 // The last post is the only one that says the match finished, and the
281 // score it carries is the one the overlay is about to show.
282 const summary = summarize(world);
283 void postResult(true).then(() => showSummary(summary), () => showSummary(summary));
251284 }
252285
253 const view = spectated(world);
286 const view = watched(world, watching);
254287 const camera: Camera = {
255288 pos: eyePos(view),
256289 yaw: view.yaw - view.punch[0] * 0.4,
@@ -278,7 +311,7 @@ function boot(): void {
278311 hudCanvas.width = w;
279312 hudCanvas.height = h;
280313 }
281 drawHud(hudCtx, world, w, h, controls.scoreboard);
314 drawHud(hudCtx, world, view, w, h, controls.scoreboard);
282315 // The fps is the frame time and nothing else; the scale is an aside, shown
283316 // only when it is costing you pixels, so a slow machine says why.
284317 const note = renderScale < MAX_SCALE ? ` · ${Math.round(renderScale * 100)}% res` : "";
src/client/spectate.test.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * Being dead, headless: who the camera lands on, what a click does to it, and
3 * what the kill feed says about how you got here.
4 */
5
6 import { expect, test } from "bun:test";
7 import { SHORT } from "./match.ts";
8 import { deathNotice, nextWatched, watchable, watched } from "./spectate.ts";
9 import { createWorld, type Player, type World } from "./world.ts";
10
11 const dead = (): World => {
12 const world = createWorld(SHORT, "me", "ct", 5, 11);
13 world.me.alive = false;
14 world.me.health = 0;
15 return world;
16 };
17
18 test("alive, you watch yourself and a click changes nothing", () => {
19 const world = createWorld(SHORT, "me", "ct", 5, 11);
20 expect(nextWatched(world, world.me.id)).toBe(world.me.id);
21 expect(nextWatched(world, world.me.id, true)).toBe(world.me.id);
22 expect(watched(world, world.me.id)).toBe(world.me);
23 });
24
25 test("dead, the camera takes a living teammate and a click cycles through them", () => {
26 const world = dead();
27 const mates = watchable(world);
28 expect(mates.length).toBe(4);
29 expect(mates.every((p) => p.team === "ct")).toBe(true);
30
31 let watching = nextWatched(world, world.me.id);
32 expect(watching).toBe((mates[0] as Player).id);
33 // Without a click it stays put — the camera does not wander on its own.
34 expect(nextWatched(world, watching)).toBe(watching);
35 for (const mate of [mates[1], mates[2], mates[3], mates[0]] as Player[]) {
36 watching = nextWatched(world, watching, true);
37 expect(watching).toBe(mate.id);
38 }
39 });
40
41 test("the teammate you were watching dying moves you to one who has not", () => {
42 const world = dead();
43 const mates = watchable(world);
44 const first = mates[0] as Player;
45 first.alive = false;
46 expect(nextWatched(world, first.id)).toBe((mates[1] as Player).id);
47
48 for (const p of mates) p.alive = false;
49 expect(nextWatched(world, first.id)).toBe(world.me.id);
50 expect(watched(world, world.me.id)).toBe(world.me);
51 });
52
53 test("the kill feed says who killed you, and says nothing about a bomb", () => {
54 const world = dead();
55 expect(deathNotice(world, world.me)).toBe(null);
56 const bot = world.players[1] as Player;
57 world.feed.push({
58 at: world.time, killer: bot.name, killerId: bot.id, victim: world.me.name, victimId: world.me.id,
59 weapon: "ak47", headshot: true, killerTeam: bot.team,
60 });
61 // A namesake killed somewhere else does not become your killer: ids decide.
62 world.feed.push({
63 at: world.time, killer: "someone", killerId: 8, victim: world.me.name, victimId: 7,
64 weapon: "usp", headshot: false, killerTeam: "ct",
65 });
66 const notice = deathNotice(world, world.me);
67 expect(notice?.killer).toBe(bot.name);
68 expect(notice?.weapon).toBe("ak47");
69 expect(notice?.headshot).toBe(true);
70 });
src/client/spectate.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * Being dead: who the camera follows, and what killed you. Pure functions over
3 * the world, so the loop only carries an id between frames and the HUD only
4 * draws what these hand back.
5 */
6
7 import type { FeedEntry, Player, World } from "./world.ts";
8
9 /** The living teammates the person can watch, in the order the world holds them. */
10 export const watchable = (world: World): Player[] =>
11 world.players.filter((p) => p.alive && p.team === world.me.team && p !== world.me);
12
13 /**
14 * The id to watch this frame. `watching` is the one followed now and `advance`
15 * asks for the next one along — a click or the fire key while dead. It falls
16 * back to the person themself while they are alive and when there is nobody
17 * left on their side, so the camera always has somewhere to be.
18 */
19 export function nextWatched(world: World, watching: number, advance = false): number {
20 if (world.me.alive) return world.me.id;
21 const options = watchable(world);
22 const first = options[0];
23 if (first === undefined) return world.me.id;
24 const at = options.findIndex((p) => p.id === watching);
25 if (at < 0) return first.id;
26 return advance ? (options[(at + 1) % options.length] as Player).id : watching;
27 }
28
29 /** The player an id names, or the person when it names nobody. */
30 export const watched = (world: World, watching: number): Player =>
31 world.players.find((p) => p.id === watching) ?? world.me;
32
33 /**
34 * The kill-feed line that killed `player`, or null — the bomb kills nobody by
35 * name, and the feed only keeps the last few lines, so this can be nothing
36 * even for a corpse.
37 */
38 export function deathNotice(world: World, player: Player): FeedEntry | null {
39 for (let i = world.feed.length - 1; i >= 0; i -= 1) {
40 const entry = world.feed[i] as FeedEntry;
41 if (entry.victimId === player.id) return entry;
42 }
43 return null;
44 }
src/client/summary.test.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * The end-of-match summary, headless: the numbers the overlay shows are read
3 * off the world here, so what a person sees when the match ends is checked
4 * without a browser.
5 */
6
7 import { expect, test } from "bun:test";
8 import { SHORT } from "./match.ts";
9 import { summarize } from "./summary.ts";
10 import { createWorld, finishRound, type World } from "./world.ts";
11
12 /** Play `mine` rounds for the person's side and `theirs` for the other one. */
13 const play = (world: World, mine: number, theirs: number): void => {
14 const me = world.me.team;
15 const them = me === "t" ? "ct" : "t";
16 for (let i = 0; i < mine; i += 1) {
17 finishRound(world, me, "elimination");
18 world.match.phase = "live";
19 }
20 for (let i = 0; i < theirs; i += 1) {
21 finishRound(world, them, "elimination");
22 world.match.phase = "live";
23 }
24 if (world.match.matchWinner !== null) world.match.phase = "match_over";
25 };
26
27 test("a win reads as a win, from the person's side of the score", () => {
28 const world = createWorld(SHORT, "Vesper", "ct", 5, 5);
29 play(world, 5, 2);
30 const summary = summarize(world);
31 expect(summary.winner).toBe("ct");
32 expect(summary.won).toBe(true);
33 expect(summary.headline).toBe("You win");
34 expect(summary.detail).toBe("Counter-Terrorists win the match");
35 expect(summary.mine).toBe(5);
36 expect(summary.theirs).toBe(2);
37 expect(summary.score).toBe("5 – 2");
38 });
39
40 test("a loss keeps the score the person's way round", () => {
41 const world = createWorld(SHORT, "Vesper", "t", 5, 5);
42 play(world, 1, 5);
43 const summary = summarize(world);
44 expect(summary.winner).toBe("ct");
45 expect(summary.won).toBe(false);
46 expect(summary.headline).toBe("You lose");
47 expect(summary.mine).toBe(1);
48 expect(summary.theirs).toBe(5);
49 expect(summary.score).toBe("1 – 5");
50 });
51
52 test("the line is what the person did, and the numbers are the ones posted", () => {
53 const world = createWorld(SHORT, "Vesper", "ct", 5, 5);
54 world.me.kills = 12;
55 world.me.deaths = 4;
56 world.me.headshots = 5;
57 world.me.damage = 1637.4;
58 world.time = 512.6;
59 play(world, 5, 0);
60 const summary = summarize(world);
61 expect(summary.name).toBe("Vesper");
62 expect(summary.kills).toBe(12);
63 expect(summary.deaths).toBe(4);
64 expect(summary.headshots).toBe(5);
65 expect(summary.damage).toBe(1637);
66 expect(summary.seconds).toBe(513);
67 expect(summary.line).toBe("12 kills · 4 deaths · 5 headshots · 1637 damage");
68 });
69
70 test("mid-match there is no winner yet, and it says the score rather than a result", () => {
71 const world = createWorld(SHORT, "Vesper", "ct", 5, 5);
72 play(world, 2, 1);
73 const summary = summarize(world);
74 expect(summary.winner).toBe(null);
75 expect(summary.won).toBe(false);
76 expect(summary.headline).toBe("Match over");
77 expect(summary.detail).toContain("Counter-Terrorists 2");
78 expect(summary.detail).toContain("Terrorists 1");
79 });
src/client/summary.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * The end of a match as plain numbers: who won, the score read from the
3 * person's side of it, and the line about what they did. A pure function over
4 * the world, so the overlay that shows it is only markup and this can be
5 * checked without a browser.
6 */
7
8 import { other, type Team } from "./match.ts";
9 import type { World } from "./world.ts";
10
11 export type MatchSummary = {
12 winner: Team | null; // null while the match is still being played
13 won: boolean;
14 headline: string; // "You win" / "You lose"
15 detail: string; // which side took it
16 mine: number;
17 theirs: number;
18 score: string; // the score from the person's side, their number first
19 name: string;
20 kills: number;
21 deaths: number;
22 headshots: number;
23 damage: number;
24 line: string; // what the person did, in one line
25 seconds: number;
26 };
27
28 const SIDE: Record<Team, string> = { t: "Terrorists", ct: "Counter-Terrorists" };
29
30 export function summarize(world: World): MatchSummary {
31 const me = world.me;
32 const winner = world.match.matchWinner;
33 // Sides swap at half time and the score swaps with them, so the score is
34 // always keyed by the team everyone is on now — including the person's.
35 const mine = world.match.score[me.team];
36 const theirs = world.match.score[other(me.team)];
37 const won = winner !== null && winner === me.team;
38 const damage = Math.round(me.damage);
39 return {
40 winner,
41 won,
42 headline: winner === null ? "Match over" : won ? "You win" : "You lose",
43 detail: winner === null
44 ? `${SIDE[me.team]} ${mine} — ${SIDE[other(me.team)]} ${theirs}`
45 : `${SIDE[winner]} win the match`,
46 mine,
47 theirs,
48 score: `${mine} – ${theirs}`,
49 name: me.name,
50 kills: me.kills,
51 deaths: me.deaths,
52 headshots: me.headshots,
53 damage,
54 line: `${me.kills} kills · ${me.deaths} deaths · ${me.headshots} headshots · ${damage} damage`,
55 seconds: Math.round(world.time),
56 };
57 }
src/client/world.ts +18 −2
@@ -69,7 +69,18 @@ export type Effect =
6969 | { kind: "hurt"; at: number; victim: number; from: Vec3; amount: number }
7070 | { kind: "sound"; at: number; pos: Vec3; name: string };
7171
72 export type FeedEntry = { at: number; killer: string; victim: string; weapon: WeaponId; headshot: boolean; killerTeam: Team };
72 // The ids are here as well as the names because the HUD asks the feed who
73 // killed the person, and two players may answer to the same name.
74 export type FeedEntry = {
75 at: number;
76 killer: string;
77 killerId: number;
78 victim: string;
79 victimId: number;
80 weapon: WeaponId;
81 headshot: boolean;
82 killerTeam: Team;
83 };
7384
7485 export type Input = {
7586 forward: number;
@@ -401,7 +412,12 @@ function onKill(world: World, killer: Player, victim: Player, weapon: WeaponId,
401412 killer.kills += 1;
402413 if (headshot) killer.headshots += 1;
403414 killer.money = rules.capMoney(killer.money + WEAPONS[weapon].killReward, world.match.rules);
404 world.feed.push({ at: world.time, killer: killer.name, victim: victim.name, weapon, headshot, killerTeam: killer.team });
415 world.feed.push({
416 at: world.time,
417 killer: killer.name, killerId: killer.id,
418 victim: victim.name, victimId: victim.id,
419 weapon, headshot, killerTeam: killer.team,
420 });
405421 if (world.feed.length > 5) world.feed.shift();
406422 if (victim.hasBomb) {
407423 victim.hasBomb = false;
src/pages/game.ts +13
@@ -66,6 +66,9 @@ button:disabled { opacity:.42; cursor:not-allowed; }
6666 button.primary { background:#2563eb; border-color:#2563eb; font-weight:600; }
6767 #buy .grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(11rem,1fr)); gap:.5rem; width:min(40rem,100%); }
6868 #buy .hint, .overlay .hint { font-size:.78rem; }
69 #summary .score { font-size:2.2rem; line-height:1.1; color:var(--text); font-variant-numeric:tabular-nums; margin:.1rem 0; }
70 #summary h2 { font-size:1.8rem; }
71 #summary #summary-line { color:var(--text); font-size:.95rem; }
6972 #fps { position:absolute; right:.5rem; bottom:.4rem; font-size:.7rem; color:#8ea; opacity:.7; pointer-events:none; }
7073 #touch { position:absolute; inset:auto 0 0 0; display:flex; justify-content:space-between; padding:.6rem; pointer-events:none; }
7174 #touch[hidden] { display:none; }
@@ -141,6 +144,16 @@ export function gamePage(db: Database, options: PageOptions): string {
141144 <h2>Paused</h2>
142145 <div class="row"><button type="button" class="primary" id="resume">Resume</button><button type="button" id="quit">Leave match</button></div>
143146 </div>
147 <div class="overlay" id="summary" hidden>
148 <h2 id="summary-title">Match over</h2>
149 <p id="summary-detail"></p>
150 <p class="score" id="summary-score"></p>
151 <p id="summary-line"></p>
152 <div class="row">
153 <button type="button" class="primary" id="again">Play again</button>
154 <button type="button" id="summary-menu">Back to menu</button>
155 </div>
156 </div>
144157 <div class="overlay" id="buy" hidden></div>
145158 </div>
146159
static/app.285984cb3a.js deleted −58

Diff not shown — a line 56,219 characters wide (limit 2,000). −58

View file
static/app.5401f6cc28.js deleted −58

Diff not shown — a line 57,887 characters wide (limit 2,000). −58

View file
static/app.85c83ea9c3.js deleted −58

Diff not shown — a line 55,766 characters wide (limit 2,000). −58

View file
static/app.e8bccf8878.js added +58

Diff not shown — a line 59,439 characters wide (limit 2,000). +58

View file

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs