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

The buy menu says why you cannot buy it, and moves out of `main.ts` into a tested module #92

Merged opened this

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

Merged

scout/cs:scout/87-the-buy-menu-says-why-you-cannot-buy-it → main 1 commit fork

  • Merged. scout/87-the-buy-menu-says-why-you-cannot-buy-it was merged into main as b97de2f.

Review

Sign in to review this change.
5 files changed +226 −34
README.md +9 −1
@@ -145,7 +145,13 @@ tabbing away mid-round is not a death — the pause overlay is what you come bac
145145 to, and the round resumes exactly where it stopped, even a minute later. The
146146 buy menu is the exception: it opens in the freeze time, and a frozen freeze
147147 clock is a round that never starts, so the world goes on while you shop (your
148 shots do not — a click on a gun is a purchase and never a trigger).
148 shots do not — a click on a gun is a purchase and never a trigger). The panel
149 counts the freeze time down in its header and closes itself the moment it
150 runs out. Every row says why it is dead when it is: too little money, the
151 other side's gear, one you are already carrying, or the buy window itself
152 being shut — the reason is on the button, not just its colour, so a screen
153 reader hears it too. The digits <kbd>1</kbd>–<kbd>9</kbd> buy the row they
154 number, the same way clicking it would.
149155
150156 **If the browser takes the 3D view away** — a phone that backgrounded the tab,
151157 an operating system reclaiming graphics memory, a driver that reset — the match
@@ -229,6 +235,8 @@ with the canvas as you turn; nobody re-walks the grid to draw it.
229235 everything that reads a grid takes the map rather than reaching for one),
230236 `physics`, `weapons`, `combat`, `grenades` (a thrown thing's flight: gravity,
231237 bounce, fuse and how far a blast reaches), `match` (the rules), `world` (the simulation),
238 `buy` (the buy panel's rows — what a side can afford, what it already owns
239 and why the rest are dead — read off `world` and handed to `main` as plain data),
232240 `bots`, `plan` (which site a side commits to, and when the carrier has run out
233241 of clock), `observe`, `action`, `policy`, `weights`, `models`, `textures`,
234242 `press` (the input latch), `loop` (how much simulation one frame is worth:
src/client/buy.test.ts added +60
@@ -0,0 +1,60 @@
1 import { expect, test } from "bun:test";
2 import { SHORT } from "./match.ts";
3 import { ARMOR_PRICE, HELMET_PRICE, WEAPONS } from "./weapons.ts";
4 import { buy, createWorld, NO_INPUT, update } from "./world.ts";
5 import { buyMenu } from "./buy.ts";
6
7 const row = (world: ReturnType<typeof createWorld>, item: string) =>
8 buyMenu(world, world.me).rows.find((r) => r.item === item);
9
10 test("too poor for a rifle: poor, and the price still shows", () => {
11 const world = createWorld(SHORT, "me", "ct", 5, 1);
12 world.me.money = 100;
13 const m4 = row(world, "m4a4");
14 expect(m4?.state).toBe("poor");
15 expect(m4?.price).toBe(WEAPONS.m4a4.price);
16 });
17
18 test("a side only sees its own gear", () => {
19 const ct = createWorld(SHORT, "me", "ct", 5, 2);
20 expect(row(ct, "ak47")).toBeUndefined();
21 const t = createWorld(SHORT, "me", "t", 5, 2);
22 expect(row(t, "kit")).toBeUndefined();
23 });
24
25 test("a gun already in hand is owned, not for sale again", () => {
26 const world = createWorld(SHORT, "me", "ct", 5, 3);
27 world.me.money = 5000;
28 buy(world, world.me, "m4a4");
29 const m4 = row(world, "m4a4");
30 expect(m4?.state).toBe("owned");
31 });
32
33 test("a second grenade is owned, not a second purchase", () => {
34 const world = createWorld(SHORT, "me", "ct", 5, 4);
35 world.me.money = 5000;
36 buy(world, world.me, "he");
37 const he = row(world, "he");
38 expect(he?.state).toBe("owned");
39 expect(he?.why).toContain("carrying");
40 });
41
42 test("every row goes closed together once canBuy is false", () => {
43 const world = createWorld(SHORT, "me", "ct", 5, 5);
44 world.me.money = 5000;
45 for (let t = 0; t < SHORT.freezeTime + 0.5; t += 1 / 64) update(world, 1 / 64, NO_INPUT);
46 expect(world.match.phase).toBe("live");
47 const menu = buyMenu(world, world.me);
48 expect(menu.rows.length).toBeGreaterThan(0);
49 expect(menu.rows.every((r) => r.state === "closed")).toBe(true);
50 });
51
52 test("armour's price is what is already worn, not a constant", () => {
53 const world = createWorld(SHORT, "me", "ct", 5, 6);
54 world.me.money = 5000;
55 const bare = row(world, "helmet");
56 expect(bare?.price).toBe(ARMOR_PRICE + HELMET_PRICE);
57 buy(world, world.me, "armor");
58 const armored = row(world, "helmet");
59 expect(armored?.price).toBe(HELMET_PRICE);
60 });
src/client/buy.ts added +73
@@ -0,0 +1,73 @@
1 /**
2 * The buy menu's rows: what each item costs, whether it can be bought right
3 * now, and why not when it cannot. Pure data in, plain data out — nothing
4 * here touches the DOM, so the panel in main.ts is free to paint it however
5 * a phone or a screen reader needs.
6 */
7
8 import { buyable, WEAPONS } from "./weapons.ts";
9 import { canBuy, MAX_GRENADES, priceOf, type BuyItem, type Player, type World } from "./world.ts";
10
11 export type BuyState = "ok" | "owned" | "poor" | "side" | "closed";
12
13 export type BuyRow = {
14 item: BuyItem;
15 label: string;
16 price: number;
17 state: BuyState;
18 why: string;
19 };
20
21 export type BuyMenu = {
22 rows: BuyRow[];
23 money: number;
24 /** Seconds left in the freeze time, however long it has been over — never negative. */
25 secondsLeft: number;
26 };
27
28 /** Every item a side can ever buy — off-side gear (the other rifle, a T's defuse kit) never appears. */
29 const catalog = (team: "t" | "ct"): [BuyItem, string][] => [
30 ...buyable(team).map((w) => [w.id, w.name] as [BuyItem, string]),
31 ["armor", "Kevlar"],
32 ["helmet", "Kevlar + Helmet"],
33 ...(team === "ct" ? ([["kit", "Defuse kit"]] as [BuyItem, string][]) : []),
34 ];
35
36 function owned(player: Player, item: BuyItem): boolean {
37 if (item === "armor") return player.armor >= 100;
38 if (item === "helmet") return player.helmet;
39 if (item === "kit") return player.defuseKit;
40 if (WEAPONS[item].kind === "grenade") return player.grenades >= MAX_GRENADES;
41 return player.primary === item || player.secondary === item;
42 }
43
44 function ownedWhy(item: BuyItem): string {
45 if (item === "armor" || item === "helmet") return "already worn";
46 if (item === "kit" || WEAPONS[item]?.kind === "grenade") return "already carrying one";
47 return "already in hand";
48 }
49
50 function closedWhy(world: World, player: Player): string {
51 if (!player.alive) return "you're dead this round";
52 if (world.match.phase !== "freeze") return "the buy window is closed";
53 return "";
54 }
55
56 /**
57 * The rows the buy panel paints. Every row goes `closed` together the moment
58 * `canBuy` does — the one rule this file is not allowed a second copy of —
59 * and a row too expensive still shows what it costs, so the number is the
60 * only thing a player has to check twice.
61 */
62 export function buyMenu(world: World, player: Player): BuyMenu {
63 const open = canBuy(world, player);
64 const reason = open ? "" : closedWhy(world, player);
65 const rows: BuyRow[] = catalog(player.team).map(([item, label]) => {
66 const price = priceOf(item, player);
67 if (!open) return { item, label, price, state: "closed", why: reason };
68 if (owned(player, item)) return { item, label, price, state: "owned", why: ownedWhy(item) };
69 if (price > player.money) return { item, label, price, state: "poor", why: "not enough money" };
70 return { item, label, price, state: "ok", why: "" };
71 });
72 return { rows, money: player.money, secondsLeft: Math.max(0, world.match.timer) };
73 }
src/client/main.ts +80 −33
@@ -9,6 +9,7 @@
99 */
1010
1111 import { createAudio } from "./audio.ts";
12 import { buyMenu, type BuyRow } from "./buy.ts";
1213 import { attachFullscreen } from "./fullscreen.ts";
1314 import { drawHud } from "./hud.ts";
1415 import { attachButtons, createControls } from "./input.ts";
@@ -20,10 +21,9 @@ import { createRenderer, type Camera } from "./renderer.ts";
2021 import { DEFAULT_SETTINGS, loadSettings, saveSettings, SENSITIVITY_MAX, SENSITIVITY_MIN } from "./settings.ts";
2122 import { nextWatched, watched } from "./spectate.ts";
2223 import { summarize, type MatchSummary } from "./summary.ts";
23 import { buyable } from "./weapons.ts";
2424 import {
25 buy, canBuy, canBuyItem, createWorld, DIFFICULTIES, eyePos, flinch, priceOf, setDifficulty, update,
26 type BuyItem, type Difficulty, type Player, type SoundName, type World,
25 buy, canBuy, createWorld, DIFFICULTIES, eyePos, flinch, setDifficulty, update,
26 type Difficulty, type Player, type SoundName, type World,
2727 } from "./world.ts";
2828
2929 /**
@@ -192,46 +192,89 @@ function boot(): void {
192192 "blocked", !(pause.hidden && buyPanel.hidden && summaryPanel.hidden));
193193 };
194194
195 // --- the buy menu, rebuilt whenever it opens so the prices are honest
196 function renderBuy(): void {
195 // --- the buy menu: built once, then updated in place so a purchase never
196 // costs the panel its listeners or the player their focus.
197 buyPanel.innerHTML =
198 `<h2>Buy <small id="buy-money"></small></h2>` +
199 `<p class="hint" id="buy-clock"></p>` +
200 `<div class="grid"></div>` +
201 `<div class="row"><button type="button" id="buy-close">Close</button></div>` +
202 `<p class="hint">B, Escape or Close closes. Digits 1-9 buy the row they number.</p>`;
203 $("buy-close").addEventListener("click", () => openBuy(false));
204 const buyGrid = buyPanel.querySelector(".grid") as HTMLElement;
205 let buyRowIds = ""; // the joined item ids the grid currently holds
206
207 function buyRowButtons(): HTMLButtonElement[] {
208 return Array.from(buyGrid.querySelectorAll("button"));
209 }
210
211 /** One purchase from wherever it came: a click, or a digit typed at the panel. */
212 function buyRow(row: BuyRow): void {
197213 if (world === null) return;
198 const me = world.me;
199 const items: [BuyItem, string][] = [
200 ...buyable(me.team).map((w) => [w.id, w.name] as [BuyItem, string]),
201 ["armor", "Kevlar"],
202 ["helmet", "Kevlar + Helmet"],
203 ...(me.team === "ct" ? ([["kit", "Defuse kit"]] as [BuyItem, string][]) : []),
204 ];
205 buyPanel.innerHTML =
206 `<h2>Buy <small>$${me.money}</small></h2><div class="grid"></div>` +
207 `<div class="row"><button type="button" id="buy-close">Close</button></div>` +
208 `<p class="hint">B, Escape or Close closes. You can only buy in the freeze time.</p>`;
209 $("buy-close").addEventListener("click", () => openBuy(false));
210 const grid = buyPanel.querySelector(".grid") as HTMLElement;
211 for (const [item, label] of items) {
212 const price = priceOf(item, me);
214 if (buy(world, world.me, row.item)) audio.beep(700, 0.05);
215 paintBuy();
216 }
217
218 // Rebuilt only when the set of items changes — half time flips a side's
219 // whole loadout, so the rifle in slot one is not always the same rifle.
220 function buildBuyGrid(rows: BuyRow[]): void {
221 buyGrid.innerHTML = "";
222 rows.forEach((row, i) => {
223 const whyId = `buy-why-${row.item}`;
213224 const button = document.createElement("button");
214225 button.type = "button";
215 button.textContent = `${label} · $${price}`;
216 button.disabled = !canBuyItem(world, me, item);
217 button.addEventListener("click", () => {
218 if (world === null) return;
219 if (buy(world, world.me, item)) audio.beep(700, 0.05);
220 renderBuy();
221 });
222 grid.appendChild(button);
223 }
226 button.className = "buy-item";
227 button.id = `buy-item-${row.item}`;
228 button.setAttribute("aria-describedby", whyId);
229 button.innerHTML =
230 `<b class="buy-index">${i + 1}</b><span class="buy-line"></span><small class="buy-why" id="${whyId}"></small>`;
231 button.addEventListener("click", () => buyRow(row));
232 buyGrid.appendChild(button);
233 });
224234 }
225235
236 function paintBuy(): void {
237 if (world === null) return;
238 const menu = buyMenu(world, world.me);
239 const ids = menu.rows.map((r) => r.item).join(",");
240 if (ids !== buyRowIds) {
241 buyRowIds = ids;
242 buildBuyGrid(menu.rows);
243 }
244 $("buy-money").textContent = `$${menu.money}`;
245 $("buy-clock").textContent = canBuy(world, world.me)
246 ? `Freeze time: ${Math.ceil(menu.secondsLeft)}s left`
247 : "Buy window closed";
248 const buttons = buyRowButtons();
249 menu.rows.forEach((row, i) => {
250 const button = buttons[i];
251 if (button === undefined) return;
252 (button.querySelector(".buy-line") as HTMLElement).textContent = `${row.label} · $${row.price}`;
253 (button.querySelector(".buy-why") as HTMLElement).textContent = row.why;
254 button.disabled = row.state !== "ok";
255 });
256 }
257
258 // Digits 1-9 buy the numbered row without also reaching the slot-switch
259 // keys bound on `window` — the panel answers the press before it gets there.
260 buyPanel.addEventListener("keydown", (event) => {
261 if (world === null || buyPanel.hidden) return;
262 const match = /^Digit([1-9])$/.exec(event.code);
263 if (match === null) return;
264 event.stopPropagation();
265 const row = buyMenu(world, world.me).rows[Number(match[1]) - 1];
266 if (row !== undefined) buyRow(row);
267 });
268
226269 function openBuy(open: boolean): void {
227270 if (world === null) return;
228271 if (open && !canBuy(world, world.me)) return;
229272 show(buyPanel, open);
230273 refreshPad();
231274 if (open) {
232 renderBuy();
275 paintBuy();
233276 document.exitPointerLock();
234 (buyPanel.querySelector("button") as HTMLButtonElement | null)?.focus();
277 (buyGrid.querySelector("button") as HTMLButtonElement | null)?.focus();
235278 } else if (running) {
236279 lock();
237280 }
@@ -468,8 +511,12 @@ function boot(): void {
468511 watching = nextWatched(world, watching, cycle);
469512 feelEffects(world, watched(world, watching));
470513
471 // The buy window closes itself when the round goes live.
472 if (!buyPanel.hidden && !canBuy(world, me)) openBuy(false);
514 // The buy window closes itself when the round goes live; while it is up
515 // the clock, the money and every row's state are kept honest every frame.
516 if (!buyPanel.hidden) {
517 if (canBuy(world, me)) paintBuy();
518 else openBuy(false);
519 }
473520 const played = world.match.score.t + world.match.score.ct;
474521 if (played !== posted) {
475522 posted = played;
src/pages/game.ts +4
@@ -117,6 +117,10 @@ button:disabled { opacity:.42; cursor:not-allowed; }
117117 button.primary { background:#2563eb; border-color:#2563eb; font-weight:600; }
118118 #buy .grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(11rem,1fr)); gap:.5rem; width:min(40rem,100%); }
119119 #buy .hint, .overlay .hint { font-size:.78rem; }
120 #buy .buy-item { display:flex; flex-direction:column; align-items:flex-start; gap:.1rem; text-align:left; white-space:normal; }
121 #buy .buy-item .buy-index { font-size:.7rem; color:var(--dim); }
122 #buy .buy-item .buy-why { font-size:.72rem; color:var(--dim); min-height:1em; }
123 #buy #buy-clock { font-variant-numeric:tabular-nums; }
120124 #summary .score { font-size:2.2rem; line-height:1.1; color:var(--text); font-variant-numeric:tabular-nums; margin:.1rem 0; }
121125 #summary h2 { font-size:1.8rem; }
122126 #summary #summary-line { color:var(--text); font-size:.95rem; }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs