Skip to content

gitflarePublicPartly agent-ready40

sketch-rush

Multiplayer draw-and-guess game on Cloudflare Workers, Durable Objects and D1.

main
Add the Apache-2.0 licencedbe1e99
TypeScript39 lines1.6 KB
export interface Env {  ROOM: DurableObjectNamespace;  LOBBY: DurableObjectNamespace;  DB?: D1Database;  ASSETS: Fetcher;} export async function topScores(env: Env, mode: string): Promise<{ entries: { name: string; score: number; created_at: number }[]; available: boolean }> {  if (!env.DB) return { entries: [], available: false };  try {    await ensureSchema(env.DB);    const r = await env.DB.prepare("SELECT name, score, created_at FROM scores WHERE game_mode = ? ORDER BY score DESC, created_at ASC LIMIT 20").bind(mode).all();    return { entries: (r.results ?? []) as { name: string; score: number; created_at: number }[], available: true };  } catch {    return { entries: [], available: false };  }} export async function saveScores(env: Env, mode: string, rows: { name: string; score: number }[]): Promise<void> {  if (!env.DB || !rows.length) return;  try {    const now = Date.now();    await ensureSchema(env.DB);    const stmt = env.DB.prepare("INSERT INTO scores (game_mode, name, score, created_at) VALUES (?, ?, ?, ?)");    await env.DB.batch(rows.map((r) => stmt.bind(mode, r.name, r.score, now)));  } catch {    /* leaderboard is best-effort */  }} let schemaReady = false;async function ensureSchema(db: D1Database): Promise<void> {  if (schemaReady) return;  await db.exec("CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY, game_mode TEXT, name TEXT, score INTEGER, created_at INTEGER);");  await db.exec("CREATE INDEX IF NOT EXISTS idx_scores_mode_score ON scores (game_mode, score DESC);");  await db.exec("CREATE INDEX IF NOT EXISTS idx_scores_created ON scores (created_at);");  schemaReady = true;}