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
JavaScript163 lines5.3 KB
import { applySnapshot, applyStrokeMsg, encodeAck, encodeJoin, encodePing, newBoard } from "./shared/protocol.js"; /** WebSocket client: join/reconnect, baseline ring, stroke board with local pending strokes. */export class Net {  constructor(code, name, cb, opts) {    this.watch = !!(opts && opts.watch);    this.code = code;    this.name = name;    this.cb = cb;    this.ws = null;    this.view = null;    this.me = "";    this.role = "";    this.tick = -1;    this.snaps = new Map();    this.seq = 0;    this.attempt = 0;    this.rtt = 0;    this.closed = false;    this.pingTimer = 0;    this.lastAck = 0;    this.ackPending = -1;    this.ackTimer = 0;    this.board = newBoard();    this.pending = new Map(); // strokeId -> local stroke object (also in board.strokes)    this.key = "sr-token-" + code;  }   get state() { return this.view; }   connect() {    const proto = location.protocol === "https:" ? "wss:" : "ws:";    const ws = new WebSocket(`${proto}//${location.host}/ws/${this.code}`);    this.ws = ws;    ws.onopen = () => {      this.attempt = 0;      this.cb.status(true);      ws.send(JSON.stringify(encodeJoin(this.name, sessionStorage.getItem(this.key), this.tick >= 0 ? this.tick : null, this.watch)));      clearInterval(this.pingTimer);      this.pingTimer = setInterval(() => this.raw(encodePing(performance.now())), 2000);    };    ws.onmessage = (ev) => this.onMessage(JSON.parse(ev.data));    ws.onclose = () => {      clearInterval(this.pingTimer);      clearTimeout(this.ackTimer);      if (this.closed) return;      this.cb.status(false);      const delay = Math.min(15000, 250 * 2 ** this.attempt++);      setTimeout(() => this.connect(), delay);    };  }   raw(msg) {    if (this.ws && this.ws.readyState === 1) this.ws.send(JSON.stringify(msg));  }   send(type, ...fields) {    this.raw([type, ++this.seq, ...fields]);  }   /** Send a stroke batch and show it immediately (zero latency); the server echo reconciles. */  stroke(strokeId, color, size, pts) {    let s = this.pending.get(strokeId);    if (!s) {      s = { id: strokeId, owner: this.me, color, size, pts: [], local: true };      this.pending.set(strokeId, s);      this.board.strokes.push(s);    }    for (let i = 0; i < pts.length; i++) s.pts.push(pts[i]);    this.board.version++;    this.cb.board && this.cb.board(this.board);    this.send("d", strokeId, color, size, ...pts);  }   /** Upgrade a watch-only socket to a player with the given name. */  join(name) {    this.name = name || this.name;    this.watch = false;    this.raw(encodeJoin(this.name, sessionStorage.getItem(this.key), null, false));  }   undo() { this.send("u"); }  clear() { this.send("c"); }  guess(text) { this.send("g", text); }  choose(idx) { this.send("w", idx); }   sendAck(tick) {    this.ackPending = tick;    const now = performance.now();    if (now - this.lastAck >= 100) this.flushAck();    else if (!this.ackTimer) this.ackTimer = setTimeout(() => this.flushAck(), 100 - (now - this.lastAck));  }   flushAck() {    this.ackTimer = 0;    if (this.ackPending < 0) return;    this.lastAck = performance.now();    this.raw(encodeAck(this.ackPending));    this.ackPending = -1;  }   onBoard(m) {    this.board.strokes = this.board.strokes.filter((s) => !s.local);    if (!applyStrokeMsg(this.board, m)) { for (const s of this.pending.values()) this.board.strokes.push(s); return; }    if (m[2] === 0) {      // Replay: drop pending strokes the server already has (matched by id and owner).      for (const s of this.board.strokes) if (s.owner === this.me) this.pending.delete(s.id);    }    const have = new Set();    for (const s of this.board.strokes) if (s.owner === this.me) have.add(s.id);    for (const [id, p] of this.pending) {      const srv = this.board.strokes.find((s) => s.id === id && s.owner === this.me);      if (srv && srv.pts.length >= p.pts.length) this.pending.delete(id);      else if (srv) this.board.strokes.splice(this.board.strokes.indexOf(srv), 1); // server copy is a prefix; show local full one    }    for (const s of this.pending.values()) this.board.strokes.push(s);    this.board.version++;    this.cb.board && this.cb.board(this.board);  }   onMessage(m) {    switch (m[0]) {      case "w":        sessionStorage.setItem(this.key, m[2]);        this.me = m[1];        this.role = m[4];        this.tick = m[5];        this.snaps.clear();        this.view = m[6];        this.snaps.set(m[5], m[6]); // welcome state is a valid baseline for the next delta        this.board = newBoard();        this.pending.clear();        this.cb.welcome(m[1], m[4]);        this.cb.state(this.view);        this.sendAck(m[5]);        break;      case "k":        this.onBoard(m);        break;      case "s": {        const base = m[2] < 0 ? null : this.snaps.get(m[2]);        if (m[2] >= 0 && !base) return;        this.view = applySnapshot(base, m[4]);        this.tick = m[1];        this.snaps.set(m[1], this.view);        this.snaps.delete(m[1] - 64);        this.sendAck(m[1]);        this.cb.state(this.view, m[3]);        break;      }      case "o":        this.rtt = performance.now() - m[1];        break;      case "v":        for (let i = 2; i < m.length; i++) this.cb.event(m[i]);        break;      case "e":        this.cb.error && this.cb.error(m[2]);        break;    }  }}