-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathgame.ts
More file actions
499 lines (446 loc) · 15.4 KB
/
game.ts
File metadata and controls
499 lines (446 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
import { generateText } from "ai";
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
import { mkdirSync, appendFileSync } from "node:fs";
import { join } from "node:path";
// ── Models ──────────────────────────────────────────────────────────────────
export const MODELS = [
{ id: "google/gemini-3.1-pro-preview", name: "Gemini 3.1 Pro" },
{ id: "moonshotai/kimi-k2", name: "Kimi K2" },
// { id: "moonshotai/kimi-k2.5", name: "Kimi K2.5" },
{ id: "deepseek/deepseek-v3.2", name: "DeepSeek 3.2" },
// { id: "z-ai/glm-5", name: "GLM-5" },
{ id: "openai/gpt-5.2", name: "GPT-5.2" },
{ id: "anthropic/claude-opus-4.6", name: "Opus 4.6" },
{ id: "anthropic/claude-sonnet-4.6", name: "Sonnet 4.6" },
{ id: "x-ai/grok-4.1-fast", name: "Grok 4.1" },
// { id: "minimax/minimax-m2.5", name: "MiniMax 2.5" },
] as const;
export type Model = (typeof MODELS)[number];
export const MODEL_COLORS: Record<string, string> = {
"Gemini 3.1 Pro": "cyan",
"Kimi K2": "green",
"Kimi K2.5": "magenta",
"DeepSeek 3.2": "greenBright",
"GLM-5": "cyanBright",
"GPT-5.2": "yellow",
"Opus 4.6": "blue",
"Sonnet 4.6": "red",
"Grok 4.1": "white",
"MiniMax 2.5": "magentaBright",
};
export const NAME_PAD = 16;
// ── Types ───────────────────────────────────────────────────────────────────
export type TaskInfo = {
model: Model;
startedAt: number;
finishedAt?: number;
result?: string;
error?: string;
};
export type VoteInfo = {
voter: Model;
startedAt: number;
finishedAt?: number;
votedFor?: Model;
error?: boolean;
};
export type RoundState = {
num: number;
phase: "prompting" | "answering" | "voting" | "done";
prompter: Model;
promptTask: TaskInfo;
prompt?: string;
contestants: [Model, Model];
answerTasks: [TaskInfo, TaskInfo];
votes: VoteInfo[];
scoreA?: number;
scoreB?: number;
viewerVotesA?: number;
viewerVotesB?: number;
viewerVotingEndsAt?: number;
};
export type GameState = {
completed: RoundState[];
active: RoundState | null;
scores: Record<string, number>;
viewerScores: Record<string, number>;
done: boolean;
isPaused: boolean;
generation: number;
};
// ── OpenRouter ──────────────────────────────────────────────────────────────
const openrouter = createOpenRouter({
apiKey: process.env.OPENROUTER_API_KEY,
extraBody: {
reasoning: {
effort: "medium",
},
},
});
// ── Logger ──────────────────────────────────────────────────────────────────
const LOGS_DIR = join(import.meta.dir, "logs");
mkdirSync(LOGS_DIR, { recursive: true });
const LOG_FILE = join(
LOGS_DIR,
`game-${new Date().toISOString().replace(/[:.]/g, "-")}.log`,
);
export { LOG_FILE };
export function log(
level: "INFO" | "WARN" | "ERROR",
category: string,
message: string,
data?: Record<string, unknown>,
) {
const ts = new Date().toISOString();
let line = `[${ts}] ${level} [${category}] ${message}`;
if (data) {
line += " " + JSON.stringify(data);
}
appendFileSync(LOG_FILE, line + "\n");
if (level === "ERROR") {
console.error(line);
} else if (level === "WARN") {
console.warn(line);
} else {
console.log(line);
}
}
// ── Helpers ─────────────────────────────────────────────────────────────────
export function shuffle<T>(arr: T[]): T[] {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j]!, a[i]!];
}
return a;
}
export async function withRetry<T>(
fn: () => Promise<T>,
validate: (result: T) => boolean,
retries = 3,
label = "unknown",
): Promise<T> {
let lastErr: unknown;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const result = await fn();
if (validate(result)) {
log("INFO", label, `Success on attempt ${attempt}`, {
result: typeof result === "string" ? result : String(result),
});
return result;
}
const msg = `Validation failed (attempt ${attempt}/${retries})`;
log("WARN", label, msg, {
result: typeof result === "string" ? result : String(result),
});
lastErr = new Error(`${msg}: ${JSON.stringify(result).slice(0, 100)}`);
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err);
log("WARN", label, `Error on attempt ${attempt}/${retries}: ${errMsg}`, {
error: errMsg,
stack: err instanceof Error ? err.stack : undefined,
});
lastErr = err;
}
if (attempt < retries) {
await new Promise((r) => setTimeout(r, 1000 * attempt));
}
}
log("ERROR", label, `All ${retries} attempts failed`, {
lastError: lastErr instanceof Error ? lastErr.message : String(lastErr),
});
throw lastErr;
}
export function isRealString(s: string, minLength = 5): boolean {
return s.length >= minLength;
}
export function cleanResponse(text: string): string {
const trimmed = text.trim();
if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
(trimmed.startsWith("'") && trimmed.endsWith("'"))) {
return trimmed.slice(1, -1);
}
return trimmed;
}
// ── AI functions ────────────────────────────────────────────────────────────
import { ALL_PROMPTS } from "./prompts";
function buildPromptSystem(): string {
const examples = shuffle([...ALL_PROMPTS]).slice(0, 80);
return `You are a comedy writer for the game Quiplash. Generate a single funny fill-in-the-blank prompt that players will try to answer. The prompt should be surprising and designed to elicit hilarious responses. Return ONLY the prompt text, nothing else. Keep it short (under 15 words).
Use a wide VARIETY of prompt formats. Do NOT always use "The worst thing to..." — mix it up! Here are examples of the range of styles:
${examples.map((p) => `- ${p}`).join("\n")}
Come up with something ORIGINAL — don't copy these examples.`;
}
export async function callGeneratePrompt(model: Model): Promise<string> {
log("INFO", `prompt:${model.name}`, "Calling API", { modelId: model.id });
const system = buildPromptSystem();
const { text, usage, reasoning } = await generateText({
model: openrouter.chat(model.id),
system,
prompt:
"Generate a single original Quiplash prompt. Be creative and don't repeat common patterns.",
});
log("INFO", `prompt:${model.name}`, "Raw response", {
rawText: text,
usage,
});
return cleanResponse(text);
}
export async function callGenerateAnswer(
model: Model,
prompt: string,
): Promise<string> {
log("INFO", `answer:${model.name}`, "Calling API", {
modelId: model.id,
prompt,
});
const { text, usage, reasoning } = await generateText({
model: openrouter.chat(model.id),
system: `You are playing Quiplash! You'll be given a fill-in-the-blank prompt. Give the FUNNIEST possible answer. Be creative, edgy, unexpected, and concise. Reply with ONLY your answer — no quotes, no explanation, no preamble. Keep it short (under 12 words). Keep it concise and witty.`,
prompt: `Fill in the blank: ${prompt}`,
});
log("INFO", `answer:${model.name}`, "Raw response", {
rawText: text,
usage,
});
return cleanResponse(text);
}
export async function callVote(
voter: Model,
prompt: string,
a: { answer: string },
b: { answer: string },
): Promise<"A" | "B"> {
log("INFO", `vote:${voter.name}`, "Calling API", {
modelId: voter.id,
prompt,
answerA: a.answer,
answerB: b.answer,
});
const { text, usage, reasoning } = await generateText({
model: openrouter.chat(voter.id),
system: `You are a judge in a comedy game. You'll see a fill-in-the-blank prompt and two answers. Pick which answer is FUNNIER. You MUST respond with exactly "A" or "B" — nothing else.`,
prompt: `Prompt: "${prompt}"\n\nAnswer A: "${a.answer}"\nAnswer B: "${b.answer}"\n\nWhich is funnier? Reply with just A or B.`,
});
log("INFO", `vote:${voter.name}`, "Raw response", { rawText: text, usage });
const cleaned = text.trim().toUpperCase();
if (!cleaned.startsWith("A") && !cleaned.startsWith("B")) {
throw new Error(`Invalid vote: "${text.trim()}"`);
}
return cleaned.startsWith("A") ? "A" : "B";
}
import { saveRound } from "./db.ts";
// ── Game loop ───────────────────────────────────────────────────────────────
export async function runGame(
runs: number,
state: GameState,
rerender: () => void,
onViewerVotingStart?: (round: RoundState) => void,
) {
let startRound = 1;
const lastCompletedRound = state.completed.at(-1);
if (lastCompletedRound) {
startRound = lastCompletedRound.num + 1;
}
let endRound = startRound + runs - 1;
for (let r = startRound; r <= endRound; r++) {
while (state.isPaused) {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
const roundGeneration = state.generation;
// Reset round counter if generation changed (e.g. admin reset)
const latest = state.completed.at(-1);
const expectedR = latest ? latest.num + 1 : 1;
if (r !== expectedR) {
r = expectedR;
endRound = r + runs - 1;
}
const shuffled = shuffle([...MODELS]);
const prompter = shuffled[0]!;
const contA = shuffled[1]!;
const contB = shuffled[2]!;
const voters = [prompter, ...shuffled.slice(3)];
const now = Date.now();
const round: RoundState = {
num: r,
phase: "prompting",
prompter,
promptTask: { model: prompter, startedAt: now },
contestants: [contA, contB],
answerTasks: [
{ model: contA, startedAt: 0 },
{ model: contB, startedAt: 0 },
],
votes: [],
};
state.active = round;
log("INFO", "round", `=== Round ${r}/${runs} ===`, {
prompter: prompter.name,
contestants: [contA.name, contB.name],
voters: voters.map((v) => v.name),
});
rerender();
// ── Prompt phase ──
try {
const prompt = await withRetry(
() => callGeneratePrompt(prompter),
(s) => isRealString(s, 10),
3,
`R${r}:prompt:${prompter.name}`,
);
if (state.generation !== roundGeneration) {
continue;
}
round.promptTask.finishedAt = Date.now();
round.promptTask.result = prompt;
round.prompt = prompt;
rerender();
} catch {
if (state.generation !== roundGeneration) {
continue;
}
round.promptTask.finishedAt = Date.now();
round.promptTask.error = "Failed after 3 attempts";
round.phase = "done";
state.completed = [...state.completed, round];
state.active = null;
rerender();
continue;
}
// ── Answer phase ──
round.phase = "answering";
const answerStart = Date.now();
round.answerTasks[0].startedAt = answerStart;
round.answerTasks[1].startedAt = answerStart;
rerender();
await Promise.all(
round.answerTasks.map(async (task) => {
if (state.generation !== roundGeneration) {
return;
}
try {
const answer = await withRetry(
() => callGenerateAnswer(task.model, round.prompt!),
(s) => isRealString(s, 3),
3,
`R${r}:answer:${task.model.name}`,
);
if (state.generation !== roundGeneration) {
return;
}
task.result = answer;
} catch {
if (state.generation !== roundGeneration) {
return;
}
task.error = "Failed to answer";
task.result = "[no answer]";
}
if (state.generation !== roundGeneration) {
return;
}
task.finishedAt = Date.now();
rerender();
}),
);
if (state.generation !== roundGeneration) {
continue;
}
// ── Vote phase ──
round.phase = "voting";
const answerA = round.answerTasks[0].result!;
const answerB = round.answerTasks[1].result!;
const voteStart = Date.now();
round.votes = voters.map((v) => ({ voter: v, startedAt: voteStart }));
// Initialize viewer voting
round.viewerVotesA = 0;
round.viewerVotesB = 0;
round.viewerVotingEndsAt = Date.now() + 30_000;
onViewerVotingStart?.(round);
rerender();
await Promise.all([
// Model votes
Promise.all(
round.votes.map(async (vote) => {
if (state.generation !== roundGeneration) {
return;
}
try {
const showAFirst = Math.random() > 0.5;
const first = showAFirst ? { answer: answerA } : { answer: answerB };
const second = showAFirst ? { answer: answerB } : { answer: answerA };
const result = await withRetry(
() => callVote(vote.voter, round.prompt!, first, second),
(v) => v === "A" || v === "B",
3,
`R${r}:vote:${vote.voter.name}`,
);
if (state.generation !== roundGeneration) {
return;
}
const votedFor = showAFirst
? result === "A"
? contA
: contB
: result === "A"
? contB
: contA;
vote.finishedAt = Date.now();
vote.votedFor = votedFor;
} catch {
if (state.generation !== roundGeneration) {
return;
}
vote.finishedAt = Date.now();
vote.error = true;
}
if (state.generation !== roundGeneration) {
return;
}
rerender();
}),
),
// 30-second viewer voting window
new Promise((r) => setTimeout(r, 30_000)),
]);
if (state.generation !== roundGeneration) {
continue;
}
// ── Score ──
let votesA = 0;
let votesB = 0;
for (const v of round.votes) {
if (v.votedFor === contA) votesA++;
else if (v.votedFor === contB) votesB++;
}
round.scoreA = votesA * 100;
round.scoreB = votesB * 100;
round.phase = "done";
if (votesA > votesB) {
state.scores[contA.name] = (state.scores[contA.name] || 0) + 1;
} else if (votesB > votesA) {
state.scores[contB.name] = (state.scores[contB.name] || 0) + 1;
}
// Viewer vote scoring
const vvA = round.viewerVotesA ?? 0;
const vvB = round.viewerVotesB ?? 0;
if (vvA > vvB) {
state.viewerScores[contA.name] = (state.viewerScores[contA.name] || 0) + 1;
} else if (vvB > vvA) {
state.viewerScores[contB.name] = (state.viewerScores[contB.name] || 0) + 1;
}
rerender();
await new Promise((r) => setTimeout(r, 5000));
if (state.generation !== roundGeneration) {
continue;
}
// Archive round
saveRound(round);
state.completed = [...state.completed, round];
state.active = null;
rerender();
}
state.done = true;
rerender();
}