@ywkrlerche/richardwho 1.0.52 → 1.0.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/krillionwho.js ADDED
@@ -0,0 +1,1849 @@
1
+ // KrillionWho: name the rarest answer you can. richardwho's own take on Krillion.
2
+ // Press Play for The Daily Dive (7 prompts, the same for everyone, 25 seconds and one guess each), Free Play (as many
3
+ // dives as you like: a themed pack or an old day) or Puffer Party (pass the pufferfish before it pops: online rooms
4
+ // or the computer). It all happens in one tall pixel ocean, and the camera dives deeper every time you score.
5
+ // Sounds are made on the fly with Web Audio, so there are no sound files.
6
+ // Answers come from krillionwho-data.js (built by tools/build-krillionwho.js). Rarity starts from that list's order
7
+ // (most-said first) and shifts toward what people here actually answer, counted in the database under krillionwho/counts.
8
+ (function () {
9
+ "use strict";
10
+
11
+ const ROUND_MS = 25000, PREROLL = 3, ROUNDS = 7, MIN_POOL = 8, DAILY_POOL = 20, PARTY_POOL = 12;
12
+ const FUSE = 25000, FLOOR = 8000, BREAK = 3500, PUFF_AT = 9000, MAX_PLAYERS = 8, ROOM_LIFE = 3 * 3600e3;
13
+ const DAILY_KEY = "rug-krillionwho", STATS_KEY = "rug-krillionwho-stats", NAME_KEY = "rug-chat-name", KW_NAME_KEY = "rug-krillionwho-name", PACK_KEY = "rug-krillionwho-pack";
14
+ const ROOM_KEY = "rug-krillionwho-room", MY_ROOMS_KEY = "rug-krillionwho-rooms", SOUND_KEY = "rug-krillionwho-sound";
15
+ const ROOM_LETTERS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; // no I, L, O, 0 or 1: they get misread
16
+ const MAX_DEPTH = 7000, S = 1.2; // the ocean is 7,000 m deep, drawn at 1.2 px per meter
17
+ const LAUNCH = new Date(2026, 11, 2); // Dive #1
18
+ const ZONES = [[0, "Sunlight Zone"], [200, "Twilight Zone"], [1000, "Midnight Zone"], [4000, "The Abyss"], [6000, "The Trench"]];
19
+ // How rare an answer was, from the obvious ones floating at the top to the deepest cuts
20
+ const TIERS = { 0: ["Missed", "💨"], 10: ["Plankton", "🦐"], 20: ["Common", "🐚"], 30: ["Schooler", "🐟"], 40: ["Uncommon", "🐠"], 50: ["Rare", "🐢"],
21
+ 60: ["Very rare", "🐬"], 70: ["Deep cut", "🦈"], 80: ["Ultra rare", "🐙"], 90: ["Abyssal", "🦑"], 100: ["One of a kind", "🐉"] };
22
+ const BOT_NAMES = ["Bubbles", "Finn", "Coral", "Kelp", "Barnacle", "Pearl", "Captain Gill"];
23
+
24
+ let ctx = null, root = null, BANK = null;
25
+ const $ = (id) => document.getElementById(id);
26
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
27
+ const clone = (o) => JSON.parse(JSON.stringify(o));
28
+ const pad = (n) => String(n).padStart(2, "0");
29
+ const dateStr = (d = new Date()) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
30
+ const dayBefore = (s, n = 1) => { const [y, m, d] = s.split("-").map(Number); return dateStr(new Date(y, m - 1, d - n)); };
31
+ const dayNumber = (s) => { const [y, m, d] = s.split("-").map(Number); return Math.round((new Date(y, m - 1, d) - LAUNCH) / 864e5) + 1; };
32
+ const fmtDate = (s) => { const [y, m, d] = s.split("-").map(Number); return new Date(y, m - 1, d).toLocaleDateString([], { weekday: "short", month: "short", day: "numeric" }); };
33
+ const fmtM = (m) => `${Math.round(m).toLocaleString()}m`;
34
+ const zoneAt = (m) => ZONES.filter(([at]) => m >= at).pop()[1];
35
+ const sum = (a) => a.reduce((t, r) => t + r.p, 0);
36
+ const wait = (ms) => new Promise((ok) => setTimeout(ok, ms));
37
+ const calm = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
38
+
39
+ // ---------- Matching answers ----------
40
+ // Must match norm() in tools/build-krillionwho.js
41
+ const norm = (s) => String(s || "").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase()
42
+ .replace(/&/g, " and ").replace(/['’‘`´ʻ.!?*]/g, "").replace(/[^a-z0-9♀♂]+/g, " ").trim()
43
+ .replace(/^the /, "").replace(/\bst\b/g, "saint").replace(/\bmt\b/g, "mount");
44
+ const tight = (s) => norm(s).replace(/ /g, "");
45
+ const keyOf = (s) => norm(s).replace(/♀/g, " f").replace(/♂/g, " m").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 48) || "x";
46
+ const TITLES = /^(?:professor|prof|mr|mrs|ms|miss|mister|madam|madame|dr|doctor|lord|lady|sir|uncle|aunt|captain|king|queen|prince|princess|general|count|admiral|chief|principal|reverend|saint) /;
47
+
48
+ // Typo distance (with swapped letters counting as one), giving up early past max
49
+ function dist(a, b, max) {
50
+ if (Math.abs(a.length - b.length) > max) return max + 1;
51
+ let two = null, one = Array.from({ length: b.length + 1 }, (_, j) => j);
52
+ for (let i = 1; i <= a.length; i++) {
53
+ const cur = [i];
54
+ let low = i;
55
+ for (let j = 1; j <= b.length; j++) {
56
+ let v = Math.min(one[j] + 1, cur[j - 1] + 1, one[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
57
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) v = Math.min(v, two[j - 2] + 1);
58
+ cur[j] = v;
59
+ if (v < low) low = v;
60
+ }
61
+ if (low > max) return max + 1;
62
+ two = one; one = cur;
63
+ }
64
+ return one[b.length];
65
+ }
66
+
67
+ function buildBank(data) {
68
+ const cats = new Map(), prompts = [];
69
+ const parse = (text) => String(text || "").split("\n").filter(Boolean).map((line) => {
70
+ const [main, tags = ""] = line.split("@");
71
+ const [names, cap] = main.split("#");
72
+ return { names: names.split("|"), cap: cap ? cap.split("|") : null, tags: tags ? tags.split(",") : [] };
73
+ });
74
+ for (const c of data.cats) {
75
+ let rows;
76
+ if (c.from) { // capitals: the source list's capitals, in its order
77
+ const seen = new Set();
78
+ rows = cats.get(c.from).rows.filter((r) => r.cap).map((r) => ({ names: r.cap, tags: r.tags, of: r.names[0] }))
79
+ .filter((r) => !seen.has(tight(r.names[0])) && seen.add(tight(r.names[0])));
80
+ } else rows = parse(c.a);
81
+ const entries = rows.map((r) => ({ name: r.names[0], key: keyOf(r.names[0]), tags: r.tags, of: r.of || null, letter: norm(r.names[0]).charAt(0).toUpperCase() }));
82
+ const forms = new Map(), loose = new Map();
83
+ rows.forEach((r, i) => r.names.forEach((n) => { const f = tight(n); if (f && !forms.has(f)) forms.set(f, i); }));
84
+ rows.forEach((r, i) => r.names.forEach((n) => { // "Professor Snape" also answers to "Snape", unless that means someone else
85
+ const f = norm(n).replace(TITLES, "").replace(/ /g, "");
86
+ if (f && !forms.has(f)) loose.set(f, loose.has(f) && loose.get(f) !== i ? -1 : i);
87
+ }));
88
+ for (const [f, i] of loose) forms.set(f, i);
89
+ const notes = new Map();
90
+ for (const line of String(c.no || "").split("\n").filter(Boolean)) {
91
+ const [names, note] = line.split("=");
92
+ for (const n of names.split("|")) notes.set(tight(n), note);
93
+ }
94
+ const cat = { ...c, rows, entries, forms, notes, byKey: new Map(entries.map((e, i) => [e.key, i])) };
95
+ cats.set(c.id, cat);
96
+ const add = (key, text, hint, pool) => {
97
+ if (pool.length >= MIN_POOL) prompts.push({ key, cat, text, hint: hint || "", pool, rank: new Map(pool.map((i, n) => [i, n])) });
98
+ };
99
+ const all = entries.map((_, i) => i);
100
+ add(c.id, c.prompt || `Name ${c.n}`, c.hint, all);
101
+ for (const [t, phrase] of Object.entries(c.tags || {})) {
102
+ const [p, hint] = phrase.split("|");
103
+ add(`${c.id}~${t}`, p.startsWith("=") ? p.slice(1) : `Name ${c.n} ${p}`, hint, all.filter((i) => entries[i].tags.includes(t)));
104
+ }
105
+ if (c.letters) {
106
+ const by = {};
107
+ for (const i of all) (by[entries[i].letter] = by[entries[i].letter] || []).push(i);
108
+ for (const [L, pool] of Object.entries(by)) if (/^[A-Z]$/.test(L)) add(`${c.id}~starts-${L.toLowerCase()}`, `Name ${c.n} starting with ${L}`, c.hint, pool);
109
+ }
110
+ }
111
+ return { cats, prompts, byKey: new Map(prompts.map((p) => [p.key, p])), packs: data.packs };
112
+ }
113
+
114
+ // Exact spelling, a plural or singular, or the name without a title. -1 = could mean more than one.
115
+ function exact(cat, raw) {
116
+ const n = norm(raw);
117
+ if (!n) return undefined;
118
+ const tries = [];
119
+ for (const b of [n, n.replace(TITLES, "")]) {
120
+ tries.push(b);
121
+ if (b.endsWith("ies")) tries.push(b.slice(0, -3) + "y");
122
+ if (b.endsWith("es")) tries.push(b.slice(0, -2));
123
+ if (b.endsWith("s")) tries.push(b.slice(0, -1)); else tries.push(b + "s");
124
+ }
125
+ for (const t of tries) { const v = cat.forms.get(t.replace(/ /g, "")); if (v !== undefined) return v; }
126
+ return undefined;
127
+ }
128
+ // A misspelling close to one answer (and only one), for "Did you mean…?": up to 1 slip in short words, 3 in long ones.
129
+ // An answer that fits the prompt wins a tie with one that doesn't.
130
+ function closest(cat, raw, prompt) {
131
+ const t = tight(raw), max = t.length <= 3 ? 0 : t.length <= 5 ? 1 : t.length <= 9 ? 2 : 3;
132
+ if (!max) return undefined;
133
+ let best = max + 1, hit, tie = false;
134
+ for (const [form, i] of cat.forms) {
135
+ if (i < 0 || Math.abs(form.length - t.length) > max) continue;
136
+ const d = dist(t, form, Math.min(max, best));
137
+ if (d > best || i === hit) continue;
138
+ if (d < best) { best = d; hit = i; tie = false; continue; }
139
+ const fitsNew = prompt.rank.has(i), fitsOld = prompt.rank.has(hit);
140
+ if (fitsNew && !fitsOld) hit = i; else if (fitsNew === fitsOld) tie = true;
141
+ }
142
+ return best <= max && !tie ? hit : undefined;
143
+ }
144
+ function check(prompt, raw) {
145
+ const cat = prompt.cat, t = tight(raw);
146
+ if (!t) return { ok: false, why: "blank" };
147
+ let i = exact(cat, raw);
148
+ if (i === -1) return { ok: false, why: "vague" };
149
+ if (i === undefined) {
150
+ const note = cat.notes.get(t);
151
+ if (note) return { ok: false, why: "note", note };
152
+ if (cat.from) { // the country (or state) instead of its capital
153
+ const src = BANK.cats.get(cat.from), j = exact(src, raw);
154
+ if (j >= 0 && src.rows[j].cap) return { ok: false, why: "note", note: `${src.entries[j].name} is the ${cat.from === "state" ? "state" : "country"}. Its capital is ${src.rows[j].cap[0]}.` };
155
+ }
156
+ const near = closest(cat, raw, prompt);
157
+ if (near === undefined) return { ok: false, why: "unknown" };
158
+ return { ok: false, why: "close", i: near, entry: cat.entries[near] }; // ask before counting it
159
+ }
160
+ if (!prompt.rank.has(i)) return { ok: false, why: "filter", entry: cat.entries[i] };
161
+ return { ok: true, i, entry: cat.entries[i] };
162
+ }
163
+ // They said yes to "Did you mean…?"
164
+ function confirmClose(prompt, res) {
165
+ return prompt.rank.has(res.i) ? { ok: true, i: res.i, entry: res.entry } : { ok: false, why: "filter", entry: res.entry };
166
+ }
167
+ function whyText(res, raw, prompt) {
168
+ if (res.why === "time") return "Time's up!";
169
+ if (res.why === "blank") return "No answer.";
170
+ if (res.why === "note") return res.note;
171
+ if (res.why === "vague") return "That could mean more than one answer. Be more specific.";
172
+ if (res.why === "filter") {
173
+ const m = prompt.key.match(/~starts-([a-z])$/);
174
+ return m ? `${res.entry.name} doesn't start with ${m[1].toUpperCase()}.` : `${res.entry.name} doesn't fit this one.`;
175
+ }
176
+ return `"${String(raw).trim().slice(0, 40)}" isn't on our list.`;
177
+ }
178
+
179
+ // ---------- Rarity ----------
180
+ // From the list's order: the share of answers more common than this one sets the points
181
+ const STEPS = [0.03, 0.08, 0.15, 0.23, 0.32, 0.42, 0.53, 0.65, 0.8];
182
+ function listPts(prompt, i) {
183
+ const at = prompt.rank.get(i) / prompt.pool.length;
184
+ let n = 0;
185
+ while (n < STEPS.length && at >= STEPS[n]) n++;
186
+ return (n + 1) * 10;
187
+ }
188
+ // From what people here have said: under 0.3% of answers is one of a kind
189
+ const CUTS = [0.2, 0.12, 0.08, 0.05, 0.035, 0.022, 0.013, 0.007, 0.003];
190
+ function sharePts(share) { for (let n = 0; n < CUTS.length; n++) if (share >= CUTS[n]) return (n + 1) * 10; return 100; }
191
+ // The more answers a prompt has collected, the more they count (fully from 70 answers on)
192
+ function blendPts(list, counts, key) {
193
+ const total = Object.values(counts).reduce((a, b) => a + (Number(b) || 0), 0);
194
+ if (total < 10) return list;
195
+ const mine = counts[key] || 0, w = Math.min(1, (total - 10) / 60);
196
+ const live = mine <= 1 && total >= 30 ? 100 : sharePts(mine / total); // nobody else has ever said it
197
+ return Math.max(10, Math.min(100, Math.round(((1 - w) * list + w * live) / 10) * 10));
198
+ }
199
+ function topNames(prompt, counts) {
200
+ const cat = prompt.cat;
201
+ const fromCounts = counts ? Object.entries(counts).filter(([k]) => prompt.rank.has(cat.byKey.get(k))).sort((a, b) => b[1] - a[1]) : [];
202
+ const total = fromCounts.reduce((t, [, n]) => t + n, 0);
203
+ return total >= 10 ? fromCounts.slice(0, 3).map(([k]) => cat.entries[cat.byKey.get(k)].name) : prompt.pool.slice(0, 3).map((i) => cat.entries[i].name);
204
+ }
205
+
206
+ // ---------- Database (all optional: without it the game still works, scored from the list) ----------
207
+ const net = { ready: null, db: null, uid: null, offset: 0 };
208
+ const now = () => Date.now() + net.offset;
209
+ const TS = () => window.firebase.database.ServerValue.TIMESTAMP;
210
+ const within = (p, ms) => Promise.race([p, new Promise((ok) => setTimeout(() => ok(null), ms))]);
211
+ function online() {
212
+ if (!net.ready) {
213
+ net.ready = (async () => {
214
+ const app = await ctx.getFirebase();
215
+ if (!app) return null;
216
+ const user = await ctx.user(app);
217
+ net.db = app.database();
218
+ net.uid = user.uid;
219
+ net.db.ref(".info/serverTimeOffset").on("value", (s) => { net.offset = s.val() || 0; });
220
+ return net;
221
+ })().catch((err) => { console.warn("KrillionWho offline:", err); net.ready = null; return null; });
222
+ }
223
+ return net.ready;
224
+ }
225
+ async function readCounts(promptKey) {
226
+ const f = await within(online(), 2500);
227
+ if (!f) return null;
228
+ try { const s = await within(f.db.ref(`krillionwho/counts/${promptKey}`).once("value"), 1800); return s ? (s.val() || {}) : null; } catch { return null; }
229
+ }
230
+ async function addCount(promptKey, key) {
231
+ const f = await online();
232
+ if (!f) return;
233
+ const FV = window.firebase.database.ServerValue;
234
+ try { await f.db.ref().update({ [`krillionwho/counts/${promptKey}/${key}`]: FV.increment(1), [`krillionwho/last/${f.uid}`]: FV.TIMESTAMP }); } catch { /* too quick after the last one, or offline */ }
235
+ }
236
+
237
+ // ---------- Sound: little 8-bit effects, made on the spot ----------
238
+ const sfx = {
239
+ ac: null, out: null, on: true,
240
+ ready() {
241
+ if (!this.on) return null;
242
+ if (!this.ac) {
243
+ const AC = window.AudioContext || window.webkitAudioContext;
244
+ if (!AC) return null;
245
+ this.ac = new AC();
246
+ this.out = this.ac.createGain();
247
+ this.out.gain.value = 0.45;
248
+ this.out.connect(this.ac.destination);
249
+ }
250
+ if (this.ac.state === "suspended") this.ac.resume().catch(() => {});
251
+ return this.ac;
252
+ },
253
+ note(freq, at, dur, { type = "square", vol = 0.1, to = 0 } = {}) {
254
+ const ac = this.ac, o = ac.createOscillator(), g = ac.createGain(), t = ac.currentTime + at;
255
+ o.type = type;
256
+ o.frequency.setValueAtTime(freq, t);
257
+ if (to) o.frequency.exponentialRampToValueAtTime(to, t + dur);
258
+ g.gain.setValueAtTime(0.0001, t);
259
+ g.gain.exponentialRampToValueAtTime(vol, t + 0.012);
260
+ g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
261
+ o.connect(g); g.connect(this.out);
262
+ o.start(t); o.stop(t + dur + 0.03);
263
+ },
264
+ noise(at, dur, { vol = 0.2, from = 2000, to = 300, q = 1 } = {}) {
265
+ const ac = this.ac, len = Math.ceil(ac.sampleRate * dur), buf = ac.createBuffer(1, len, ac.sampleRate), data = buf.getChannelData(0);
266
+ for (let i = 0; i < len; i++) data[i] = Math.random() * 2 - 1;
267
+ const src = ac.createBufferSource(), f = ac.createBiquadFilter(), g = ac.createGain(), t = ac.currentTime + at;
268
+ src.buffer = buf;
269
+ f.type = "bandpass"; f.Q.value = q;
270
+ f.frequency.setValueAtTime(from, t);
271
+ f.frequency.exponentialRampToValueAtTime(to, t + dur);
272
+ g.gain.setValueAtTime(vol, t);
273
+ g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
274
+ src.connect(f); f.connect(g); g.connect(this.out);
275
+ src.start(t); src.stop(t + dur);
276
+ },
277
+ play(name, arg = 0) {
278
+ if (!this.ready()) return;
279
+ const n = (f, at, dur, o) => this.note(f, at, dur, o);
280
+ if (name === "click") n(700, 0, 0.05, { vol: 0.05 });
281
+ else if (name === "open") { n(520, 0, 0.06, { vol: 0.06 }); n(780, 0.05, 0.09, { vol: 0.06 }); }
282
+ else if (name === "tick") n(440, 0, 0.09, { vol: 0.07 });
283
+ else if (name === "go") { n(880, 0, 0.14, { vol: 0.09 }); n(1320, 0.07, 0.16, { vol: 0.05, type: "triangle" }); }
284
+ else if (name === "hurry") n(1150, 0, 0.05, { vol: 0.045 });
285
+ else if (name === "ping") { n(1250, 0, 0.55, { type: "sine", vol: 0.12, to: 880 }); n(1250, 0.25, 0.45, { type: "sine", vol: 0.035, to: 880 }); } // sonar
286
+ else if (name === "ask") { n(440, 0, 0.1, { vol: 0.07, type: "triangle" }); n(587, 0.1, 0.16, { vol: 0.07, type: "triangle" }); }
287
+ else if (name === "score") {
288
+ const scale = [523, 659, 784, 1047, 1319, 1568, 2093], steps = Math.max(1, Math.round(arg / 15));
289
+ for (let i = 0; i <= Math.min(steps, scale.length - 1); i++) n(scale[i], i * 0.065, 0.16, { vol: 0.075 });
290
+ if (arg >= 100) { [1047, 1319, 1568, 2093].forEach((f, i) => n(f, 0.5 + i * 0.09, 0.4, { vol: 0.07, type: "triangle" })); this.noise(0.5, 1.1, { vol: 0.05, from: 9000, to: 4000, q: 4 }); }
291
+ } else if (name === "miss") n(330, 0, 0.38, { vol: 0.09, to: 110, type: "sawtooth" });
292
+ else if (name === "dive") {
293
+ this.noise(0, 1.5, { vol: 0.14, from: 1200, to: 160 });
294
+ for (let i = 0; i < 6; i++) n(260 + Math.random() * 480, 0.12 + i * 0.2, 0.08, { type: "sine", vol: 0.035, to: 950 });
295
+ } else if (name === "splash") { this.noise(0, 0.7, { vol: 0.26, from: 3000, to: 350, q: 0.7 }); n(180, 0, 0.3, { type: "sine", vol: 0.12, to: 70 }); }
296
+ else if (name === "pass") n(480, 0, 0.12, { vol: 0.07, to: 1000, type: "triangle" });
297
+ else if (name === "fuse") n(arg ? 1500 : 1050, 0, 0.03, { vol: 0.035 });
298
+ else if (name === "pop") { this.noise(0, 0.55, { vol: 0.45, from: 3200, to: 200, q: 0.6 }); n(160, 0, 0.32, { type: "sine", vol: 0.28, to: 45 }); }
299
+ else if (name === "puff") { this.noise(0, 0.3, { vol: 0.16, from: 380, to: 2400, q: 1.4 }); n(200, 0, 0.28, { type: "sine", vol: 0.12, to: 640 }); } // swelling up
300
+ else if (name === "win") [523, 659, 784, 1047, 784, 1047, 1319].forEach((f, i) => n(f, i * 0.11, 0.2, { vol: 0.08 }));
301
+ else if (name === "lose") [392, 370, 349, 311].forEach((f, i) => n(f, i * 0.26, 0.3, { vol: 0.07, type: "sawtooth" }));
302
+ else if (name === "done") [392, 523, 659, 784].forEach((f, i) => n(f, i * 0.12, 0.22, { vol: 0.07, type: "triangle" }));
303
+ else if (name === "line") n(330 * Math.pow(1.122, arg), 0, 0.1, { type: "triangle", vol: 0.06 }); // each tier line passed, a step higher
304
+ else if (name === "thunk") { n(120, 0, 0.24, { type: "sine", vol: 0.22, to: 52 }); this.noise(0, 0.3, { vol: 0.1, from: 700, to: 120 }); }
305
+ },
306
+ };
307
+
308
+ // ---------- Pixel art ----------
309
+ // Rows of letters, one per pixel ("." is empty), turned into an SVG; runs of one color become one rectangle.
310
+ // A color can name a class after it ("#fcd34d pY") so the CSS can recolor those pixels.
311
+ function sprite(rows, colors, cls) {
312
+ let rects = "";
313
+ rows.forEach((row, y) => {
314
+ for (let x = 0; x < row.length;) {
315
+ let w = 1;
316
+ while (x + w < row.length && row[x + w] === row[x]) w++;
317
+ const [fill, k] = (colors[row[x]] || "").split(" ");
318
+ if (fill) rects += `<rect x="${x}" y="${y}" width="${w}" height="1" fill="${fill}"${k ? ` class="${k}"` : ""}/>`;
319
+ x += w;
320
+ }
321
+ });
322
+ return `<svg class="${cls}" viewBox="0 0 ${rows[0].length} ${rows.length}" shape-rendering="crispEdges" aria-hidden="true">${rects}</svg>`;
323
+ }
324
+ const GLYPHS = {
325
+ K: ["X...X", "X..X.", "X.X..", "XX...", "X.X..", "X..X.", "X...X"],
326
+ R: ["XXXX.", "X...X", "X...X", "XXXX.", "X.X..", "X..X.", "X...X"],
327
+ I: ["XXXXX", "..X..", "..X..", "..X..", "..X..", "..X..", "XXXXX"],
328
+ L: ["X....", "X....", "X....", "X....", "X....", "X....", "XXXXX"],
329
+ O: [".XXX.", "X...X", "X...X", "X...X", "X...X", "X...X", ".XXX."],
330
+ N: ["X...X", "XX..X", "XX..X", "X.X.X", "X..XX", "X..XX", "X...X"],
331
+ W: ["X...X", "X...X", "X...X", "X.X.X", "X.X.X", "XX.XX", "X...X"],
332
+ H: ["X...X", "X...X", "X...X", "XXXXX", "X...X", "X...X", "X...X"],
333
+ };
334
+ const LOGO = (() => {
335
+ const word = "KRILLIONWHO", rows = Array.from({ length: 7 }, (_, y) => [...word].map((c) => GLYPHS[c][y]).join("."));
336
+ return `<div class="kw-logo" role="img" aria-label="KrillionWho">${sprite(rows, { X: "#22d3ee" }, "kw-logo-cyan")}${sprite(rows, { X: "#ff5c9f" }, "kw-logo-pink")}</div>`;
337
+ })();
338
+ const KRILL = sprite([
339
+ "........aa..",
340
+ ".......a....",
341
+ "...RRRRa....",
342
+ "..RrrrrRR...",
343
+ ".RrrrrrrRe..",
344
+ ".Rrr..RrrR..",
345
+ "Rrr....RrR..",
346
+ "Rr......R...",
347
+ "Rr..........",
348
+ ".Rr.........",
349
+ "..RR........",
350
+ ], { R: "#e11d48", r: "#fb7185", a: "#fda4af", e: "#1f0a14" }, "kw-krill-art");
351
+ const BOAT = sprite([
352
+ ".........FFFFm............",
353
+ "........FFFFFm............",
354
+ "..........FFFm............",
355
+ ".............m............",
356
+ ".............m............",
357
+ "........CCCCCCCCC.........",
358
+ "........CwwCwwCCC.........",
359
+ "........CwwCwwCCC.........",
360
+ "..HHHHHHHHHHHHHHHHHHHHHHH.",
361
+ ".HHHHHHHHHHHHHHHHHHHHHHHHH",
362
+ "..HHHHHHHHHHHHHHHHHHHHHHH.",
363
+ "...HHHHHHHHHHHHHHHHHHHHH..",
364
+ ".....HHHHHHHHHHHHHHHHH....",
365
+ ], { F: "#f472b6", m: "#0f1d2e", C: "#14263d", w: "#7dd3fc", H: "#0c1a2b" }, "kw-boat-art");
366
+ const CLOUD = (shade) => sprite([
367
+ "..........WWWWW...........",
368
+ "........WWWWWWWWW.........",
369
+ "....WWWWWWWWWWWWWWWW......",
370
+ "..WWWWWWWWWWWWWWWWWWWWW...",
371
+ "WWWWWWWWWWWWWWWWWWWWWWWWWW",
372
+ "GGGGGGGGGGGGGGGGGGGGGGGGGG",
373
+ ], { W: "#ffffff", G: shade }, "kw-cloud-art");
374
+ const FISH = sprite([".FFFF.F", "FFFFFFF", ".FFFF.F"], { F: "#0a2038" }, "kw-fish-art");
375
+ const JELLY = sprite([
376
+ "..JJJJJ..",
377
+ ".JjjjjjJ.",
378
+ "JjjjjjjjJ",
379
+ "JJJJJJJJJ",
380
+ ".t.t.t.t.",
381
+ ".t..t..t.",
382
+ "..t..t...",
383
+ ".t..t..t.",
384
+ ], { J: "#f0abfc", j: "#fae8ff", t: "#e879f9" }, "kw-jelly-art");
385
+ const ANGLER = sprite([
386
+ "......L.........",
387
+ ".......s........",
388
+ "........s.......",
389
+ "....DDDDDD....D.",
390
+ "..DDDDDDDDDD.DD.",
391
+ ".DeDDDDDDDDDDDD.",
392
+ "DzzDDDDDDDDDDDD.",
393
+ ".DzDDDDDDDDD.DD.",
394
+ "..DDDDDDDDDD..D.",
395
+ "....DDDDDD......",
396
+ ], { D: "#0d1526", e: "#a5f3fc", z: "#e5e7eb", s: "#334155", L: "#fde047" }, "kw-angler-art");
397
+ const CHEST = sprite([
398
+ "..GGGGGGGGGG..",
399
+ ".GBBBBBBBBBBG.",
400
+ "GBBBBBBBBBBBBG",
401
+ "GGGGGGyyGGGGGG",
402
+ "GBBBBByyBBBBBG",
403
+ "GBBBBBBBBBBBBG",
404
+ "GGGGGGGGGGGGGG",
405
+ ], { G: "#f59e0b", B: "#78350f", y: "#fde68a" }, "kw-chest-art");
406
+ // The pufferfish: a calm fish most of the time, then a spiky ball when its time runs low. Both sit on one 34×28 grid so
407
+ // the pixels line up when it puffs up, and the p… classes let the CSS turn it red as it heats up.
408
+ const PUFF_COLORS = { L: "#fff1a8 pL", Y: "#fcd34d pY", D: "#f59e0b pD", R: "#b45309 pR", W: "#fff7e6 pW", w: "#f2d7a6 pw", S: "#a16207 pS",
409
+ F: "#f97316 pF", f: "#fdba74 pf", T: "#c2410c pT", t: "#fb923c pt", m: "#fb923c pm", E: "#fff", h: "#fff", P: "#0f172a", O: "#5b2a0a", M: "#7c2d12", K: "#fb7185" };
410
+ const PUFFER = sprite([
411
+ "............t...t.................", "........t...T...T...t.............", "........T...TT.TT...T.............", "........TT.DDDDDDD.TT.............",
412
+ "....t....DDYYYYYYYDD....t.........", ".....TTDDYYYYYSYYYYYRRTT..........", ".....TDOOLLYYYYYYYSYYDRT..........", "..t..DOEEEOYSYYYYYYYYDDR..........",
413
+ "...TTOEEEEEOYYYYSYYYYSDR.....FF...", "...TDOPPPEEOYYYYYYYYYDDDR...FFF...", "....DOPhPEEOYYYYYYYYYDDDR..FFFfF..", "....DOPPPEEOYYYSYYYSYDDSR.FFfffF..",
414
+ "...DYYOEEEOYYYYYYYYYDDDDRRfffffF..", ".mmDYYYOOOYYYYYYYYYDDDDDRRFFFFFFF.", "mMMDYYYYYYYYYYYFYYYDDDSDRRffffffF.", "mMMwWWWWKKYYYYfFFYDDDDDRRRFFfffF..",
415
+ ".mm.wWWWWWWWWWWWWDDDDDDRR.FFFFFF..", "....wWWWWWWWWWWWWWWwwwwww..FfFFF..", "...TwWWWWWWWWWWWWWwwwwwww...FFF...", "...TTwWWWWWWWWWWWwwwwwww.....FF...",
416
+ "..t..wWWWWWWWWWwwwwwwwww..........", ".....TRWWWWWWwwwwwwwwwRT..........", ".....TTRRwwwwwwwwwwwRRTT..........", "....t....RRwwwwwwwRR....t.........",
417
+ "........TT.RRRRRRR.TT.............", "........T...TT.TT...T.............", "........t...T...T...t.............", "............t...t.................",
418
+ ], PUFF_COLORS, "kw-puff-art kw-puff-ball");
419
+ const PUFF_CALM = sprite([...Array(5).fill(".".repeat(34)),
420
+ ".................FF...............", "...............FFFf...............", "..........DDDDD.Fff...............", ".......DDSYYYYYSDRf...............",
421
+ ".....DDLLYYSYYYYYYRR..........FF..", "....DOOOLYYYYYYYYYSDR........FFFF.", "...DOEEEOYYYYSYYYYYDDR......FFffF.", "..DYPPhEOYYYYYYYSYYDSDRR...FFfffFF",
422
+ "..DYPPPEOYYYYYYYYYDDDDRRRRFffFFFFF", "..DYYOOOYYYYYYYYYDDDDRRRRRfffffffF", "mMwWWWWWWWWWYYYYDDDDDRRRRRFFFffffF", "m.wWWWWKWWWfFFFWWwwwwwww...FfFFFFF",
423
+ "...wWWWWWWWfFfFWwwwwww......FffFF.", "....wWWWWWWWfFwwwwwww........FffF.", ".....RRWWWwwwwwwwwRR..........FF..", ".......RRRwwwwwRRRF...............",
424
+ "..........RRRRR.FFF...............", "...............FFFF...............", ".................FF...............", ...Array(4).fill(".".repeat(34)),
425
+ ], PUFF_COLORS, "kw-puff-art kw-puff-calm");
426
+ // Puffer Party players: everyone at the table gets their own sea creature, floating in a bubble
427
+ const CRITTERS = [
428
+ sprite([".CC........CC.", "CcCC......CCcC", "CccC......CccC", ".CC..e..e..CC.", "..C..R..R..C..", "..CRRRRRRRRC..", "..RRRRRRRRRR..",
429
+ ".RRrrrrrrrrRR.", ".RRRRRRRRRRRR.", "..RRRRRRRRRR..", ".R.R.R..R.R.R.", "R.R.R....R.R.R"], { C: "#dc2626", c: "#fecaca", R: "#ef4444", r: "#fca5a5", e: "#1f0a14" }, "kw-critter"),
430
+ sprite([".....PPPP.....", "...PPPPPPPP...", "..PPpPPPPPPP..", "..PpPPPPPPPP..", "..PwePPPPweP..", "..PPPPPPPPPP..", "..PPPPPPPPPP..",
431
+ "...PPPPPPPP...", "..PP.PPPP.PP..", ".PP..P..P..PP.", ".P..PP..PP..P.", "P...P....P...P"], { P: "#a855f7", p: "#d8b4fe", w: "#fff", e: "#1e1b4b" }, "kw-critter"),
432
+ sprite(["....JJJJJJ....", "..JJjjjjjjJJ..", ".JjjjjjjjjjjJ.", ".JjwejjjjwejJ.", "JjjjjjjjjjjjjJ", "JJJJJJJJJJJJJJ",
433
+ ".t.t.t..t.t.t.", "..t.t..t..t.t.", ".t...t..t..t..", "..t....t....t."], { J: "#ec4899", j: "#f9a8d4", w: "#fff", e: "#500724", t: "#f472b6" }, "kw-critter"),
434
+ sprite(["......YYY.....", ".....YYYYY....", "YYYYYYeYYY....", ".....YYYYY....", "......YYYYy...", ".....YYYYYyy..", ".....yYYYYYy..",
435
+ "......YYYYYy..", ".......YYYY...", "........YYY...", ".........YY...", ".......Y..Y...", "........YY...."], { Y: "#facc15", y: "#fde68a", e: "#422006" }, "kw-critter"),
436
+ sprite(["....SSSSS.....", "..SSsSSsSS.KK.", ".SSsSSsSSsSKKe", ".SsSSsSSsSSKKK", "GGGGGGGGGGGG..", ".KK......KK...", "KK........KK.."],
437
+ { S: "#15803d", s: "#4ade80", G: "#bef264", K: "#86efac", e: "#052e16" }, "kw-critter"),
438
+ sprite([".....OOOOO....", ".O..OOWOOWOO..", ".OOOOOWOOWOeO.", ".OOOOOWOOWOOOO", ".O..OOWOOWOO..", ".....OOOOO...."], { O: "#f97316", W: "#fff", e: "#111827" }, "kw-critter"),
439
+ sprite([".........w.w..", "..........w...", ".....BBBBBB...", "B..BBBBBBBBBB.", "BBBBBBBBBBBeB.", ".BBBBbbbbbbbBB", "..BBBbbbbbbbB.", ".....BBBBBB..."],
440
+ { B: "#3b82f6", b: "#bfdbfe", w: "#93c5fd", e: "#0f172a" }, "kw-critter"),
441
+ sprite(["......D.......", ".....DD.......", "D...DDDDDDD...", "DD.DDDDDDDDDD.", ".DDDDDDDDDDeDD", "DD.DLLLLLLLLL.", "D....LLLLLL..."],
442
+ { D: "#64748b", L: "#e2e8f0", e: "#0f172a" }, "kw-critter"),
443
+ ];
444
+
445
+ // ---------- The scene: one tall ocean, and a camera that moves down it ----------
446
+ const sc = { H: 0, sky: 0, at: null };
447
+ const deepAt = (m) => `top:calc(var(--sky) + ${Math.round(m * S)}px)`;
448
+ function worldHtml() {
449
+ const school = (m, n, dir, speed, size) => `<div class="kw-school ${dir}" style="${deepAt(m)};--speed:${speed}s;--size:${size}px">` +
450
+ Array.from({ length: n }, (_, i) => `<i style="top:${(i * 17) % 46}px;animation-delay:-${((i * speed) / n).toFixed(1)}s">${FISH}</i>`).join("") + "</div>";
451
+ const ticks = Array.from({ length: MAX_DEPTH / 1000 + 1 }, (_, k) => `<span style="${deepAt(k * 1000)}">${(k * 1000).toLocaleString()}m</span>`).join("");
452
+ const zones = ZONES.map(([m, label]) => `<p class="kw-zone" style="${deepAt(m + (m ? 0 : 6))}">${label}<small>${fmtM(m)}</small></p>`).join("");
453
+ return `<div class="kw-sky"><div class="kw-sun"></div>
454
+ <div class="kw-cloud c1">${CLOUD("#e3edf3")}</div><div class="kw-cloud c2">${CLOUD("#e8f0f5")}</div><div class="kw-cloud c3">${CLOUD("#dde9f0")}</div></div>
455
+ <div class="kw-water"></div><div class="kw-snow"></div><div class="kw-rays"></div><div class="kw-surface"></div>
456
+ <div class="kw-boat">${BOAT}</div>
457
+ ${school(35, 7, "right", 26, 22)}${school(95, 9, "left", 34, 16)}${school(180, 12, "right", 40, 12)}${school(320, 6, "left", 30, 20)}
458
+ <div class="kw-jelly" style="${deepAt(420)};left:72%">${JELLY}</div><div class="kw-jelly j2" style="${deepAt(640)};left:12%">${JELLY}</div>
459
+ <div class="kw-jelly j3" style="${deepAt(930)};left:82%">${JELLY}</div>
460
+ <div class="kw-whale" style="${deepAt(1250)}"><svg viewBox="0 0 220 70" aria-hidden="true"><path d="M8 38c18-24 70-32 120-26 26 3 44 14 56 24l20-18c4 12 2 24-6 32 7 6 12 14 12 20-12-6-24-7-34-4-14 10-38 16-66 16C60 82 22 64 8 38Z" fill="#06182c"/></svg></div>
461
+ <div class="kw-angler" style="${deepAt(1900)};left:74%">${ANGLER}</div><div class="kw-angler a2" style="${deepAt(3100)};left:10%">${ANGLER}</div>
462
+ <div class="kw-angler" style="${deepAt(4700)};left:68%">${ANGLER}</div>
463
+ <div class="kw-glow" style="${deepAt(2800)}"></div>
464
+ <div class="kw-trench l" style="${deepAt(5600)}"></div><div class="kw-trench r" style="${deepAt(5600)}"></div>
465
+ <div class="kw-floor" style="${deepAt(MAX_DEPTH)}"><div class="kw-chest" id="kw-chest">${CHEST}</div><p>7,000m · the trench floor</p></div>
466
+ ${zones}<div class="kw-ruler">${ticks}</div>`;
467
+ }
468
+ function sceneHtml() {
469
+ return `<div class="kw-stage" id="kw-stage" data-mode="home">
470
+ <div class="kw-world" id="kw-world">${worldHtml()}</div>
471
+ <div class="kw-krill" id="kw-krill">${KRILL}<span class="kw-trail"><i></i><i></i><i></i><i></i></span></div>
472
+ <div class="kw-fx" id="kw-fx" aria-hidden="true"></div>
473
+ <div class="kw-ui" id="kw-ui"></div>
474
+ <div class="kw-modal" id="kw-modal" hidden></div>
475
+ <div class="kw-scan" aria-hidden="true"></div>
476
+ <div class="kw-corner left"><button class="kw-icon" type="button" data-act="menu" title="Menu" aria-label="Menu"><span class="kw-burger"></span></button></div>
477
+ <div class="kw-corner right">
478
+ <button class="kw-icon" type="button" data-act="sound" id="kw-sound" title="Sound on/off" aria-label="Sound on or off"></button>
479
+ <button class="kw-icon" type="button" data-act="board" title="Today's leaderboard" aria-label="Today's leaderboard">🏆</button>
480
+ </div>
481
+ </div>`;
482
+ }
483
+ function soundIcon() { const b = $("kw-sound"); if (b) { b.textContent = sfx.on ? "🔊" : "🔇"; b.setAttribute("aria-pressed", String(sfx.on)); } }
484
+ function layout() {
485
+ const stage = $("kw-stage");
486
+ if (!stage || !stage.clientHeight) return;
487
+ sc.H = stage.clientHeight;
488
+ sc.sky = Math.round(sc.H * 0.58);
489
+ stage.style.setProperty("--sky", `${sc.sky}px`);
490
+ stage.style.setProperty("--m", `${S}px`); // pixels per meter, for the ocean's sizes in the stylesheet
491
+ camTo(sc.at, 0);
492
+ }
493
+ // The camera: null = up in the sky (the home screen); a number = that many meters down
494
+ function camY(m) { return m === null ? 0 : sc.sky - sc.H * 0.17 + Math.min(m, MAX_DEPTH) * S; }
495
+ function camTo(m, ms = 1700) {
496
+ sc.at = m;
497
+ const w = $("kw-world");
498
+ if (!w) return;
499
+ if (calm()) ms = 0;
500
+ w.style.transition = ms ? `transform ${ms}ms cubic-bezier(.55, 0, .2, 1)` : "none";
501
+ w.style.transform = `translate3d(0, ${-Math.round(camY(m))}px, 0)`;
502
+ }
503
+ function setMode(mode) { const stage = $("kw-stage"); if (stage) stage.dataset.mode = mode; }
504
+ function uiHtml(html) { const el = $("kw-ui"); if (el) el.innerHTML = html; }
505
+
506
+ // Numbers that count up instead of jumping
507
+ function countTo(el, from, to, ms, fmt) {
508
+ if (!el) return;
509
+ if (calm() || from === to) { el.textContent = fmt(to); return; }
510
+ const t0 = performance.now();
511
+ const step = (t) => {
512
+ const k = Math.min(1, (t - t0) / ms), e = 1 - Math.pow(1 - k, 3);
513
+ el.textContent = fmt(Math.round(from + (to - from) * e));
514
+ if (k < 1) requestAnimationFrame(step);
515
+ };
516
+ requestAnimationFrame(step);
517
+ setTimeout(() => { el.textContent = fmt(to); }, ms + 120); // animation frames stop in background tabs: land on the number anyway
518
+ }
519
+ // The points pop out (of the landed answer, or the krill) with sparks in the tier's color
520
+ function burst(pts, x, y) {
521
+ const fx = $("kw-fx"), krill = $("kw-krill"), stage = $("kw-stage");
522
+ if (!fx || !krill) return;
523
+ if (x === undefined) { const k = krill.getBoundingClientRect(), s = stage.getBoundingClientRect(); x = k.left - s.left + k.width / 2; y = k.top - s.top; }
524
+ const [name, emoji] = TIERS[pts];
525
+ const pop = document.createElement("div");
526
+ pop.className = `kw-pop t${pts}`;
527
+ pop.style.left = `${x}px`;
528
+ pop.style.top = `${y}px`;
529
+ pop.innerHTML = `<b>+${pts}</b><small>${emoji} ${name.toUpperCase()}</small>`;
530
+ fx.appendChild(pop);
531
+ const sparks = pts >= 90 ? 30 : pts >= 50 ? 20 : pts ? 12 : 0;
532
+ for (let i = 0; i < sparks; i++) {
533
+ const d = document.createElement("i"), a = Math.random() * Math.PI * 2, r = 50 + Math.random() * (pts >= 90 ? 170 : 100);
534
+ d.className = `kw-spark t${pts}`;
535
+ d.style.cssText = `left:${x}px;top:${y + 16}px;--dx:${(Math.cos(a) * r).toFixed(0)}px;--dy:${(Math.sin(a) * r).toFixed(0)}px;animation-delay:${(Math.random() * 0.12).toFixed(2)}s`;
536
+ fx.appendChild(d);
537
+ }
538
+ if (pts >= 100) { stage.classList.remove("legend"); void stage.offsetWidth; stage.classList.add("legend"); }
539
+ if (!pts) { krill.classList.remove("sad"); void krill.offsetWidth; krill.classList.add("sad"); }
540
+ setTimeout(() => { pop.remove(); fx.querySelectorAll(".kw-spark").forEach((el) => el.remove()); }, 2300);
541
+ }
542
+ // Your answer sinks: the camera dives with it past a dashed line for every tier it beats, and it lands on its own tier.
543
+ // The lines are part of the ocean, so they fly past along with the fish while the answer rides in the middle of the screen.
544
+ function sink(text, pts, before) {
545
+ return new Promise((done) => {
546
+ const stage = $("kw-stage"), fx = $("kw-fx"), card = $("kw-card"), world = $("kw-world");
547
+ if (!stage || !fx || !card || !world) return done();
548
+ clearSink();
549
+ const s = stage.getBoundingClientRect(), c = card.getBoundingClientRect(), H = s.height;
550
+ const anchor = Math.round(H * (H < 640 ? 0.36 : 0.42)), from = before * 10, to = (before + pts) * 10, steps = pts / 10;
551
+ // line k reaches the anchor row just as the camera gets k*100 m deeper (the camera's own row is 17% down)
552
+ const offset = anchor - H * 0.17;
553
+ world.insertAdjacentHTML("beforeend", `<div class="kw-lines" id="kw-lines">${Array.from({ length: Math.min(10, steps + 1) }, (_, n) => {
554
+ const p = (n + 1) * 10, [name, emoji] = TIERS[p];
555
+ return `<div class="kw-line t${p}${n >= steps ? " beyond" : ""}" style="top:calc(var(--sky) + ${Math.round((from + (n + 1) * 100) * S + offset)}px)"><span>${emoji} ${name.toUpperCase()} · ${p}</span></div>`;
556
+ }).join("")}</div>`);
557
+ const lineEls = [...$("kw-lines").children];
558
+ const fizz = Array.from({ length: 16 }, () => `<i style="left:${(Math.random() * 100).toFixed(0)}%;width:${(3 + Math.random() * 6).toFixed(0)}px;animation-delay:-${(Math.random() * 1.2).toFixed(2)}s"></i>`).join("");
559
+ const rush = Array.from({ length: 16 }, () => `<i style="left:${(Math.random() * 100).toFixed(0)}%;animation-delay:-${(Math.random() * 0.5).toFixed(2)}s;height:${(60 + Math.random() * 160).toFixed(0)}px"></i>`).join("");
560
+ const box = document.createElement("div");
561
+ box.className = `kw-sink${pts >= 50 ? " fast" : ""}`;
562
+ box.id = "kw-sink";
563
+ box.innerHTML = `<div class="kw-rush">${rush}</div>` +
564
+ `<div class="kw-plaque${pts ? "" : " miss"} t${pts}" style="top:${Math.round(Math.min(c.bottom - s.top, anchor))}px"><span>“${esc(text)}”</span><em>${pts ? "▼" : "~"}</em><i class="kw-rider">${KRILL}</i><b class="kw-fizz">${fizz}</b></div>`;
565
+ fx.appendChild(box);
566
+ stage.classList.add("sinking");
567
+ card.classList.add("sunk");
568
+ const plaque = box.querySelector(".kw-plaque");
569
+ requestAnimationFrame(() => { plaque.style.top = `${anchor}px`; }); // drops onto the anchor row, then rides there
570
+ const dur = calm() ? 0 : pts ? 600 + pts * 13 : 0;
571
+ const depthEl = $("kw-depth"), scoreEl = $("kw-score");
572
+ let passed = 0, landed = false;
573
+ const land = () => {
574
+ if (landed) return;
575
+ landed = true;
576
+ sc.at = to;
577
+ world.style.transition = "none";
578
+ world.style.transform = `translate3d(0, ${-Math.round(camY(to))}px, 0)`;
579
+ if (depthEl) depthEl.textContent = fmtM(to);
580
+ if (scoreEl) scoreEl.textContent = String(before + pts);
581
+ lineEls.forEach((l, n) => { if (n < steps) l.classList.add("passed"); });
582
+ box.classList.remove("fast");
583
+ if (pts) {
584
+ lineEls[steps - 1].classList.add("hit");
585
+ plaque.classList.add("land");
586
+ sfx.play("thunk");
587
+ sfx.play("score", pts);
588
+ if (pts >= 60 && pts < 100) { stage.classList.remove("thud"); void stage.offsetWidth; stage.classList.add("thud"); }
589
+ } else { plaque.classList.add("float"); sfx.play("miss"); }
590
+ setTimeout(() => {
591
+ const r = plaque.getBoundingClientRect();
592
+ burst(pts, r.left - s.left + r.width / 2, r.top - s.top - 6);
593
+ }, 40);
594
+ setTimeout(done, pts ? 650 : 1000);
595
+ };
596
+ if (!dur) return setTimeout(land, pts ? 0 : 300);
597
+ sfx.play("splash");
598
+ world.style.transition = "none";
599
+ const ease = (k) => (k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2); // speeds up, then slows to a stop
600
+ const t0 = performance.now();
601
+ const frame = (t) => {
602
+ if (landed) return;
603
+ const k = Math.min(1, (t - t0) / dur), e = ease(k), d = from + (to - from) * e;
604
+ world.style.transform = `translate3d(0, ${-Math.round(camY(d))}px, 0)`;
605
+ if (depthEl) depthEl.textContent = fmtM(d);
606
+ if (scoreEl) scoreEl.textContent = String(Math.round(before + pts * e));
607
+ while (passed < steps && d >= from + (passed + 1) * 100 - 0.5) { lineEls[passed].classList.add("passed"); sfx.play("line", passed); passed++; }
608
+ if (k < 1) requestAnimationFrame(frame); else land();
609
+ };
610
+ requestAnimationFrame(frame);
611
+ setTimeout(land, dur + 600); // animation frames stop in background tabs
612
+ });
613
+ }
614
+ function clearSink() {
615
+ const old = $("kw-sink");
616
+ if (old) old.remove();
617
+ const lines = $("kw-lines");
618
+ if (lines) lines.remove();
619
+ const stage = $("kw-stage");
620
+ if (stage) stage.classList.remove("sinking", "thud");
621
+ }
622
+ function diveKrill() {
623
+ const krill = $("kw-krill");
624
+ if (!krill) return;
625
+ krill.classList.remove("diving"); void krill.offsetWidth; krill.classList.add("diving");
626
+ }
627
+
628
+ // ---------- Sheets (the Play menu and other pop-ups) ----------
629
+ let afterName = null;
630
+ function openSheet(html, back) {
631
+ const m = $("kw-modal");
632
+ m.hidden = false;
633
+ m.innerHTML = `<div class="kw-sheet" role="dialog" aria-modal="true">${back ? `<button class="kw-back" type="button" data-act="${back}">◀ BACK</button>` : ""}` +
634
+ `<button class="kw-x" type="button" data-act="close" aria-label="Close">✕</button>${html}</div>`;
635
+ sfx.play("open");
636
+ const first = m.querySelector("input, .kw-mode, .kw-btn");
637
+ if (first && !matchMedia("(pointer: coarse)").matches) first.focus();
638
+ }
639
+ function closeSheet() { const m = $("kw-modal"); if (m) { m.hidden = true; m.innerHTML = ""; } if (ui.boardRef && ui.screen !== "results") { ui.boardRef.off(); ui.boardRef = null; } }
640
+ function sheetNote(text, bad) { const n = $("kw-sheet-note"); if (n) { n.textContent = text || ""; n.classList.toggle("err", !!bad); } }
641
+
642
+ // ---------- Names ----------
643
+ function cleanName(raw) {
644
+ const name = String(raw || "").replace(/\s+/g, " ").trim();
645
+ if (!name) return { error: "Pick a name first." };
646
+ if ([...name].length > 16) return { error: "Names can be up to 16 characters." };
647
+ return { name: ctx.maskSlurs(name) };
648
+ }
649
+ // Your diver name is your own (any name, Richard included); it starts out as your chat name until you pick one here
650
+ function myName() { return cleanName(ctx.store.get(KW_NAME_KEY, "") || ctx.store.get(NAME_KEY, "")).name || ""; }
651
+ function askName(then, why) {
652
+ const have = myName();
653
+ if (have) return then(have);
654
+ afterName = then;
655
+ openSheet(`<p class="kw-sheet-title">WHAT'S YOUR DIVER NAME?</p><p class="kw-muted">${esc(why)}</p>
656
+ <form class="kw-inline" data-form="name" autocomplete="off"><input id="kw-name-in" maxlength="16" spellcheck="false" autocomplete="off" placeholder="your name" aria-label="Your name">
657
+ <button class="kw-btn" type="submit">GO ▶</button></form><p class="kw-note" id="kw-sheet-note" aria-live="polite"></p>`);
658
+ }
659
+
660
+ // ---------- Home ----------
661
+ const ui = { screen: null, pack: "all", boardRef: null, timers: new Set() };
662
+ function every(ms, fn) { const t = setInterval(fn, ms); ui.timers.add(t); return t; }
663
+ function stopTimers() { for (const t of ui.timers) clearInterval(t); ui.timers.clear(); }
664
+ function dailyProgress() { const d = ctx.store.get(DAILY_KEY, null); return d && d.date === dateStr() && Array.isArray(d.keys) ? d : null; }
665
+ function streakNow() {
666
+ const s = ctx.store.get(STATS_KEY, {}), today = dateStr();
667
+ return s.streak && (s.last === today || s.last === dayBefore(today)) ? s.streak : 0;
668
+ }
669
+ function renderHome(rising) {
670
+ endDive();
671
+ closeSheet();
672
+ ui.screen = "home";
673
+ setMode("home");
674
+ camTo(null, rising ? 2600 : 0);
675
+ const prog = dailyProgress(), streak = streakNow(), room = ctx.store.get(ROOM_KEY, "");
676
+ uiHtml(`<div class="kw-home">
677
+ <div class="kw-hero">${LOGO}<p class="kw-subtitle">THE DAILY DIVE</p><p class="kw-tagline">7 prompts · 25 seconds each · rarer answers sink deeper</p></div>
678
+ <div class="kw-menu">
679
+ <button class="kw-howto" type="button" data-act="howto">▸ HOW TO PLAY</button>
680
+ ${prog && prog.done ? `<p class="kw-today">TODAY: ${fmtM(prog.total * 10)} · ${esc(zoneAt(prog.total * 10)).toUpperCase()}</p>` : ""}
681
+ ${room ? `<button class="kw-btn ghost" type="button" data-act="pp-rejoin">BACK TO ROOM ${esc(room)}</button>` : ""}
682
+ <button class="kw-play" type="button" data-act="play">▶ PLAY ◀</button>
683
+ <div class="kw-foot"><span>DIVE #${dayNumber(dateStr())}</span>${streak ? `<span>🔥 ${streak} DAY STREAK</span>` : ""}<span>${BANK.prompts.length} PROMPTS · ${BANK.cats.size} CATEGORIES</span></div>
684
+ </div></div>`);
685
+ }
686
+ function playSheet() {
687
+ const prog = dailyProgress(), done = prog && prog.done, going = prog && !done && prog.answers.length > 0;
688
+ openSheet(`<p class="kw-sheet-title">PICK YOUR DIVE</p>
689
+ <button class="kw-mode" type="button" data-act="daily"><span class="kw-mode-art">${KRILL}</span>
690
+ <span class="kw-mode-text"><b>THE DAILY DIVE</b><small>7 prompts · the same for everyone · one try a day</small></span><em>${done ? "SEE MY DIVE" : going ? "KEEP DIVING" : `DIVE #${dayNumber(dateStr())} ▼`}</em></button>
691
+ <button class="kw-mode" type="button" data-act="free-menu"><span class="kw-mode-art">${FISH}</span>
692
+ <span class="kw-mode-text"><b>FREE PLAY</b><small>Unlimited dives · themed packs · old days</small></span><em>∞</em></button>
693
+ <button class="kw-mode" type="button" data-act="pp-menu"><span class="kw-mode-art">${PUFFER}</span>
694
+ <span class="kw-mode-text"><b>PUFFER PARTY</b><small>Pass the pufferfish before it pops · 2 to 8 players</small></span><em id="kw-waiting">PLAY</em></button>`);
695
+ online().then(async (f) => { // how many people are waiting in open rooms
696
+ if (!f) return;
697
+ try {
698
+ const s = await f.db.ref("krillionwho/lobbies").orderByChild("ts").startAt(now() - 15 * 60e3).once("value");
699
+ let n = 0;
700
+ s.forEach((c) => { n += Number((c.val() || {}).n) || 0; });
701
+ const el = $("kw-waiting");
702
+ if (el && n) el.textContent = `● ${n} WAITING`;
703
+ } catch { /* older rules */ }
704
+ });
705
+ }
706
+ function freeSheet() {
707
+ const packs = [["all", "Everything"], ...BANK.packs].map(([id, label]) => `<button class="kw-tile${ui.pack === id ? " on" : ""}" type="button" data-act="free" data-pack="${id}">${esc(label).toUpperCase()}</button>`).join("");
708
+ const today = dateStr();
709
+ const past = Array.from({ length: 6 }, (_, n) => dayBefore(today, n + 1)).map((d) =>
710
+ `<button class="kw-tile" type="button" data-act="past" data-date="${d}">${dayNumber(d) >= 1 ? `DIVE #${dayNumber(d)}` : "PRACTICE"}<small>${esc(fmtDate(d))}</small></button>`).join("");
711
+ openSheet(`<p class="kw-sheet-title">FREE PLAY ∞</p><p class="kw-muted">Seven prompts, as many dives as you want. Doesn't count for the leaderboard.</p>
712
+ <p class="kw-label">THEMED PACKS</p><div class="kw-tiles">${packs}</div>
713
+ <p class="kw-label">ARCHIVE ↺</p><div class="kw-tiles">${past}</div>`, "play");
714
+ }
715
+ function partySheet() {
716
+ const room = ctx.store.get(ROOM_KEY, "");
717
+ openSheet(`<p class="kw-sheet-title"><span class="kw-title-puff">${PUFFER}</span>PUFFER PARTY</p>
718
+ <p class="kw-muted">When the pufferfish comes to you, name something that fits the prompt to pass it on. The fuse keeps burning, answers can't repeat, and if it pops on you, you lose a life. Last diver standing wins.</p>
719
+ ${room ? `<button class="kw-btn wide" type="button" data-act="pp-rejoin">BACK TO ROOM ${esc(room)}</button>` : ""}
720
+ <div class="kw-two"><button class="kw-btn" type="button" data-act="pp-create">CREATE A ROOM</button><button class="kw-btn ghost" type="button" data-act="pp-quick">QUICK PLAY</button></div>
721
+ <form class="kw-inline" data-form="pp-join" autocomplete="off"><input id="kw-code" maxlength="6" spellcheck="false" autocomplete="off" placeholder="ROOM CODE" aria-label="Room code"><button class="kw-btn ghost" type="submit">JOIN</button></form>
722
+ <button class="kw-link" type="button" data-act="pp-bots">No one around? Play against the computer ▸</button>
723
+ <p class="kw-note" id="kw-sheet-note" aria-live="polite"></p>`, "play");
724
+ }
725
+ function howSheet() {
726
+ const tiers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100].map((p) => `<li class="t${p}"><span>${TIERS[p][1]}</span><b>${p}</b><small>${TIERS[p][0]}</small></li>`).join("");
727
+ openSheet(`<p class="kw-sheet-title">HOW TO PLAY</p>
728
+ <ol class="kw-steps"><li>You get a prompt like <b>"Name a fruit"</b> and 25 seconds.</li><li>Type one answer. Skip the obvious ones: the fewer people who'd say it, the more it's worth.</li>
729
+ <li>Every point sinks your krill 10 meters. Seven perfect answers reach the trench at 7,000m.</li><li>Misspell something? You'll get a "did you mean…?" before it counts.</li></ol>
730
+ <ul class="kw-tiers">${tiers}</ul>
731
+ <p class="kw-muted">Rarity comes from what everyone here actually answers. Brand-new prompts start from how well-known each answer is.</p>`);
732
+ }
733
+ function boardSheet() {
734
+ const s = ctx.store.get(STATS_KEY, {});
735
+ openSheet(`<p class="kw-sheet-title">🏆 TODAY'S DEEPEST DIVES</p><ol class="kw-board" id="kw-board-sheet"></ol>
736
+ ${s.dives ? `<p class="kw-muted">You: ${s.dives} daily dive${s.dives === 1 ? "" : "s"} · deepest ${fmtM((s.best || 0) * 10)}${streakNow() ? ` · 🔥 ${streakNow()} day streak` : ""}</p>` : ""}`);
737
+ watchBoard("kw-board-sheet");
738
+ }
739
+ function menuSheet() {
740
+ openSheet(`<p class="kw-sheet-title">MENU</p>
741
+ <form class="kw-inline" data-form="rename" autocomplete="off"><input id="kw-name-in" maxlength="16" spellcheck="false" value="${esc(myName())}" placeholder="your diver name" aria-label="Your name"><button class="kw-btn ghost" type="submit">SAVE NAME</button></form>
742
+ <p class="kw-note" id="kw-sheet-note" aria-live="polite"></p>
743
+ <div class="kw-two"><button class="kw-btn ghost" type="button" data-act="howto">HOW TO PLAY</button><button class="kw-btn ghost" type="button" data-act="board">LEADERBOARD</button></div>
744
+ <div class="kw-two"><button class="kw-btn ghost" type="button" data-act="sound">SOUND: ${sfx.on ? "ON" : "OFF"}</button><button class="kw-btn ghost" type="button" data-act="surface">BACK TO THE SURFACE</button></div>`);
745
+ }
746
+ function watchBoard(listId) {
747
+ if (ui.boardRef) { ui.boardRef.off(); ui.boardRef = null; }
748
+ const list = $(listId);
749
+ if (!list) return;
750
+ list.innerHTML = `<li class="kw-muted">Loading…</li>`;
751
+ online().then((f) => {
752
+ if (!$(listId)) return;
753
+ if (!f) { $(listId).innerHTML = `<li class="kw-muted">The leaderboard isn't available right now.</li>`; return; }
754
+ sweepOld(f);
755
+ ui.boardRef = f.db.ref(`krillionwho/board/${dateStr()}`).orderByChild("pts").limitToLast(10);
756
+ ui.boardRef.on("value", (s) => {
757
+ const rows = [];
758
+ s.forEach((c) => { const v = c.val(); if (v && typeof v.name === "string") rows.push({ ...v, uid: c.key }); });
759
+ rows.sort((a, b) => b.pts - a.pts || a.ts - b.ts);
760
+ const el = $(listId);
761
+ if (!el) return;
762
+ el.innerHTML = rows.length ? rows.map((r, n) => `<li class="${r.uid === net.uid ? "me" : ""}"><span class="kw-rank">${n + 1}</span>` +
763
+ `<span class="kw-who">${esc(ctx.maskSlurs(r.name))}</span><span class="kw-deep">${fmtM(r.pts * 10)}</span></li>`).join("")
764
+ : `<li class="kw-muted">Nobody has dived yet today. Be the first!</li>`;
765
+ }, () => { const el = $(listId); if (el) el.innerHTML = `<li class="kw-muted">The leaderboard isn't available right now.</li>`; });
766
+ });
767
+ }
768
+ // Old leaderboards and rooms clean themselves up: whoever opens KrillionWho deletes a few that have run out
769
+ let swept = false;
770
+ async function sweepOld(f) {
771
+ if (swept) return;
772
+ swept = true;
773
+ try {
774
+ const cutoff = dayBefore(dateStr(), 3), old = now() - 2 * 864e5, changes = {};
775
+ const days = await f.db.ref("krillionwho/board").orderByKey().endAt(cutoff).limitToFirst(4).once("value");
776
+ days.forEach((day) => { day.forEach((row) => { if ((row.val() || {}).ts < old) changes[`krillionwho/board/${day.key}/${row.key}`] = null; }); });
777
+ const lobbies = await f.db.ref("krillionwho/lobbies").orderByChild("ts").endAt(now() - 3600e3).limitToFirst(10).once("value");
778
+ lobbies.forEach((l) => { changes[`krillionwho/lobbies/${l.key}`] = null; });
779
+ if (Object.keys(changes).length) await f.db.ref().update(changes);
780
+ } catch { /* someone else swept first, or older rules */ }
781
+ const mine = ctx.store.get(MY_ROOMS_KEY, {});
782
+ for (const [code, ts] of Object.entries(mine)) {
783
+ if (now() - ts < ROOM_LIFE) continue;
784
+ delete mine[code];
785
+ f.db.ref(`krillionwho/rooms/${code}`).remove().catch(() => {});
786
+ }
787
+ ctx.store.set(MY_ROOMS_KEY, mine);
788
+ }
789
+
790
+ // ---------- Dives (the daily one, free play, or an old day) ----------
791
+ const dive = { mode: null, date: null, keys: [], answers: [], prompt: null, endsAt: 0, locked: true, tick: 0, close: null, run: 0 };
792
+ function seeded(text) { // the same text always gives the same numbers
793
+ let h = 1779033703 ^ text.length;
794
+ for (let i = 0; i < text.length; i++) { h = Math.imul(h ^ text.charCodeAt(i), 3432918353); h = (h << 13) | (h >>> 19); }
795
+ return () => { h = Math.imul(h ^ (h >>> 16), 2246822507); h = Math.imul(h ^ (h >>> 13), 3266489909); h ^= h >>> 16; return (h >>> 0) / 4294967296; };
796
+ }
797
+ // The same 7 prompts for everyone: one per category, at most 2 per pack. Adding answers or prompts must never change a day
798
+ // people may already have played, so the first days (through FIRST_DAYS_END) draw from the prompts that existed then
799
+ // (FIRST_DAYS), exactly as the version they played on did. From then on every category gets its own repeatable score for
800
+ // the day, so each is as likely as any other however many prompts it has, and shows its own best-scoring prompt: a new
801
+ // prompt only takes over where it outscores its category's old ones, and a category with `since` (a date) waits until that day.
802
+ const FIRST_DAYS_END = "2026-12-05", FIRST_DAYS = new Set("animal,animal~bird,animal~fish,animal~ins,animal~mam,animal~rep,animal~sea,animal~starts-b,animal~starts-c,animal~starts-g,animal~starts-m,animal~starts-p,animal~starts-s,candy,capital,capital~af,capital~as,capital~eu,capital~eun,capital~na,capital~starts-b,car,cheese,color,color~starts-c,console,constellation,constellation~starts-c,country,country~af,country~as,country~eu,country~eun,country~ll,country~na,country~starts-s,dc,dinosaur,dinosaur~starts-s,disney,disney~pixar,disney~wdas,dog,dog~starts-b,dog~starts-c,dog~starts-s,element,element~rad,epl,fastfood,fruit,fruit~berry,fruit~cit,fruit~trop,game,game~board,game~card,game~starts-c,game~starts-s,greekgod,icecream,instrument,instrument~perc,instrument~starts-s,instrument~string,instrument~wind,mario,marvel,marvel~starts-m,marvel~starts-s,mcu,minecraft,mlb,nba,nfl,nhl,pasta,pizza,pokemon,pokemon~g1,pokemon~g2,pokemon~starts-m,pokemon~starts-p,pokemon~starts-s,potter,president,shakespeare,simpsons,smash,spongebob,sport,sport~oly,sport~starts-s,starwars,state,state-capital,vegetable,vegetable~root".split(","));
803
+ function pickDaily(date) {
804
+ const big = BANK.prompts.filter((p) => p.pool.length >= DAILY_POOL);
805
+ if (date <= FIRST_DAYS_END) {
806
+ const rnd = seeded("krillionwho " + date);
807
+ const pool = big.filter((p) => FIRST_DAYS.has(p.key)).sort((a, b) => (a.key < b.key ? -1 : 1));
808
+ for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; }
809
+ return spread(pool);
810
+ }
811
+ const score = (text) => seeded(`krillionwho ${date} ${text}`)(), best = new Map();
812
+ for (const p of big) {
813
+ if (p.cat.since && p.cat.since > date) continue;
814
+ const s = score(p.key), had = best.get(p.cat.id);
815
+ if (!had || s < had[0]) best.set(p.cat.id, [s, p]);
816
+ }
817
+ return spread([...best.values()].map(([, p]) => [score(`category ${p.cat.id}`), p]).sort((a, b) => a[0] - b[0]).map(([, p]) => p));
818
+ }
819
+ function spread(pool) {
820
+ const out = [], cats = new Set(), packs = {};
821
+ for (const p of pool) {
822
+ if (cats.has(p.cat.id) || (packs[p.cat.pack] || 0) >= 2) continue;
823
+ out.push(p.key); cats.add(p.cat.id); packs[p.cat.pack] = (packs[p.cat.pack] || 0) + 1;
824
+ if (out.length === ROUNDS) break;
825
+ }
826
+ return out;
827
+ }
828
+ // Free play: each category as likely as any other however many prompts it has. Everything takes one prompt per category
829
+ // (at most 2 per pack); one pack takes each of its categories once, then more of their prompts if it has fewer than 7.
830
+ function pickFree(pack) {
831
+ const shuffle = (a) => { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; };
832
+ const pool = shuffle(BANK.prompts.filter((p) => p.pool.length >= PARTY_POOL && (pack === "all" || p.cat.pack === pack)));
833
+ const first = new Map();
834
+ for (const p of pool) if (!first.has(p.cat.id)) first.set(p.cat.id, p);
835
+ const picks = shuffle([...first.values()]);
836
+ if (pack === "all") return spread(picks);
837
+ const out = picks.slice(0, ROUNDS).map((p) => p.key);
838
+ for (const p of pool) { if (out.length >= ROUNDS) break; if (!out.includes(p.key)) out.push(p.key); }
839
+ return out;
840
+ }
841
+ const promptFor = (key) => BANK.byKey.get(key) || BANK.prompts.find((p) => p.pool.length >= DAILY_POOL && p.cat.id === key.split("~")[0]) || BANK.prompts[0];
842
+ const packName = (id) => (id === "all" ? "Everything" : (BANK.packs.find(([p]) => p === id) || [, id])[1]);
843
+
844
+ function startDaily() {
845
+ const prog = dailyProgress();
846
+ if (prog && prog.done) { Object.assign(dive, { mode: "daily", keys: prog.keys, answers: prog.answers.slice(), date: prog.date }); return finishDive(true); }
847
+ askName(() => {
848
+ let p = dailyProgress();
849
+ if (!p) { p = { date: dateStr(), keys: pickDaily(dateStr()), answers: [], started: -1 }; ctx.store.set(DAILY_KEY, p); ctx.track("KrillionWho: daily dive"); }
850
+ if (p.started >= p.answers.length && p.answers.length < ROUNDS) { // left during a prompt: that one's gone
851
+ p.answers.push({ k: p.keys[p.answers.length], p: 0, w: "left" });
852
+ ctx.store.set(DAILY_KEY, p);
853
+ }
854
+ beginDive("daily", p.keys, p.answers, p.date);
855
+ }, "It goes on today's leaderboard.");
856
+ }
857
+ function beginDive(mode, keys, answers = [], date = null) {
858
+ stopTimers();
859
+ closeSheet();
860
+ const run = ++dive.run;
861
+ Object.assign(dive, { mode, keys, answers: answers.slice(), date, locked: true, close: null });
862
+ ui.screen = "dive";
863
+ setMode("dive");
864
+ const depth = sum(dive.answers) * 10;
865
+ uiHtml(diveHtml());
866
+ $("kw-depth").textContent = fmtM(depth);
867
+ $("kw-score").textContent = String(sum(dive.answers));
868
+ renderDots();
869
+ sfx.play("splash");
870
+ diveKrill();
871
+ camTo(depth, 2200);
872
+ if (dive.answers.length >= ROUNDS) return setTimeout(() => run === dive.run && finishDive(), 900);
873
+ setTimeout(() => run === dive.run && nextRound(), 700);
874
+ }
875
+ function diveHtml() {
876
+ return `<div class="kw-hud">
877
+ <div class="kw-box"><small>DEPTH</small><b id="kw-depth">0m</b></div>
878
+ <div class="kw-progress"><ol id="kw-dots"></ol><small id="kw-round">PROMPT 1 OF ${ROUNDS}</small></div>
879
+ <div class="kw-box score"><small>SCORE</small><b id="kw-score">0</b></div>
880
+ </div>
881
+ <div class="kw-card" id="kw-card">
882
+ <p class="kw-card-top" id="kw-kicker"></p>
883
+ <h2 class="kw-prompt" id="kw-prompt"></h2>
884
+ <p class="kw-hint" id="kw-hint"></p>
885
+ <form class="kw-answer" data-form="answer" id="kw-form" autocomplete="off">
886
+ <input id="kw-input" maxlength="60" spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="type a rare answer…" aria-label="Your answer">
887
+ <button class="kw-btn" type="submit">DIVE ▼</button>
888
+ </form>
889
+ <div class="kw-close" id="kw-close" hidden aria-live="assertive"></div>
890
+ <p class="kw-wrong" id="kw-wrong" hidden aria-live="assertive"></p>
891
+ <div class="kw-reveal" id="kw-reveal" hidden aria-live="polite"></div>
892
+ </div>
893
+ <div class="kw-status" id="kw-status"></div>
894
+ <button class="kw-leave" type="button" data-act="quit">${dive.mode === "daily" ? "◀ LEAVE" : "◀ END DIVE"}</button>`;
895
+ }
896
+ function renderDots() {
897
+ const el = $("kw-dots");
898
+ if (!el) return;
899
+ el.innerHTML = Array.from({ length: ROUNDS }, (_, n) => { const a = dive.answers[n]; return `<li class="${a ? `t${a.p} done` : n === dive.answers.length ? "now" : ""}" title="${a ? `+${a.p}` : ""}"></li>`; }).join("");
900
+ }
901
+ function status(html) { const el = $("kw-status"); if (el) el.innerHTML = html; }
902
+ function nextRound() {
903
+ if (dive.answers.length >= ROUNDS) return finishDive();
904
+ const run = dive.run, n = dive.answers.length, p = dive.prompt = promptFor(dive.keys[n]);
905
+ dive.locked = true;
906
+ dive.close = null;
907
+ clearSink();
908
+ $("kw-card").classList.remove("sunk", "result");
909
+ $("kw-round").textContent = `PROMPT ${n + 1} OF ${ROUNDS}`;
910
+ $("kw-kicker").textContent = `PROMPT ${n + 1} OF ${ROUNDS} · ${packName(p.cat.pack).toUpperCase()}`;
911
+ $("kw-prompt").textContent = p.text;
912
+ $("kw-hint").textContent = p.hint ? `${p.hint}` : "▼ rarer answers sink deeper ▼";
913
+ $("kw-reveal").hidden = true;
914
+ $("kw-close").hidden = true;
915
+ $("kw-wrong").hidden = true;
916
+ $("kw-form").hidden = false;
917
+ const input = $("kw-input");
918
+ input.value = "";
919
+ input.disabled = true;
920
+ const card = $("kw-card");
921
+ card.classList.remove("in"); void card.offsetWidth; card.classList.add("in");
922
+ renderDots();
923
+ if (dive.mode === "daily") { const prog = dailyProgress(); if (prog) { prog.started = n; ctx.store.set(DAILY_KEY, prog); } }
924
+ let left = PREROLL;
925
+ const roll = () => { status(`descending · the clock starts in <b>${left}</b>`); sfx.play("tick"); };
926
+ roll();
927
+ clearInterval(dive.tick);
928
+ dive.tick = every(1000, () => {
929
+ if (run !== dive.run) return;
930
+ left--;
931
+ if (left > 0) return roll();
932
+ clearInterval(dive.tick);
933
+ startClock();
934
+ });
935
+ }
936
+ function startClock() {
937
+ const input = $("kw-input");
938
+ if (!input) return;
939
+ input.disabled = false;
940
+ input.focus();
941
+ sfx.play("go");
942
+ dive.locked = false;
943
+ dive.endsAt = Date.now() + ROUND_MS;
944
+ status(`<div class="kw-clock"><span id="kw-timefill"></span></div><b class="kw-secs" id="kw-secs">25</b>`);
945
+ const fill = $("kw-timefill");
946
+ fill.style.animation = `kwTime ${ROUND_MS}ms linear forwards`;
947
+ let lastBeep = 99;
948
+ dive.tick = every(100, () => {
949
+ const left = Math.max(0, dive.endsAt - Date.now()), secs = Math.ceil(left / 1000), el = $("kw-secs");
950
+ if (el) { el.textContent = secs; el.classList.toggle("hurry", left < 6000); }
951
+ if (left < 5500 && secs < lastBeep && secs > 0) { lastBeep = secs; sfx.play("hurry"); }
952
+ if (!left) answer(true);
953
+ });
954
+ }
955
+ // A misspelling close to a real answer asks first ("Did you mean…?"); the clock keeps running meanwhile
956
+ function askClose(res) {
957
+ dive.close = res;
958
+ const box = $("kw-close");
959
+ box.hidden = false;
960
+ box.innerHTML = `<span>did you mean <b>${esc(res.entry.name)}</b>?</span>` +
961
+ `<button class="kw-btn small" type="button" data-act="close-yes" id="kw-close-yes">YES ▼</button>` +
962
+ `<button class="kw-link" type="button" data-act="close-no">no, let me fix it</button>`;
963
+ sfx.play("ask");
964
+ $("kw-close-yes").focus();
965
+ }
966
+ function dropClose(refocus) {
967
+ dive.close = null;
968
+ const box = $("kw-close");
969
+ if (box) box.hidden = true;
970
+ if (refocus) { const input = $("kw-input"); input.focus(); input.select(); }
971
+ }
972
+ function reject(res, raw, p) {
973
+ const box = $("kw-wrong"), input = $("kw-input");
974
+ if (res.why === "blank") return input.focus();
975
+ box.hidden = false;
976
+ box.innerHTML = `✖ ${esc(whyText(res, raw, p))} <span>try another!</span>` +
977
+ (res.why === "unknown" ? ` <button class="kw-link" type="button" data-act="report" data-text="${esc(`${p.text}: ${String(raw).trim().slice(0, 60)}`)}">should it count?</button>` : "");
978
+ sfx.play("miss");
979
+ input.classList.remove("shake"); void input.offsetWidth; input.classList.add("shake");
980
+ input.focus();
981
+ input.select();
982
+ }
983
+ async function answer(timeUp, accepted) {
984
+ if (dive.locked) return;
985
+ const run = dive.run, input = $("kw-input"), raw = timeUp ? "" : input.value, p = dive.prompt;
986
+ const res = timeUp ? { ok: false, why: "time" } : accepted || check(p, raw);
987
+ if (res.why === "close") return askClose(res);
988
+ dropClose(false);
989
+ if (!timeUp && !res.ok) return reject(res, raw, p); // a wrong answer doesn't use up the guess: try again while the clock runs
990
+ dive.locked = true;
991
+ clearInterval(dive.tick);
992
+ const fill = $("kw-timefill");
993
+ if (fill) fill.style.animationPlayState = "paused";
994
+ input.disabled = true;
995
+ if (res.ok) sfx.play("ping");
996
+ $("kw-wrong").hidden = true;
997
+ status(res.ok ? "sonar ping · measuring how rare that is…" : "the krill wobbles…");
998
+ const counts = await readCounts(p.key);
999
+ if (run !== dive.run || ui.screen !== "dive") return; // left in the meantime
1000
+ let pts = 0, share = null;
1001
+ if (res.ok) {
1002
+ const key = res.entry.key, list = listPts(p, res.i);
1003
+ const c = counts ? { ...counts, [key]: (counts[key] || 0) + 1 } : null;
1004
+ pts = c ? blendPts(list, c, key) : list;
1005
+ const total = c ? Object.values(c).reduce((a, b) => a + (Number(b) || 0), 0) : 0;
1006
+ if (total >= 10) share = c[key] / total;
1007
+ addCount(p.key, key);
1008
+ }
1009
+ const before = sum(dive.answers);
1010
+ dive.answers.push({ k: p.key, p: pts, n: res.ok ? res.entry.name : String(raw).trim().slice(0, 40), w: res.ok ? "" : res.why });
1011
+ if (dive.mode === "daily") { const prog = dailyProgress(); if (prog) { prog.answers = dive.answers.slice(); ctx.store.set(DAILY_KEY, prog); } }
1012
+ renderDots();
1013
+ $("kw-form").hidden = true;
1014
+ // the payoff: the answer sinks past the tier lines with the camera following, and lands on its tier
1015
+ status(pts ? "sinking…" : "time's up…");
1016
+ await sink(res.ok ? res.entry.name : "time's up", pts, before);
1017
+ if (run !== dive.run || ui.screen !== "dive") return;
1018
+ const card = $("kw-card");
1019
+ card.classList.remove("sunk");
1020
+ card.classList.add("result"); // the result shows at the bottom, under the answer that just landed
1021
+ const [tier, emoji] = TIERS[pts], last = dive.answers.length >= ROUNDS;
1022
+ const reveal = $("kw-reveal");
1023
+ reveal.hidden = false;
1024
+ reveal.innerHTML = (res.ok
1025
+ ? `<p class="kw-said">you said <b class="kw-tc t${pts}">${esc(res.entry.name)}</b>${res.entry.of ? ` <span class="kw-muted">(${esc(res.entry.of)})</span>` : ""} · <span class="t${pts} kw-tierword">${emoji} ${tier.toLowerCase()}</span> · ${fmtM(pts * 10)} deeper</p>` +
1026
+ (share !== null ? `<p class="kw-stat">${share < 0.01 ? "under 1%" : `${Math.round(share * 100)}%`} of divers here said that${pts >= 100 ? " · one of a kind!" : ""}</p>` : pts >= 100 ? `<p class="kw-stat">one of a kind!</p>` : "")
1027
+ : `<p class="kw-said miss">💨 ${esc(whyText(res, raw, p))}</p>`) +
1028
+ `<p class="kw-common">most said: ${topNames(p, counts).map(esc).join(" · ")}</p>` +
1029
+ `<div class="kw-actions"><button class="kw-btn" type="button" data-act="next" id="kw-next">${last ? "SURFACE THE RESULTS ▲" : "NEXT PROMPT ▼"}</button>` +
1030
+ (!res.ok && res.why === "unknown" ? `<button class="kw-link" type="button" data-act="report" data-text="${esc(`${p.text}: ${String(raw).trim().slice(0, 60)}`)}">that should count</button>` : "") + `</div>`;
1031
+ status(last ? "that's the last prompt · press enter for your results" : "press enter for the next prompt");
1032
+ $("kw-next").focus();
1033
+ }
1034
+ function finishDive(again) {
1035
+ clearInterval(dive.tick);
1036
+ clearSink();
1037
+ dive.locked = true;
1038
+ ui.screen = "results";
1039
+ setMode("dive");
1040
+ const total = sum(dive.answers), m = total * 10;
1041
+ if (dive.mode === "daily") {
1042
+ const prog = dailyProgress();
1043
+ if (prog && !prog.done) {
1044
+ Object.assign(prog, { done: true, total, answers: dive.answers.slice() });
1045
+ ctx.store.set(DAILY_KEY, prog);
1046
+ const s = ctx.store.get(STATS_KEY, {});
1047
+ s.streak = s.last === dayBefore(prog.date) ? (s.streak || 0) + 1 : s.last === prog.date ? s.streak || 1 : 1;
1048
+ s.last = prog.date; s.best = Math.max(s.best || 0, total); s.dives = (s.dives || 0) + 1;
1049
+ ctx.store.set(STATS_KEY, s);
1050
+ postScore(prog);
1051
+ }
1052
+ }
1053
+ camTo(m, again ? 2200 : 900);
1054
+ const title = dive.mode === "daily" ? `DIVE #${dayNumber(dive.date || dateStr())}` : dive.mode === "past" ? `ARCHIVE · ${fmtDate(dive.date).toUpperCase()}` : "FREE PLAY";
1055
+ uiHtml(`<div class="kw-hud">
1056
+ <div class="kw-box"><small>DEPTH</small><b id="kw-depth">${fmtM(m)}</b></div>
1057
+ <div class="kw-progress"><ol id="kw-dots"></ol><small>DIVE COMPLETE</small></div>
1058
+ <div class="kw-box score"><small>SCORE</small><b id="kw-score">${total}</b></div>
1059
+ </div>
1060
+ <div class="kw-card kw-results in">
1061
+ <p class="kw-card-top">${esc(title)} · DIVE COMPLETE</p>
1062
+ <h2 class="kw-big">${fmtM(m)}</h2>
1063
+ <p class="kw-zoneline">${esc(zoneAt(m)).toUpperCase()} · ${total} POINTS${total >= ROUNDS * 100 ? " · PERFECT DIVE!" : ""}</p>
1064
+ <p class="kw-emoji">${dive.answers.map((r) => TIERS[r.p][1]).join(" ")}</p>
1065
+ ${dive.mode === "daily" ? `<div class="kw-pct" id="kw-pct"><p class="kw-pct-sub">comparing with today's divers…</p></div>` : ""}
1066
+ <ol class="kw-rounds">${dive.answers.map((r) => `<li class="t${r.p}"><span class="kw-rq">${esc(promptFor(r.k).text)}</span>` +
1067
+ `<b>${r.w && r.w !== "left" && r.n ? `<s>${esc(r.n)}</s>` : esc(r.n || (r.w === "left" ? "left early" : "no answer"))}</b><span class="kw-rp">+${r.p}</span></li>`).join("")}</ol>
1068
+ <div class="kw-actions">
1069
+ ${dive.mode === "daily" ? `<button class="kw-btn" type="button" data-act="share">COPY MY RESULT</button>` : `<button class="kw-btn" type="button" data-act="again">DIVE AGAIN ▼</button>`}
1070
+ <button class="kw-btn ghost" type="button" data-act="surface">▲ BACK TO THE SURFACE</button>
1071
+ </div>
1072
+ ${dive.mode === "daily" ? `<p class="kw-muted" id="kw-countdown"></p><p class="kw-label">TODAY'S DEEPEST</p><ol class="kw-board" id="kw-board"></ol>` : ""}
1073
+ </div>`);
1074
+ renderDots();
1075
+ if (!again) sfx.play(total >= ROUNDS * 100 ? "win" : "done");
1076
+ if (m >= MAX_DEPTH) { const chest = $("kw-chest"); if (chest) chest.classList.add("open"); }
1077
+ if (dive.mode === "daily") {
1078
+ watchBoard("kw-board");
1079
+ showPercent(total, dive.date || dateStr());
1080
+ const tick = () => {
1081
+ const end = new Date(); end.setHours(24, 0, 0, 0);
1082
+ const left = end - Date.now(), el = $("kw-countdown");
1083
+ if (el) el.textContent = `next dive in ${Math.floor(left / 3600e3)}h ${Math.floor((left % 3600e3) / 60e3)}m`;
1084
+ };
1085
+ tick(); every(30e3, tick);
1086
+ }
1087
+ }
1088
+ // "Better than 62% of today's players": everyone else's score today from the leaderboard, and once a few people have
1089
+ // dived, all the scores drawn as a curve with you marked on it
1090
+ async function showPercent(total, date) {
1091
+ const f = await within(online(), 5000);
1092
+ let others = null;
1093
+ if (f) {
1094
+ try {
1095
+ const s = await within(f.db.ref(`krillionwho/board/${date}`).once("value"), 5000);
1096
+ if (s) { others = []; s.forEach((c) => { const v = c.val(); if (c.key !== f.uid && v && typeof v.pts === "number") others.push(v.pts); }); }
1097
+ } catch { /* offline, or older rules */ }
1098
+ }
1099
+ const el = $("kw-pct");
1100
+ if (!el) return;
1101
+ if (!others) { el.remove(); return; }
1102
+ const n = others.length, below = others.filter((p) => p < total).length;
1103
+ const pct = below === n ? 100 : Math.floor((below / n) * 100);
1104
+ el.innerHTML = (n + 1 >= 5 ? curveHtml([...others, total], total) : "") + (n
1105
+ ? `<p class="kw-pct-text">BETTER THAN <b id="kw-pct-n">0%</b> OF TODAY'S PLAYERS</p><p class="kw-pct-sub">${(n + 1).toLocaleString()} divers so far today</p>`
1106
+ : `<p class="kw-pct-text">YOU'RE TODAY'S <b>FIRST DIVER!</b></p><p class="kw-pct-sub">check back later to see how you stack up</p>`);
1107
+ if (n) countTo($("kw-pct-n"), 0, pct, 1100, (v) => `${v}%`);
1108
+ }
1109
+ function curveHtml(all, me) {
1110
+ const mean = all.reduce((a, b) => a + b, 0) / all.length;
1111
+ const sd = Math.sqrt(all.reduce((a, b) => a + (b - mean) ** 2, 0) / all.length) || 60;
1112
+ const h = Math.min(90, Math.max(28, 1.06 * sd * Math.pow(all.length, -0.2))); // how much to smooth (Silverman's rule)
1113
+ const dens = (x) => all.reduce((t, p) => t + Math.exp(-0.5 * ((x - p) / h) ** 2), 0);
1114
+ const xs = Array.from({ length: 71 }, (_, i) => i * 10), ys = xs.map(dens), peak = Math.max(...ys) || 1;
1115
+ const y = (v) => 96 - (v / peak) * 86; // 0-100 down the plot
1116
+ const line = xs.map((x, i) => `${i ? "L" : "M"}${x} ${y(ys[i]).toFixed(1)}`).join("");
1117
+ const x = Math.max(0, Math.min(700, me)), at = (v) => `${(v / 7).toFixed(2)}%`;
1118
+ const ticks = [0, 100, 200, 300, 400, 500, 600, 700].filter((t) => Math.abs(t - x) > 45)
1119
+ .map((t) => `<span style="left:${at(t)}"${t === 0 ? ' class="first"' : t === 700 ? ' class="last"' : ""}>${t}</span>`).join("");
1120
+ return `<div class="kw-curve" aria-hidden="true"><div class="kw-curve-plot">
1121
+ <svg viewBox="0 0 700 100" preserveAspectRatio="none"><path class="kw-curve-fill" d="${line}L700 100L0 100Z"/><path class="kw-curve-line" d="${line}"/></svg>
1122
+ <i class="kw-curve-stem" style="left:${at(x)};top:${y(dens(x)).toFixed(1)}%"></i><i class="kw-curve-dot" style="left:${at(x)};top:${y(dens(x)).toFixed(1)}%"></i>
1123
+ </div><div class="kw-curve-axis">${ticks}<b style="left:${at(x)}">YOU</b></div></div>`;
1124
+ }
1125
+ async function postScore(prog) {
1126
+ const name = myName(), f = await online();
1127
+ if (!name || !f) return;
1128
+ try { await f.db.ref(`krillionwho/board/${prog.date}/${f.uid}`).set({ name, pts: prog.total, ts: TS() }); } catch { /* already posted today, or offline */ }
1129
+ }
1130
+ function shareText() {
1131
+ const prog = dailyProgress();
1132
+ if (!prog) return "";
1133
+ return `KrillionWho · Dive #${dayNumber(prog.date)}\n${prog.answers.map((r) => TIERS[r.p][1]).join("")} ${prog.total} pts · ${fmtM(prog.total * 10)}\nCan you dive deeper? richardwho`;
1134
+ }
1135
+ function endDive() { clearInterval(dive.tick); stopTimers(); clearSink(); dive.run++; dive.locked = true; dive.mode = null; const chest = $("kw-chest"); if (chest) chest.classList.remove("open"); }
1136
+ async function report(text) {
1137
+ const f = await online();
1138
+ if (!f) return ctx.toast("Couldn't send that right now.");
1139
+ try {
1140
+ const id = f.db.ref("reports/items").push().key;
1141
+ await f.db.ref().update({ [`reports/items/${id}`]: { type: "request", game: "KrillionWho: missing answer", note: String(text).slice(0, 200), uid: f.uid, ts: TS() }, [`reports/last/${f.uid}`]: TS() });
1142
+ ctx.toast("Thanks! We'll look at adding it.");
1143
+ } catch { ctx.toast("You can send one of these every 20 seconds."); }
1144
+ }
1145
+
1146
+ // ---------- Puffer Party ----------
1147
+ // The rules, as plain functions: each takes a copy of the room and returns the next one, or a reason it can't happen.
1148
+ // Online, they run inside database transactions; against the computer, on a local copy.
1149
+ const PP = {
1150
+ seats: (room) => Object.entries(room.players || {}).sort((a, b) => a[1].seat - b[1].seat).map(([id]) => id),
1151
+ alive: (room) => PP.seats(room).filter((id) => room.players[id].lives > 0),
1152
+ next(room, from) {
1153
+ const s = PP.seats(room);
1154
+ let k = s.indexOf(from);
1155
+ for (let n = 0; n < s.length; n++) { k = (k + 1) % s.length; if (room.players[s[k]].lives > 0) return s[k]; }
1156
+ return from;
1157
+ },
1158
+ pick(room, rnd) {
1159
+ const recent = String(room.recent || "").split(",").filter(Boolean);
1160
+ const pool = BANK.prompts.filter((p) => p.pool.length >= PARTY_POOL && (room.pack === "all" || p.cat.pack === room.pack));
1161
+ const fresh = pool.filter((p) => !recent.includes(p.cat.id));
1162
+ const list = fresh.length ? fresh : pool, p = list[Math.floor(rnd() * list.length)];
1163
+ room.recent = [...recent, p.cat.id].slice(-Math.min(10, Math.floor(new Set(pool.map((x) => x.cat.id)).size / 2))).join(",");
1164
+ return p.key;
1165
+ },
1166
+ round(room, n, holder, t, rnd) { room.round = { n, key: PP.pick(room, rnd), holder, at: t + BREAK, startsAt: t + BREAK, endsAt: t + BREAK + FUSE }; },
1167
+ join(room, uid, name) {
1168
+ const p = room.players || (room.players = {});
1169
+ if (p[uid]) { p[uid].name = name; p[uid].on = true; room.seq++; return room; }
1170
+ if (room.state !== "lobby") return "started";
1171
+ if (Object.keys(p).length >= MAX_PLAYERS) return "full";
1172
+ p[uid] = { name, seat: Math.max(0, ...Object.values(p).map((x) => x.seat)) + 1, lives: room.lives, on: true };
1173
+ room.seq++;
1174
+ return room;
1175
+ },
1176
+ start(room, t, rnd) {
1177
+ if (room.state === "playing") return "started";
1178
+ for (const id of Object.keys(room.players)) if (room.players[id].on === false) delete room.players[id];
1179
+ const ids = PP.seats(room);
1180
+ if (ids.length < 2) return "few";
1181
+ for (const id of ids) room.players[id].lives = room.lives;
1182
+ room.state = "playing"; room.recent = "";
1183
+ delete room.winner; delete room.pop;
1184
+ PP.round(room, 1, ids[Math.floor(rnd() * ids.length)], t, rnd);
1185
+ room.seq++;
1186
+ return room;
1187
+ },
1188
+ pass(room, uid, ans, pts, t) {
1189
+ const r = room.round;
1190
+ if (room.state !== "playing" || !r || r.holder !== uid) return "turn";
1191
+ if (t > r.endsAt + 600) return "late";
1192
+ if (r.used && r.used[ans]) return "used";
1193
+ (r.used || (r.used = {}))[ans] = uid;
1194
+ const p = room.players[uid];
1195
+ r.last = { uid, a: ans, pts, at: t };
1196
+ if (pts >= 100 && p.lives < room.lives) { p.lives++; r.last.bonus = true; }
1197
+ r.holder = PP.next(room, uid);
1198
+ r.at = t;
1199
+ r.endsAt = Math.max(r.endsAt, t + FLOOR); // the fuse keeps burning, but nobody gets under 8 seconds
1200
+ room.seq++;
1201
+ return room;
1202
+ },
1203
+ pop(room, t, rnd) {
1204
+ const r = room.round;
1205
+ if (room.state !== "playing" || !r || t < r.endsAt) return "early";
1206
+ const id = r.holder, p = room.players[id];
1207
+ if (p) p.lives = Math.max(0, p.lives - 1);
1208
+ room.pop = { uid: id, at: t, n: r.n };
1209
+ const alive = PP.alive(room);
1210
+ if (alive.length <= 1) { room.state = "over"; if (alive[0] || id) room.winner = alive[0] || id; delete room.round; }
1211
+ else PP.round(room, r.n + 1, PP.next(room, id), t, rnd);
1212
+ room.seq++;
1213
+ return room;
1214
+ },
1215
+ leave(room, uid, t) {
1216
+ const p = room.players && room.players[uid];
1217
+ if (!p) return room;
1218
+ if (room.state === "playing") {
1219
+ p.lives = 0; p.on = false;
1220
+ const r = room.round;
1221
+ if (r && r.holder === uid) { r.holder = PP.next(room, uid); r.at = t; r.endsAt = Math.max(r.endsAt, t + FLOOR); }
1222
+ const alive = PP.alive(room);
1223
+ if (alive.length <= 1) { room.state = "over"; if (alive[0]) room.winner = alive[0]; delete room.round; }
1224
+ } else delete room.players[uid];
1225
+ const left = PP.seats(room).filter((id) => room.players[id].on !== false || room.state === "playing");
1226
+ if (!left.length || !PP.seats(room).some((id) => room.players[id].on !== false)) return null; // last one out closes the room
1227
+ if (room.host === uid || !room.players[room.host]) room.host = left.find((id) => room.players[id].on !== false) || left[0];
1228
+ room.seq++;
1229
+ return room;
1230
+ },
1231
+ reset(room) {
1232
+ room.state = "lobby";
1233
+ delete room.round; delete room.pop; delete room.winner;
1234
+ for (const id of Object.keys(room.players)) { if (room.players[id].on === false) delete room.players[id]; else room.players[id].lives = room.lives; }
1235
+ room.seq++;
1236
+ return room;
1237
+ },
1238
+ };
1239
+
1240
+ const pp = { mode: null, code: null, me: null, room: null, ref: null, tick: 0, busy: false, plan: null, level: 1, bots: 3,
1241
+ shownPop: 0, lastPass: 0, lastFuse: 0, listSig: "", screen: null, close: null, connected: null, overSeen: false, goneUntil: 0, hit: null };
1242
+ const ppNow = () => (pp.mode === "online" ? now() : Date.now());
1243
+ const personName = (id) => (pp.room && pp.room.players[id] ? ctx.maskSlurs(pp.room.players[id].name) : "Someone");
1244
+ function answerName(promptKey, key) {
1245
+ const p = BANK.byKey.get(promptKey), i = p ? p.cat.byKey.get(key) : undefined;
1246
+ return i === undefined ? key : p.cat.entries[i].name;
1247
+ }
1248
+ // Change the room: a transaction online (so two people can't both grab the puffer), a plain update vs the computer
1249
+ async function ppDo(rule) {
1250
+ if (pp.mode === "bots") {
1251
+ const out = rule(clone(pp.room), ppNow());
1252
+ if (typeof out === "string") return out;
1253
+ pp.room = out;
1254
+ ppRender();
1255
+ return null;
1256
+ }
1257
+ if (!pp.ref) return "gone";
1258
+ let why = null;
1259
+ try {
1260
+ const res = await pp.ref.transaction((cur) => {
1261
+ if (!cur) { why = "gone"; return; }
1262
+ const out = rule(clone(cur), now());
1263
+ if (typeof out === "string") { why = out; return; }
1264
+ why = null;
1265
+ return out;
1266
+ });
1267
+ return res.committed ? null : why || "busy";
1268
+ } catch { return "error"; }
1269
+ }
1270
+ function ppNoteText(why) {
1271
+ return { gone: "That room doesn't exist (or it closed).", full: "That room is full.", started: "That game already started.", few: "You need at least 2 players.",
1272
+ error: "Couldn't reach the room. Check your connection and try again.", busy: "Try that again." }[why] || "Something went wrong.";
1273
+ }
1274
+ function ppCreate(pub, name) {
1275
+ sheetNote("Making a room…");
1276
+ within(online(), 8000).then(async (f) => {
1277
+ if (!f) return sheetNote("Online rooms aren't available right now. Try playing against the computer.", true);
1278
+ const code = [...crypto.getRandomValues(new Uint32Array(6))].map((n) => ROOM_LETTERS[n % ROOM_LETTERS.length]).join("");
1279
+ const room = { host: f.uid, ts: TS(), pub: !!pub, pack: ui.pack, lives: 2, state: "lobby", seq: 1, players: { [f.uid]: { name, seat: 1, lives: 2, on: true } } };
1280
+ try {
1281
+ await f.db.ref().update({ [`krillionwho/rooms/${code}`]: room, [`krillionwho/roomLast/${f.uid}`]: TS() });
1282
+ } catch {
1283
+ return sheetNote("Couldn't make a room. You can make one every 15 seconds, so wait a moment and try again.", true);
1284
+ }
1285
+ const mine = ctx.store.get(MY_ROOMS_KEY, {});
1286
+ mine[code] = now();
1287
+ ctx.store.set(MY_ROOMS_KEY, mine);
1288
+ ctx.track("KrillionWho: Puffer Party room");
1289
+ ppEnter(code);
1290
+ });
1291
+ }
1292
+ async function ppJoin(raw, name, quiet) {
1293
+ const code = String(raw || "").toUpperCase().replace(/[^A-Z0-9]/g, "");
1294
+ if (code.length !== 6) { if (!quiet) sheetNote("Room codes are 6 letters and numbers.", true); return "code"; }
1295
+ const f = await within(online(), 8000);
1296
+ if (!f) { if (!quiet) sheetNote(ppNoteText("error"), true); return "error"; }
1297
+ const ref = f.db.ref(`krillionwho/rooms/${code}`);
1298
+ const hold = () => {}; // keeps the room cached so the transaction starts from real data
1299
+ ref.on("value", hold, () => {});
1300
+ let why = null;
1301
+ try {
1302
+ await within(ref.once("value"), 5000);
1303
+ const res = await ref.transaction((cur) => {
1304
+ if (!cur) { why = "gone"; return; }
1305
+ const out = PP.join(clone(cur), f.uid, name);
1306
+ if (typeof out === "string") { why = out; return; }
1307
+ why = null;
1308
+ return out;
1309
+ });
1310
+ if (!res.committed) why = why || "busy";
1311
+ } catch { why = "gone"; }
1312
+ ref.off("value", hold);
1313
+ if (why) { if (!quiet) sheetNote(ppNoteText(why), true); return why; }
1314
+ ppEnter(code);
1315
+ return null;
1316
+ }
1317
+ async function ppQuick(name) {
1318
+ sheetNote("Looking for an open room…");
1319
+ const f = await within(online(), 8000);
1320
+ if (!f) return sheetNote("Online rooms aren't available right now. Try playing against the computer.", true);
1321
+ let rows = [];
1322
+ try {
1323
+ const s = await f.db.ref("krillionwho/lobbies").orderByChild("ts").limitToLast(25).once("value");
1324
+ s.forEach((c) => { const v = c.val(); if (v) rows.push({ code: c.key, ...v }); });
1325
+ } catch { /* older rules */ }
1326
+ rows = rows.filter((r) => r.n < MAX_PLAYERS && now() - r.ts < 15 * 60e3).sort((a, b) => b.ts - a.ts);
1327
+ for (const r of rows) if (!(await ppJoin(r.code, name, true))) return;
1328
+ ppCreate(true, name);
1329
+ }
1330
+ function ppScreen() {
1331
+ endDive();
1332
+ closeSheet();
1333
+ ui.screen = "pp";
1334
+ setMode("party");
1335
+ camTo(700, 1800);
1336
+ uiHtml(`<div class="kw-party" id="kw-pp"></div>`);
1337
+ }
1338
+ function ppEnter(code) {
1339
+ ppStop();
1340
+ Object.assign(pp, { mode: "online", code, me: net.uid, room: null, busy: false, shownPop: 0, lastPass: 0, listSig: "", screen: null, overSeen: false });
1341
+ ctx.store.set(ROOM_KEY, code);
1342
+ pp.ref = net.db.ref(`krillionwho/rooms/${code}`);
1343
+ const on = pp.ref.child(`players/${net.uid}/on`);
1344
+ on.onDisconnect().set(false).catch(() => {});
1345
+ net.db.ref(".info/connected").on("value", pp.connected = (s) => { if (s.val() && pp.room) on.set(true).catch(() => {}); });
1346
+ ppScreen();
1347
+ $("kw-pp").innerHTML = `<div class="kw-panel"><p class="kw-muted">Joining room ${esc(code)}…</p></div>`;
1348
+ sfx.play("splash");
1349
+ pp.ref.on("value", (s) => {
1350
+ const room = s.val();
1351
+ if (!room || !room.players || !room.players[pp.me]) return ppGone(room ? "You're not in that room anymore." : "That room closed.");
1352
+ if (!pp.room) { if (room.pop) pp.shownPop = room.pop.at; if (room.round && room.round.last) pp.lastPass = room.round.last.at; } // don't replay old events when joining
1353
+ pp.room = room;
1354
+ ppRender();
1355
+ }, () => ppGone("Couldn't open that room."));
1356
+ pp.tick = setInterval(ppTick, 200);
1357
+ }
1358
+ function ppBots(name) {
1359
+ ppStop();
1360
+ const players = { you: { name: name || "You", seat: 1, lives: 2, on: true } };
1361
+ for (let i = 0; i < pp.bots; i++) players[`bot${i}`] = { name: BOT_NAMES[i], seat: i + 2, lives: 2, on: true, bot: true };
1362
+ Object.assign(pp, { mode: "bots", code: null, me: "you", ref: null, plan: null, shownPop: 0, lastPass: 0, screen: null, overSeen: false,
1363
+ room: { host: "you", ts: Date.now(), pub: false, pack: ui.pack, lives: 2, state: "lobby", seq: 1, players } });
1364
+ ppScreen();
1365
+ ppRender();
1366
+ pp.tick = setInterval(ppTick, 150);
1367
+ ctx.track("KrillionWho: Puffer Party vs computer");
1368
+ }
1369
+ function setBots(n) {
1370
+ const room = pp.room, players = { you: room.players.you };
1371
+ for (let i = 0; i < n; i++) players[`bot${i}`] = { name: BOT_NAMES[i], seat: i + 2, lives: room.lives, on: true, bot: true };
1372
+ pp.bots = n;
1373
+ room.players = players;
1374
+ ppRender();
1375
+ }
1376
+ function ppStop() {
1377
+ clearInterval(pp.tick);
1378
+ if (pp.ref) { pp.ref.off(); pp.ref.child(`players/${pp.me}/on`).onDisconnect().cancel().catch(() => {}); }
1379
+ if (pp.connected && net.db) net.db.ref(".info/connected").off("value", pp.connected);
1380
+ Object.assign(pp, { mode: null, ref: null, room: null, connected: null, close: null });
1381
+ }
1382
+ async function ppLeave() {
1383
+ if (pp.mode === "online") {
1384
+ const code = pp.code, wasHost = pp.room && pp.room.host === pp.me;
1385
+ await ppDo((room, t) => PP.leave(room, pp.me, t));
1386
+ if (wasHost) net.db.ref(`krillionwho/lobbies/${code}`).remove().catch(() => {});
1387
+ ctx.store.set(ROOM_KEY, "");
1388
+ }
1389
+ ppStop();
1390
+ renderHome(true);
1391
+ }
1392
+ function ppGone(msg) {
1393
+ const code = pp.code;
1394
+ ppStop();
1395
+ ctx.store.set(ROOM_KEY, "");
1396
+ if (code && net.db) net.db.ref(`krillionwho/lobbies/${code}`).remove().catch(() => {});
1397
+ if (ui.screen === "pp") { renderHome(true); ctx.toast(msg); }
1398
+ }
1399
+ // Whoever runs the clock: the host, or the first player still here if the host dropped
1400
+ function referee(room) {
1401
+ const here = PP.seats(room).filter((id) => room.players[id].on !== false);
1402
+ return room.players[room.host] && room.players[room.host].on !== false ? room.host : here[0];
1403
+ }
1404
+ function ppTick() {
1405
+ const room = pp.room;
1406
+ if (!room) return;
1407
+ const t = ppNow();
1408
+ ppClock(room, t);
1409
+ if (pp.mode === "bots") return botTurn(room, t);
1410
+ const r = room.round;
1411
+ if (room.state === "playing" && r && t > r.endsAt + 250 && !pp.busy && (referee(room) === pp.me || t > r.endsAt + 3000)) {
1412
+ pp.busy = true;
1413
+ ppDo((x, tt) => PP.pop(x, tt, Math.random)).finally(() => { pp.busy = false; });
1414
+ }
1415
+ if (room.players[room.host] && room.players[room.host].on === false && referee(room) === pp.me && !pp.busy) {
1416
+ pp.busy = true;
1417
+ ppDo((x) => { if (x.players[x.host] && x.players[x.host].on !== false) return "ok"; x.host = pp.me; x.seq++; return x; }).finally(() => { pp.busy = false; });
1418
+ }
1419
+ if (room.host === pp.me) { // keep this room's spot in the public list up to date
1420
+ const n = PP.seats(room).length, want = room.pub && room.state === "lobby" && n < MAX_PLAYERS, sig = want ? `${n}|${room.pack}` : "off";
1421
+ if (sig !== pp.listSig) {
1422
+ pp.listSig = sig;
1423
+ const ref = net.db.ref(`krillionwho/lobbies/${pp.code}`);
1424
+ (want ? ref.set({ name: room.players[pp.me].name, n, pack: room.pack, ts: TS() }) : ref.remove()).catch(() => {});
1425
+ }
1426
+ }
1427
+ }
1428
+ // The computer's turn: decide once per pass whether it knows one, then answer after a "thinking" pause
1429
+ function botTurn(room, t) {
1430
+ const r = room.round;
1431
+ if (room.state !== "playing" || !r) return;
1432
+ if (t > r.endsAt) { ppDo((x, tt) => PP.pop(x, tt, Math.random)); return; }
1433
+ if (!room.players[r.holder].bot || t < r.startsAt) return;
1434
+ if (!pp.plan || pp.plan.at !== r.at || pp.plan.holder !== r.holder) {
1435
+ const p = BANK.byKey.get(r.key), lv = pp.level;
1436
+ const free = p.pool.filter((i) => !(r.used && r.used[p.cat.entries[i].key]));
1437
+ const usedUp = 1 - free.length / p.pool.length;
1438
+ const blank = !free.length || Math.random() < [0.09, 0.045, 0.02][lv] + usedUp * usedUp * [0.9, 0.6, 0.35][lv];
1439
+ const think = [2400, 1500, 900][lv] + Math.random() * [5200, 4000, 2600][lv];
1440
+ const reach = Math.max(3, Math.ceil(free.length * [0.35, 0.6, 1][lv]));
1441
+ const i = free[Math.floor(Math.random() * Math.min(reach, free.length))];
1442
+ pp.plan = { at: r.at, holder: r.holder, when: Math.max(t, r.startsAt) + think, ans: blank ? null : { key: p.cat.entries[i].key, pts: listPts(p, i) } };
1443
+ }
1444
+ if (pp.plan.ans && t >= pp.plan.when) {
1445
+ const { key, pts } = pp.plan.ans, who = r.holder;
1446
+ pp.plan.ans = null;
1447
+ ppDo((x, tt) => PP.pass(x, who, key, pts, tt));
1448
+ }
1449
+ }
1450
+ async function ppAnswer(raw, accepted) {
1451
+ const room = pp.room, r = room && room.round;
1452
+ if (!r || r.holder !== pp.me || ppNow() < r.startsAt) return;
1453
+ const p = BANK.byKey.get(r.key), res = accepted || check(p, raw);
1454
+ const input = $("kw-pp-input");
1455
+ ppDropClose();
1456
+ if (res.why === "close") { // "Did you mean…?": Enter again (or a click) takes it
1457
+ pp.close = { res, raw, prompt: p, at: r.at };
1458
+ const box = $("kw-pp-close");
1459
+ box.hidden = false;
1460
+ box.innerHTML = `did you mean <button class="kw-btn small" type="button" data-act="pp-close-yes">${esc(res.entry.name)}</button>? <small>press enter to pass it on</small>`;
1461
+ sfx.play("ask");
1462
+ return;
1463
+ }
1464
+ if (!res.ok) { sfx.play("miss"); return ppSay(whyText(res, raw, p), true, input); }
1465
+ const key = res.entry.key;
1466
+ if (r.used && r.used[key]) { sfx.play("miss"); return ppSay(`${res.entry.name} was already said by ${personName(r.used[key])}.`, true, input); }
1467
+ const pts = listPts(p, res.i);
1468
+ if (input) input.value = "";
1469
+ const why = await ppDo((x, t) => PP.pass(x, pp.me, key, pts, t));
1470
+ if (why) return ppSay(why === "used" ? `Someone just said ${res.entry.name}.` : "Too late!", true);
1471
+ ppSay("");
1472
+ if (pp.mode === "online") addCount(p.key, key);
1473
+ }
1474
+ function ppDropClose() {
1475
+ pp.close = null;
1476
+ const box = $("kw-pp-close");
1477
+ if (box) box.hidden = true;
1478
+ }
1479
+ function ppSay(text, bad, input) {
1480
+ const n = $("kw-pp-msg");
1481
+ if (n) { n.textContent = text || ""; n.classList.toggle("err", !!bad); }
1482
+ if (bad && input) { input.classList.remove("shake"); void input.offsetWidth; input.classList.add("shake"); input.select(); }
1483
+ }
1484
+
1485
+ function ppRender() {
1486
+ const room = pp.room;
1487
+ if (!room || ui.screen !== "pp") return;
1488
+ const box = $("kw-pp");
1489
+ if (!box) return;
1490
+ if (pp.screen !== room.state) {
1491
+ pp.screen = room.state;
1492
+ box.dataset.state = room.state;
1493
+ box.innerHTML = ppShell(room.state);
1494
+ if (room.state !== "over") pp.overSeen = false;
1495
+ }
1496
+ const mine = room.host === pp.me, ids = PP.seats(room);
1497
+ const head = $("kw-pp-head"), lobby = room.state === "lobby";
1498
+ if (head) head.innerHTML = pp.mode === "bots" ? `<span class="kw-label">PUFFER PARTY · VS THE COMPUTER</span>`
1499
+ : `<span class="kw-label">PUFFER PARTY · ROOM</span>${lobby ? "" : `<button class="kw-code" type="button" data-act="pp-copy" title="Copy the code">${esc(pp.code)}</button>`}` +
1500
+ `${room.pub ? `<span class="kw-tag">PUBLIC</span>` : ""}${lobby ? `<span class="kw-count">${ids.length}/${MAX_PLAYERS} DIVERS</span>` : ""}`;
1501
+ // In an online lobby the room code gets its own big card, so it's easy to read out to friends
1502
+ const card = $("kw-pp-room");
1503
+ if (card) {
1504
+ card.hidden = pp.mode !== "online";
1505
+ if (pp.mode === "online" && card.dataset.code !== pp.code) {
1506
+ card.dataset.code = pp.code;
1507
+ card.innerHTML = `<p class="kw-label">ROOM CODE</p>
1508
+ <button class="kw-bigcode" type="button" data-act="pp-copy" title="Copy the code" aria-label="Room code ${esc([...pp.code].join(" "))}. Copy it">${[...pp.code].map((c) => `<b>${esc(c)}</b>`).join("")}</button>
1509
+ <p class="kw-muted">Friends open Puffer Party, type this code and press <b>JOIN</b>. Click the code to copy it.</p>`;
1510
+ }
1511
+ }
1512
+ ppSeats(room);
1513
+ const burst = ppPopped(room);
1514
+ if (lobby) {
1515
+ const here = ids.filter((id) => room.players[id].on !== false).length;
1516
+ const packs = [["all", "Everything"], ...BANK.packs].map(([id, label]) => `<option value="${id}"${room.pack === id ? " selected" : ""}>${esc(label)}</option>`).join("");
1517
+ $("kw-pp-setup").innerHTML = mine
1518
+ ? `<label>PACK <select data-set="pack">${packs}</select></label>
1519
+ <label>LIVES <select data-set="lives">${[1, 2, 3].map((n) => `<option${room.lives === n ? " selected" : ""}>${n}</option>`).join("")}</select></label>
1520
+ ${pp.mode === "bots" ? `<label>OPPONENTS <select data-set="bots">${[1, 2, 3, 4, 5].map((n) => `<option${pp.bots === n ? " selected" : ""}>${n}</option>`).join("")}</select></label>
1521
+ <label>COMPUTER <select data-set="level">${["Easy", "Normal", "Hard"].map((l, n) => `<option value="${n}"${pp.level === n ? " selected" : ""}>${l}</option>`).join("")}</select></label>`
1522
+ : `<label class="kw-check"><input type="checkbox" data-set="pub"${room.pub ? " checked" : ""}> Anyone can join with Quick play</label>`}`
1523
+ : `<p class="kw-muted">Pack: <b>${esc(packName(room.pack))}</b> · Lives: <b>${room.lives}</b></p>`;
1524
+ $("kw-pp-go").innerHTML = mine
1525
+ ? `<button class="kw-play small" type="button" data-act="pp-start"${here < 2 ? " disabled" : ""}>▶ START ◀</button>${here < 2 ? `<p class="kw-muted">You need at least 2 players to start.</p>` : ""}`
1526
+ : `<p class="kw-muted">Waiting for the host to start…</p>`;
1527
+ } else if (room.state === "playing") ppGame(room);
1528
+ else {
1529
+ const w = room.winner;
1530
+ const win = $("kw-pp-win");
1531
+ win.innerHTML = `<span class="kw-trophy">🏆</span><h2>${w === pp.me ? "YOU WIN!" : `${esc(personName(w)).toUpperCase()} WINS!`}</h2>` +
1532
+ `<p class="kw-muted">${w === pp.me ? "Last diver standing." : "Better luck next time."}</p>`;
1533
+ if (!pp.overSeen) { // the last pufferfish bursts first, then the winner comes up
1534
+ pp.overSeen = true;
1535
+ win.classList.toggle("late", burst);
1536
+ setTimeout(() => sfx.play(w === pp.me ? "win" : "lose"), burst ? 1100 : 0);
1537
+ }
1538
+ $("kw-pp-go").innerHTML = mine ? `<button class="kw-play small" type="button" data-act="pp-again">▶ PLAY AGAIN ◀</button>` : `<p class="kw-muted">Waiting for the host to start another game…</p>`;
1539
+ }
1540
+ }
1541
+ // The table (everyone in a ring of bubbles around the pufferfish) on one side, the prompt and your answer on the other
1542
+ function ppShell(state) {
1543
+ const top = `<div class="kw-pp-top"><div id="kw-pp-head"></div><button class="kw-link" type="button" data-act="pp-leave">◀ LEAVE</button></div>`;
1544
+ const table = (extra = "") => `<div class="kw-arena" id="kw-pp-stage"><ul class="kw-seats" id="kw-pp-seats"></ul>
1545
+ <div class="kw-pf" id="kw-pf"><div class="kw-puffer" id="kw-puffer" data-act="pp-poke">${PUFF_CALM}${PUFFER}</div></div>${extra}</div>`;
1546
+ if (state === "lobby") return `${top}${table()}<div class="kw-side"><div class="kw-panel kw-pp-room" id="kw-pp-room" hidden></div><div class="kw-panel kw-pp-lobby">
1547
+ <div class="kw-pp-setup" id="kw-pp-setup"></div><div id="kw-pp-go"></div>
1548
+ <p class="kw-muted kw-rules">When the pufferfish comes to you, type an answer that fits the prompt to pass it on. The fuse keeps burning between turns, but nobody gets less than 8 seconds. No repeats. If it pops on you, you lose a life and a new prompt starts. A 100-point answer wins back a life.</p></div></div>`;
1549
+ if (state === "playing") return `${top}${table()}<div class="kw-side">
1550
+ <div class="kw-panel kw-pp-ask"><p class="kw-card-top" id="kw-pp-round"></p><h2 class="kw-prompt" id="kw-pp-prompt"></h2><p class="kw-hint" id="kw-pp-hint"></p></div>
1551
+ <div class="kw-panel kw-pp-play">
1552
+ <p class="kw-pp-clock" id="kw-pp-clock"></p>
1553
+ <p class="kw-pp-turn" id="kw-pp-turn"></p>
1554
+ <form class="kw-answer" data-form="pp-answer" id="kw-pp-form" autocomplete="off">
1555
+ <input id="kw-pp-input" maxlength="60" spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="type an answer to pass it on…" aria-label="Your answer">
1556
+ <button class="kw-btn" type="submit">PASS ▶</button>
1557
+ </form>
1558
+ <div class="kw-close" id="kw-pp-close" hidden aria-live="assertive"></div>
1559
+ <p class="kw-note" id="kw-pp-msg" aria-live="polite"></p>
1560
+ <p class="kw-pp-last" id="kw-pp-last"></p>
1561
+ </div>
1562
+ <div class="kw-panel kw-used"><p class="kw-label">ALREADY SAID</p><ul class="kw-chips" id="kw-pp-used"></ul></div></div>`;
1563
+ return `${top}${table(`<div class="kw-pp-win" id="kw-pp-win"></div>`)}<div class="kw-side"><div class="kw-panel kw-pp-over" id="kw-pp-go"></div></div>`;
1564
+ }
1565
+ // A different creature for everyone at the table: their seat's, or the next one nobody has
1566
+ function critters(room) {
1567
+ const out = {}, taken = new Set();
1568
+ for (const id of PP.seats(room)) {
1569
+ let c = (Math.max(1, room.players[id].seat || 1) - 1) % CRITTERS.length;
1570
+ while (taken.has(c)) c = (c + 1) % CRITTERS.length;
1571
+ taken.add(c);
1572
+ out[id] = c;
1573
+ }
1574
+ return out;
1575
+ }
1576
+ // Seats go round the table with you at the bottom; the rest follow in seat order. Seats are kept and moved, not rebuilt,
1577
+ // so the bubbles keep bobbing and slide when someone joins or leaves. An online lobby shows its open seats too.
1578
+ function ppSeats(room) {
1579
+ const box = $("kw-pp-seats");
1580
+ if (!box) return;
1581
+ const ids = PP.seats(room), at = ids.indexOf(pp.me), order = at > 0 ? [...ids.slice(at), ...ids.slice(0, at)] : ids;
1582
+ const lobby = room.state === "lobby", open = lobby && pp.mode === "online" ? Math.max(0, MAX_PLAYERS - ids.length) : 0;
1583
+ const n = order.length + open, look = critters(room), hold = room.state === "playing" && room.round ? room.round.holder : null;
1584
+ const spot = (k) => { const a = Math.PI / 2 + (k / n) * Math.PI * 2; return [50 + 37 * Math.cos(a), 50 + 35 * Math.sin(a)]; };
1585
+ const seen = new Set();
1586
+ const put = (key, k, cls, c, name, hearts) => {
1587
+ let li = [...box.children].find((x) => x.dataset.k === key);
1588
+ if (!li) {
1589
+ li = document.createElement("li");
1590
+ li.dataset.k = key;
1591
+ li.innerHTML = `<span class="kw-bub"></span><span class="kw-pn"></span><span class="kw-hearts"></span>`;
1592
+ li.style.setProperty("--d", `-${((box.children.length * 0.83) % 3.2).toFixed(2)}s`);
1593
+ box.appendChild(li);
1594
+ }
1595
+ seen.add(li);
1596
+ const [x, y] = spot(k), [bub, nm, ht] = li.children;
1597
+ li.className = `kw-seat ${cls}`;
1598
+ li.style.left = `${x.toFixed(2)}%`;
1599
+ li.style.top = `${y.toFixed(2)}%`;
1600
+ if (bub.dataset.c !== String(c)) { bub.dataset.c = c; bub.innerHTML = c >= 0 ? CRITTERS[c] : ""; }
1601
+ if (nm.dataset.v !== name) { nm.dataset.v = name; nm.innerHTML = name; }
1602
+ if (ht.dataset.v !== hearts) { ht.dataset.v = hearts; ht.innerHTML = hearts; }
1603
+ return [x, y];
1604
+ };
1605
+ pp.spots = {};
1606
+ order.forEach((id, k) => {
1607
+ const p = room.players[id], out = !lobby && p.lives <= 0;
1608
+ const cls = [id === pp.me && "me", id === hold && "hold", out && "out", p.on === false && "off", room.state === "over" && room.winner === id && "won",
1609
+ pp.hit && pp.hit.uid === id && Date.now() < pp.hit.until && "hit"].filter(Boolean).join(" ");
1610
+ const hearts = lobby ? "" : `${"♥".repeat(Math.max(0, p.lives))}<i>${"♥".repeat(Math.max(0, room.lives - p.lives))}</i>`;
1611
+ pp.spots[id] = put(id, k, cls, look[id], `${id === room.host ? "👑 " : ""}${esc(ctx.maskSlurs(p.name))}`, hearts);
1612
+ });
1613
+ for (let j = 0; j < open; j++) put(`open${j}`, order.length + j, "open", -1, "open", "");
1614
+ for (const li of [...box.children]) if (!seen.has(li)) li.remove();
1615
+ }
1616
+ function ppGame(room) {
1617
+ const r = room.round;
1618
+ if (!r) return;
1619
+ const p = BANK.byKey.get(r.key);
1620
+ $("kw-pp-round").textContent = `ROUND ${r.n} · ${p ? packName(p.cat.pack).toUpperCase() : ""}`;
1621
+ $("kw-pp-prompt").textContent = p ? p.text : "…";
1622
+ $("kw-pp-hint").textContent = p ? p.hint : "";
1623
+ // every answer shows in the color of the rarity it got
1624
+ const used = Object.entries(r.used || {}), tierOf = (k) => { const i = p ? p.cat.entries.findIndex((e) => e.key === k) : -1; return i >= 0 ? listPts(p, i) : 0; };
1625
+ $("kw-pp-used").innerHTML = used.length ? used.map(([k, who]) => `<li class="tier t${tierOf(k)}${who === pp.me ? " me" : ""}">${esc(answerName(r.key, k))}</li>`).join("") : `<li class="kw-muted">Nothing yet.</li>`;
1626
+ const last = r.last, lastEl = $("kw-pp-last");
1627
+ lastEl.innerHTML = last ? `${last.uid === pp.me ? "You" : esc(personName(last.uid))} said <b class="kw-tc t${last.pts}">${esc(answerName(r.key, last.a))}</b> ` +
1628
+ `<span class="kw-tag t${last.pts}">${TIERS[last.pts] ? `${TIERS[last.pts][1]} ${TIERS[last.pts][0].toUpperCase()} ` : ""}+${last.pts}</span>${last.bonus ? " and won back a life! ♥" : ""}` : "";
1629
+ if (last && last.at !== pp.lastPass) { pp.lastPass = last.at; sfx.play("pass"); lastEl.classList.remove("fresh"); void lastEl.offsetWidth; lastEl.classList.add("fresh"); }
1630
+ const mineTurn = r.holder === pp.me;
1631
+ const input = $("kw-pp-input"), form = $("kw-pp-form");
1632
+ if (pp.close && (!mineTurn || pp.close.at !== r.at)) ppDropClose(); // the puffer moved on: the suggestion is stale
1633
+ if (mineTurn && form.hidden) sfx.play("go");
1634
+ form.hidden = !mineTurn;
1635
+ if (mineTurn && document.activeElement !== input && ppNow() >= r.startsAt) { input.focus(); form.scrollIntoView({ block: "nearest" }); }
1636
+ ppClock(room, ppNow());
1637
+ }
1638
+ // Where the pufferfish hangs out: partway from the middle of the table toward someone's seat
1639
+ const near = (s) => [50 + (s[0] - 50) * 0.4, 50 + (s[1] - 50) * 0.4];
1640
+ // Someone's time ran out: the pufferfish bursts where it was, their bubble shakes, and a fresh one swims in after
1641
+ function ppPopped(room) {
1642
+ const pop = room.pop, arena = $("kw-pp-stage"), s = pp.spots && pop && pp.spots[pop.uid];
1643
+ if (!pop || pop.at === pp.shownPop) return false;
1644
+ pp.shownPop = pop.at;
1645
+ if (!arena || !s || ppNow() - pop.at > 4000) return false;
1646
+ const [x, y] = near(s), me = pop.uid === pp.me, lives = room.players[pop.uid] ? room.players[pop.uid].lives : 0;
1647
+ const colors = ["#ef4444", "#f97316", "#fbbf24", "#fde68a", "#fff7e6", "#b91c1c", "#fcd34d", "#c2410c"];
1648
+ let bits = "";
1649
+ for (let i = 0; i < 26; i++) {
1650
+ const a = (i / 26) * Math.PI * 2 + Math.random() * 0.4, d = 0.55 + Math.random() * 0.8;
1651
+ bits += `<i style="--x:${(Math.cos(a) * d).toFixed(2)};--y:${(Math.sin(a) * d).toFixed(2)};--r:${Math.round(Math.random() * 720 - 360)}deg;` +
1652
+ `--z:${(0.5 + Math.random() * 0.9).toFixed(2)};--c:${colors[i % colors.length]};--t:${(0.65 + Math.random() * 0.5).toFixed(2)}s"></i>`;
1653
+ }
1654
+ const boom = document.createElement("div");
1655
+ boom.className = "kw-boom";
1656
+ boom.style.left = `${x.toFixed(2)}%`;
1657
+ boom.style.top = `${y.toFixed(2)}%`;
1658
+ boom.innerHTML = `<span class="kw-boom-flash"></span><span class="kw-boom-ring"></span>${bits}<b class="kw-boom-word">POP!</b>`;
1659
+ const lost = document.createElement("b");
1660
+ lost.className = "kw-lost";
1661
+ lost.style.left = `${s[0].toFixed(2)}%`;
1662
+ lost.style.top = `${s[1].toFixed(2)}%`;
1663
+ lost.textContent = "−♥";
1664
+ arena.append(boom, lost);
1665
+ setTimeout(() => { boom.remove(); lost.remove(); }, 1800);
1666
+ arena.classList.remove("shake"); void arena.offsetWidth; arena.classList.add("shake");
1667
+ pp.goneUntil = Date.now() + 1500;
1668
+ pp.hit = { uid: pop.uid, until: Date.now() + 900 };
1669
+ const seat = [...$("kw-pp-seats").children].find((li) => li.dataset.k === pop.uid);
1670
+ if (seat) seat.classList.add("hit");
1671
+ const wrap = $("kw-pf");
1672
+ if (wrap) wrap.classList.add("gone");
1673
+ sfx.play("pop");
1674
+ ppSay(`💥 ${me ? "You" : personName(pop.uid)} ${me ? "lose" : "loses"} a life${lives <= 0 ? ` and ${me ? "are" : "is"} out` : ""}!`, false);
1675
+ return true;
1676
+ }
1677
+ // The pufferfish swims over toward whoever has it (facing them), and the ring round their bubble burns down with their time
1678
+ function ppAim(r, part) {
1679
+ const s = pp.spots && pp.spots[r.holder], wrap = $("kw-pf"), seats = $("kw-pp-seats");
1680
+ if (wrap && s) {
1681
+ const [x, y] = near(s);
1682
+ wrap.style.left = `${x.toFixed(2)}%`;
1683
+ wrap.style.top = `${y.toFixed(2)}%`;
1684
+ wrap.classList.toggle("right", s[0] > 52);
1685
+ }
1686
+ const seat = seats && [...seats.children].find((li) => li.dataset.k === r.holder);
1687
+ if (seat) seat.style.setProperty("--left", Math.max(0, Math.min(1, part)).toFixed(3));
1688
+ }
1689
+ // Calm while there's time; with under PUFF_AT left it puffs up into a spiky ball that swells, reddens and shakes until someone passes it or it pops
1690
+ function ppPuff(fish, heat, grown) {
1691
+ const puffed = heat > 0;
1692
+ if (puffed !== fish.classList.contains("puffed")) { fish.classList.toggle("puffed", puffed); if (puffed) sfx.play("puff"); }
1693
+ fish.classList.toggle("critical", heat > 0.6);
1694
+ fish.style.setProperty("--s", (puffed ? 1 + heat * 0.6 : 0.9 + grown * 0.15).toFixed(3));
1695
+ fish.style.setProperty("--heat", heat.toFixed(3));
1696
+ }
1697
+ function ppClock(room, t) {
1698
+ const r = room.round, fish = $("kw-puffer"), wrap = $("kw-pf");
1699
+ if (room.state !== "playing" || !r || !fish) return;
1700
+ if (wrap) wrap.classList.toggle("gone", Date.now() < pp.goneUntil);
1701
+ const turn = $("kw-pp-turn"), clock = $("kw-pp-clock"), mineTurn = r.holder === pp.me, input = $("kw-pp-input");
1702
+ if (t < r.startsAt) {
1703
+ clock.textContent = `next prompt in ${Math.ceil((r.startsAt - t) / 1000)}…`;
1704
+ turn.textContent = mineTurn ? "You start with the pufferfish. Get ready!" : `${personName(r.holder)} starts with the pufferfish.`;
1705
+ input.disabled = true;
1706
+ ppPuff(fish, 0, 0);
1707
+ ppAim(r, 1);
1708
+ return;
1709
+ }
1710
+ input.disabled = !mineTurn;
1711
+ const left = Math.max(0, r.endsAt - t), span = Math.max(1, r.endsAt - Math.max(r.at, r.startsAt));
1712
+ ppAim(r, left / span);
1713
+ const heat = Math.min(1, Math.max(0, 1 - left / PUFF_AT));
1714
+ ppPuff(fish, heat, Math.min(1, 1 - left / Math.max(span, FLOOR)));
1715
+ clock.textContent = `${(left / 1000).toFixed(1)}s`;
1716
+ clock.classList.toggle("hurry", left < 4000);
1717
+ if (left > 0 && Date.now() - pp.lastFuse > 650 - heat * 500) { pp.lastFuse = Date.now(); sfx.play("fuse", heat > 0.6 ? 1 : 0); } // the fuse ticks faster as it burns down
1718
+ const holder = room.players[r.holder];
1719
+ turn.textContent = mineTurn ? "Your turn! Type an answer to pass it on." : holder && holder.bot ? `${holder.name} is thinking…` : `${personName(r.holder)} has the pufferfish…`;
1720
+ }
1721
+
1722
+ // ---------- Events ----------
1723
+ function onClick(e) {
1724
+ if (e.target.id === "kw-modal") { closeSheet(); return; } // clicked outside a pop-up
1725
+ const b = e.target.closest("[data-act]");
1726
+ if (!b || !root.contains(b)) return;
1727
+ const act = b.dataset.act, quiet = ["sound", "next", "close-yes", "pp-close-yes", "daily", "free", "past", "again", "pp-poke"];
1728
+ if (!quiet.includes(act)) sfx.play("click");
1729
+ if (act === "play") playSheet();
1730
+ else if (act === "howto") howSheet();
1731
+ else if (act === "board") boardSheet();
1732
+ else if (act === "menu") menuSheet();
1733
+ else if (act === "close") closeSheet();
1734
+ else if (act === "sound") { sfx.on = !sfx.on; ctx.store.set(SOUND_KEY, sfx.on); soundIcon(); if (sfx.on) sfx.play("click"); if ($("kw-modal").querySelector("[data-form=rename]")) menuSheet(); }
1735
+ else if (act === "daily") startDaily();
1736
+ else if (act === "free-menu") freeSheet();
1737
+ else if (act === "pp-menu") partySheet();
1738
+ else if (act === "free") { ui.pack = b.dataset.pack; ctx.store.set(PACK_KEY, ui.pack); ctx.track("KrillionWho: free play"); beginDive("free", pickFree(ui.pack)); }
1739
+ else if (act === "past") beginDive("past", pickDaily(b.dataset.date), [], b.dataset.date);
1740
+ else if (act === "again") beginDive(dive.mode === "past" ? "past" : "free", dive.mode === "past" ? pickDaily(dive.date) : pickFree(ui.pack), [], dive.date);
1741
+ else if (act === "next") { if (dive.answers.length >= ROUNDS) finishDive(); else nextRound(); }
1742
+ else if (act === "close-yes" && dive.close) answer(false, confirmClose(dive.prompt, dive.close));
1743
+ else if (act === "close-no") dropClose(true);
1744
+ else if (act === "quit" || act === "surface") { if (ui.screen === "pp") ppLeave(); else renderHome(true); }
1745
+ else if (act === "share") { const text = shareText(); navigator.clipboard?.writeText(text).then(() => ctx.toast("Copied! Paste it anywhere."), () => ctx.toast(text)); }
1746
+ else if (act === "report") { b.disabled = true; report(b.dataset.text); }
1747
+ else if (act === "pp-create") askName((name) => ppCreate(false, name), "So the others know who's who.");
1748
+ else if (act === "pp-quick") askName((name) => ppQuick(name), "So the others know who's who.");
1749
+ else if (act === "pp-bots") ppBots(myName());
1750
+ else if (act === "pp-rejoin") askName((name) => ppJoin(ctx.store.get(ROOM_KEY, ""), name), "So the others know who's who.");
1751
+ else if (act === "pp-leave") ppLeave();
1752
+ else if (act === "pp-copy") navigator.clipboard?.writeText(pp.code).then(() => ctx.toast(`Room code ${pp.code} copied.`), () => {});
1753
+ else if (act === "pp-poke") { // poke the pufferfish while you wait and it puffs up for a moment
1754
+ if (!pp.room || pp.room.state !== "lobby" || b.classList.contains("puffed")) return;
1755
+ b.classList.add("puffed");
1756
+ sfx.play("puff");
1757
+ setTimeout(() => b.classList.remove("puffed"), 1400);
1758
+ }
1759
+ else if (act === "pp-start") ppDo((x, t) => PP.start(x, t, Math.random)).then((why) => { if (why) ppSay(ppNoteText(why), true); });
1760
+ else if (act === "pp-again") ppDo((x) => PP.reset(x));
1761
+ else if (act === "pp-close-yes" && pp.close) ppAnswer(pp.close.raw, confirmClose(pp.close.prompt, pp.close.res));
1762
+ }
1763
+ function onChange(e) {
1764
+ const el = e.target.closest("[data-set]");
1765
+ if (!el || !pp.room || pp.room.host !== pp.me) return;
1766
+ const what = el.dataset.set;
1767
+ if (what === "bots") return setBots(Number(el.value));
1768
+ if (what === "level") { pp.level = Number(el.value); return; }
1769
+ const val = what === "lives" ? Number(el.value) : what === "pub" ? el.checked : el.value;
1770
+ if (what === "pack") { ui.pack = val; ctx.store.set(PACK_KEY, val); }
1771
+ ppDo((x) => { x[what] = val; if (what === "lives") for (const p of Object.values(x.players)) p.lives = val; x.seq++; return x; });
1772
+ }
1773
+ function onSubmit(e) {
1774
+ const form = e.target.closest("[data-form]");
1775
+ if (!form || !root.contains(form)) return;
1776
+ e.preventDefault();
1777
+ const kind = form.dataset.form;
1778
+ if (kind === "answer") answer(false);
1779
+ else if (kind === "pp-answer") {
1780
+ const raw = $("kw-pp-input").value;
1781
+ if (pp.close && pp.close.raw === raw) ppAnswer(raw, confirmClose(pp.close.prompt, pp.close.res));
1782
+ else ppAnswer(raw);
1783
+ } else if (kind === "pp-join") askName((name) => ppJoin($("kw-code").value, name), "So the others know who's who.");
1784
+ else if (kind === "name" || kind === "rename") {
1785
+ const res = cleanName($("kw-name-in").value);
1786
+ if (res.error) return sheetNote(res.error, true);
1787
+ ctx.store.set(KW_NAME_KEY, res.name); // KrillionWho's own, so a name the chat doesn't allow can't break chat
1788
+ if (!ctx.store.get(NAME_KEY, "") && !/^ *richard *$/i.test(res.name)) ctx.store.set(NAME_KEY, res.name); // chat can use it too, if chat has none yet
1789
+ sfx.play("click");
1790
+ if (kind === "rename") return sheetNote(`Saved: ${res.name}`);
1791
+ const then = afterName;
1792
+ afterName = null;
1793
+ closeSheet();
1794
+ if (then) then(res.name);
1795
+ }
1796
+ }
1797
+ function onKey(e) { // Enter moves on from a revealed answer
1798
+ if (e.key === "Escape" && !$("kw-modal").hidden) { closeSheet(); return; }
1799
+ if (e.key !== "Enter" || ui.screen !== "dive" || root.closest("[hidden]")) return;
1800
+ const next = $("kw-next");
1801
+ if (next && !$("kw-reveal").hidden && document.activeElement !== next) { e.preventDefault(); next.click(); }
1802
+ }
1803
+
1804
+ // ---------- Hooking into the page ----------
1805
+ function mount(el, helpers) {
1806
+ ctx = helpers;
1807
+ root = el;
1808
+ BANK = buildBank(window.KRILLIONWHO_DATA);
1809
+ sfx.on = ctx.store.get(SOUND_KEY, true) !== false;
1810
+ ui.pack = ctx.store.get(PACK_KEY, "all");
1811
+ if (ui.pack !== "all" && !BANK.packs.some(([id]) => id === ui.pack)) ui.pack = "all";
1812
+ root.innerHTML = sceneHtml();
1813
+ soundIcon();
1814
+ root.addEventListener("click", onClick);
1815
+ root.addEventListener("change", onChange);
1816
+ root.addEventListener("submit", onSubmit);
1817
+ root.addEventListener("input", (e) => { // typing again dismisses "Did you mean…?"
1818
+ if (e.target.id === "kw-input" && dive.close) dropClose(false);
1819
+ if (e.target.id === "kw-input" && $("kw-wrong")) $("kw-wrong").hidden = true;
1820
+ if (e.target.id === "kw-pp-input" && pp.close) ppDropClose();
1821
+ });
1822
+ document.addEventListener("keydown", onKey);
1823
+ if (window.ResizeObserver) new ResizeObserver(() => layout()).observe($("kw-stage")); // window resizes, and the section reopening
1824
+ else addEventListener("resize", layout);
1825
+ layout();
1826
+ renderHome();
1827
+ }
1828
+ // Opening the section again: a game in progress carries on; otherwise back to the surface
1829
+ function enter() {
1830
+ layout();
1831
+ if (ui.screen === "pp" && pp.mode) return ppRender();
1832
+ if (ui.screen === "dive" || ui.screen === "results" || ui.screen === "pp") return;
1833
+ renderHome();
1834
+ }
1835
+ // Leaving the section: an unanswered prompt in the daily dive is used up; a room keeps going without you watching
1836
+ function leave() {
1837
+ if (ui.screen === "dive" && dive.mode) { renderHome(); return; }
1838
+ if (pp.mode === "bots") { ppStop(); renderHome(); }
1839
+ }
1840
+ // From elsewhere on the site (the Daily Dive banner on the Games page): straight into today's dive, or the PLAY menu.
1841
+ // Someone sitting in a Puffer Party room stays there.
1842
+ function open(action) {
1843
+ if (!BANK || (ui.screen === "pp" && pp.mode)) return;
1844
+ if (action === "daily") startDaily();
1845
+ else if (action === "play") { if (ui.screen !== "home") renderHome(); playSheet(); }
1846
+ }
1847
+ const testBank = () => BANK || (BANK = buildBank(window.KRILLIONWHO_DATA));
1848
+ window.KrillionWho = { mount, enter, leave, open, _test: { bank: testBank, check: (key, raw) => check(testBank().byKey.get(key), raw), listPts, blendPts, pickDaily: (d) => (testBank(), pickDaily(d)), PP } };
1849
+ })();