gitflarePublicPartly agent-ready40
sketch-rush
Multiplayer draw-and-guess game on Cloudflare Workers, Durable Objects and D1.
- LicenseApache-2.0
- LanguageJavaScript
- Last landed
dbe1e99Oct 23, 2026
Add the Apache-2.0 licence
dbe1e99import { Net } from "/net.js";import { createRenderer, PALETTE, WIDTHS } from "/render.js";import { bindInput } from "/input.js";import { createToolbar } from "/tools.js";import { createAudio } from "/audio.js";import { avatarColor, turnPoints, sortPlayers, timerFraction, podium, inviteUrl, chatLine } from "/ui-helpers.js"; const $ = (id) => document.getElementById(id);const CODE_RE = /^\/r\/([A-Z2-9]{6})$/i;let net = null, rend = null, code = "";const audio = createAudio();let tool = { colorIdx: 0, size: 1 };let strokeId = 1, curStroke = 0;let last = { ph: "", mask: "", tm: -1, choose: "" };let toastT = 0; const saved = localStorage.getItem("sr-name");if (saved) $("name").value = saved;const myName = () => { const v = $("name").value.trim().slice(0, 16) || "Player"; localStorage.setItem("sr-name", v); return v;};const nameOf = (id) => (net && net.view && net.view.ps && net.view.ps[id] ? net.view.ps[id][0] : "Someone"); async function jget(url, opt) { return (await fetch(url, opt)).json(); }async function go(c) { history.replaceState(null, "", "/r/" + c); start(c); }$("quick").onclick = async () => { try { go((await jget("/api/quickplay")).code); } catch { $("err").textContent = "Server unreachable"; } };$("create").onclick = async () => { try { go((await jget("/api/rooms", { method: "POST" })).code); } catch { $("err").textContent = "Server unreachable"; } }; async function loadLanding() { try { const h = await jget("/health"); $("live").textContent = (h.players ? `${h.players} playing in ${h.rooms} rooms` : "Be the first to play"); } catch { $("live").textContent = "offline"; } try { const lb = await jget("/api/leaderboard?mode=classic"); const ol = $("board-list"); ol.textContent = ""; if (!lb.entries.length) { const li = document.createElement("li"); li.className = "dim"; li.textContent = lb.available ? "Be the first on the board" : "Leaderboard is taking a nap"; ol.appendChild(li); } for (const e of lb.entries) { const li = document.createElement("li"); li.textContent = `${e.name} — ${e.score}`; ol.appendChild(li); } } catch { /* ignore */ }} function addChat(text, cls, line) { const li = document.createElement("li"); if (line && line.name) { const n = document.createElement("b"); n.textContent = line.name + ": "; n.style.color = avatarColor(line.name); li.appendChild(n); li.appendChild(document.createTextNode((line.locked ? "\uD83D\uDD12 " : "") + line.body)); if (line.locked) cls = "lockedmsg"; } else li.textContent = text; if (cls) li.className = cls; const chat = $("chat"); chat.appendChild(li); while (chat.children.length > 100) chat.removeChild(chat.firstChild); chat.scrollTop = chat.scrollHeight;} function toast(text) { const t = $("toast"); t.textContent = text; t.hidden = false; clearTimeout(toastT); toastT = setTimeout(() => { t.hidden = true; }, 1500);} function renderScores(s) { const list = $("scores"); list.textContent = ""; const done = Array.isArray(s.dn) ? s.dn : []; for (const p of sortPlayers(s.ps)) { const li = document.createElement("li"); const guessed = done.includes(p.id); let h = 0; for (const ch of p.name) h = (h * 31 + ch.charCodeAt(0)) % 360; const av = document.createElement("i"); av.className = "av"; av.style.background = `hsl(${h} 70% 62%)`; av.textContent = (p.name[0] || "?").toUpperCase(); const nm = document.createElement("span"); nm.textContent = `${p.name}${p.id === net.me ? " (you)" : ""}`; const sc = document.createElement("b"); sc.textContent = `${p.score}${p.id === s.dr ? " ✏️" : ""}${guessed ? " ✓" : ""}`; li.append(av, nm, sc); if (p.id === s.dr) li.className = "drawer"; if (guessed) li.classList.add("done"); list.appendChild(li); }} function renderMask(text) { const el = $("mask"); const old = el.textContent.replace(/\u00a0| /g, ""); el.textContent = ""; let i = 0; for (const ch of text.replace(/ /g, "\u00a0")) { const sp = document.createElement("span"); sp.className = "ltr"; sp.textContent = ch; if (old && old[i] === "_" && ch !== "_" && ch !== "\u00a0") sp.classList.add("pop"); if (ch !== "\u00a0") i++; el.appendChild(sp); }} function showChoices(s) { const key = s.ch.join("|"); if (key === last.choose) return; last.choose = key; const box = $("choices"); box.textContent = ""; s.ch.forEach((w, i) => { const b = document.createElement("button"); b.textContent = w; b.onclick = () => { net.choose(i); $("modal").hidden = true; }; box.appendChild(b); }); $("modal").hidden = !s.ch.length;} function onState(s) { const isDrawer = net.role === "player" && (s.ph === "waiting" || (s.dr === net.me && s.ph === "drawing")); $("tools").hidden = !isDrawer; $("spec").hidden = net.role !== "spectator"; if (s.ph !== last.ph) { last.ph = s.ph; $("phase").textContent = s.ph === "results" ? "game over" : s.ph === "waiting" ? "" : `Round ${s.rd}/${s.rs || 3}`; $("results").hidden = s.ph !== "results"; if (s.ph !== "results") $("banner").hidden = true; } const np = sortPlayers(s.ps).length; const wt = s.ph === "waiting" ? `Waiting for players · ${np}/3 — share the invite link` : ""; if (wt !== last.wt) { last.wt = wt; $("wait").textContent = wt; $("wait").hidden = !wt; $("mask").hidden = !!wt; } const mask = s.wd && s.dr === net.me ? s.wd : s.mk; if (mask !== last.mask) { last.mask = mask; renderMask(mask || ""); } if (s.tm !== last.tm) { last.tm = s.tm; $("timer").textContent = s.ph === "waiting" ? "" : String(Math.ceil(s.tm)); $("ringfg").style.strokeDashoffset = String(94.2 * (1 - timerFraction(s.tm, s.tt))); if (s.ph === "drawing" && s.tm <= 10 && s.tm > 0) audio.play("tick"); if (s.ph === "results") $("next").textContent = `New game in ${Math.ceil(s.tm)}s`; } if (s.ph === "choosing" && s.dr === net.me) showChoices(s); else { last.choose = ""; $("modal").hidden = true; } renderScores(s);} let turnStart = {}, bannerT = 0;function onEvent(ev) { const k = ev[1]; const line = chatLine(ev, nameOf); if (line && k !== "close" && k !== "reveal") addChat(line.text, line.cls, line); if (k === "close") { toast("So close!"); audio.play("close"); } else if (k === "correct" && false) {} else if (k === "correct") { audio.play("correct"); rend.fx("correct"); } else if (k === "chat") audio.play("pop"); else if (k === "turn") { audio.play("turn"); turnStart = JSON.parse(JSON.stringify((net.view && net.view.ps) || {})); } else if (k === "reveal") { audio.play("reveal"); rend.fx("reveal"); const b = $("banner"); b.textContent = ""; b.className = "reveal"; const h = document.createElement("div"); h.textContent = `The word was ${ev[2]}`; b.appendChild(h); for (const t of turnPoints(turnStart, net.view && net.view.ps)) { const r = document.createElement("div"); r.textContent = `${t.name} +${t.pts}`; b.appendChild(r); } b.hidden = false; clearTimeout(bannerT); bannerT = setTimeout(() => { b.hidden = true; }, 3000); } else if (k === "results") { audio.play("win"); rend.fx("confetti"); const pod = $("podium"); pod.textContent = ""; for (const p of podium(ev[2])) { const d = document.createElement("div"); d.className = "p" + p.place; d.textContent = `#${p.place} ${p.name} — ${p.score}`; d.style.animationDelay = (3 - p.place) * 250 + "ms"; pod.appendChild(d); } }} function start(c, watch) { code = c; $("landing").hidden = true; $("game").hidden = false; $("joinsheet").hidden = !watch; if (watch) $("game").classList.add("blurred"); const canvas = $("board"); net = new Net(c, myName(), { status: (ok) => { $("badge").hidden = ok; }, welcome: () => {}, state: onState, event: onEvent, board: () => {}, }, watch ? { watch: true } : undefined); rend = createRenderer(canvas, net); createToolbar($("tools"), (t) => { if (t.action === "undo") net.undo(); else if (t.action === "clear") net.clear(); else tool = t; }); const canDraw = () => !!net.view && net.role === "player" && (net.view.ph === "waiting" || (net.view.dr === net.me && net.view.ph === "drawing")); bindInput(canvas, { enabled: canDraw, onStrokeStart: () => { curStroke = strokeId++; }, onBatch: (id, pts) => net.stroke(id || curStroke, tool.eraser ? 7 : (tool.colorIdx || 0), tool.size ?? 1, pts), onStrokeEnd: () => {}, onMove: (x, y, on) => { const er = !!tool.eraser; rend.setCursor(x, y, on, er ? 18 : WIDTHS[tool.size ?? 1] || 9, PALETTE[tool.colorIdx || 0], er); }, }); canvas.addEventListener("pointerleave", () => rend.setCursor(0, 0, false, 9, PALETTE[0], false)); canvas.addEventListener("pointerdown", (e) => { if (e.pointerType !== "mouse") rend.setCursor(0, 0, false, 9, PALETTE[0], false); }); $("guessForm").onsubmit = (e) => { e.preventDefault(); const v = $("guess").value.trim(); if (v) net.guess(v); $("guess").value = ""; }; $("invite").onclick = async () => { const url = inviteUrl(location.origin, code); try { await navigator.clipboard.writeText(url); toast("Invite link copied"); } catch { toast(url); } }; document.addEventListener("pointerdown", () => audio.unlock(), { once: true }); net.connect();} const m = CODE_RE.exec(location.pathname);if (m) { const rc = m[1].toUpperCase(); $("jcode").textContent = rc; $("joinsheet").hidden = false; $("jname").value = ($("name").value || localStorage.getItem("sr-name") || ""); $("jgo").onclick = () => { const n = $("jname").value.trim(); $("name").value = n; try { localStorage.setItem("sr-name", n); } catch {} $("joinsheet").hidden = true; $("game").classList.remove("blurred"); if (net) net.join(n); else start(rc, false); }; $("jname").onkeydown = (e) => { if (e.key === "Enter") $("jgo").click(); }; $("jname").focus(); start(rc, true);}loadLanding();