@ywkrlerche/richardwho 1.0.52 → 1.0.53
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/app.js +87 -8
- package/games.json +10 -1
- package/index.html +10 -0
- package/krillionwho-data.js +2 -0
- package/krillionwho.css +377 -0
- package/krillionwho.js +1670 -0
- package/logos/krillionwho.svg +27 -0
- package/package.json +4 -1
- package/style.css +37 -0
package/krillionwho.js
ADDED
|
@@ -0,0 +1,1670 @@
|
|
|
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, MAX_PLAYERS = 8, ROOM_LIFE = 3 * 3600e3;
|
|
13
|
+
const DAILY_KEY = "rug-krillionwho", STATS_KEY = "rug-krillionwho-stats", NAME_KEY = "rug-chat-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
|
+
const TIERS = { 0: ["Missed", "💨"], 10: ["Seaweed", "🌿"], 20: ["Minnow", "🐟"], 30: ["Reef fish", "🐠"], 40: ["Sea turtle", "🐢"], 50: ["Dolphin", "🐬"],
|
|
20
|
+
60: ["Shark", "🦈"], 70: ["Octopus", "🐙"], 80: ["Giant squid", "🦑"], 90: ["Anglerfish", "🏮"], 100: ["Sea monster", "🐉"] };
|
|
21
|
+
const BOT_NAMES = ["Bubbles", "Finn", "Coral", "Kelp", "Barnacle", "Pearl", "Captain Gill"];
|
|
22
|
+
|
|
23
|
+
let ctx = null, root = null, BANK = null;
|
|
24
|
+
const $ = (id) => document.getElementById(id);
|
|
25
|
+
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
|
26
|
+
const clone = (o) => JSON.parse(JSON.stringify(o));
|
|
27
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
28
|
+
const dateStr = (d = new Date()) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
29
|
+
const dayBefore = (s, n = 1) => { const [y, m, d] = s.split("-").map(Number); return dateStr(new Date(y, m - 1, d - n)); };
|
|
30
|
+
const dayNumber = (s) => { const [y, m, d] = s.split("-").map(Number); return Math.round((new Date(y, m - 1, d) - LAUNCH) / 864e5) + 1; };
|
|
31
|
+
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" }); };
|
|
32
|
+
const fmtM = (m) => `${Math.round(m).toLocaleString()}m`;
|
|
33
|
+
const zoneAt = (m) => ZONES.filter(([at]) => m >= at).pop()[1];
|
|
34
|
+
const sum = (a) => a.reduce((t, r) => t + r.p, 0);
|
|
35
|
+
const wait = (ms) => new Promise((ok) => setTimeout(ok, ms));
|
|
36
|
+
const calm = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
37
|
+
|
|
38
|
+
// ---------- Matching answers ----------
|
|
39
|
+
// Must match norm() in tools/build-krillionwho.js
|
|
40
|
+
const norm = (s) => String(s || "").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase()
|
|
41
|
+
.replace(/&/g, " and ").replace(/['’‘`´ʻ.!?*]/g, "").replace(/[^a-z0-9♀♂]+/g, " ").trim()
|
|
42
|
+
.replace(/^the /, "").replace(/\bst\b/g, "saint").replace(/\bmt\b/g, "mount");
|
|
43
|
+
const tight = (s) => norm(s).replace(/ /g, "");
|
|
44
|
+
const keyOf = (s) => norm(s).replace(/♀/g, " f").replace(/♂/g, " m").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 48) || "x";
|
|
45
|
+
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) /;
|
|
46
|
+
|
|
47
|
+
// Typo distance (with swapped letters counting as one), giving up early past max
|
|
48
|
+
function dist(a, b, max) {
|
|
49
|
+
if (Math.abs(a.length - b.length) > max) return max + 1;
|
|
50
|
+
let two = null, one = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
51
|
+
for (let i = 1; i <= a.length; i++) {
|
|
52
|
+
const cur = [i];
|
|
53
|
+
let low = i;
|
|
54
|
+
for (let j = 1; j <= b.length; j++) {
|
|
55
|
+
let v = Math.min(one[j] + 1, cur[j - 1] + 1, one[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
56
|
+
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);
|
|
57
|
+
cur[j] = v;
|
|
58
|
+
if (v < low) low = v;
|
|
59
|
+
}
|
|
60
|
+
if (low > max) return max + 1;
|
|
61
|
+
two = one; one = cur;
|
|
62
|
+
}
|
|
63
|
+
return one[b.length];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function buildBank(data) {
|
|
67
|
+
const cats = new Map(), prompts = [];
|
|
68
|
+
const parse = (text) => String(text || "").split("\n").filter(Boolean).map((line) => {
|
|
69
|
+
const [main, tags = ""] = line.split("@");
|
|
70
|
+
const [names, cap] = main.split("#");
|
|
71
|
+
return { names: names.split("|"), cap: cap ? cap.split("|") : null, tags: tags ? tags.split(",") : [] };
|
|
72
|
+
});
|
|
73
|
+
for (const c of data.cats) {
|
|
74
|
+
let rows;
|
|
75
|
+
if (c.from) { // capitals: the source list's capitals, in its order
|
|
76
|
+
const seen = new Set();
|
|
77
|
+
rows = cats.get(c.from).rows.filter((r) => r.cap).map((r) => ({ names: r.cap, tags: r.tags, of: r.names[0] }))
|
|
78
|
+
.filter((r) => !seen.has(tight(r.names[0])) && seen.add(tight(r.names[0])));
|
|
79
|
+
} else rows = parse(c.a);
|
|
80
|
+
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() }));
|
|
81
|
+
const forms = new Map(), loose = new Map();
|
|
82
|
+
rows.forEach((r, i) => r.names.forEach((n) => { const f = tight(n); if (f && !forms.has(f)) forms.set(f, i); }));
|
|
83
|
+
rows.forEach((r, i) => r.names.forEach((n) => { // "Professor Snape" also answers to "Snape", unless that means someone else
|
|
84
|
+
const f = norm(n).replace(TITLES, "").replace(/ /g, "");
|
|
85
|
+
if (f && !forms.has(f)) loose.set(f, loose.has(f) && loose.get(f) !== i ? -1 : i);
|
|
86
|
+
}));
|
|
87
|
+
for (const [f, i] of loose) forms.set(f, i);
|
|
88
|
+
const notes = new Map();
|
|
89
|
+
for (const line of String(c.no || "").split("\n").filter(Boolean)) {
|
|
90
|
+
const [names, note] = line.split("=");
|
|
91
|
+
for (const n of names.split("|")) notes.set(tight(n), note);
|
|
92
|
+
}
|
|
93
|
+
const cat = { ...c, rows, entries, forms, notes, byKey: new Map(entries.map((e, i) => [e.key, i])) };
|
|
94
|
+
cats.set(c.id, cat);
|
|
95
|
+
const add = (key, text, hint, pool) => {
|
|
96
|
+
if (pool.length >= MIN_POOL) prompts.push({ key, cat, text, hint: hint || "", pool, rank: new Map(pool.map((i, n) => [i, n])) });
|
|
97
|
+
};
|
|
98
|
+
const all = entries.map((_, i) => i);
|
|
99
|
+
add(c.id, c.prompt || `Name ${c.n}`, c.hint, all);
|
|
100
|
+
for (const [t, phrase] of Object.entries(c.tags || {})) {
|
|
101
|
+
const [p, hint] = phrase.split("|");
|
|
102
|
+
add(`${c.id}~${t}`, p.startsWith("=") ? p.slice(1) : `Name ${c.n} ${p}`, hint, all.filter((i) => entries[i].tags.includes(t)));
|
|
103
|
+
}
|
|
104
|
+
if (c.letters) {
|
|
105
|
+
const by = {};
|
|
106
|
+
for (const i of all) (by[entries[i].letter] = by[entries[i].letter] || []).push(i);
|
|
107
|
+
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);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { cats, prompts, byKey: new Map(prompts.map((p) => [p.key, p])), packs: data.packs };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Exact spelling, a plural or singular, or the name without a title. -1 = could mean more than one.
|
|
114
|
+
function exact(cat, raw) {
|
|
115
|
+
const n = norm(raw);
|
|
116
|
+
if (!n) return undefined;
|
|
117
|
+
const tries = [];
|
|
118
|
+
for (const b of [n, n.replace(TITLES, "")]) {
|
|
119
|
+
tries.push(b);
|
|
120
|
+
if (b.endsWith("ies")) tries.push(b.slice(0, -3) + "y");
|
|
121
|
+
if (b.endsWith("es")) tries.push(b.slice(0, -2));
|
|
122
|
+
if (b.endsWith("s")) tries.push(b.slice(0, -1)); else tries.push(b + "s");
|
|
123
|
+
}
|
|
124
|
+
for (const t of tries) { const v = cat.forms.get(t.replace(/ /g, "")); if (v !== undefined) return v; }
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
// A misspelling close to one answer (and only one), for "Did you mean…?": up to 1 slip in short words, 3 in long ones.
|
|
128
|
+
// An answer that fits the prompt wins a tie with one that doesn't.
|
|
129
|
+
function closest(cat, raw, prompt) {
|
|
130
|
+
const t = tight(raw), max = t.length <= 3 ? 0 : t.length <= 5 ? 1 : t.length <= 9 ? 2 : 3;
|
|
131
|
+
if (!max) return undefined;
|
|
132
|
+
let best = max + 1, hit, tie = false;
|
|
133
|
+
for (const [form, i] of cat.forms) {
|
|
134
|
+
if (i < 0 || Math.abs(form.length - t.length) > max) continue;
|
|
135
|
+
const d = dist(t, form, Math.min(max, best));
|
|
136
|
+
if (d > best || i === hit) continue;
|
|
137
|
+
if (d < best) { best = d; hit = i; tie = false; continue; }
|
|
138
|
+
const fitsNew = prompt.rank.has(i), fitsOld = prompt.rank.has(hit);
|
|
139
|
+
if (fitsNew && !fitsOld) hit = i; else if (fitsNew === fitsOld) tie = true;
|
|
140
|
+
}
|
|
141
|
+
return best <= max && !tie ? hit : undefined;
|
|
142
|
+
}
|
|
143
|
+
function check(prompt, raw) {
|
|
144
|
+
const cat = prompt.cat, t = tight(raw);
|
|
145
|
+
if (!t) return { ok: false, why: "blank" };
|
|
146
|
+
let i = exact(cat, raw);
|
|
147
|
+
if (i === -1) return { ok: false, why: "vague" };
|
|
148
|
+
if (i === undefined) {
|
|
149
|
+
const note = cat.notes.get(t);
|
|
150
|
+
if (note) return { ok: false, why: "note", note };
|
|
151
|
+
if (cat.from) { // the country (or state) instead of its capital
|
|
152
|
+
const src = BANK.cats.get(cat.from), j = exact(src, raw);
|
|
153
|
+
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]}.` };
|
|
154
|
+
}
|
|
155
|
+
const near = closest(cat, raw, prompt);
|
|
156
|
+
if (near === undefined) return { ok: false, why: "unknown" };
|
|
157
|
+
return { ok: false, why: "close", i: near, entry: cat.entries[near] }; // ask before counting it
|
|
158
|
+
}
|
|
159
|
+
if (!prompt.rank.has(i)) return { ok: false, why: "filter", entry: cat.entries[i] };
|
|
160
|
+
return { ok: true, i, entry: cat.entries[i] };
|
|
161
|
+
}
|
|
162
|
+
// They said yes to "Did you mean…?"
|
|
163
|
+
function confirmClose(prompt, res) {
|
|
164
|
+
return prompt.rank.has(res.i) ? { ok: true, i: res.i, entry: res.entry } : { ok: false, why: "filter", entry: res.entry };
|
|
165
|
+
}
|
|
166
|
+
function whyText(res, raw, prompt) {
|
|
167
|
+
if (res.why === "time") return "Time's up!";
|
|
168
|
+
if (res.why === "blank") return "No answer.";
|
|
169
|
+
if (res.why === "note") return res.note;
|
|
170
|
+
if (res.why === "vague") return "That could mean more than one answer. Be more specific.";
|
|
171
|
+
if (res.why === "filter") {
|
|
172
|
+
const m = prompt.key.match(/~starts-([a-z])$/);
|
|
173
|
+
return m ? `${res.entry.name} doesn't start with ${m[1].toUpperCase()}.` : `${res.entry.name} doesn't fit this one.`;
|
|
174
|
+
}
|
|
175
|
+
return `"${String(raw).trim().slice(0, 40)}" isn't on our list.`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ---------- Rarity ----------
|
|
179
|
+
// From the list's order: the share of answers more common than this one sets the points
|
|
180
|
+
const STEPS = [0.03, 0.08, 0.15, 0.23, 0.32, 0.42, 0.53, 0.65, 0.8];
|
|
181
|
+
function listPts(prompt, i) {
|
|
182
|
+
const at = prompt.rank.get(i) / prompt.pool.length;
|
|
183
|
+
let n = 0;
|
|
184
|
+
while (n < STEPS.length && at >= STEPS[n]) n++;
|
|
185
|
+
return (n + 1) * 10;
|
|
186
|
+
}
|
|
187
|
+
// From what people here have said: under 0.3% of answers is a sea monster
|
|
188
|
+
const CUTS = [0.2, 0.12, 0.08, 0.05, 0.035, 0.022, 0.013, 0.007, 0.003];
|
|
189
|
+
function sharePts(share) { for (let n = 0; n < CUTS.length; n++) if (share >= CUTS[n]) return (n + 1) * 10; return 100; }
|
|
190
|
+
// The more answers a prompt has collected, the more they count (fully from 70 answers on)
|
|
191
|
+
function blendPts(list, counts, key) {
|
|
192
|
+
const total = Object.values(counts).reduce((a, b) => a + (Number(b) || 0), 0);
|
|
193
|
+
if (total < 10) return list;
|
|
194
|
+
const mine = counts[key] || 0, w = Math.min(1, (total - 10) / 60);
|
|
195
|
+
const live = mine <= 1 && total >= 30 ? 100 : sharePts(mine / total); // nobody else has ever said it
|
|
196
|
+
return Math.max(10, Math.min(100, Math.round(((1 - w) * list + w * live) / 10) * 10));
|
|
197
|
+
}
|
|
198
|
+
function topNames(prompt, counts) {
|
|
199
|
+
const cat = prompt.cat;
|
|
200
|
+
const fromCounts = counts ? Object.entries(counts).filter(([k]) => prompt.rank.has(cat.byKey.get(k))).sort((a, b) => b[1] - a[1]) : [];
|
|
201
|
+
const total = fromCounts.reduce((t, [, n]) => t + n, 0);
|
|
202
|
+
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);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---------- Database (all optional: without it the game still works, scored from the list) ----------
|
|
206
|
+
const net = { ready: null, db: null, uid: null, offset: 0 };
|
|
207
|
+
const now = () => Date.now() + net.offset;
|
|
208
|
+
const TS = () => window.firebase.database.ServerValue.TIMESTAMP;
|
|
209
|
+
const within = (p, ms) => Promise.race([p, new Promise((ok) => setTimeout(() => ok(null), ms))]);
|
|
210
|
+
function online() {
|
|
211
|
+
if (!net.ready) {
|
|
212
|
+
net.ready = (async () => {
|
|
213
|
+
const app = await ctx.getFirebase();
|
|
214
|
+
if (!app) return null;
|
|
215
|
+
const user = await ctx.user(app);
|
|
216
|
+
net.db = app.database();
|
|
217
|
+
net.uid = user.uid;
|
|
218
|
+
net.db.ref(".info/serverTimeOffset").on("value", (s) => { net.offset = s.val() || 0; });
|
|
219
|
+
return net;
|
|
220
|
+
})().catch((err) => { console.warn("KrillionWho offline:", err); net.ready = null; return null; });
|
|
221
|
+
}
|
|
222
|
+
return net.ready;
|
|
223
|
+
}
|
|
224
|
+
async function readCounts(promptKey) {
|
|
225
|
+
const f = await within(online(), 2500);
|
|
226
|
+
if (!f) return null;
|
|
227
|
+
try { const s = await within(f.db.ref(`krillionwho/counts/${promptKey}`).once("value"), 1800); return s ? (s.val() || {}) : null; } catch { return null; }
|
|
228
|
+
}
|
|
229
|
+
async function addCount(promptKey, key) {
|
|
230
|
+
const f = await online();
|
|
231
|
+
if (!f) return;
|
|
232
|
+
const FV = window.firebase.database.ServerValue;
|
|
233
|
+
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 */ }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ---------- Sound: little 8-bit effects, made on the spot ----------
|
|
237
|
+
const sfx = {
|
|
238
|
+
ac: null, out: null, on: true,
|
|
239
|
+
ready() {
|
|
240
|
+
if (!this.on) return null;
|
|
241
|
+
if (!this.ac) {
|
|
242
|
+
const AC = window.AudioContext || window.webkitAudioContext;
|
|
243
|
+
if (!AC) return null;
|
|
244
|
+
this.ac = new AC();
|
|
245
|
+
this.out = this.ac.createGain();
|
|
246
|
+
this.out.gain.value = 0.45;
|
|
247
|
+
this.out.connect(this.ac.destination);
|
|
248
|
+
}
|
|
249
|
+
if (this.ac.state === "suspended") this.ac.resume().catch(() => {});
|
|
250
|
+
return this.ac;
|
|
251
|
+
},
|
|
252
|
+
note(freq, at, dur, { type = "square", vol = 0.1, to = 0 } = {}) {
|
|
253
|
+
const ac = this.ac, o = ac.createOscillator(), g = ac.createGain(), t = ac.currentTime + at;
|
|
254
|
+
o.type = type;
|
|
255
|
+
o.frequency.setValueAtTime(freq, t);
|
|
256
|
+
if (to) o.frequency.exponentialRampToValueAtTime(to, t + dur);
|
|
257
|
+
g.gain.setValueAtTime(0.0001, t);
|
|
258
|
+
g.gain.exponentialRampToValueAtTime(vol, t + 0.012);
|
|
259
|
+
g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
|
|
260
|
+
o.connect(g); g.connect(this.out);
|
|
261
|
+
o.start(t); o.stop(t + dur + 0.03);
|
|
262
|
+
},
|
|
263
|
+
noise(at, dur, { vol = 0.2, from = 2000, to = 300, q = 1 } = {}) {
|
|
264
|
+
const ac = this.ac, len = Math.ceil(ac.sampleRate * dur), buf = ac.createBuffer(1, len, ac.sampleRate), data = buf.getChannelData(0);
|
|
265
|
+
for (let i = 0; i < len; i++) data[i] = Math.random() * 2 - 1;
|
|
266
|
+
const src = ac.createBufferSource(), f = ac.createBiquadFilter(), g = ac.createGain(), t = ac.currentTime + at;
|
|
267
|
+
src.buffer = buf;
|
|
268
|
+
f.type = "bandpass"; f.Q.value = q;
|
|
269
|
+
f.frequency.setValueAtTime(from, t);
|
|
270
|
+
f.frequency.exponentialRampToValueAtTime(to, t + dur);
|
|
271
|
+
g.gain.setValueAtTime(vol, t);
|
|
272
|
+
g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
|
|
273
|
+
src.connect(f); f.connect(g); g.connect(this.out);
|
|
274
|
+
src.start(t); src.stop(t + dur);
|
|
275
|
+
},
|
|
276
|
+
play(name, arg = 0) {
|
|
277
|
+
if (!this.ready()) return;
|
|
278
|
+
const n = (f, at, dur, o) => this.note(f, at, dur, o);
|
|
279
|
+
if (name === "click") n(700, 0, 0.05, { vol: 0.05 });
|
|
280
|
+
else if (name === "open") { n(520, 0, 0.06, { vol: 0.06 }); n(780, 0.05, 0.09, { vol: 0.06 }); }
|
|
281
|
+
else if (name === "tick") n(440, 0, 0.09, { vol: 0.07 });
|
|
282
|
+
else if (name === "go") { n(880, 0, 0.14, { vol: 0.09 }); n(1320, 0.07, 0.16, { vol: 0.05, type: "triangle" }); }
|
|
283
|
+
else if (name === "hurry") n(1150, 0, 0.05, { vol: 0.045 });
|
|
284
|
+
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
|
|
285
|
+
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" }); }
|
|
286
|
+
else if (name === "score") {
|
|
287
|
+
const scale = [523, 659, 784, 1047, 1319, 1568, 2093], steps = Math.max(1, Math.round(arg / 15));
|
|
288
|
+
for (let i = 0; i <= Math.min(steps, scale.length - 1); i++) n(scale[i], i * 0.065, 0.16, { vol: 0.075 });
|
|
289
|
+
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 }); }
|
|
290
|
+
} else if (name === "miss") n(330, 0, 0.38, { vol: 0.09, to: 110, type: "sawtooth" });
|
|
291
|
+
else if (name === "dive") {
|
|
292
|
+
this.noise(0, 1.5, { vol: 0.14, from: 1200, to: 160 });
|
|
293
|
+
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 });
|
|
294
|
+
} 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 }); }
|
|
295
|
+
else if (name === "pass") n(480, 0, 0.12, { vol: 0.07, to: 1000, type: "triangle" });
|
|
296
|
+
else if (name === "fuse") n(arg ? 1500 : 1050, 0, 0.03, { vol: 0.035 });
|
|
297
|
+
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 }); }
|
|
298
|
+
else if (name === "win") [523, 659, 784, 1047, 784, 1047, 1319].forEach((f, i) => n(f, i * 0.11, 0.2, { vol: 0.08 }));
|
|
299
|
+
else if (name === "lose") [392, 370, 349, 311].forEach((f, i) => n(f, i * 0.26, 0.3, { vol: 0.07, type: "sawtooth" }));
|
|
300
|
+
else if (name === "done") [392, 523, 659, 784].forEach((f, i) => n(f, i * 0.12, 0.22, { vol: 0.07, type: "triangle" }));
|
|
301
|
+
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
|
|
302
|
+
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 }); }
|
|
303
|
+
},
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
// ---------- Pixel art ----------
|
|
307
|
+
// Rows of letters, one per pixel ("." is empty), turned into an SVG; runs of one color become one rectangle
|
|
308
|
+
function sprite(rows, colors, cls) {
|
|
309
|
+
let rects = "";
|
|
310
|
+
rows.forEach((row, y) => {
|
|
311
|
+
for (let x = 0; x < row.length;) {
|
|
312
|
+
let w = 1;
|
|
313
|
+
while (x + w < row.length && row[x + w] === row[x]) w++;
|
|
314
|
+
if (colors[row[x]]) rects += `<rect x="${x}" y="${y}" width="${w}" height="1" fill="${colors[row[x]]}"/>`;
|
|
315
|
+
x += w;
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
return `<svg class="${cls}" viewBox="0 0 ${rows[0].length} ${rows.length}" shape-rendering="crispEdges" aria-hidden="true">${rects}</svg>`;
|
|
319
|
+
}
|
|
320
|
+
const GLYPHS = {
|
|
321
|
+
K: ["X...X", "X..X.", "X.X..", "XX...", "X.X..", "X..X.", "X...X"],
|
|
322
|
+
R: ["XXXX.", "X...X", "X...X", "XXXX.", "X.X..", "X..X.", "X...X"],
|
|
323
|
+
I: ["XXXXX", "..X..", "..X..", "..X..", "..X..", "..X..", "XXXXX"],
|
|
324
|
+
L: ["X....", "X....", "X....", "X....", "X....", "X....", "XXXXX"],
|
|
325
|
+
O: [".XXX.", "X...X", "X...X", "X...X", "X...X", "X...X", ".XXX."],
|
|
326
|
+
N: ["X...X", "XX..X", "XX..X", "X.X.X", "X..XX", "X..XX", "X...X"],
|
|
327
|
+
W: ["X...X", "X...X", "X...X", "X.X.X", "X.X.X", "XX.XX", "X...X"],
|
|
328
|
+
H: ["X...X", "X...X", "X...X", "XXXXX", "X...X", "X...X", "X...X"],
|
|
329
|
+
};
|
|
330
|
+
const LOGO = (() => {
|
|
331
|
+
const word = "KRILLIONWHO", rows = Array.from({ length: 7 }, (_, y) => [...word].map((c) => GLYPHS[c][y]).join("."));
|
|
332
|
+
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>`;
|
|
333
|
+
})();
|
|
334
|
+
const KRILL = sprite([
|
|
335
|
+
"........aa..",
|
|
336
|
+
".......a....",
|
|
337
|
+
"...RRRRa....",
|
|
338
|
+
"..RrrrrRR...",
|
|
339
|
+
".RrrrrrrRe..",
|
|
340
|
+
".Rrr..RrrR..",
|
|
341
|
+
"Rrr....RrR..",
|
|
342
|
+
"Rr......R...",
|
|
343
|
+
"Rr..........",
|
|
344
|
+
".Rr.........",
|
|
345
|
+
"..RR........",
|
|
346
|
+
], { R: "#e11d48", r: "#fb7185", a: "#fda4af", e: "#1f0a14" }, "kw-krill-art");
|
|
347
|
+
const BOAT = sprite([
|
|
348
|
+
".........FFFFm............",
|
|
349
|
+
"........FFFFFm............",
|
|
350
|
+
"..........FFFm............",
|
|
351
|
+
".............m............",
|
|
352
|
+
".............m............",
|
|
353
|
+
"........CCCCCCCCC.........",
|
|
354
|
+
"........CwwCwwCCC.........",
|
|
355
|
+
"........CwwCwwCCC.........",
|
|
356
|
+
"..HHHHHHHHHHHHHHHHHHHHHHH.",
|
|
357
|
+
".HHHHHHHHHHHHHHHHHHHHHHHHH",
|
|
358
|
+
"..HHHHHHHHHHHHHHHHHHHHHHH.",
|
|
359
|
+
"...HHHHHHHHHHHHHHHHHHHHH..",
|
|
360
|
+
".....HHHHHHHHHHHHHHHHH....",
|
|
361
|
+
], { F: "#f472b6", m: "#0f1d2e", C: "#14263d", w: "#7dd3fc", H: "#0c1a2b" }, "kw-boat-art");
|
|
362
|
+
const CLOUD = (shade) => sprite([
|
|
363
|
+
"..........WWWWW...........",
|
|
364
|
+
"........WWWWWWWWW.........",
|
|
365
|
+
"....WWWWWWWWWWWWWWWW......",
|
|
366
|
+
"..WWWWWWWWWWWWWWWWWWWWW...",
|
|
367
|
+
"WWWWWWWWWWWWWWWWWWWWWWWWWW",
|
|
368
|
+
"GGGGGGGGGGGGGGGGGGGGGGGGGG",
|
|
369
|
+
], { W: "#ffffff", G: shade }, "kw-cloud-art");
|
|
370
|
+
const FISH = sprite([".FFFF.F", "FFFFFFF", ".FFFF.F"], { F: "#0a2038" }, "kw-fish-art");
|
|
371
|
+
const JELLY = sprite([
|
|
372
|
+
"..JJJJJ..",
|
|
373
|
+
".JjjjjjJ.",
|
|
374
|
+
"JjjjjjjjJ",
|
|
375
|
+
"JJJJJJJJJ",
|
|
376
|
+
".t.t.t.t.",
|
|
377
|
+
".t..t..t.",
|
|
378
|
+
"..t..t...",
|
|
379
|
+
".t..t..t.",
|
|
380
|
+
], { J: "#f0abfc", j: "#fae8ff", t: "#e879f9" }, "kw-jelly-art");
|
|
381
|
+
const ANGLER = sprite([
|
|
382
|
+
"......L.........",
|
|
383
|
+
".......s........",
|
|
384
|
+
"........s.......",
|
|
385
|
+
"....DDDDDD....D.",
|
|
386
|
+
"..DDDDDDDDDD.DD.",
|
|
387
|
+
".DeDDDDDDDDDDDD.",
|
|
388
|
+
"DzzDDDDDDDDDDDD.",
|
|
389
|
+
".DzDDDDDDDDD.DD.",
|
|
390
|
+
"..DDDDDDDDDD..D.",
|
|
391
|
+
"....DDDDDD......",
|
|
392
|
+
], { D: "#0d1526", e: "#a5f3fc", z: "#e5e7eb", s: "#334155", L: "#fde047" }, "kw-angler-art");
|
|
393
|
+
const CHEST = sprite([
|
|
394
|
+
"..GGGGGGGGGG..",
|
|
395
|
+
".GBBBBBBBBBBG.",
|
|
396
|
+
"GBBBBBBBBBBBBG",
|
|
397
|
+
"GGGGGGyyGGGGGG",
|
|
398
|
+
"GBBBBByyBBBBBG",
|
|
399
|
+
"GBBBBBBBBBBBBG",
|
|
400
|
+
"GGGGGGGGGGGGGG",
|
|
401
|
+
], { G: "#f59e0b", B: "#78350f", y: "#fde68a" }, "kw-chest-art");
|
|
402
|
+
const SPIKES = Array.from({ length: 14 }, (_, k) => {
|
|
403
|
+
const a = (k / 14) * Math.PI * 2, b = a + 0.16, c = a - 0.16, P = (r, t) => `${(60 + r * Math.cos(t)).toFixed(1)},${(62 + r * Math.sin(t)).toFixed(1)}`;
|
|
404
|
+
return `<polygon points="${P(35, b)} ${P(50, a)} ${P(35, c)}"/>`;
|
|
405
|
+
}).join("");
|
|
406
|
+
const PUFFER = `<svg class="kw-puff-art" viewBox="0 0 120 124" aria-hidden="true"><g class="kw-spikes">${SPIKES}</g>` +
|
|
407
|
+
`<path d="M95 62l20-15v30z" class="kw-fin"/><circle cx="60" cy="62" r="38" class="kw-body"/><ellipse cx="60" cy="80" rx="25" ry="15" fill="#fff" opacity=".35"/>` +
|
|
408
|
+
`<circle cx="46" cy="52" r="8" fill="#fff"/><circle cx="48" cy="53" r="4" fill="#111827"/><circle cx="74" cy="52" r="8" fill="#fff"/><circle cx="76" cy="53" r="4" fill="#111827"/>` +
|
|
409
|
+
`<ellipse cx="61" cy="71" rx="5.5" ry="4.5" fill="#9a3412"/><path d="M33 34q-9-10-2-17q8 5 10 15z" class="kw-fin"/></svg>`;
|
|
410
|
+
|
|
411
|
+
// ---------- The scene: one tall ocean, and a camera that moves down it ----------
|
|
412
|
+
const sc = { H: 0, sky: 0, at: null };
|
|
413
|
+
const deepAt = (m) => `top:calc(var(--sky) + ${Math.round(m * S)}px)`;
|
|
414
|
+
function worldHtml() {
|
|
415
|
+
const school = (m, n, dir, speed, size) => `<div class="kw-school ${dir}" style="${deepAt(m)};--speed:${speed}s;--size:${size}px">` +
|
|
416
|
+
Array.from({ length: n }, (_, i) => `<i style="top:${(i * 17) % 46}px;animation-delay:-${((i * speed) / n).toFixed(1)}s">${FISH}</i>`).join("") + "</div>";
|
|
417
|
+
const ticks = Array.from({ length: MAX_DEPTH / 1000 + 1 }, (_, k) => `<span style="${deepAt(k * 1000)}">${(k * 1000).toLocaleString()}m</span>`).join("");
|
|
418
|
+
const zones = ZONES.map(([m, label]) => `<p class="kw-zone" style="${deepAt(m + (m ? 0 : 6))}">${label}<small>${fmtM(m)}</small></p>`).join("");
|
|
419
|
+
return `<div class="kw-sky"><div class="kw-sun"></div>
|
|
420
|
+
<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>
|
|
421
|
+
<div class="kw-water"></div><div class="kw-snow"></div><div class="kw-rays"></div><div class="kw-surface"></div>
|
|
422
|
+
<div class="kw-boat">${BOAT}</div>
|
|
423
|
+
${school(35, 7, "right", 26, 22)}${school(95, 9, "left", 34, 16)}${school(180, 12, "right", 40, 12)}${school(320, 6, "left", 30, 20)}
|
|
424
|
+
<div class="kw-jelly" style="${deepAt(420)};left:72%">${JELLY}</div><div class="kw-jelly j2" style="${deepAt(640)};left:12%">${JELLY}</div>
|
|
425
|
+
<div class="kw-jelly j3" style="${deepAt(930)};left:82%">${JELLY}</div>
|
|
426
|
+
<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>
|
|
427
|
+
<div class="kw-angler" style="${deepAt(1900)};left:74%">${ANGLER}</div><div class="kw-angler a2" style="${deepAt(3100)};left:10%">${ANGLER}</div>
|
|
428
|
+
<div class="kw-angler" style="${deepAt(4700)};left:68%">${ANGLER}</div>
|
|
429
|
+
<div class="kw-glow" style="${deepAt(2800)}"></div>
|
|
430
|
+
<div class="kw-trench l" style="${deepAt(5600)}"></div><div class="kw-trench r" style="${deepAt(5600)}"></div>
|
|
431
|
+
<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>
|
|
432
|
+
${zones}<div class="kw-ruler">${ticks}</div>`;
|
|
433
|
+
}
|
|
434
|
+
function sceneHtml() {
|
|
435
|
+
return `<div class="kw-stage" id="kw-stage" data-mode="home">
|
|
436
|
+
<div class="kw-world" id="kw-world">${worldHtml()}</div>
|
|
437
|
+
<div class="kw-krill" id="kw-krill">${KRILL}<span class="kw-trail"><i></i><i></i><i></i><i></i></span></div>
|
|
438
|
+
<div class="kw-fx" id="kw-fx" aria-hidden="true"></div>
|
|
439
|
+
<div class="kw-ui" id="kw-ui"></div>
|
|
440
|
+
<div class="kw-modal" id="kw-modal" hidden></div>
|
|
441
|
+
<div class="kw-scan" aria-hidden="true"></div>
|
|
442
|
+
<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>
|
|
443
|
+
<div class="kw-corner right">
|
|
444
|
+
<button class="kw-icon" type="button" data-act="sound" id="kw-sound" title="Sound on/off" aria-label="Sound on or off"></button>
|
|
445
|
+
<button class="kw-icon" type="button" data-act="board" title="Today's leaderboard" aria-label="Today's leaderboard">🏆</button>
|
|
446
|
+
</div>
|
|
447
|
+
</div>`;
|
|
448
|
+
}
|
|
449
|
+
function soundIcon() { const b = $("kw-sound"); if (b) { b.textContent = sfx.on ? "🔊" : "🔇"; b.setAttribute("aria-pressed", String(sfx.on)); } }
|
|
450
|
+
function layout() {
|
|
451
|
+
const stage = $("kw-stage");
|
|
452
|
+
if (!stage || !stage.clientHeight) return;
|
|
453
|
+
sc.H = stage.clientHeight;
|
|
454
|
+
sc.sky = Math.round(sc.H * 0.58);
|
|
455
|
+
stage.style.setProperty("--sky", `${sc.sky}px`);
|
|
456
|
+
stage.style.setProperty("--m", `${S}px`); // pixels per meter, for the ocean's sizes in the stylesheet
|
|
457
|
+
camTo(sc.at, 0);
|
|
458
|
+
}
|
|
459
|
+
// The camera: null = up in the sky (the home screen); a number = that many meters down
|
|
460
|
+
function camY(m) { return m === null ? 0 : sc.sky - sc.H * 0.17 + Math.min(m, MAX_DEPTH) * S; }
|
|
461
|
+
function camTo(m, ms = 1700) {
|
|
462
|
+
sc.at = m;
|
|
463
|
+
const w = $("kw-world");
|
|
464
|
+
if (!w) return;
|
|
465
|
+
if (calm()) ms = 0;
|
|
466
|
+
w.style.transition = ms ? `transform ${ms}ms cubic-bezier(.55, 0, .2, 1)` : "none";
|
|
467
|
+
w.style.transform = `translate3d(0, ${-Math.round(camY(m))}px, 0)`;
|
|
468
|
+
}
|
|
469
|
+
function setMode(mode) { const stage = $("kw-stage"); if (stage) stage.dataset.mode = mode; }
|
|
470
|
+
function uiHtml(html) { const el = $("kw-ui"); if (el) el.innerHTML = html; }
|
|
471
|
+
|
|
472
|
+
// Numbers that count up instead of jumping
|
|
473
|
+
function countTo(el, from, to, ms, fmt) {
|
|
474
|
+
if (!el) return;
|
|
475
|
+
if (calm() || from === to) { el.textContent = fmt(to); return; }
|
|
476
|
+
const t0 = performance.now();
|
|
477
|
+
const step = (t) => {
|
|
478
|
+
const k = Math.min(1, (t - t0) / ms), e = 1 - Math.pow(1 - k, 3);
|
|
479
|
+
el.textContent = fmt(Math.round(from + (to - from) * e));
|
|
480
|
+
if (k < 1) requestAnimationFrame(step);
|
|
481
|
+
};
|
|
482
|
+
requestAnimationFrame(step);
|
|
483
|
+
setTimeout(() => { el.textContent = fmt(to); }, ms + 120); // animation frames stop in background tabs: land on the number anyway
|
|
484
|
+
}
|
|
485
|
+
// The points pop out (of the landed answer, or the krill) with sparks in the tier's color
|
|
486
|
+
function burst(pts, x, y) {
|
|
487
|
+
const fx = $("kw-fx"), krill = $("kw-krill"), stage = $("kw-stage");
|
|
488
|
+
if (!fx || !krill) return;
|
|
489
|
+
if (x === undefined) { const k = krill.getBoundingClientRect(), s = stage.getBoundingClientRect(); x = k.left - s.left + k.width / 2; y = k.top - s.top; }
|
|
490
|
+
const [name, emoji] = TIERS[pts];
|
|
491
|
+
const pop = document.createElement("div");
|
|
492
|
+
pop.className = `kw-pop t${pts}`;
|
|
493
|
+
pop.style.left = `${x}px`;
|
|
494
|
+
pop.style.top = `${y}px`;
|
|
495
|
+
pop.innerHTML = `<b>+${pts}</b><small>${emoji} ${name.toUpperCase()}</small>`;
|
|
496
|
+
fx.appendChild(pop);
|
|
497
|
+
const sparks = pts >= 90 ? 30 : pts >= 50 ? 20 : pts ? 12 : 0;
|
|
498
|
+
for (let i = 0; i < sparks; i++) {
|
|
499
|
+
const d = document.createElement("i"), a = Math.random() * Math.PI * 2, r = 50 + Math.random() * (pts >= 90 ? 170 : 100);
|
|
500
|
+
d.className = `kw-spark t${pts}`;
|
|
501
|
+
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`;
|
|
502
|
+
fx.appendChild(d);
|
|
503
|
+
}
|
|
504
|
+
if (pts >= 100) { stage.classList.remove("legend"); void stage.offsetWidth; stage.classList.add("legend"); }
|
|
505
|
+
if (!pts) { krill.classList.remove("sad"); void krill.offsetWidth; krill.classList.add("sad"); }
|
|
506
|
+
setTimeout(() => { pop.remove(); fx.querySelectorAll(".kw-spark").forEach((el) => el.remove()); }, 2300);
|
|
507
|
+
}
|
|
508
|
+
// Your answer sinks: the camera dives with it past a dashed line for every tier it beats, and it lands on its own tier.
|
|
509
|
+
// 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.
|
|
510
|
+
function sink(text, pts, before) {
|
|
511
|
+
return new Promise((done) => {
|
|
512
|
+
const stage = $("kw-stage"), fx = $("kw-fx"), card = $("kw-card"), world = $("kw-world");
|
|
513
|
+
if (!stage || !fx || !card || !world) return done();
|
|
514
|
+
clearSink();
|
|
515
|
+
const s = stage.getBoundingClientRect(), c = card.getBoundingClientRect(), H = s.height;
|
|
516
|
+
const anchor = Math.round(H * (H < 640 ? 0.36 : 0.42)), from = before * 10, to = (before + pts) * 10, steps = pts / 10;
|
|
517
|
+
// line k reaches the anchor row just as the camera gets k*100 m deeper (the camera's own row is 17% down)
|
|
518
|
+
const offset = anchor - H * 0.17;
|
|
519
|
+
world.insertAdjacentHTML("beforeend", `<div class="kw-lines" id="kw-lines">${Array.from({ length: Math.min(10, steps + 1) }, (_, n) => {
|
|
520
|
+
const p = (n + 1) * 10, [name, emoji] = TIERS[p];
|
|
521
|
+
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>`;
|
|
522
|
+
}).join("")}</div>`);
|
|
523
|
+
const lineEls = [...$("kw-lines").children];
|
|
524
|
+
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("");
|
|
525
|
+
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("");
|
|
526
|
+
const box = document.createElement("div");
|
|
527
|
+
box.className = `kw-sink${pts >= 50 ? " fast" : ""}`;
|
|
528
|
+
box.id = "kw-sink";
|
|
529
|
+
box.innerHTML = `<div class="kw-rush">${rush}</div>` +
|
|
530
|
+
`<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>`;
|
|
531
|
+
fx.appendChild(box);
|
|
532
|
+
stage.classList.add("sinking");
|
|
533
|
+
card.classList.add("sunk");
|
|
534
|
+
const plaque = box.querySelector(".kw-plaque");
|
|
535
|
+
requestAnimationFrame(() => { plaque.style.top = `${anchor}px`; }); // drops onto the anchor row, then rides there
|
|
536
|
+
const dur = calm() ? 0 : pts ? 600 + pts * 13 : 0;
|
|
537
|
+
const depthEl = $("kw-depth"), scoreEl = $("kw-score");
|
|
538
|
+
let passed = 0, landed = false;
|
|
539
|
+
const land = () => {
|
|
540
|
+
if (landed) return;
|
|
541
|
+
landed = true;
|
|
542
|
+
sc.at = to;
|
|
543
|
+
world.style.transition = "none";
|
|
544
|
+
world.style.transform = `translate3d(0, ${-Math.round(camY(to))}px, 0)`;
|
|
545
|
+
if (depthEl) depthEl.textContent = fmtM(to);
|
|
546
|
+
if (scoreEl) scoreEl.textContent = String(before + pts);
|
|
547
|
+
lineEls.forEach((l, n) => { if (n < steps) l.classList.add("passed"); });
|
|
548
|
+
box.classList.remove("fast");
|
|
549
|
+
if (pts) {
|
|
550
|
+
lineEls[steps - 1].classList.add("hit");
|
|
551
|
+
plaque.classList.add("land");
|
|
552
|
+
sfx.play("thunk");
|
|
553
|
+
sfx.play("score", pts);
|
|
554
|
+
if (pts >= 60 && pts < 100) { stage.classList.remove("thud"); void stage.offsetWidth; stage.classList.add("thud"); }
|
|
555
|
+
} else { plaque.classList.add("float"); sfx.play("miss"); }
|
|
556
|
+
setTimeout(() => {
|
|
557
|
+
const r = plaque.getBoundingClientRect();
|
|
558
|
+
burst(pts, r.left - s.left + r.width / 2, r.top - s.top - 6);
|
|
559
|
+
}, 40);
|
|
560
|
+
setTimeout(done, pts ? 650 : 1000);
|
|
561
|
+
};
|
|
562
|
+
if (!dur) return setTimeout(land, pts ? 0 : 300);
|
|
563
|
+
sfx.play("splash");
|
|
564
|
+
world.style.transition = "none";
|
|
565
|
+
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
|
|
566
|
+
const t0 = performance.now();
|
|
567
|
+
const frame = (t) => {
|
|
568
|
+
if (landed) return;
|
|
569
|
+
const k = Math.min(1, (t - t0) / dur), e = ease(k), d = from + (to - from) * e;
|
|
570
|
+
world.style.transform = `translate3d(0, ${-Math.round(camY(d))}px, 0)`;
|
|
571
|
+
if (depthEl) depthEl.textContent = fmtM(d);
|
|
572
|
+
if (scoreEl) scoreEl.textContent = String(Math.round(before + pts * e));
|
|
573
|
+
while (passed < steps && d >= from + (passed + 1) * 100 - 0.5) { lineEls[passed].classList.add("passed"); sfx.play("line", passed); passed++; }
|
|
574
|
+
if (k < 1) requestAnimationFrame(frame); else land();
|
|
575
|
+
};
|
|
576
|
+
requestAnimationFrame(frame);
|
|
577
|
+
setTimeout(land, dur + 600); // animation frames stop in background tabs
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
function clearSink() {
|
|
581
|
+
const old = $("kw-sink");
|
|
582
|
+
if (old) old.remove();
|
|
583
|
+
const lines = $("kw-lines");
|
|
584
|
+
if (lines) lines.remove();
|
|
585
|
+
const stage = $("kw-stage");
|
|
586
|
+
if (stage) stage.classList.remove("sinking", "thud");
|
|
587
|
+
}
|
|
588
|
+
function diveKrill() {
|
|
589
|
+
const krill = $("kw-krill");
|
|
590
|
+
if (!krill) return;
|
|
591
|
+
krill.classList.remove("diving"); void krill.offsetWidth; krill.classList.add("diving");
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// ---------- Sheets (the Play menu and other pop-ups) ----------
|
|
595
|
+
let afterName = null;
|
|
596
|
+
function openSheet(html, back) {
|
|
597
|
+
const m = $("kw-modal");
|
|
598
|
+
m.hidden = false;
|
|
599
|
+
m.innerHTML = `<div class="kw-sheet" role="dialog" aria-modal="true">${back ? `<button class="kw-back" type="button" data-act="${back}">◀ BACK</button>` : ""}` +
|
|
600
|
+
`<button class="kw-x" type="button" data-act="close" aria-label="Close">✕</button>${html}</div>`;
|
|
601
|
+
sfx.play("open");
|
|
602
|
+
const first = m.querySelector("input, .kw-mode, .kw-btn");
|
|
603
|
+
if (first && !matchMedia("(pointer: coarse)").matches) first.focus();
|
|
604
|
+
}
|
|
605
|
+
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; } }
|
|
606
|
+
function sheetNote(text, bad) { const n = $("kw-sheet-note"); if (n) { n.textContent = text || ""; n.classList.toggle("err", !!bad); } }
|
|
607
|
+
|
|
608
|
+
// ---------- Names ----------
|
|
609
|
+
function cleanName(raw) {
|
|
610
|
+
const name = String(raw || "").replace(/\s+/g, " ").trim();
|
|
611
|
+
if (!name) return { error: "Pick a name first." };
|
|
612
|
+
if ([...name].length > 16) return { error: "Names can be up to 16 characters." };
|
|
613
|
+
if (/^ *richard *$/i.test(name)) return { error: "That name is taken." };
|
|
614
|
+
return { name: ctx.maskSlurs(name) };
|
|
615
|
+
}
|
|
616
|
+
function myName() { return cleanName(ctx.store.get(NAME_KEY, "")).name || ""; }
|
|
617
|
+
function askName(then, why) {
|
|
618
|
+
const have = myName();
|
|
619
|
+
if (have) return then(have);
|
|
620
|
+
afterName = then;
|
|
621
|
+
openSheet(`<p class="kw-sheet-title">WHAT'S YOUR DIVER NAME?</p><p class="kw-muted">${esc(why)}</p>
|
|
622
|
+
<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">
|
|
623
|
+
<button class="kw-btn" type="submit">GO ▶</button></form><p class="kw-note" id="kw-sheet-note" aria-live="polite"></p>`);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// ---------- Home ----------
|
|
627
|
+
const ui = { screen: null, pack: "all", boardRef: null, timers: new Set() };
|
|
628
|
+
function every(ms, fn) { const t = setInterval(fn, ms); ui.timers.add(t); return t; }
|
|
629
|
+
function stopTimers() { for (const t of ui.timers) clearInterval(t); ui.timers.clear(); }
|
|
630
|
+
function dailyProgress() { const d = ctx.store.get(DAILY_KEY, null); return d && d.date === dateStr() && Array.isArray(d.keys) ? d : null; }
|
|
631
|
+
function streakNow() {
|
|
632
|
+
const s = ctx.store.get(STATS_KEY, {}), today = dateStr();
|
|
633
|
+
return s.streak && (s.last === today || s.last === dayBefore(today)) ? s.streak : 0;
|
|
634
|
+
}
|
|
635
|
+
function renderHome(rising) {
|
|
636
|
+
endDive();
|
|
637
|
+
closeSheet();
|
|
638
|
+
ui.screen = "home";
|
|
639
|
+
setMode("home");
|
|
640
|
+
camTo(null, rising ? 2600 : 0);
|
|
641
|
+
const prog = dailyProgress(), streak = streakNow(), room = ctx.store.get(ROOM_KEY, "");
|
|
642
|
+
uiHtml(`<div class="kw-home">
|
|
643
|
+
<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>
|
|
644
|
+
<div class="kw-menu">
|
|
645
|
+
<button class="kw-howto" type="button" data-act="howto">▸ HOW TO PLAY</button>
|
|
646
|
+
${prog && prog.done ? `<p class="kw-today">TODAY: ${fmtM(prog.total * 10)} · ${esc(zoneAt(prog.total * 10)).toUpperCase()}</p>` : ""}
|
|
647
|
+
${room ? `<button class="kw-btn ghost" type="button" data-act="pp-rejoin">BACK TO ROOM ${esc(room)}</button>` : ""}
|
|
648
|
+
<button class="kw-play" type="button" data-act="play">▶ PLAY ◀</button>
|
|
649
|
+
<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>
|
|
650
|
+
</div></div>`);
|
|
651
|
+
}
|
|
652
|
+
function playSheet() {
|
|
653
|
+
const prog = dailyProgress(), done = prog && prog.done, going = prog && !done && prog.answers.length > 0;
|
|
654
|
+
openSheet(`<p class="kw-sheet-title">PICK YOUR DIVE</p>
|
|
655
|
+
<button class="kw-mode" type="button" data-act="daily"><span class="kw-mode-art">${KRILL}</span>
|
|
656
|
+
<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>
|
|
657
|
+
<button class="kw-mode" type="button" data-act="free-menu"><span class="kw-mode-art">${FISH}</span>
|
|
658
|
+
<span class="kw-mode-text"><b>FREE PLAY</b><small>Unlimited dives · themed packs · old days</small></span><em>∞</em></button>
|
|
659
|
+
<button class="kw-mode" type="button" data-act="pp-menu"><span class="kw-mode-art">${PUFFER}</span>
|
|
660
|
+
<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>`);
|
|
661
|
+
online().then(async (f) => { // how many people are waiting in open rooms
|
|
662
|
+
if (!f) return;
|
|
663
|
+
try {
|
|
664
|
+
const s = await f.db.ref("krillionwho/lobbies").orderByChild("ts").startAt(now() - 15 * 60e3).once("value");
|
|
665
|
+
let n = 0;
|
|
666
|
+
s.forEach((c) => { n += Number((c.val() || {}).n) || 0; });
|
|
667
|
+
const el = $("kw-waiting");
|
|
668
|
+
if (el && n) el.textContent = `● ${n} WAITING`;
|
|
669
|
+
} catch { /* older rules */ }
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
function freeSheet() {
|
|
673
|
+
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("");
|
|
674
|
+
const today = dateStr();
|
|
675
|
+
const past = Array.from({ length: 6 }, (_, n) => dayBefore(today, n + 1)).map((d) =>
|
|
676
|
+
`<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("");
|
|
677
|
+
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>
|
|
678
|
+
<p class="kw-label">THEMED PACKS</p><div class="kw-tiles">${packs}</div>
|
|
679
|
+
<p class="kw-label">ARCHIVE ↺</p><div class="kw-tiles">${past}</div>`, "play");
|
|
680
|
+
}
|
|
681
|
+
function partySheet() {
|
|
682
|
+
const room = ctx.store.get(ROOM_KEY, "");
|
|
683
|
+
openSheet(`<p class="kw-sheet-title"><span class="kw-title-puff">${PUFFER}</span>PUFFER PARTY</p>
|
|
684
|
+
<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>
|
|
685
|
+
${room ? `<button class="kw-btn wide" type="button" data-act="pp-rejoin">BACK TO ROOM ${esc(room)}</button>` : ""}
|
|
686
|
+
<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>
|
|
687
|
+
<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>
|
|
688
|
+
<button class="kw-link" type="button" data-act="pp-bots">No one around? Play against the computer ▸</button>
|
|
689
|
+
<p class="kw-note" id="kw-sheet-note" aria-live="polite"></p>`, "play");
|
|
690
|
+
}
|
|
691
|
+
function howSheet() {
|
|
692
|
+
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("");
|
|
693
|
+
openSheet(`<p class="kw-sheet-title">HOW TO PLAY</p>
|
|
694
|
+
<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>
|
|
695
|
+
<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>
|
|
696
|
+
<ul class="kw-tiers">${tiers}</ul>
|
|
697
|
+
<p class="kw-muted">Rarity comes from what everyone here actually answers. Brand-new prompts start from how well-known each answer is.</p>`);
|
|
698
|
+
}
|
|
699
|
+
function boardSheet() {
|
|
700
|
+
const s = ctx.store.get(STATS_KEY, {});
|
|
701
|
+
openSheet(`<p class="kw-sheet-title">🏆 TODAY'S DEEPEST DIVES</p><ol class="kw-board" id="kw-board-sheet"></ol>
|
|
702
|
+
${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>` : ""}`);
|
|
703
|
+
watchBoard("kw-board-sheet");
|
|
704
|
+
}
|
|
705
|
+
function menuSheet() {
|
|
706
|
+
openSheet(`<p class="kw-sheet-title">MENU</p>
|
|
707
|
+
<form class="kw-inline" data-form="rename" autocomplete="off"><input id="kw-name-in" maxlength="16" spellcheck="false" value="${esc(ctx.store.get(NAME_KEY, ""))}" placeholder="your diver name" aria-label="Your name"><button class="kw-btn ghost" type="submit">SAVE NAME</button></form>
|
|
708
|
+
<p class="kw-note" id="kw-sheet-note" aria-live="polite"></p>
|
|
709
|
+
<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>
|
|
710
|
+
<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>`);
|
|
711
|
+
}
|
|
712
|
+
function watchBoard(listId) {
|
|
713
|
+
if (ui.boardRef) { ui.boardRef.off(); ui.boardRef = null; }
|
|
714
|
+
const list = $(listId);
|
|
715
|
+
if (!list) return;
|
|
716
|
+
list.innerHTML = `<li class="kw-muted">Loading…</li>`;
|
|
717
|
+
online().then((f) => {
|
|
718
|
+
if (!$(listId)) return;
|
|
719
|
+
if (!f) { $(listId).innerHTML = `<li class="kw-muted">The leaderboard isn't available right now.</li>`; return; }
|
|
720
|
+
sweepOld(f);
|
|
721
|
+
ui.boardRef = f.db.ref(`krillionwho/board/${dateStr()}`).orderByChild("pts").limitToLast(10);
|
|
722
|
+
ui.boardRef.on("value", (s) => {
|
|
723
|
+
const rows = [];
|
|
724
|
+
s.forEach((c) => { const v = c.val(); if (v && typeof v.name === "string") rows.push({ ...v, uid: c.key }); });
|
|
725
|
+
rows.sort((a, b) => b.pts - a.pts || a.ts - b.ts);
|
|
726
|
+
const el = $(listId);
|
|
727
|
+
if (!el) return;
|
|
728
|
+
el.innerHTML = rows.length ? rows.map((r, n) => `<li class="${r.uid === net.uid ? "me" : ""}"><span class="kw-rank">${n + 1}</span>` +
|
|
729
|
+
`<span class="kw-who">${esc(ctx.maskSlurs(r.name))}</span><span class="kw-deep">${fmtM(r.pts * 10)}</span></li>`).join("")
|
|
730
|
+
: `<li class="kw-muted">Nobody has dived yet today. Be the first!</li>`;
|
|
731
|
+
}, () => { const el = $(listId); if (el) el.innerHTML = `<li class="kw-muted">The leaderboard isn't available right now.</li>`; });
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
// Old leaderboards and rooms clean themselves up: whoever opens KrillionWho deletes a few that have run out
|
|
735
|
+
let swept = false;
|
|
736
|
+
async function sweepOld(f) {
|
|
737
|
+
if (swept) return;
|
|
738
|
+
swept = true;
|
|
739
|
+
try {
|
|
740
|
+
const cutoff = dayBefore(dateStr(), 3), old = now() - 2 * 864e5, changes = {};
|
|
741
|
+
const days = await f.db.ref("krillionwho/board").orderByKey().endAt(cutoff).limitToFirst(4).once("value");
|
|
742
|
+
days.forEach((day) => { day.forEach((row) => { if ((row.val() || {}).ts < old) changes[`krillionwho/board/${day.key}/${row.key}`] = null; }); });
|
|
743
|
+
const lobbies = await f.db.ref("krillionwho/lobbies").orderByChild("ts").endAt(now() - 3600e3).limitToFirst(10).once("value");
|
|
744
|
+
lobbies.forEach((l) => { changes[`krillionwho/lobbies/${l.key}`] = null; });
|
|
745
|
+
if (Object.keys(changes).length) await f.db.ref().update(changes);
|
|
746
|
+
} catch { /* someone else swept first, or older rules */ }
|
|
747
|
+
const mine = ctx.store.get(MY_ROOMS_KEY, {});
|
|
748
|
+
for (const [code, ts] of Object.entries(mine)) {
|
|
749
|
+
if (now() - ts < ROOM_LIFE) continue;
|
|
750
|
+
delete mine[code];
|
|
751
|
+
f.db.ref(`krillionwho/rooms/${code}`).remove().catch(() => {});
|
|
752
|
+
}
|
|
753
|
+
ctx.store.set(MY_ROOMS_KEY, mine);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// ---------- Dives (the daily one, free play, or an old day) ----------
|
|
757
|
+
const dive = { mode: null, date: null, keys: [], answers: [], prompt: null, endsAt: 0, locked: true, tick: 0, close: null, run: 0 };
|
|
758
|
+
function seeded(text) { // the same text always gives the same numbers
|
|
759
|
+
let h = 1779033703 ^ text.length;
|
|
760
|
+
for (let i = 0; i < text.length; i++) { h = Math.imul(h ^ text.charCodeAt(i), 3432918353); h = (h << 13) | (h >>> 19); }
|
|
761
|
+
return () => { h = Math.imul(h ^ (h >>> 16), 2246822507); h = Math.imul(h ^ (h >>> 13), 3266489909); h ^= h >>> 16; return (h >>> 0) / 4294967296; };
|
|
762
|
+
}
|
|
763
|
+
function pickDaily(date) { // the same 7 prompts for everyone: one per category, at most 2 per pack
|
|
764
|
+
const rnd = seeded("krillionwho " + date);
|
|
765
|
+
const pool = BANK.prompts.filter((p) => p.pool.length >= DAILY_POOL).sort((a, b) => (a.key < b.key ? -1 : 1));
|
|
766
|
+
for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; }
|
|
767
|
+
return spread(pool);
|
|
768
|
+
}
|
|
769
|
+
function spread(pool) {
|
|
770
|
+
const out = [], cats = new Set(), packs = {};
|
|
771
|
+
for (const p of pool) {
|
|
772
|
+
if (cats.has(p.cat.id) || (packs[p.cat.pack] || 0) >= 2) continue;
|
|
773
|
+
out.push(p.key); cats.add(p.cat.id); packs[p.cat.pack] = (packs[p.cat.pack] || 0) + 1;
|
|
774
|
+
if (out.length === ROUNDS) break;
|
|
775
|
+
}
|
|
776
|
+
return out;
|
|
777
|
+
}
|
|
778
|
+
function pickFree(pack) {
|
|
779
|
+
const pool = BANK.prompts.filter((p) => p.pool.length >= PARTY_POOL && (pack === "all" || p.cat.pack === pack));
|
|
780
|
+
for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; }
|
|
781
|
+
if (pack === "all") return spread(pool);
|
|
782
|
+
const out = [], cats = new Set();
|
|
783
|
+
for (const p of pool) { if (!cats.has(p.cat.id) || pool.length < 30) { out.push(p.key); cats.add(p.cat.id); } if (out.length === ROUNDS) break; }
|
|
784
|
+
return out;
|
|
785
|
+
}
|
|
786
|
+
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];
|
|
787
|
+
const packName = (id) => (id === "all" ? "Everything" : (BANK.packs.find(([p]) => p === id) || [, id])[1]);
|
|
788
|
+
|
|
789
|
+
function startDaily() {
|
|
790
|
+
const prog = dailyProgress();
|
|
791
|
+
if (prog && prog.done) { Object.assign(dive, { mode: "daily", keys: prog.keys, answers: prog.answers.slice(), date: prog.date }); return finishDive(true); }
|
|
792
|
+
askName(() => {
|
|
793
|
+
let p = dailyProgress();
|
|
794
|
+
if (!p) { p = { date: dateStr(), keys: pickDaily(dateStr()), answers: [], started: -1 }; ctx.store.set(DAILY_KEY, p); ctx.track("KrillionWho: daily dive"); }
|
|
795
|
+
if (p.started >= p.answers.length && p.answers.length < ROUNDS) { // left during a prompt: that one's gone
|
|
796
|
+
p.answers.push({ k: p.keys[p.answers.length], p: 0, w: "left" });
|
|
797
|
+
ctx.store.set(DAILY_KEY, p);
|
|
798
|
+
}
|
|
799
|
+
beginDive("daily", p.keys, p.answers, p.date);
|
|
800
|
+
}, "It goes on today's leaderboard.");
|
|
801
|
+
}
|
|
802
|
+
function beginDive(mode, keys, answers = [], date = null) {
|
|
803
|
+
stopTimers();
|
|
804
|
+
closeSheet();
|
|
805
|
+
const run = ++dive.run;
|
|
806
|
+
Object.assign(dive, { mode, keys, answers: answers.slice(), date, locked: true, close: null });
|
|
807
|
+
ui.screen = "dive";
|
|
808
|
+
setMode("dive");
|
|
809
|
+
const depth = sum(dive.answers) * 10;
|
|
810
|
+
uiHtml(diveHtml());
|
|
811
|
+
$("kw-depth").textContent = fmtM(depth);
|
|
812
|
+
$("kw-score").textContent = String(sum(dive.answers));
|
|
813
|
+
renderDots();
|
|
814
|
+
sfx.play("splash");
|
|
815
|
+
diveKrill();
|
|
816
|
+
camTo(depth, 2200);
|
|
817
|
+
if (dive.answers.length >= ROUNDS) return setTimeout(() => run === dive.run && finishDive(), 900);
|
|
818
|
+
setTimeout(() => run === dive.run && nextRound(), 700);
|
|
819
|
+
}
|
|
820
|
+
function diveHtml() {
|
|
821
|
+
return `<div class="kw-hud">
|
|
822
|
+
<div class="kw-box"><small>DEPTH</small><b id="kw-depth">0m</b></div>
|
|
823
|
+
<div class="kw-progress"><ol id="kw-dots"></ol><small id="kw-round">PROMPT 1 OF ${ROUNDS}</small></div>
|
|
824
|
+
<div class="kw-box score"><small>SCORE</small><b id="kw-score">0</b></div>
|
|
825
|
+
</div>
|
|
826
|
+
<div class="kw-card" id="kw-card">
|
|
827
|
+
<p class="kw-card-top" id="kw-kicker"></p>
|
|
828
|
+
<h2 class="kw-prompt" id="kw-prompt"></h2>
|
|
829
|
+
<p class="kw-hint" id="kw-hint"></p>
|
|
830
|
+
<form class="kw-answer" data-form="answer" id="kw-form" autocomplete="off">
|
|
831
|
+
<input id="kw-input" maxlength="60" spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="type a rare answer…" aria-label="Your answer">
|
|
832
|
+
<button class="kw-btn" type="submit">DIVE ▼</button>
|
|
833
|
+
</form>
|
|
834
|
+
<div class="kw-close" id="kw-close" hidden aria-live="assertive"></div>
|
|
835
|
+
<p class="kw-wrong" id="kw-wrong" hidden aria-live="assertive"></p>
|
|
836
|
+
<div class="kw-reveal" id="kw-reveal" hidden aria-live="polite"></div>
|
|
837
|
+
</div>
|
|
838
|
+
<div class="kw-status" id="kw-status"></div>
|
|
839
|
+
<button class="kw-leave" type="button" data-act="quit">${dive.mode === "daily" ? "◀ LEAVE" : "◀ END DIVE"}</button>`;
|
|
840
|
+
}
|
|
841
|
+
function renderDots() {
|
|
842
|
+
const el = $("kw-dots");
|
|
843
|
+
if (!el) return;
|
|
844
|
+
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("");
|
|
845
|
+
}
|
|
846
|
+
function status(html) { const el = $("kw-status"); if (el) el.innerHTML = html; }
|
|
847
|
+
function nextRound() {
|
|
848
|
+
if (dive.answers.length >= ROUNDS) return finishDive();
|
|
849
|
+
const run = dive.run, n = dive.answers.length, p = dive.prompt = promptFor(dive.keys[n]);
|
|
850
|
+
dive.locked = true;
|
|
851
|
+
dive.close = null;
|
|
852
|
+
clearSink();
|
|
853
|
+
$("kw-card").classList.remove("sunk", "result");
|
|
854
|
+
$("kw-round").textContent = `PROMPT ${n + 1} OF ${ROUNDS}`;
|
|
855
|
+
$("kw-kicker").textContent = `PROMPT ${n + 1} OF ${ROUNDS} · ${packName(p.cat.pack).toUpperCase()}`;
|
|
856
|
+
$("kw-prompt").textContent = p.text;
|
|
857
|
+
$("kw-hint").textContent = p.hint ? `${p.hint}` : "▼ rarer answers sink deeper ▼";
|
|
858
|
+
$("kw-reveal").hidden = true;
|
|
859
|
+
$("kw-close").hidden = true;
|
|
860
|
+
$("kw-wrong").hidden = true;
|
|
861
|
+
$("kw-form").hidden = false;
|
|
862
|
+
const input = $("kw-input");
|
|
863
|
+
input.value = "";
|
|
864
|
+
input.disabled = true;
|
|
865
|
+
const card = $("kw-card");
|
|
866
|
+
card.classList.remove("in"); void card.offsetWidth; card.classList.add("in");
|
|
867
|
+
renderDots();
|
|
868
|
+
if (dive.mode === "daily") { const prog = dailyProgress(); if (prog) { prog.started = n; ctx.store.set(DAILY_KEY, prog); } }
|
|
869
|
+
let left = PREROLL;
|
|
870
|
+
const roll = () => { status(`descending · the clock starts in <b>${left}</b>`); sfx.play("tick"); };
|
|
871
|
+
roll();
|
|
872
|
+
clearInterval(dive.tick);
|
|
873
|
+
dive.tick = every(1000, () => {
|
|
874
|
+
if (run !== dive.run) return;
|
|
875
|
+
left--;
|
|
876
|
+
if (left > 0) return roll();
|
|
877
|
+
clearInterval(dive.tick);
|
|
878
|
+
startClock();
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
function startClock() {
|
|
882
|
+
const input = $("kw-input");
|
|
883
|
+
if (!input) return;
|
|
884
|
+
input.disabled = false;
|
|
885
|
+
input.focus();
|
|
886
|
+
sfx.play("go");
|
|
887
|
+
dive.locked = false;
|
|
888
|
+
dive.endsAt = Date.now() + ROUND_MS;
|
|
889
|
+
status(`<div class="kw-clock"><span id="kw-timefill"></span></div><b class="kw-secs" id="kw-secs">25</b>`);
|
|
890
|
+
const fill = $("kw-timefill");
|
|
891
|
+
fill.style.animation = `kwTime ${ROUND_MS}ms linear forwards`;
|
|
892
|
+
let lastBeep = 99;
|
|
893
|
+
dive.tick = every(100, () => {
|
|
894
|
+
const left = Math.max(0, dive.endsAt - Date.now()), secs = Math.ceil(left / 1000), el = $("kw-secs");
|
|
895
|
+
if (el) { el.textContent = secs; el.classList.toggle("hurry", left < 6000); }
|
|
896
|
+
if (left < 5500 && secs < lastBeep && secs > 0) { lastBeep = secs; sfx.play("hurry"); }
|
|
897
|
+
if (!left) answer(true);
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
// A misspelling close to a real answer asks first ("Did you mean…?"); the clock keeps running meanwhile
|
|
901
|
+
function askClose(res) {
|
|
902
|
+
dive.close = res;
|
|
903
|
+
const box = $("kw-close");
|
|
904
|
+
box.hidden = false;
|
|
905
|
+
box.innerHTML = `<span>did you mean <b>${esc(res.entry.name)}</b>?</span>` +
|
|
906
|
+
`<button class="kw-btn small" type="button" data-act="close-yes" id="kw-close-yes">YES ▼</button>` +
|
|
907
|
+
`<button class="kw-link" type="button" data-act="close-no">no, let me fix it</button>`;
|
|
908
|
+
sfx.play("ask");
|
|
909
|
+
$("kw-close-yes").focus();
|
|
910
|
+
}
|
|
911
|
+
function dropClose(refocus) {
|
|
912
|
+
dive.close = null;
|
|
913
|
+
const box = $("kw-close");
|
|
914
|
+
if (box) box.hidden = true;
|
|
915
|
+
if (refocus) { const input = $("kw-input"); input.focus(); input.select(); }
|
|
916
|
+
}
|
|
917
|
+
function reject(res, raw, p) {
|
|
918
|
+
const box = $("kw-wrong"), input = $("kw-input");
|
|
919
|
+
if (res.why === "blank") return input.focus();
|
|
920
|
+
box.hidden = false;
|
|
921
|
+
box.innerHTML = `✖ ${esc(whyText(res, raw, p))} <span>try another!</span>` +
|
|
922
|
+
(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>` : "");
|
|
923
|
+
sfx.play("miss");
|
|
924
|
+
input.classList.remove("shake"); void input.offsetWidth; input.classList.add("shake");
|
|
925
|
+
input.focus();
|
|
926
|
+
input.select();
|
|
927
|
+
}
|
|
928
|
+
async function answer(timeUp, accepted) {
|
|
929
|
+
if (dive.locked) return;
|
|
930
|
+
const run = dive.run, input = $("kw-input"), raw = timeUp ? "" : input.value, p = dive.prompt;
|
|
931
|
+
const res = timeUp ? { ok: false, why: "time" } : accepted || check(p, raw);
|
|
932
|
+
if (res.why === "close") return askClose(res);
|
|
933
|
+
dropClose(false);
|
|
934
|
+
if (!timeUp && !res.ok) return reject(res, raw, p); // a wrong answer doesn't use up the guess: try again while the clock runs
|
|
935
|
+
dive.locked = true;
|
|
936
|
+
clearInterval(dive.tick);
|
|
937
|
+
const fill = $("kw-timefill");
|
|
938
|
+
if (fill) fill.style.animationPlayState = "paused";
|
|
939
|
+
input.disabled = true;
|
|
940
|
+
if (res.ok) sfx.play("ping");
|
|
941
|
+
$("kw-wrong").hidden = true;
|
|
942
|
+
status(res.ok ? "sonar ping · measuring how rare that is…" : "the krill wobbles…");
|
|
943
|
+
const counts = await readCounts(p.key);
|
|
944
|
+
if (run !== dive.run || ui.screen !== "dive") return; // left in the meantime
|
|
945
|
+
let pts = 0, share = null;
|
|
946
|
+
if (res.ok) {
|
|
947
|
+
const key = res.entry.key, list = listPts(p, res.i);
|
|
948
|
+
const c = counts ? { ...counts, [key]: (counts[key] || 0) + 1 } : null;
|
|
949
|
+
pts = c ? blendPts(list, c, key) : list;
|
|
950
|
+
const total = c ? Object.values(c).reduce((a, b) => a + (Number(b) || 0), 0) : 0;
|
|
951
|
+
if (total >= 10) share = c[key] / total;
|
|
952
|
+
addCount(p.key, key);
|
|
953
|
+
}
|
|
954
|
+
const before = sum(dive.answers);
|
|
955
|
+
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 });
|
|
956
|
+
if (dive.mode === "daily") { const prog = dailyProgress(); if (prog) { prog.answers = dive.answers.slice(); ctx.store.set(DAILY_KEY, prog); } }
|
|
957
|
+
renderDots();
|
|
958
|
+
$("kw-form").hidden = true;
|
|
959
|
+
// the payoff: the answer sinks past the tier lines with the camera following, and lands on its tier
|
|
960
|
+
status(pts ? "sinking…" : "time's up…");
|
|
961
|
+
await sink(res.ok ? res.entry.name : "time's up", pts, before);
|
|
962
|
+
if (run !== dive.run || ui.screen !== "dive") return;
|
|
963
|
+
const card = $("kw-card");
|
|
964
|
+
card.classList.remove("sunk");
|
|
965
|
+
card.classList.add("result"); // the result shows at the bottom, under the answer that just landed
|
|
966
|
+
const [tier, emoji] = TIERS[pts], last = dive.answers.length >= ROUNDS;
|
|
967
|
+
const reveal = $("kw-reveal");
|
|
968
|
+
reveal.hidden = false;
|
|
969
|
+
reveal.innerHTML = (res.ok
|
|
970
|
+
? `<p class="kw-said">you said <b>${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>` +
|
|
971
|
+
(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>` : "")
|
|
972
|
+
: `<p class="kw-said miss">💨 ${esc(whyText(res, raw, p))}</p>`) +
|
|
973
|
+
`<p class="kw-common">most said: ${topNames(p, counts).map(esc).join(" · ")}</p>` +
|
|
974
|
+
`<div class="kw-actions"><button class="kw-btn" type="button" data-act="next" id="kw-next">${last ? "SURFACE THE RESULTS ▲" : "NEXT PROMPT ▼"}</button>` +
|
|
975
|
+
(!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>`;
|
|
976
|
+
status(last ? "that's the last prompt · press enter for your results" : "press enter for the next prompt");
|
|
977
|
+
$("kw-next").focus();
|
|
978
|
+
}
|
|
979
|
+
function finishDive(again) {
|
|
980
|
+
clearInterval(dive.tick);
|
|
981
|
+
clearSink();
|
|
982
|
+
dive.locked = true;
|
|
983
|
+
ui.screen = "results";
|
|
984
|
+
setMode("dive");
|
|
985
|
+
const total = sum(dive.answers), m = total * 10;
|
|
986
|
+
if (dive.mode === "daily") {
|
|
987
|
+
const prog = dailyProgress();
|
|
988
|
+
if (prog && !prog.done) {
|
|
989
|
+
Object.assign(prog, { done: true, total, answers: dive.answers.slice() });
|
|
990
|
+
ctx.store.set(DAILY_KEY, prog);
|
|
991
|
+
const s = ctx.store.get(STATS_KEY, {});
|
|
992
|
+
s.streak = s.last === dayBefore(prog.date) ? (s.streak || 0) + 1 : s.last === prog.date ? s.streak || 1 : 1;
|
|
993
|
+
s.last = prog.date; s.best = Math.max(s.best || 0, total); s.dives = (s.dives || 0) + 1;
|
|
994
|
+
ctx.store.set(STATS_KEY, s);
|
|
995
|
+
postScore(prog);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
camTo(m, again ? 2200 : 900);
|
|
999
|
+
const title = dive.mode === "daily" ? `DIVE #${dayNumber(dive.date || dateStr())}` : dive.mode === "past" ? `ARCHIVE · ${fmtDate(dive.date).toUpperCase()}` : "FREE PLAY";
|
|
1000
|
+
uiHtml(`<div class="kw-hud">
|
|
1001
|
+
<div class="kw-box"><small>DEPTH</small><b id="kw-depth">${fmtM(m)}</b></div>
|
|
1002
|
+
<div class="kw-progress"><ol id="kw-dots"></ol><small>DIVE COMPLETE</small></div>
|
|
1003
|
+
<div class="kw-box score"><small>SCORE</small><b id="kw-score">${total}</b></div>
|
|
1004
|
+
</div>
|
|
1005
|
+
<div class="kw-card kw-results in">
|
|
1006
|
+
<p class="kw-card-top">${esc(title)} · DIVE COMPLETE</p>
|
|
1007
|
+
<h2 class="kw-big">${fmtM(m)}</h2>
|
|
1008
|
+
<p class="kw-zoneline">${esc(zoneAt(m)).toUpperCase()} · ${total} POINTS${total >= ROUNDS * 100 ? " · PERFECT DIVE!" : ""}</p>
|
|
1009
|
+
<p class="kw-emoji">${dive.answers.map((r) => TIERS[r.p][1]).join(" ")}</p>
|
|
1010
|
+
${dive.mode === "daily" ? `<div class="kw-pct" id="kw-pct"><p class="kw-pct-sub">comparing with today's divers…</p></div>` : ""}
|
|
1011
|
+
<ol class="kw-rounds">${dive.answers.map((r) => `<li class="t${r.p}"><span class="kw-rq">${esc(promptFor(r.k).text)}</span>` +
|
|
1012
|
+
`<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>
|
|
1013
|
+
<div class="kw-actions">
|
|
1014
|
+
${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>`}
|
|
1015
|
+
<button class="kw-btn ghost" type="button" data-act="surface">▲ BACK TO THE SURFACE</button>
|
|
1016
|
+
</div>
|
|
1017
|
+
${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>` : ""}
|
|
1018
|
+
</div>`);
|
|
1019
|
+
renderDots();
|
|
1020
|
+
if (!again) sfx.play(total >= ROUNDS * 100 ? "win" : "done");
|
|
1021
|
+
if (m >= MAX_DEPTH) { const chest = $("kw-chest"); if (chest) chest.classList.add("open"); }
|
|
1022
|
+
if (dive.mode === "daily") {
|
|
1023
|
+
watchBoard("kw-board");
|
|
1024
|
+
showPercent(total, dive.date || dateStr());
|
|
1025
|
+
const tick = () => {
|
|
1026
|
+
const end = new Date(); end.setHours(24, 0, 0, 0);
|
|
1027
|
+
const left = end - Date.now(), el = $("kw-countdown");
|
|
1028
|
+
if (el) el.textContent = `next dive in ${Math.floor(left / 3600e3)}h ${Math.floor((left % 3600e3) / 60e3)}m`;
|
|
1029
|
+
};
|
|
1030
|
+
tick(); every(30e3, tick);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
// "Better than 62% of today's players": everyone else's score today from the leaderboard, and once a few people have
|
|
1034
|
+
// dived, all the scores drawn as a curve with you marked on it
|
|
1035
|
+
async function showPercent(total, date) {
|
|
1036
|
+
const f = await within(online(), 5000);
|
|
1037
|
+
let others = null;
|
|
1038
|
+
if (f) {
|
|
1039
|
+
try {
|
|
1040
|
+
const s = await within(f.db.ref(`krillionwho/board/${date}`).once("value"), 5000);
|
|
1041
|
+
if (s) { others = []; s.forEach((c) => { const v = c.val(); if (c.key !== f.uid && v && typeof v.pts === "number") others.push(v.pts); }); }
|
|
1042
|
+
} catch { /* offline, or older rules */ }
|
|
1043
|
+
}
|
|
1044
|
+
const el = $("kw-pct");
|
|
1045
|
+
if (!el) return;
|
|
1046
|
+
if (!others) { el.remove(); return; }
|
|
1047
|
+
const n = others.length, below = others.filter((p) => p < total).length;
|
|
1048
|
+
const pct = below === n ? 100 : Math.floor((below / n) * 100);
|
|
1049
|
+
el.innerHTML = (n + 1 >= 5 ? curveHtml([...others, total], total) : "") + (n
|
|
1050
|
+
? `<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>`
|
|
1051
|
+
: `<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>`);
|
|
1052
|
+
if (n) countTo($("kw-pct-n"), 0, pct, 1100, (v) => `${v}%`);
|
|
1053
|
+
}
|
|
1054
|
+
function curveHtml(all, me) {
|
|
1055
|
+
const mean = all.reduce((a, b) => a + b, 0) / all.length;
|
|
1056
|
+
const sd = Math.sqrt(all.reduce((a, b) => a + (b - mean) ** 2, 0) / all.length) || 60;
|
|
1057
|
+
const h = Math.min(90, Math.max(28, 1.06 * sd * Math.pow(all.length, -0.2))); // how much to smooth (Silverman's rule)
|
|
1058
|
+
const dens = (x) => all.reduce((t, p) => t + Math.exp(-0.5 * ((x - p) / h) ** 2), 0);
|
|
1059
|
+
const xs = Array.from({ length: 71 }, (_, i) => i * 10), ys = xs.map(dens), peak = Math.max(...ys) || 1;
|
|
1060
|
+
const y = (v) => 96 - (v / peak) * 86; // 0-100 down the plot
|
|
1061
|
+
const line = xs.map((x, i) => `${i ? "L" : "M"}${x} ${y(ys[i]).toFixed(1)}`).join("");
|
|
1062
|
+
const x = Math.max(0, Math.min(700, me)), at = (v) => `${(v / 7).toFixed(2)}%`;
|
|
1063
|
+
const ticks = [0, 100, 200, 300, 400, 500, 600, 700].filter((t) => Math.abs(t - x) > 45)
|
|
1064
|
+
.map((t) => `<span style="left:${at(t)}"${t === 0 ? ' class="first"' : t === 700 ? ' class="last"' : ""}>${t}</span>`).join("");
|
|
1065
|
+
return `<div class="kw-curve" aria-hidden="true"><div class="kw-curve-plot">
|
|
1066
|
+
<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>
|
|
1067
|
+
<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>
|
|
1068
|
+
</div><div class="kw-curve-axis">${ticks}<b style="left:${at(x)}">YOU</b></div></div>`;
|
|
1069
|
+
}
|
|
1070
|
+
async function postScore(prog) {
|
|
1071
|
+
const name = myName(), f = await online();
|
|
1072
|
+
if (!name || !f) return;
|
|
1073
|
+
try { await f.db.ref(`krillionwho/board/${prog.date}/${f.uid}`).set({ name, pts: prog.total, ts: TS() }); } catch { /* already posted today, or offline */ }
|
|
1074
|
+
}
|
|
1075
|
+
function shareText() {
|
|
1076
|
+
const prog = dailyProgress();
|
|
1077
|
+
if (!prog) return "";
|
|
1078
|
+
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`;
|
|
1079
|
+
}
|
|
1080
|
+
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"); }
|
|
1081
|
+
async function report(text) {
|
|
1082
|
+
const f = await online();
|
|
1083
|
+
if (!f) return ctx.toast("Couldn't send that right now.");
|
|
1084
|
+
try {
|
|
1085
|
+
const id = f.db.ref("reports/items").push().key;
|
|
1086
|
+
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() });
|
|
1087
|
+
ctx.toast("Thanks! We'll look at adding it.");
|
|
1088
|
+
} catch { ctx.toast("You can send one of these every 20 seconds."); }
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// ---------- Puffer Party ----------
|
|
1092
|
+
// The rules, as plain functions: each takes a copy of the room and returns the next one, or a reason it can't happen.
|
|
1093
|
+
// Online, they run inside database transactions; against the computer, on a local copy.
|
|
1094
|
+
const PP = {
|
|
1095
|
+
seats: (room) => Object.entries(room.players || {}).sort((a, b) => a[1].seat - b[1].seat).map(([id]) => id),
|
|
1096
|
+
alive: (room) => PP.seats(room).filter((id) => room.players[id].lives > 0),
|
|
1097
|
+
next(room, from) {
|
|
1098
|
+
const s = PP.seats(room);
|
|
1099
|
+
let k = s.indexOf(from);
|
|
1100
|
+
for (let n = 0; n < s.length; n++) { k = (k + 1) % s.length; if (room.players[s[k]].lives > 0) return s[k]; }
|
|
1101
|
+
return from;
|
|
1102
|
+
},
|
|
1103
|
+
pick(room, rnd) {
|
|
1104
|
+
const recent = String(room.recent || "").split(",").filter(Boolean);
|
|
1105
|
+
const pool = BANK.prompts.filter((p) => p.pool.length >= PARTY_POOL && (room.pack === "all" || p.cat.pack === room.pack));
|
|
1106
|
+
const fresh = pool.filter((p) => !recent.includes(p.cat.id));
|
|
1107
|
+
const list = fresh.length ? fresh : pool, p = list[Math.floor(rnd() * list.length)];
|
|
1108
|
+
room.recent = [...recent, p.cat.id].slice(-Math.min(10, Math.floor(new Set(pool.map((x) => x.cat.id)).size / 2))).join(",");
|
|
1109
|
+
return p.key;
|
|
1110
|
+
},
|
|
1111
|
+
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 }; },
|
|
1112
|
+
join(room, uid, name) {
|
|
1113
|
+
const p = room.players || (room.players = {});
|
|
1114
|
+
if (p[uid]) { p[uid].name = name; p[uid].on = true; room.seq++; return room; }
|
|
1115
|
+
if (room.state !== "lobby") return "started";
|
|
1116
|
+
if (Object.keys(p).length >= MAX_PLAYERS) return "full";
|
|
1117
|
+
p[uid] = { name, seat: Math.max(0, ...Object.values(p).map((x) => x.seat)) + 1, lives: room.lives, on: true };
|
|
1118
|
+
room.seq++;
|
|
1119
|
+
return room;
|
|
1120
|
+
},
|
|
1121
|
+
start(room, t, rnd) {
|
|
1122
|
+
if (room.state === "playing") return "started";
|
|
1123
|
+
for (const id of Object.keys(room.players)) if (room.players[id].on === false) delete room.players[id];
|
|
1124
|
+
const ids = PP.seats(room);
|
|
1125
|
+
if (ids.length < 2) return "few";
|
|
1126
|
+
for (const id of ids) room.players[id].lives = room.lives;
|
|
1127
|
+
room.state = "playing"; room.recent = "";
|
|
1128
|
+
delete room.winner; delete room.pop;
|
|
1129
|
+
PP.round(room, 1, ids[Math.floor(rnd() * ids.length)], t, rnd);
|
|
1130
|
+
room.seq++;
|
|
1131
|
+
return room;
|
|
1132
|
+
},
|
|
1133
|
+
pass(room, uid, ans, pts, t) {
|
|
1134
|
+
const r = room.round;
|
|
1135
|
+
if (room.state !== "playing" || !r || r.holder !== uid) return "turn";
|
|
1136
|
+
if (t > r.endsAt + 600) return "late";
|
|
1137
|
+
if (r.used && r.used[ans]) return "used";
|
|
1138
|
+
(r.used || (r.used = {}))[ans] = uid;
|
|
1139
|
+
const p = room.players[uid];
|
|
1140
|
+
r.last = { uid, a: ans, pts, at: t };
|
|
1141
|
+
if (pts >= 100 && p.lives < room.lives) { p.lives++; r.last.bonus = true; }
|
|
1142
|
+
r.holder = PP.next(room, uid);
|
|
1143
|
+
r.at = t;
|
|
1144
|
+
r.endsAt = Math.max(r.endsAt, t + FLOOR); // the fuse keeps burning, but nobody gets under 8 seconds
|
|
1145
|
+
room.seq++;
|
|
1146
|
+
return room;
|
|
1147
|
+
},
|
|
1148
|
+
pop(room, t, rnd) {
|
|
1149
|
+
const r = room.round;
|
|
1150
|
+
if (room.state !== "playing" || !r || t < r.endsAt) return "early";
|
|
1151
|
+
const id = r.holder, p = room.players[id];
|
|
1152
|
+
if (p) p.lives = Math.max(0, p.lives - 1);
|
|
1153
|
+
room.pop = { uid: id, at: t, n: r.n };
|
|
1154
|
+
const alive = PP.alive(room);
|
|
1155
|
+
if (alive.length <= 1) { room.state = "over"; if (alive[0] || id) room.winner = alive[0] || id; delete room.round; }
|
|
1156
|
+
else PP.round(room, r.n + 1, PP.next(room, id), t, rnd);
|
|
1157
|
+
room.seq++;
|
|
1158
|
+
return room;
|
|
1159
|
+
},
|
|
1160
|
+
leave(room, uid, t) {
|
|
1161
|
+
const p = room.players && room.players[uid];
|
|
1162
|
+
if (!p) return room;
|
|
1163
|
+
if (room.state === "playing") {
|
|
1164
|
+
p.lives = 0; p.on = false;
|
|
1165
|
+
const r = room.round;
|
|
1166
|
+
if (r && r.holder === uid) { r.holder = PP.next(room, uid); r.at = t; r.endsAt = Math.max(r.endsAt, t + FLOOR); }
|
|
1167
|
+
const alive = PP.alive(room);
|
|
1168
|
+
if (alive.length <= 1) { room.state = "over"; if (alive[0]) room.winner = alive[0]; delete room.round; }
|
|
1169
|
+
} else delete room.players[uid];
|
|
1170
|
+
const left = PP.seats(room).filter((id) => room.players[id].on !== false || room.state === "playing");
|
|
1171
|
+
if (!left.length || !PP.seats(room).some((id) => room.players[id].on !== false)) return null; // last one out closes the room
|
|
1172
|
+
if (room.host === uid || !room.players[room.host]) room.host = left.find((id) => room.players[id].on !== false) || left[0];
|
|
1173
|
+
room.seq++;
|
|
1174
|
+
return room;
|
|
1175
|
+
},
|
|
1176
|
+
reset(room) {
|
|
1177
|
+
room.state = "lobby";
|
|
1178
|
+
delete room.round; delete room.pop; delete room.winner;
|
|
1179
|
+
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; }
|
|
1180
|
+
room.seq++;
|
|
1181
|
+
return room;
|
|
1182
|
+
},
|
|
1183
|
+
};
|
|
1184
|
+
|
|
1185
|
+
const pp = { mode: null, code: null, me: null, room: null, ref: null, tick: 0, busy: false, plan: null, level: 1, bots: 3,
|
|
1186
|
+
shownPop: 0, lastPass: 0, lastFuse: 0, listSig: "", screen: null, close: null, connected: null, overSeen: false };
|
|
1187
|
+
const ppNow = () => (pp.mode === "online" ? now() : Date.now());
|
|
1188
|
+
const personName = (id) => (pp.room && pp.room.players[id] ? ctx.maskSlurs(pp.room.players[id].name) : "Someone");
|
|
1189
|
+
function answerName(promptKey, key) {
|
|
1190
|
+
const p = BANK.byKey.get(promptKey), i = p ? p.cat.byKey.get(key) : undefined;
|
|
1191
|
+
return i === undefined ? key : p.cat.entries[i].name;
|
|
1192
|
+
}
|
|
1193
|
+
// Change the room: a transaction online (so two people can't both grab the puffer), a plain update vs the computer
|
|
1194
|
+
async function ppDo(rule) {
|
|
1195
|
+
if (pp.mode === "bots") {
|
|
1196
|
+
const out = rule(clone(pp.room), ppNow());
|
|
1197
|
+
if (typeof out === "string") return out;
|
|
1198
|
+
pp.room = out;
|
|
1199
|
+
ppRender();
|
|
1200
|
+
return null;
|
|
1201
|
+
}
|
|
1202
|
+
if (!pp.ref) return "gone";
|
|
1203
|
+
let why = null;
|
|
1204
|
+
try {
|
|
1205
|
+
const res = await pp.ref.transaction((cur) => {
|
|
1206
|
+
if (!cur) { why = "gone"; return; }
|
|
1207
|
+
const out = rule(clone(cur), now());
|
|
1208
|
+
if (typeof out === "string") { why = out; return; }
|
|
1209
|
+
why = null;
|
|
1210
|
+
return out;
|
|
1211
|
+
});
|
|
1212
|
+
return res.committed ? null : why || "busy";
|
|
1213
|
+
} catch { return "error"; }
|
|
1214
|
+
}
|
|
1215
|
+
function ppNoteText(why) {
|
|
1216
|
+
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.",
|
|
1217
|
+
error: "Couldn't reach the room. Check your connection and try again.", busy: "Try that again." }[why] || "Something went wrong.";
|
|
1218
|
+
}
|
|
1219
|
+
function ppCreate(pub, name) {
|
|
1220
|
+
sheetNote("Making a room…");
|
|
1221
|
+
within(online(), 8000).then(async (f) => {
|
|
1222
|
+
if (!f) return sheetNote("Online rooms aren't available right now. Try playing against the computer.", true);
|
|
1223
|
+
const code = [...crypto.getRandomValues(new Uint32Array(6))].map((n) => ROOM_LETTERS[n % ROOM_LETTERS.length]).join("");
|
|
1224
|
+
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 } } };
|
|
1225
|
+
try {
|
|
1226
|
+
await f.db.ref().update({ [`krillionwho/rooms/${code}`]: room, [`krillionwho/roomLast/${f.uid}`]: TS() });
|
|
1227
|
+
} catch {
|
|
1228
|
+
return sheetNote("Couldn't make a room. You can make one every 15 seconds, so wait a moment and try again.", true);
|
|
1229
|
+
}
|
|
1230
|
+
const mine = ctx.store.get(MY_ROOMS_KEY, {});
|
|
1231
|
+
mine[code] = now();
|
|
1232
|
+
ctx.store.set(MY_ROOMS_KEY, mine);
|
|
1233
|
+
ctx.track("KrillionWho: Puffer Party room");
|
|
1234
|
+
ppEnter(code);
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
async function ppJoin(raw, name, quiet) {
|
|
1238
|
+
const code = String(raw || "").toUpperCase().replace(/[^A-Z0-9]/g, "");
|
|
1239
|
+
if (code.length !== 6) { if (!quiet) sheetNote("Room codes are 6 letters and numbers.", true); return "code"; }
|
|
1240
|
+
const f = await within(online(), 8000);
|
|
1241
|
+
if (!f) { if (!quiet) sheetNote(ppNoteText("error"), true); return "error"; }
|
|
1242
|
+
const ref = f.db.ref(`krillionwho/rooms/${code}`);
|
|
1243
|
+
const hold = () => {}; // keeps the room cached so the transaction starts from real data
|
|
1244
|
+
ref.on("value", hold, () => {});
|
|
1245
|
+
let why = null;
|
|
1246
|
+
try {
|
|
1247
|
+
await within(ref.once("value"), 5000);
|
|
1248
|
+
const res = await ref.transaction((cur) => {
|
|
1249
|
+
if (!cur) { why = "gone"; return; }
|
|
1250
|
+
const out = PP.join(clone(cur), f.uid, name);
|
|
1251
|
+
if (typeof out === "string") { why = out; return; }
|
|
1252
|
+
why = null;
|
|
1253
|
+
return out;
|
|
1254
|
+
});
|
|
1255
|
+
if (!res.committed) why = why || "busy";
|
|
1256
|
+
} catch { why = "gone"; }
|
|
1257
|
+
ref.off("value", hold);
|
|
1258
|
+
if (why) { if (!quiet) sheetNote(ppNoteText(why), true); return why; }
|
|
1259
|
+
ppEnter(code);
|
|
1260
|
+
return null;
|
|
1261
|
+
}
|
|
1262
|
+
async function ppQuick(name) {
|
|
1263
|
+
sheetNote("Looking for an open room…");
|
|
1264
|
+
const f = await within(online(), 8000);
|
|
1265
|
+
if (!f) return sheetNote("Online rooms aren't available right now. Try playing against the computer.", true);
|
|
1266
|
+
let rows = [];
|
|
1267
|
+
try {
|
|
1268
|
+
const s = await f.db.ref("krillionwho/lobbies").orderByChild("ts").limitToLast(25).once("value");
|
|
1269
|
+
s.forEach((c) => { const v = c.val(); if (v) rows.push({ code: c.key, ...v }); });
|
|
1270
|
+
} catch { /* older rules */ }
|
|
1271
|
+
rows = rows.filter((r) => r.n < MAX_PLAYERS && now() - r.ts < 15 * 60e3).sort((a, b) => b.ts - a.ts);
|
|
1272
|
+
for (const r of rows) if (!(await ppJoin(r.code, name, true))) return;
|
|
1273
|
+
ppCreate(true, name);
|
|
1274
|
+
}
|
|
1275
|
+
function ppScreen() {
|
|
1276
|
+
endDive();
|
|
1277
|
+
closeSheet();
|
|
1278
|
+
ui.screen = "pp";
|
|
1279
|
+
setMode("party");
|
|
1280
|
+
camTo(700, 1800);
|
|
1281
|
+
uiHtml(`<div class="kw-party" id="kw-pp"></div>`);
|
|
1282
|
+
}
|
|
1283
|
+
function ppEnter(code) {
|
|
1284
|
+
ppStop();
|
|
1285
|
+
Object.assign(pp, { mode: "online", code, me: net.uid, room: null, busy: false, shownPop: 0, lastPass: 0, listSig: "", screen: null, overSeen: false });
|
|
1286
|
+
ctx.store.set(ROOM_KEY, code);
|
|
1287
|
+
pp.ref = net.db.ref(`krillionwho/rooms/${code}`);
|
|
1288
|
+
const on = pp.ref.child(`players/${net.uid}/on`);
|
|
1289
|
+
on.onDisconnect().set(false).catch(() => {});
|
|
1290
|
+
net.db.ref(".info/connected").on("value", pp.connected = (s) => { if (s.val() && pp.room) on.set(true).catch(() => {}); });
|
|
1291
|
+
ppScreen();
|
|
1292
|
+
$("kw-pp").innerHTML = `<div class="kw-panel"><p class="kw-muted">Joining room ${esc(code)}…</p></div>`;
|
|
1293
|
+
sfx.play("splash");
|
|
1294
|
+
pp.ref.on("value", (s) => {
|
|
1295
|
+
const room = s.val();
|
|
1296
|
+
if (!room || !room.players || !room.players[pp.me]) return ppGone(room ? "You're not in that room anymore." : "That room closed.");
|
|
1297
|
+
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
|
|
1298
|
+
pp.room = room;
|
|
1299
|
+
ppRender();
|
|
1300
|
+
}, () => ppGone("Couldn't open that room."));
|
|
1301
|
+
pp.tick = setInterval(ppTick, 200);
|
|
1302
|
+
}
|
|
1303
|
+
function ppBots(name) {
|
|
1304
|
+
ppStop();
|
|
1305
|
+
const players = { you: { name: name || "You", seat: 1, lives: 2, on: true } };
|
|
1306
|
+
for (let i = 0; i < pp.bots; i++) players[`bot${i}`] = { name: BOT_NAMES[i], seat: i + 2, lives: 2, on: true, bot: true };
|
|
1307
|
+
Object.assign(pp, { mode: "bots", code: null, me: "you", ref: null, plan: null, shownPop: 0, lastPass: 0, screen: null, overSeen: false,
|
|
1308
|
+
room: { host: "you", ts: Date.now(), pub: false, pack: ui.pack, lives: 2, state: "lobby", seq: 1, players } });
|
|
1309
|
+
ppScreen();
|
|
1310
|
+
ppRender();
|
|
1311
|
+
pp.tick = setInterval(ppTick, 150);
|
|
1312
|
+
ctx.track("KrillionWho: Puffer Party vs computer");
|
|
1313
|
+
}
|
|
1314
|
+
function setBots(n) {
|
|
1315
|
+
const room = pp.room, players = { you: room.players.you };
|
|
1316
|
+
for (let i = 0; i < n; i++) players[`bot${i}`] = { name: BOT_NAMES[i], seat: i + 2, lives: room.lives, on: true, bot: true };
|
|
1317
|
+
pp.bots = n;
|
|
1318
|
+
room.players = players;
|
|
1319
|
+
ppRender();
|
|
1320
|
+
}
|
|
1321
|
+
function ppStop() {
|
|
1322
|
+
clearInterval(pp.tick);
|
|
1323
|
+
if (pp.ref) { pp.ref.off(); pp.ref.child(`players/${pp.me}/on`).onDisconnect().cancel().catch(() => {}); }
|
|
1324
|
+
if (pp.connected && net.db) net.db.ref(".info/connected").off("value", pp.connected);
|
|
1325
|
+
Object.assign(pp, { mode: null, ref: null, room: null, connected: null, close: null });
|
|
1326
|
+
}
|
|
1327
|
+
async function ppLeave() {
|
|
1328
|
+
if (pp.mode === "online") {
|
|
1329
|
+
const code = pp.code, wasHost = pp.room && pp.room.host === pp.me;
|
|
1330
|
+
await ppDo((room, t) => PP.leave(room, pp.me, t));
|
|
1331
|
+
if (wasHost) net.db.ref(`krillionwho/lobbies/${code}`).remove().catch(() => {});
|
|
1332
|
+
ctx.store.set(ROOM_KEY, "");
|
|
1333
|
+
}
|
|
1334
|
+
ppStop();
|
|
1335
|
+
renderHome(true);
|
|
1336
|
+
}
|
|
1337
|
+
function ppGone(msg) {
|
|
1338
|
+
const code = pp.code;
|
|
1339
|
+
ppStop();
|
|
1340
|
+
ctx.store.set(ROOM_KEY, "");
|
|
1341
|
+
if (code && net.db) net.db.ref(`krillionwho/lobbies/${code}`).remove().catch(() => {});
|
|
1342
|
+
if (ui.screen === "pp") { renderHome(true); ctx.toast(msg); }
|
|
1343
|
+
}
|
|
1344
|
+
// Whoever runs the clock: the host, or the first player still here if the host dropped
|
|
1345
|
+
function referee(room) {
|
|
1346
|
+
const here = PP.seats(room).filter((id) => room.players[id].on !== false);
|
|
1347
|
+
return room.players[room.host] && room.players[room.host].on !== false ? room.host : here[0];
|
|
1348
|
+
}
|
|
1349
|
+
function ppTick() {
|
|
1350
|
+
const room = pp.room;
|
|
1351
|
+
if (!room) return;
|
|
1352
|
+
const t = ppNow();
|
|
1353
|
+
ppClock(room, t);
|
|
1354
|
+
if (pp.mode === "bots") return botTurn(room, t);
|
|
1355
|
+
const r = room.round;
|
|
1356
|
+
if (room.state === "playing" && r && t > r.endsAt + 250 && !pp.busy && (referee(room) === pp.me || t > r.endsAt + 3000)) {
|
|
1357
|
+
pp.busy = true;
|
|
1358
|
+
ppDo((x, tt) => PP.pop(x, tt, Math.random)).finally(() => { pp.busy = false; });
|
|
1359
|
+
}
|
|
1360
|
+
if (room.players[room.host] && room.players[room.host].on === false && referee(room) === pp.me && !pp.busy) {
|
|
1361
|
+
pp.busy = true;
|
|
1362
|
+
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; });
|
|
1363
|
+
}
|
|
1364
|
+
if (room.host === pp.me) { // keep this room's spot in the public list up to date
|
|
1365
|
+
const n = PP.seats(room).length, want = room.pub && room.state === "lobby" && n < MAX_PLAYERS, sig = want ? `${n}|${room.pack}` : "off";
|
|
1366
|
+
if (sig !== pp.listSig) {
|
|
1367
|
+
pp.listSig = sig;
|
|
1368
|
+
const ref = net.db.ref(`krillionwho/lobbies/${pp.code}`);
|
|
1369
|
+
(want ? ref.set({ name: room.players[pp.me].name, n, pack: room.pack, ts: TS() }) : ref.remove()).catch(() => {});
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
// The computer's turn: decide once per pass whether it knows one, then answer after a "thinking" pause
|
|
1374
|
+
function botTurn(room, t) {
|
|
1375
|
+
const r = room.round;
|
|
1376
|
+
if (room.state !== "playing" || !r) return;
|
|
1377
|
+
if (t > r.endsAt) { ppDo((x, tt) => PP.pop(x, tt, Math.random)); return; }
|
|
1378
|
+
if (!room.players[r.holder].bot || t < r.startsAt) return;
|
|
1379
|
+
if (!pp.plan || pp.plan.at !== r.at || pp.plan.holder !== r.holder) {
|
|
1380
|
+
const p = BANK.byKey.get(r.key), lv = pp.level;
|
|
1381
|
+
const free = p.pool.filter((i) => !(r.used && r.used[p.cat.entries[i].key]));
|
|
1382
|
+
const usedUp = 1 - free.length / p.pool.length;
|
|
1383
|
+
const blank = !free.length || Math.random() < [0.09, 0.045, 0.02][lv] + usedUp * usedUp * [0.9, 0.6, 0.35][lv];
|
|
1384
|
+
const think = [2400, 1500, 900][lv] + Math.random() * [5200, 4000, 2600][lv];
|
|
1385
|
+
const reach = Math.max(3, Math.ceil(free.length * [0.35, 0.6, 1][lv]));
|
|
1386
|
+
const i = free[Math.floor(Math.random() * Math.min(reach, free.length))];
|
|
1387
|
+
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) } };
|
|
1388
|
+
}
|
|
1389
|
+
if (pp.plan.ans && t >= pp.plan.when) {
|
|
1390
|
+
const { key, pts } = pp.plan.ans, who = r.holder;
|
|
1391
|
+
pp.plan.ans = null;
|
|
1392
|
+
ppDo((x, tt) => PP.pass(x, who, key, pts, tt));
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
async function ppAnswer(raw, accepted) {
|
|
1396
|
+
const room = pp.room, r = room && room.round;
|
|
1397
|
+
if (!r || r.holder !== pp.me || ppNow() < r.startsAt) return;
|
|
1398
|
+
const p = BANK.byKey.get(r.key), res = accepted || check(p, raw);
|
|
1399
|
+
const input = $("kw-pp-input");
|
|
1400
|
+
ppDropClose();
|
|
1401
|
+
if (res.why === "close") { // "Did you mean…?": Enter again (or a click) takes it
|
|
1402
|
+
pp.close = { res, raw, prompt: p, at: r.at };
|
|
1403
|
+
const box = $("kw-pp-close");
|
|
1404
|
+
box.hidden = false;
|
|
1405
|
+
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>`;
|
|
1406
|
+
sfx.play("ask");
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
if (!res.ok) { sfx.play("miss"); return ppSay(whyText(res, raw, p), true, input); }
|
|
1410
|
+
const key = res.entry.key;
|
|
1411
|
+
if (r.used && r.used[key]) { sfx.play("miss"); return ppSay(`${res.entry.name} was already said by ${personName(r.used[key])}.`, true, input); }
|
|
1412
|
+
const pts = listPts(p, res.i);
|
|
1413
|
+
if (input) input.value = "";
|
|
1414
|
+
const why = await ppDo((x, t) => PP.pass(x, pp.me, key, pts, t));
|
|
1415
|
+
if (why) return ppSay(why === "used" ? `Someone just said ${res.entry.name}.` : "Too late!", true);
|
|
1416
|
+
ppSay("");
|
|
1417
|
+
if (pp.mode === "online") addCount(p.key, key);
|
|
1418
|
+
}
|
|
1419
|
+
function ppDropClose() {
|
|
1420
|
+
pp.close = null;
|
|
1421
|
+
const box = $("kw-pp-close");
|
|
1422
|
+
if (box) box.hidden = true;
|
|
1423
|
+
}
|
|
1424
|
+
function ppSay(text, bad, input) {
|
|
1425
|
+
const n = $("kw-pp-msg");
|
|
1426
|
+
if (n) { n.textContent = text || ""; n.classList.toggle("err", !!bad); }
|
|
1427
|
+
if (bad && input) { input.classList.remove("shake"); void input.offsetWidth; input.classList.add("shake"); input.select(); }
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
function ppRender() {
|
|
1431
|
+
const room = pp.room;
|
|
1432
|
+
if (!room || ui.screen !== "pp") return;
|
|
1433
|
+
const box = $("kw-pp");
|
|
1434
|
+
if (!box) return;
|
|
1435
|
+
if (pp.screen !== room.state) {
|
|
1436
|
+
pp.screen = room.state;
|
|
1437
|
+
box.innerHTML = ppShell(room.state);
|
|
1438
|
+
if (room.state === "over" && !pp.overSeen) { pp.overSeen = true; sfx.play(room.winner === pp.me ? "win" : "lose"); }
|
|
1439
|
+
if (room.state !== "over") pp.overSeen = false;
|
|
1440
|
+
}
|
|
1441
|
+
const mine = room.host === pp.me, ids = PP.seats(room);
|
|
1442
|
+
const head = $("kw-pp-head");
|
|
1443
|
+
if (head) head.innerHTML = pp.mode === "bots" ? `<span class="kw-label">PUFFER PARTY · VS THE COMPUTER</span>`
|
|
1444
|
+
: `<span class="kw-label">PUFFER PARTY · ROOM</span><button class="kw-code" type="button" data-act="pp-copy" title="Copy the code">${esc(pp.code)}</button>${room.pub ? `<span class="kw-tag">PUBLIC</span>` : ""}`;
|
|
1445
|
+
const players = $("kw-pp-players");
|
|
1446
|
+
if (players) players.innerHTML = ids.map((id) => {
|
|
1447
|
+
const p = room.players[id], hold = room.round && room.round.holder === id;
|
|
1448
|
+
const hearts = room.state === "lobby" ? "" : `<span class="kw-hearts">${"♥".repeat(p.lives)}<i>${"♥".repeat(Math.max(0, room.lives - p.lives))}</i></span>`;
|
|
1449
|
+
return `<li class="${hold ? "hold" : ""} ${p.lives <= 0 && room.state !== "lobby" ? "out" : ""} ${p.on === false ? "off" : ""}">` +
|
|
1450
|
+
`<span class="kw-pn">${id === room.host ? "👑 " : ""}${esc(ctx.maskSlurs(p.name))}${id === pp.me ? " <small>(you)</small>" : ""}</span>${hearts}` +
|
|
1451
|
+
`${hold ? `<span class="kw-has">${PUFFER}</span>` : ""}</li>`;
|
|
1452
|
+
}).join("");
|
|
1453
|
+
if (room.state === "lobby") {
|
|
1454
|
+
const here = ids.filter((id) => room.players[id].on !== false).length;
|
|
1455
|
+
const packs = [["all", "Everything"], ...BANK.packs].map(([id, label]) => `<option value="${id}"${room.pack === id ? " selected" : ""}>${esc(label)}</option>`).join("");
|
|
1456
|
+
$("kw-pp-setup").innerHTML = mine
|
|
1457
|
+
? `<label>PACK <select data-set="pack">${packs}</select></label>
|
|
1458
|
+
<label>LIVES <select data-set="lives">${[1, 2, 3].map((n) => `<option${room.lives === n ? " selected" : ""}>${n}</option>`).join("")}</select></label>
|
|
1459
|
+
${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>
|
|
1460
|
+
<label>COMPUTER <select data-set="level">${["Easy", "Normal", "Hard"].map((l, n) => `<option value="${n}"${pp.level === n ? " selected" : ""}>${l}</option>`).join("")}</select></label>`
|
|
1461
|
+
: `<label class="kw-check"><input type="checkbox" data-set="pub"${room.pub ? " checked" : ""}> Anyone can join with Quick play</label>`}`
|
|
1462
|
+
: `<p class="kw-muted">Pack: <b>${esc(packName(room.pack))}</b> · Lives: <b>${room.lives}</b></p>`;
|
|
1463
|
+
$("kw-pp-go").innerHTML = mine
|
|
1464
|
+
? `<button class="kw-play small" type="button" data-act="pp-start"${here < 2 ? " disabled" : ""}>▶ START ◀</button>${here < 2 ? `<p class="kw-muted">Share the code <b>${esc(pp.code || "")}</b> so friends can join. You need at least 2 players.</p>` : ""}`
|
|
1465
|
+
: `<p class="kw-muted">Waiting for the host to start…</p>`;
|
|
1466
|
+
} else if (room.state === "playing") ppGame(room);
|
|
1467
|
+
else {
|
|
1468
|
+
const w = room.winner;
|
|
1469
|
+
$("kw-pp-win").innerHTML = `<span class="kw-trophy">🏆</span><h2>${w === pp.me ? "YOU WIN!" : `${esc(personName(w)).toUpperCase()} WINS!`}</h2>` +
|
|
1470
|
+
`<p class="kw-muted">${w === pp.me ? "Last diver standing." : "Better luck next time."}</p>`;
|
|
1471
|
+
$("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>`;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
function ppShell(state) {
|
|
1475
|
+
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>`;
|
|
1476
|
+
if (state === "lobby") return `<div class="kw-panel">${top}
|
|
1477
|
+
<p class="kw-label">DIVERS</p><ul class="kw-pp-players" id="kw-pp-players"></ul>
|
|
1478
|
+
<div class="kw-pp-setup" id="kw-pp-setup"></div><div id="kw-pp-go"></div>
|
|
1479
|
+
<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>`;
|
|
1480
|
+
if (state === "playing") return `${top}<ul class="kw-pp-players row" id="kw-pp-players"></ul>
|
|
1481
|
+
<div class="kw-pp-stage" id="kw-pp-stage">
|
|
1482
|
+
<p class="kw-card-top" id="kw-pp-round"></p>
|
|
1483
|
+
<h2 class="kw-prompt" id="kw-pp-prompt"></h2><p class="kw-hint" id="kw-pp-hint"></p>
|
|
1484
|
+
<div class="kw-puffer" id="kw-puffer">${PUFFER}<span class="kw-pop-word">POP!</span></div>
|
|
1485
|
+
<p class="kw-pp-clock" id="kw-pp-clock"></p>
|
|
1486
|
+
<p class="kw-pp-turn" id="kw-pp-turn"></p>
|
|
1487
|
+
<form class="kw-answer" data-form="pp-answer" id="kw-pp-form" autocomplete="off">
|
|
1488
|
+
<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">
|
|
1489
|
+
<button class="kw-btn" type="submit">PASS ▶</button>
|
|
1490
|
+
</form>
|
|
1491
|
+
<div class="kw-close" id="kw-pp-close" hidden aria-live="assertive"></div>
|
|
1492
|
+
<p class="kw-note" id="kw-pp-msg" aria-live="polite"></p>
|
|
1493
|
+
<p class="kw-pp-last" id="kw-pp-last"></p>
|
|
1494
|
+
</div>
|
|
1495
|
+
<div class="kw-panel kw-used"><p class="kw-label">ALREADY SAID</p><ul class="kw-chips" id="kw-pp-used"></ul></div>`;
|
|
1496
|
+
return `<div class="kw-panel kw-pp-over">${top}<div class="kw-pp-win" id="kw-pp-win"></div><ul class="kw-pp-players" id="kw-pp-players"></ul><div id="kw-pp-go"></div></div>`;
|
|
1497
|
+
}
|
|
1498
|
+
function ppGame(room) {
|
|
1499
|
+
const r = room.round;
|
|
1500
|
+
if (!r) return;
|
|
1501
|
+
const p = BANK.byKey.get(r.key);
|
|
1502
|
+
$("kw-pp-round").textContent = `ROUND ${r.n} · ${p ? packName(p.cat.pack).toUpperCase() : ""}`;
|
|
1503
|
+
$("kw-pp-prompt").textContent = p ? p.text : "…";
|
|
1504
|
+
$("kw-pp-hint").textContent = p ? p.hint : "";
|
|
1505
|
+
const used = Object.entries(r.used || {});
|
|
1506
|
+
$("kw-pp-used").innerHTML = used.length ? used.map(([k, who]) => `<li class="${who === pp.me ? "me" : ""}">${esc(answerName(r.key, k))}</li>`).join("") : `<li class="kw-muted">Nothing yet.</li>`;
|
|
1507
|
+
const last = r.last;
|
|
1508
|
+
$("kw-pp-last").innerHTML = last ? `${esc(personName(last.uid))} said <b>${esc(answerName(r.key, last.a))}</b> <span class="kw-tag t${last.pts}">+${last.pts}</span>${last.bonus ? " and won back a life! ♥" : ""}` : "";
|
|
1509
|
+
if (last && last.at !== pp.lastPass) { pp.lastPass = last.at; sfx.play("pass"); }
|
|
1510
|
+
const mineTurn = r.holder === pp.me;
|
|
1511
|
+
const input = $("kw-pp-input"), form = $("kw-pp-form");
|
|
1512
|
+
if (pp.close && (!mineTurn || pp.close.at !== r.at)) ppDropClose(); // the puffer moved on: the suggestion is stale
|
|
1513
|
+
if (mineTurn && form.hidden) sfx.play("go");
|
|
1514
|
+
form.hidden = !mineTurn;
|
|
1515
|
+
if (mineTurn && document.activeElement !== input && ppNow() >= r.startsAt) input.focus();
|
|
1516
|
+
if (room.pop && room.pop.at !== pp.shownPop && ppNow() - room.pop.at < 4000) { // someone just popped
|
|
1517
|
+
pp.shownPop = room.pop.at;
|
|
1518
|
+
const stage = $("kw-pp-stage");
|
|
1519
|
+
stage.classList.remove("popped"); void stage.offsetWidth; stage.classList.add("popped");
|
|
1520
|
+
sfx.play("pop");
|
|
1521
|
+
const me = room.pop.uid === pp.me, lives = room.players[room.pop.uid] ? room.players[room.pop.uid].lives : 0;
|
|
1522
|
+
ppSay(`💥 ${me ? "You" : personName(room.pop.uid)} ${me ? "lose" : "loses"} a life${lives <= 0 ? ` and ${me ? "are" : "is"} out` : ""}!`, false);
|
|
1523
|
+
}
|
|
1524
|
+
ppClock(room, ppNow());
|
|
1525
|
+
}
|
|
1526
|
+
function ppClock(room, t) {
|
|
1527
|
+
const r = room.round, fish = $("kw-puffer");
|
|
1528
|
+
if (room.state !== "playing" || !r || !fish) return;
|
|
1529
|
+
const turn = $("kw-pp-turn"), clock = $("kw-pp-clock"), mineTurn = r.holder === pp.me, input = $("kw-pp-input");
|
|
1530
|
+
if (t < r.startsAt) {
|
|
1531
|
+
clock.textContent = `next prompt in ${Math.ceil((r.startsAt - t) / 1000)}…`;
|
|
1532
|
+
turn.textContent = mineTurn ? "You start with the pufferfish. Get ready!" : `${personName(r.holder)} starts with the pufferfish.`;
|
|
1533
|
+
input.disabled = true;
|
|
1534
|
+
fish.style.setProperty("--s", "0.85");
|
|
1535
|
+
fish.style.setProperty("--heat", "0");
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
input.disabled = !mineTurn;
|
|
1539
|
+
const left = Math.max(0, r.endsAt - t), span = Math.max(1, r.endsAt - Math.max(r.at, r.startsAt));
|
|
1540
|
+
const grown = Math.min(1, 1 - left / Math.max(span, FLOOR)), heat = Math.min(1, Math.max(0, 1 - left / 9000));
|
|
1541
|
+
fish.style.setProperty("--s", (0.85 + grown * 0.75).toFixed(3));
|
|
1542
|
+
fish.style.setProperty("--heat", heat.toFixed(3));
|
|
1543
|
+
clock.textContent = `${(left / 1000).toFixed(1)}s`;
|
|
1544
|
+
clock.classList.toggle("hurry", left < 4000);
|
|
1545
|
+
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
|
|
1546
|
+
const holder = room.players[r.holder];
|
|
1547
|
+
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…`;
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
// ---------- Events ----------
|
|
1551
|
+
function onClick(e) {
|
|
1552
|
+
if (e.target.id === "kw-modal") { closeSheet(); return; } // clicked outside a pop-up
|
|
1553
|
+
const b = e.target.closest("[data-act]");
|
|
1554
|
+
if (!b || !root.contains(b)) return;
|
|
1555
|
+
const act = b.dataset.act, quiet = ["sound", "next", "close-yes", "pp-close-yes", "daily", "free", "past", "again"];
|
|
1556
|
+
if (!quiet.includes(act)) sfx.play("click");
|
|
1557
|
+
if (act === "play") playSheet();
|
|
1558
|
+
else if (act === "howto") howSheet();
|
|
1559
|
+
else if (act === "board") boardSheet();
|
|
1560
|
+
else if (act === "menu") menuSheet();
|
|
1561
|
+
else if (act === "close") closeSheet();
|
|
1562
|
+
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(); }
|
|
1563
|
+
else if (act === "daily") startDaily();
|
|
1564
|
+
else if (act === "free-menu") freeSheet();
|
|
1565
|
+
else if (act === "pp-menu") partySheet();
|
|
1566
|
+
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)); }
|
|
1567
|
+
else if (act === "past") beginDive("past", pickDaily(b.dataset.date), [], b.dataset.date);
|
|
1568
|
+
else if (act === "again") beginDive(dive.mode === "past" ? "past" : "free", dive.mode === "past" ? pickDaily(dive.date) : pickFree(ui.pack), [], dive.date);
|
|
1569
|
+
else if (act === "next") { if (dive.answers.length >= ROUNDS) finishDive(); else nextRound(); }
|
|
1570
|
+
else if (act === "close-yes" && dive.close) answer(false, confirmClose(dive.prompt, dive.close));
|
|
1571
|
+
else if (act === "close-no") dropClose(true);
|
|
1572
|
+
else if (act === "quit" || act === "surface") { if (ui.screen === "pp") ppLeave(); else renderHome(true); }
|
|
1573
|
+
else if (act === "share") { const text = shareText(); navigator.clipboard?.writeText(text).then(() => ctx.toast("Copied! Paste it anywhere."), () => ctx.toast(text)); }
|
|
1574
|
+
else if (act === "report") { b.disabled = true; report(b.dataset.text); }
|
|
1575
|
+
else if (act === "pp-create") askName((name) => ppCreate(false, name), "So the others know who's who.");
|
|
1576
|
+
else if (act === "pp-quick") askName((name) => ppQuick(name), "So the others know who's who.");
|
|
1577
|
+
else if (act === "pp-bots") ppBots(myName());
|
|
1578
|
+
else if (act === "pp-rejoin") askName((name) => ppJoin(ctx.store.get(ROOM_KEY, ""), name), "So the others know who's who.");
|
|
1579
|
+
else if (act === "pp-leave") ppLeave();
|
|
1580
|
+
else if (act === "pp-copy") navigator.clipboard?.writeText(pp.code).then(() => ctx.toast(`Room code ${pp.code} copied.`), () => {});
|
|
1581
|
+
else if (act === "pp-start") ppDo((x, t) => PP.start(x, t, Math.random)).then((why) => { if (why) ppSay(ppNoteText(why), true); });
|
|
1582
|
+
else if (act === "pp-again") ppDo((x) => PP.reset(x));
|
|
1583
|
+
else if (act === "pp-close-yes" && pp.close) ppAnswer(pp.close.raw, confirmClose(pp.close.prompt, pp.close.res));
|
|
1584
|
+
}
|
|
1585
|
+
function onChange(e) {
|
|
1586
|
+
const el = e.target.closest("[data-set]");
|
|
1587
|
+
if (!el || !pp.room || pp.room.host !== pp.me) return;
|
|
1588
|
+
const what = el.dataset.set;
|
|
1589
|
+
if (what === "bots") return setBots(Number(el.value));
|
|
1590
|
+
if (what === "level") { pp.level = Number(el.value); return; }
|
|
1591
|
+
const val = what === "lives" ? Number(el.value) : what === "pub" ? el.checked : el.value;
|
|
1592
|
+
if (what === "pack") { ui.pack = val; ctx.store.set(PACK_KEY, val); }
|
|
1593
|
+
ppDo((x) => { x[what] = val; if (what === "lives") for (const p of Object.values(x.players)) p.lives = val; x.seq++; return x; });
|
|
1594
|
+
}
|
|
1595
|
+
function onSubmit(e) {
|
|
1596
|
+
const form = e.target.closest("[data-form]");
|
|
1597
|
+
if (!form || !root.contains(form)) return;
|
|
1598
|
+
e.preventDefault();
|
|
1599
|
+
const kind = form.dataset.form;
|
|
1600
|
+
if (kind === "answer") answer(false);
|
|
1601
|
+
else if (kind === "pp-answer") {
|
|
1602
|
+
const raw = $("kw-pp-input").value;
|
|
1603
|
+
if (pp.close && pp.close.raw === raw) ppAnswer(raw, confirmClose(pp.close.prompt, pp.close.res));
|
|
1604
|
+
else ppAnswer(raw);
|
|
1605
|
+
} else if (kind === "pp-join") askName((name) => ppJoin($("kw-code").value, name), "So the others know who's who.");
|
|
1606
|
+
else if (kind === "name" || kind === "rename") {
|
|
1607
|
+
const res = cleanName($("kw-name-in").value);
|
|
1608
|
+
if (res.error) return sheetNote(res.error, true);
|
|
1609
|
+
ctx.store.set(NAME_KEY, res.name);
|
|
1610
|
+
sfx.play("click");
|
|
1611
|
+
if (kind === "rename") return sheetNote(`Saved: ${res.name}`);
|
|
1612
|
+
const then = afterName;
|
|
1613
|
+
afterName = null;
|
|
1614
|
+
closeSheet();
|
|
1615
|
+
if (then) then(res.name);
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
function onKey(e) { // Enter moves on from a revealed answer
|
|
1619
|
+
if (e.key === "Escape" && !$("kw-modal").hidden) { closeSheet(); return; }
|
|
1620
|
+
if (e.key !== "Enter" || ui.screen !== "dive" || root.closest("[hidden]")) return;
|
|
1621
|
+
const next = $("kw-next");
|
|
1622
|
+
if (next && !$("kw-reveal").hidden && document.activeElement !== next) { e.preventDefault(); next.click(); }
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
// ---------- Hooking into the page ----------
|
|
1626
|
+
function mount(el, helpers) {
|
|
1627
|
+
ctx = helpers;
|
|
1628
|
+
root = el;
|
|
1629
|
+
BANK = buildBank(window.KRILLIONWHO_DATA);
|
|
1630
|
+
sfx.on = ctx.store.get(SOUND_KEY, true) !== false;
|
|
1631
|
+
ui.pack = ctx.store.get(PACK_KEY, "all");
|
|
1632
|
+
if (ui.pack !== "all" && !BANK.packs.some(([id]) => id === ui.pack)) ui.pack = "all";
|
|
1633
|
+
root.innerHTML = sceneHtml();
|
|
1634
|
+
soundIcon();
|
|
1635
|
+
root.addEventListener("click", onClick);
|
|
1636
|
+
root.addEventListener("change", onChange);
|
|
1637
|
+
root.addEventListener("submit", onSubmit);
|
|
1638
|
+
root.addEventListener("input", (e) => { // typing again dismisses "Did you mean…?"
|
|
1639
|
+
if (e.target.id === "kw-input" && dive.close) dropClose(false);
|
|
1640
|
+
if (e.target.id === "kw-input" && $("kw-wrong")) $("kw-wrong").hidden = true;
|
|
1641
|
+
if (e.target.id === "kw-pp-input" && pp.close) ppDropClose();
|
|
1642
|
+
});
|
|
1643
|
+
document.addEventListener("keydown", onKey);
|
|
1644
|
+
if (window.ResizeObserver) new ResizeObserver(() => layout()).observe($("kw-stage")); // window resizes, and the section reopening
|
|
1645
|
+
else addEventListener("resize", layout);
|
|
1646
|
+
layout();
|
|
1647
|
+
renderHome();
|
|
1648
|
+
}
|
|
1649
|
+
// Opening the section again: a game in progress carries on; otherwise back to the surface
|
|
1650
|
+
function enter() {
|
|
1651
|
+
layout();
|
|
1652
|
+
if (ui.screen === "pp" && pp.mode) return ppRender();
|
|
1653
|
+
if (ui.screen === "dive" || ui.screen === "results" || ui.screen === "pp") return;
|
|
1654
|
+
renderHome();
|
|
1655
|
+
}
|
|
1656
|
+
// Leaving the section: an unanswered prompt in the daily dive is used up; a room keeps going without you watching
|
|
1657
|
+
function leave() {
|
|
1658
|
+
if (ui.screen === "dive" && dive.mode) { renderHome(); return; }
|
|
1659
|
+
if (pp.mode === "bots") { ppStop(); renderHome(); }
|
|
1660
|
+
}
|
|
1661
|
+
// From elsewhere on the site (the Daily Dive banner on the Games page): straight into today's dive, or the PLAY menu.
|
|
1662
|
+
// Someone sitting in a Puffer Party room stays there.
|
|
1663
|
+
function open(action) {
|
|
1664
|
+
if (!BANK || (ui.screen === "pp" && pp.mode)) return;
|
|
1665
|
+
if (action === "daily") startDaily();
|
|
1666
|
+
else if (action === "play") { if (ui.screen !== "home") renderHome(); playSheet(); }
|
|
1667
|
+
}
|
|
1668
|
+
const testBank = () => BANK || (BANK = buildBank(window.KRILLIONWHO_DATA));
|
|
1669
|
+
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 } };
|
|
1670
|
+
})();
|