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
JavaScript152 lines6.5 KB
export const FULL_EVERY = 60;export const RING = 64;export const MAX_PAYLOAD = 2048; export const encodeJoin = (name, token, lastTick, watch) => watch ? ["j", name, token ?? null, lastTick ?? null, 1] : ["j", name, token ?? null, lastTick ?? null];export const encodeAck = (tick) => ["a", tick];export const encodePing = (t) => ["p", t];export const encodePong = (t, tick) => ["o", t, tick];export const encodeError = (code, msg) => ["e", code, msg];export const encodeWelcome = (id, token, code, role, tick, full) => ["w", id, token, code, role, tick, full];export const encodeSnapshotMsg = (tick, baseTick, lastSeq, delta) => ["s", tick, baseTick, lastSeq, delta]; const SCALARS = ["ph", "tm", "dr", "mk", "rd", "wd", "ep", "rs", "tt"];const EXTRA = ["ep", "rs", "tt"];const same = (a, b) => JSON.stringify(a) === JSON.stringify(b); /** * Snapshot shape: {ph,tm,dr,mk,rd,wd,ch:[],ps:{id:[name,score,guessed,connected]},sk:[[id,color,size,pts]]}. * Delta: changed scalars, ch, ps (changed players), rm (removed ids) and * sk = [keep, ext, ...strokes]: first `keep` strokes are unchanged; if ext is a * non-null array it holds the points appended to stroke keep-1 (grown in place); * the remaining entries are new/replaced strokes. prev = null gives a full snapshot. */export function encodeSnapshot(prev, next) {  const d = {};  for (const k of SCALARS) if ((!prev || prev[k] !== next[k]) && (next[k] !== undefined || EXTRA.indexOf(k) < 0)) d[k] = next[k];  if (!prev || !same(prev.ch, next.ch)) d.ch = next.ch;  const pc = {};  const rm = [];  let any = false;  for (const id in next.ps) {    if (!prev || !prev.ps[id] || !same(prev.ps[id], next.ps[id])) { pc[id] = next.ps[id]; any = true; }  }  if (prev) for (const id in prev.ps) if (!(id in next.ps)) { rm.push(id); any = true; }  if (any) d.ps = pc;  if (rm.length) d.rm = rm;  const old = (prev && prev.sk) || [];  const nw = next.sk || [];  let keep = 0;  while (keep < old.length && keep < nw.length && same(old[keep], nw[keep])) keep++;  if (keep === old.length && keep === nw.length) return d;  let ext = null;  if (keep < old.length && keep < nw.length) {    const a = old[keep], b = nw[keep];    if (a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && b[3].length > a[3].length && same(a[3], b[3].slice(0, a[3].length))) {      ext = [b[3].slice(a[3].length)];      d.sk = [keep, ext[0], ...nw.slice(keep + 1)];      d.sx = 1;      return d;    }  }  d.sk = [keep, null, ...nw.slice(keep)];  return d;} export function applySnapshot(base, d) {  const out = base    ? { ph: base.ph, tm: base.tm, dr: base.dr, mk: base.mk, rd: base.rd, wd: base.wd, ch: base.ch, ps: { ...base.ps }, sk: base.sk || [] }    : { ph: "waiting", tm: 0, dr: "", mk: "", rd: 0, wd: "", ch: [], ps: {}, sk: [] };  for (const k of EXTRA) if (base && k in base) out[k] = base[k];  for (const k of SCALARS) if (k in d) out[k] = d[k];  if ("ch" in d) out.ch = d.ch;  if (d.ps) for (const id in d.ps) out.ps[id] = d.ps[id];  if (d.rm) for (const id of d.rm) delete out.ps[id];  if (d.sk) {    const keep = d.sk[0];    const head = out.sk.slice(0, keep);    if (d.sx) {      const g = out.sk[keep];      head.push([g[0], g[1], g[2], g[3].concat(d.sk[1])]);      out.sk = head.concat(d.sk.slice(2));    } else {      out.sk = head.concat(d.sk.slice(2));    }  }  return out;} // ---- stroke ops -----------------------------------------------------------// Sim ops: ['add', idx] ['pts', idx, fromPt] ['undo', idx] ['clear'] (idx = position in the// live state.strokes list at that moment). The client list mirrors the server list, so wire// ops use the same indices://   ["a", id, owner, color, size]  push stroke   ["p", idx, ...pts] append points//   ["u", idx]                     remove idx    ["c"]              clear// An epoch change or fromOp 0 resets the client board first. /** Wire ops for sim ops [from, to). Reads pts only from the new range; no log copies. * Point appends read the stroke's current tail, so a stroke that was undone later in the * same tick is skipped (its later undo op removes it anyway). */export function encodeOps(state, from, to) {  const ops = state.strokeOps, strokes = state.strokes, out = [];  const sent = new Map();  let removed = false;  for (let i = from; i < to; i++) if (ops[i][0] === "undo" || ops[i][0] === "clear") { removed = true; break; }  if (removed) return null; // caller falls back to a compact replay  for (let i = from; i < to; i++) {    const o = ops[i];    if (o[0] === "add") {      const s = strokes[o[1]];      out.push(["a", s.id, s.owner, s.color, s.size]);      sent.set(o[1], 0);    } else if (o[0] === "pts") {      const s = strokes[o[1]];      const start = sent.has(o[1]) ? sent.get(o[1]) : o[2];      if (start >= s.pts.length) continue;      out.push(["p", o[1], ...s.pts.slice(start)]);      sent.set(o[1], s.pts.length);    }  }  return out;} export function encodeStrokeMsg(epoch, fromOp, wireOps) { return ["k", epoch, fromOp, ...wireOps]; } /** Exact wire ops for a range that may contain undo/clear, applied in order. */export function encodeOpsExact(state, from, to) {  // Undo/clear ticks are rare; send a compact replay marker: the full board at `to`.  return encodeReplay(state, to);} /** Full board as a compact replay (undo/clear compacted away); opCount marks position. */export function encodeReplay(state, opCount) {  const wire = [];  state.strokes.forEach((s, i) => {    wire.push(["a", s.id, s.owner, s.color, s.size]);    if (s.pts.length) wire.push(["p", i, ...s.pts]);  });  return ["k", state.boardEpoch, 0, ...wire, opCount ?? state.opCount];} export function newBoard() { return { epoch: 0, strokes: [], version: 0, opCount: 0 }; } /** * Apply ["k", epoch, fromOp, ...ops]. A replay (fromOp 0) ends with a bare number = opCount * after replay. Incremental messages advance opCount by their op count (tracked via the * trailing number too, so both forms carry it): last element is always the new opCount. */export function applyStrokeMsg(board, m) {  const epoch = m[1], from = m[2];  const end = m[m.length - 1];  if (epoch !== board.epoch || from === 0) { board.epoch = epoch; board.strokes = []; }  else if (from !== board.opCount) return false; // gap: ignore until next replay  for (let i = 3; i < m.length - 1; i++) {    const o = m[i];    if (o[0] === "a") board.strokes.push({ id: o[1], owner: o[2], color: o[3], size: o[4], pts: [] });    else if (o[0] === "p") { const s = board.strokes[o[1]]; if (s) for (let j = 2; j < o.length; j++) s.pts.push(o[j]); }  }  board.opCount = end;  board.version++;  return true;}