Skip to content

gitflarePublicPartly agent-ready40

sketch-rush

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

Add the Apache-2.0 licencedbe1e99
JavaScript355 lines11.9 KB
import { createRng } from "./rng.js";import { WORDS, pickChoices } from "./words.js"; export const TICK_HZ = 30;export const DT = 1 / 30;export const MAX_PLAYERS = 12;export const MIN_PLAYERS = 3;export const ROUNDS = 3;export const CHOICE_SEC = 10;export const TURN_SEC = 80;export const RESULTS_SEC = 10;export const BOARD_W = 1000;export const BOARD_H = 750;export const MAX_POINTS_MSG = 64;export const MAX_STROKE_POINTS = 20000;export const COLORS = 8;export const SIZES = 3;export const MAX_GUESS = 64; export function sanitizeName(raw) {  if (typeof raw !== "string") return "Player";  const s = raw.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e]/g, "").replace(/\s+/g, " ").trim().slice(0, 16).trim();  return s || "Player";} export function normalizeText(s) {  return String(s).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/\s+/g, " ");} export function editDistance(a, b) {  if (a === b) return 0;  let prev = [];  for (let j = 0; j <= b.length; j++) prev[j] = j;  for (let i = 1; i <= a.length; i++) {    const cur = [i];    for (let j = 1; j <= b.length; j++) {      cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));    }    prev = cur;  }  return prev[b.length];} export function maskWord(word, revealed) {  let out = "";  for (let i = 0; i < word.length; i++) {    if (i) out += " ";    const c = word[i];    out += c === " " || c === "-" ? c : revealed.includes(i) ? c : "_";  }  return out;} export function guessScore(timeLeft, first) {  return Math.max(50, Math.round((500 * timeLeft) / TURN_SEC)) + (first ? 50 : 0);} export function createState(seed, config = {}) {  return {    seed: seed >>> 0,    rng: createRng(seed),    config: { maxPlayers: MAX_PLAYERS, ...config },    tick: 0,    phase: "waiting",    timer: 0,    round: 0,    order: [],    turnIdx: 0,    drawer: "",    choices: [],    word: "",    revealed: [],    mask: "",    strokes: [],    strokeOps: [],    opCount: 0,    strokeSeq: 0,    boardEpoch: 0,    points: 0,    correct: 0,    players: new Map(),    joinedAt: new Map(),    seq: new Map(),  };} function resetBoard(state) {  state.strokes = [];  state.strokeOps = [];  state.opCount = 0;  state.points = 0;  state.strokeSeq++;  state.boardEpoch++;} export function addPlayer(state, id, name) {  if (state.players.has(id)) return state.players.get(id);  const p = { id, name: sanitizeName(name), score: 0, guessed: false, connected: true, turnScore: 0 };  state.players.set(id, p);  if (state.phase !== "waiting" && state.phase !== "results" && state.round <= ROUNDS && !state.order.includes(id)) state.order.push(id);  return p;} export function removePlayer(state, id) {  const wasDrawer = state.drawer === id;  state.players.delete(id);  state.seq.delete(id);  if (wasDrawer && (state.phase === "choosing" || state.phase === "drawing")) state.pendingEvents = endTurn(state, state.pendingEvents || []);} const isInt = (v, lo, hi) => typeof v === "number" && Number.isInteger(v) && v >= lo && v <= hi; /** Validates a raw client action array; returns a normalised action or null. */export function sanitizeInput(raw) {  if (!Array.isArray(raw) || raw.length < 2 || raw.length > 5 + MAX_POINTS_MSG * 2) return null;  const t = raw[0], seq = raw[1];  if (!isInt(seq, 0, 2147483647)) return null;  switch (t) {    case "d": {      const strokeId = raw[2], color = raw[3], size = raw[4];      if (!isInt(strokeId, 0, 1e9) || !isInt(color, 0, COLORS - 1) || !isInt(size, 0, SIZES - 1)) return null;      const n = raw.length - 5;      if (n < 2 || n % 2 || n / 2 > MAX_POINTS_MSG) return null;      const pts = new Array(n);      for (let i = 0; i < n; i++) {        if (!isInt(raw[5 + i], 0, i % 2 ? BOARD_H : BOARD_W)) return null;        pts[i] = raw[5 + i];      }      return { t, seq, strokeId, color, size, pts };    }    case "u":    case "c":      return raw.length === 2 ? { t, seq } : null;    case "g": {      if (raw.length !== 3 || typeof raw[2] !== "string") return null;      const text = raw[2].replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim().slice(0, MAX_GUESS);      return text ? { t, seq, text } : null;    }    case "w":      return raw.length === 3 && isInt(raw[2], 0, 2) ? { t, seq, idx: raw[2] } : null;    default:      return null;  }} function startGame(state, events) {  state.round = 1;  state.order = [...state.players.keys()];  state.turnIdx = -1;  for (const p of state.players.values()) p.score = 0;  nextTurn(state, events);} function nextTurn(state, events = []) {  state.turnIdx++;  while (state.turnIdx < state.order.length && !state.players.has(state.order[state.turnIdx])) state.order.splice(state.turnIdx, 1);  if (state.turnIdx >= state.order.length) {    state.turnIdx = 0;    state.round++;    while (state.turnIdx < state.order.length && !state.players.has(state.order[state.turnIdx])) state.order.splice(state.turnIdx, 1);  }  if (state.round > ROUNDS || state.players.size < MIN_PLAYERS || !state.order.length) return toResults(state, events);  state.drawer = state.order[state.turnIdx];  state.phase = "choosing";  state.timer = CHOICE_SEC;  state.choices = pickChoices(state.rng, 3);  state.word = "";  state.revealed = [];  state.mask = "";  resetBoard(state);  state.correct = 0;  for (const p of state.players.values()) { p.guessed = false; p.turnScore = 0; }  events.push(["v", "turn", state.drawer, state.round], ["v", "phase", "choosing"]);} function toResults(state, events) {  events.push(["v", "results", [...state.players.values()].map((p) => [p.id, p.name, p.score]).sort((a, b) => b[2] - a[2])]);  events.push(["v", "phase", "results"]);  state.phase = "results";  state.timer = RESULTS_SEC;  state.drawer = "";  state.word = "";  state.mask = "";} function beginDrawing(state, idx) {  state.word = state.choices[idx] ?? state.choices[0];  state.phase = "drawing";  state.timer = TURN_SEC;  state.revealed = [];  state.mask = maskWord(state.word, state.revealed);} function endTurn(state, events) {  if (state.phase === "turnend") return events;  if (!state.word) state.word = state.choices[0] || "";  events.push(["v", "reveal", state.word]);  state.phase = "turnend";  state.timer = 3;  state.mask = state.word;  return events;} function reveal(state) {  const idx = [];  for (let i = 0; i < state.word.length; i++) {    const c = state.word[i];    if (c !== " " && c !== "-" && !state.revealed.includes(i)) idx.push(i);  }  if (idx.length > 1) {    state.revealed.push(idx[state.rng.int(idx.length)]);    state.mask = maskWord(state.word, state.revealed);    return true;  }  return false;} function handleGuess(state, id, text, events) {  const p = state.players.get(id);  if (!p || state.phase !== "drawing" || id === state.drawer) return;  if (p.guessed) {    events.push(["v", "chat", id, text, 1]);    return;  }  const g = normalizeText(text), w = normalizeText(state.word);  if (g === w) {    p.guessed = true;    const pts = guessScore(state.timer, state.correct === 0);    state.correct++;    p.score += pts;    p.turnScore = pts;    const d = state.players.get(state.drawer);    if (d) d.score += 50;    events.push(["v", "correct", id, pts]);    let all = true;    for (const q of state.players.values()) if (q.id !== state.drawer && q.connected && !q.guessed) all = false;    if (all) endTurn(state, events);  } else if (editDistance(g, w) === 1) {    events.push(["v", "close", id]);  } else {    events.push(["v", "chat", id, text, 0]);  }} function handleDraw(state, id, a) {  const free = state.phase === "waiting";  if (!free && (id !== state.drawer || state.phase !== "drawing")) return;  if (a.t === "c") {    resetBoard(state);    state.strokeOps.push(["clear"]);    state.opCount = state.strokeOps.length;    return;  }  if (a.t === "u") {    // undo removes the last stroke of the acting player    let i = state.strokes.length - 1;    while (i >= 0 && state.strokes[i].owner !== id) i--;    if (i < 0) return;    const [s] = state.strokes.splice(i, 1);    state.points -= s.pts.length / 2;    state.strokeOps.push(["undo", i]);    state.opCount = state.strokeOps.length;    state.strokeSeq++;    return;  }  if (state.points + a.pts.length / 2 > MAX_STROKE_POINTS) return;  let last = state.strokes[state.strokes.length - 1];  if (last && last.id === a.strokeId && last.owner === id) {    const from = last.pts.length / 2;    for (let i = 0; i < a.pts.length; i++) last.pts.push(a.pts[i]);    state.strokeOps.push(["pts", state.strokes.length - 1, from]);  } else {    state.strokes.push({ id: a.strokeId, owner: id, color: a.color, size: a.size, pts: a.pts.slice() });    state.strokeOps.push(["add", state.strokes.length - 1]);  }  state.opCount = state.strokeOps.length;  state.points += a.pts.length / 2;  state.strokeSeq++;} /** Advances the game one fixed tick. inputsById: Map<id, sanitised action[]>. Returns events. */export function step(state, inputsById, dt = DT) {  const events = state.pendingEvents || [];  state.pendingEvents = null;  state.tick++;  const entries = inputsById instanceof Map ? inputsById : new Map(Object.entries(inputsById || {}));  for (const [id, list] of entries) {    if (!state.players.has(id)) continue;    for (const a of list) {      if (!a) continue;      state.seq.set(id, a.seq);      if (a.t === "g") handleGuess(state, id, a.text, events);      else if (a.t === "w") {        if (state.phase === "choosing" && id === state.drawer) beginDrawing(state, a.idx);      } else handleDraw(state, id, a);    }  }  const n = state.players.size;  if (state.phase === "waiting") {    if (n >= MIN_PLAYERS) { events.push(["v", "start"]); startGame(state, events); }    return events;  }  if (n < MIN_PLAYERS && state.phase !== "results") {    state.phase = "waiting";    state.drawer = "";    state.word = "";    state.mask = "";    resetBoard(state);    return events;  }  const before = state.timer;  state.timer = Math.max(0, state.timer - dt);  if (state.phase === "choosing" && state.timer === 0) { beginDrawing(state, state.rng.int(3)); events.push(["v", "phase", "drawing"]); }  else if (state.phase === "drawing") {    const half = TURN_SEC * 0.5, q = TURN_SEC * 0.25;    if (before > half && state.timer <= half && reveal(state)) events.push(["v", "hint", state.mask]);    if (before > q && state.timer <= q && reveal(state)) events.push(["v", "hint", state.mask]);    if (state.timer === 0) endTurn(state, events);  } else if (state.phase === "turnend" && state.timer === 0) nextTurn(state, events);  else if (state.phase === "results" && state.timer === 0) {    state.phase = "waiting";    resetBoard(state);    events.push(["v", "newgame"]);  }  return events;} export function hashState(state) {  let h = 2166136261;  const s = JSON.stringify([state.tick, state.phase, Math.round(state.timer * 1000), state.round, state.drawer, state.word, state.mask, state.rng.state,    [...state.players.values()].map((p) => [p.id, p.score, p.guessed]), state.strokes, state.opCount, state.boardEpoch]);  for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619) >>> 0;  return h;} /** Per-viewer snapshot; the word is only revealed to the drawer and after the turn. */export function snapshot(state, viewerId) {  const showWord = (viewerId === state.drawer && state.phase === "drawing") || state.phase === "turnend";  const ps = {};  for (const p of state.players.values()) ps[p.id] = [p.name, p.score, p.guessed ? 1 : 0, p.connected ? 1 : 0];  return {    ph: state.phase,    tm: Math.ceil(state.timer),    dr: state.drawer,    mk: state.mask,    rd: state.round,    wd: showWord ? state.word : "",    ch: viewerId === state.drawer && state.phase === "choosing" ? state.choices.slice() : [],    ps,    ep: state.boardEpoch,    rs: ROUNDS,    tt: state.phase === "choosing" ? CHOICE_SEC : state.phase === "drawing" ? TURN_SEC : state.phase === "turnend" ? 3 : state.phase === "results" ? RESULTS_SEC : 0,  };}