TExcelTAD
Home › Multiplayer Game Networking › Mini Project: Authoritative Arena

Mini Project: Authoritative Arena

Time to put the whole course into one small game: a top-down arena for 2–4 players. Players move, shoot projectiles, lose health, get eliminated and respawn. One player's Wi-Fi drops and comes back; another leaves for good. The server is authoritative, clients predict and reconcile their own movement and interpolate everything else, and the network is as bad as you choose to make it.

It is small on purpose, the scale the roadmap recommends for a first networked game, yet it exercises every technique you need for a bigger one. We build it in two steps:

  1. the server rules as a deterministic TypeScript model, tested without any network or graphics;
  2. the playable arena: the same rules inside the lag simulator, with you, up to three bots, sliders for latency, jitter and loss, and a button that unplugs your cable.
Feature Lessons
Fixed tick, inputs with sequence numbers, redundant inputs Tick Rate & Clock Sync, The Authoritative Server
Server validation: clamped input, fire cooldown, dead players can't act Never Trust the Client
Snapshots at 20 Hz, newest wins State Sync & Snapshots
Prediction + reconciliation for your own player Client-Side Prediction, Server Reconciliation
Interpolation for other players and projectiles Snapshot Interpolation
Join handshake with a token, timeouts, grace period, reconnect Connections, Timeouts & Reconnects
Keyboard input and the fixed-step loop the play kit from 2D Games with JavaScript & Canvas

Step 1: the server rules, without a network

The server's job fits in one class: join creates a player and returns a secret token, receive handles one packet (the token plus the client's last three inputs), and step advances the world by one 30 Hz tick: cooldowns, respawns, timeouts, projectiles and hits. There is no clock and no randomness, so a scripted match prints exactly the same events every time. That makes it a test: change a rule, run it, and compare.

In the script, ana and ben duel, ben's client "cheats" by asking to fire on every tick, ben's Wi-Fi drops for 6 seconds, an attacker guesses ben's token, and cy joins late and then closes the game:

ts · try it yourself
// Arena server rules: pure logic, fixed 30 Hz tick, no clock, no randomness.
const W = 160, H = 100, R = 4, SPEED = 40, DT = 1 / 30;
const SHOT_SPEED = 120, SHOT_LIFE = 30, COOLDOWN = 12, DAMAGE = 25, RESPAWN = 60;
const TIMEOUT = 90, GRACE = 300;                         // ticks: 3 s silence = dropped, 10 s to come back
const SPAWNS = [{ x: 20, y: 50 }, { x: 140, y: 50 }, { x: 80, y: 15 }, { x: 80, y: 85 }];

type Input = { seq: number; dx: number; dy: number; fire: boolean };
type Player = {
  name: string; token: string; x: number; y: number; fx: number; fy: number; hp: number; score: number;
  cooldown: number; respawnIn: number; lastSeq: number; lastHeard: number; online: boolean; droppedAt: number;
  rejected: number;
};
type Shot = { id: number; owner: string; x: number; y: number; vx: number; vy: number; life: number };

class ArenaServer {
  tick = 0;
  players = new Map<string, Player>();
  shots: Shot[] = [];
  private nextShot = 0;
  private log(msg: string) { console.log(`[tick ${String(this.tick).padStart(3)}] ${msg}`); }

  join(name: string): string | null {
    if (this.players.size >= 4) { this.log(`${name} refused: arena full`); return null; }
    const spawn = SPAWNS[this.players.size];
    const token = `${name}-${this.tick}-secret`;            // a real server uses crypto-random bytes
    this.players.set(name, { name, token, ...spawn, fx: spawn.x < 80 ? 1 : -1, fy: 0, hp: 100, score: 0, cooldown: 0,
      respawnIn: 0, lastSeq: -1, lastHeard: this.tick, online: true, droppedAt: -1, rejected: 0 });
    this.log(`${name} joined at (${spawn.x}, ${spawn.y})`);
    return token;
  }

  /** One packet from a client: its token and its last few inputs (redundant copies). */
  receive(name: string, token: string, inputs: Input[]) {
    const p = this.players.get(name);
    if (!p || p.token !== token) { this.log(`packet from ${name} rejected: bad token`); return; }
    if (!p.online) { p.online = true; this.log(`${name} RECONNECTED after ${this.tick - p.droppedAt} ticks, hp ${p.hp}, score ${p.score} kept`); }
    p.lastHeard = this.tick;
    for (const inp of inputs) {
      if (inp.seq <= p.lastSeq) continue;                    // already applied (redundant copy)
      p.lastSeq = inp.seq;
      if (p.respawnIn > 0) continue;                          // dead players can't act
      const dx = Math.sign(inp.dx), dy = Math.sign(inp.dy);   // never trust the client: clamp to -1..1
      const len = Math.hypot(dx, dy) || 1;
      p.x = Math.max(R, Math.min(W - R, p.x + (dx / len) * SPEED * DT));
      p.y = Math.max(R, Math.min(H - R, p.y + (dy / len) * SPEED * DT));
      if (dx || dy) { p.fx = dx / len; p.fy = dy / len; }
      if (inp.fire) {
        if (p.cooldown > 0) { p.rejected++; continue; }     // fire-rate check on the server
        p.cooldown = COOLDOWN;
        this.shots.push({ id: this.nextShot++, owner: p.name, x: p.x + p.fx * (R + 1), y: p.y + p.fy * (R + 1),
          vx: p.fx * SHOT_SPEED, vy: p.fy * SHOT_SPEED, life: SHOT_LIFE });
      }
    }
  }

  step() {
    this.tick++;
    for (const p of this.players.values()) {
      if (p.cooldown > 0) p.cooldown--;
      if (p.respawnIn > 0 && --p.respawnIn === 0) {
        const s = SPAWNS[[...this.players.keys()].indexOf(p.name)];
        Object.assign(p, { x: s.x, y: s.y, hp: 100 });
        this.log(`${p.name} respawned`);
      }
      if (p.online && this.tick - p.lastHeard >= TIMEOUT) {
        p.online = false; p.droppedAt = this.tick;
        this.log(`${p.name} timed out: keeping the slot for ${GRACE / 30} s`);
      } else if (!p.online && this.tick - p.droppedAt >= GRACE) {
        this.players.delete(p.name);
        this.log(`${p.name} did not come back: slot freed`);
      }
    }
    for (const s of this.shots) {
      s.x += s.vx * DT; s.y += s.vy * DT; s.life--;
      for (const p of this.players.values()) {
        if (p.name === s.owner || p.respawnIn > 0 || s.life <= 0) continue;
        if (Math.hypot(p.x - s.x, p.y - s.y) <= R + 1) {
          s.life = 0;
          p.hp -= DAMAGE;
          const shooter = this.players.get(s.owner);
          if (p.hp <= 0) {
            p.respawnIn = RESPAWN;
            if (shooter) shooter.score++;
            this.log(`${s.owner} eliminated ${p.name} (score ${shooter?.score ?? '?'})`);
          } else this.log(`${s.owner} hit ${p.name}: hp ${p.hp}`);
        }
      }
    }
    this.shots = this.shots.filter((s) => s.life > 0 && s.x > 0 && s.x < W && s.y > 0 && s.y < H);
  }
}

// ---- a scripted match: ana and ben duel, ben spams fire, ben's Wi-Fi drops, cy joins late and quits ----
const server = new ArenaServer();
const tokens: Record<string, string> = {};
const seqs: Record<string, number> = {};
const sent: Record<string, Input[]> = {};
function play(name: string, dx: number, dy: number, fire: boolean) {
  const inp = { seq: seqs[name] = (seqs[name] ?? -1) + 1, dx, dy, fire };
  sent[name] = [...(sent[name] ?? []), inp].slice(-3);
  server.receive(name, tokens[name], sent[name]);
}
tokens.ana = server.join('ana')!;
tokens.ben = server.join('ben')!;
for (let t = 0; t < 660; t++) {
  if (t === 20) tokens.cy = server.join('cy')!;
  play('ana', 0, 0, t % 15 === 0 && t < 200);               // ana fires right every half second
  if (t < 150 || t >= 330) play('ben', 0, t >= 330 && t < 345 ? -1 : 0, true);   // fires EVERY tick; Wi-Fi gone 150..329
  if (t === 400) server.receive('ben', 'ben-0-guessed', []); // an attacker guessing a token
  if (tokens.cy && t < 250) play('cy', t % 60 < 30 ? 1 : -1, 0, false);        // cy closes the game at 250
  server.step();
}
console.log('--- scoreboard ---');
for (const p of server.players.values()) {
  console.log(`${p.name.padEnd(4)} score ${p.score}  hp ${String(p.hp).padStart(3)}  ${p.online ? 'online' : 'offline'}  rejected fire inputs: ${p.rejected}`);
}
[tick   0] ana joined at (20, 50)
[tick   0] ben joined at (140, 50)
[tick  20] cy joined at (80, 15)
[tick  28] ana hit ben: hp 75
[tick  28] ben hit ana: hp 75
[tick  40] ben hit ana: hp 50
[tick  43] ana hit ben: hp 50
[tick  52] ben hit ana: hp 25
[tick  58] ana hit ben: hp 25
[tick  64] ben eliminated ana (score 1)
[tick  73] ana eliminated ben (score 1)
[tick 124] ana respawned
[tick 133] ben respawned
[tick 161] ben hit ana: hp 75
[tick 163] ana hit ben: hp 75
[tick 173] ben hit ana: hp 50
[tick 178] ana hit ben: hp 50
[tick 193] ana hit ben: hp 25
[tick 208] ana eliminated ben (score 2)
[tick 239] ben timed out: keeping the slot for 10 s
[tick 268] ben respawned
[tick 330] ben RECONNECTED after 91 ticks, hp 100, score 1 kept
[tick 339] cy timed out: keeping the slot for 10 s
[tick 400] packet from ben rejected: bad token
[tick 639] cy did not come back: slot freed
--- scoreboard ---
ana  score 2  hp  50  online  rejected fire inputs: 0
ben  score 1  hp 100  online  rejected fire inputs: 383

Read the log from the top:

  • The duel: hits land every 12–15 ticks, the cooldown (COOLDOWN = 12 ticks, 0.4 s) caps the fire rate, and eliminations award a point and start a 2-second respawn timer.
  • Ben's client asked to fire on every tick; the server applied one shot per cooldown and counted the rest as rejected inputs. In a real game that counter feeds the cheat-detection and rate-limit logic.
  • Ben goes silent at tick 150; 3 seconds later (TIMEOUT) he is marked offline but keeps his slot, and when his packets come back at tick 330 he reconnects with his score intact. He even respawned while offline: the world doesn't wait for him.
  • The packet with a guessed token is rejected. Cy's slot is freed 10 seconds (GRACE) after cy went silent.

Step 2: the playable arena

The page below runs the same rules (at 60 Hz, with the tick counts doubled) inside the simulator from the Real-Time Techniques section. On the left is your screen: your own circle is predicted and reconciled, everything else is interpolated 100 ms in the past. On the right is the server's truth, with the scoreboard and the kill feed it sends.

Click the left panel, move with arrows/WASD and fire with Space (you shoot in the direction you last moved). Then experiment:

  1. 150 ms, 2% loss (the default): movement feels instant; your shots appear a moment after you fire, because projectiles are spawned by the server and reach you through snapshots.
  2. Tick "unplug my cable" for a few seconds: your screen freezes with "connection problem", and the server panel shows you as reconnecting…. Untick it within 10 seconds and you're back with your score. Wait longer and the server frees your slot; your client is told to rejoin and comes back as a new player.
  3. Bots slider to 3: a fourth player joins. Back to 1: the extra bots stop sending, time out after 3 seconds and leave after 10.
  4. RTT 400, jitter 80: your movement is still instant, but you'll notice how far in the past the bots are: aim at where a bot was, and the server (which has no lag compensation here) disagrees.
html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; color: #cfd8dc; font: 12px system-ui, sans-serif; overflow: hidden; }
  #ui { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: center; align-content: center; padding: 4px 8px; height: 46px; box-sizing: border-box; }
  #ui label { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
  #ui input[type=range] { width: 60px; }
  #ui b { color: #fff; font-weight: 600; min-width: 3em; display: inline-block; }
  canvas { display: block; margin: 0 auto; height: min(calc(100vh - 50px), calc(100vw * 250 / 600)); aspect-ratio: 600 / 250; outline: none; }
</style>
<div id="ui"></div>
<canvas width="600" height="250"></canvas>
<script>
// ---- play kit (from canvas-games), adapted: the simulation keeps running without focus ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();
let active = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (!active) return;
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault();
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function run(update, draw) {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    acc += dt;
    while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
    draw();
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

function mulberry32(seed) {
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const rnd = mulberry32(7);

// ---- settings and UI ----
const cfg = { rtt: 150, jitter: 20, loss: 2, bots: 2, unplugged: false };
const ui = document.getElementById('ui');
function slider(key, label, min, max, unit) {
  const l = document.createElement('label');
  l.innerHTML = `${label} <input type="range" min="${min}" max="${max}" value="${cfg[key]}"> <b>${cfg[key]}${unit}</b>`;
  const [input, out] = [l.querySelector('input'), l.querySelector('b')];
  input.addEventListener('input', () => { cfg[key] = +input.value; out.textContent = input.value + unit; });
  ui.appendChild(l);
}
slider('rtt', 'RTT', 0, 500, ' ms');
slider('jitter', '±', 0, 100, ' ms');
slider('loss', 'loss', 0, 20, '%');
slider('bots', 'bots', 1, 3, '');
const plug = document.createElement('label');
plug.innerHTML = '<input type="checkbox"> unplug my cable';
plug.querySelector('input').addEventListener('change', (e) => { cfg.unplugged = e.target.checked; });
ui.appendChild(plug);

// ---- shared rules (the same numbers as the TypeScript model) ----
const AW = 160, AH = 100, R = 4, SPEED = 40, DT = 1 / 60;
const SHOT_SPEED = 120, SHOT_LIFE = 60, COOLDOWN = 24, DAMAGE = 25, RESPAWN = 120;
const TIMEOUT = 180, GRACE = 600;                 // ticks at 60 Hz: 3 s and 10 s
const SPAWNS = [{ x: 20, y: 50 }, { x: 140, y: 50 }, { x: 80, y: 15 }, { x: 80, y: 85 }];
function move(p, inp) {
  const dx = Math.sign(inp.dx), dy = Math.sign(inp.dy), len = Math.hypot(dx, dy) || 1;
  p.x = Math.max(R, Math.min(AW - R, p.x + (dx / len) * SPEED * DT));
  p.y = Math.max(R, Math.min(AH - R, p.y + (dy / len) * SPEED * DT));
  if (dx || dy) { p.fx = dx / len; p.fy = dy / len; }
}

// ---- network ----
let now = 0;
class Pipe {
  constructor(owner) { this.owner = owner; this.q = []; }
  send(msg) {
    if (this.owner === 0 && cfg.unplugged) return;
    if (rnd() * 100 < cfg.loss) return;
    this.q.push({ at: now + Math.max(0, cfg.rtt / 2 + (rnd() * 2 - 1) * cfg.jitter), msg });
  }
  receive() {
    const due = this.q.filter((p) => p.at <= now).sort((a, b) => a.at - b.at);
    this.q = this.q.filter((p) => p.at > now);
    return due.map((p) => p.msg);
  }
}
const up = [0, 1, 2, 3].map((i) => new Pipe(i)), down = [0, 1, 2, 3].map((i) => new Pipe(i));

// ---- authoritative server ----
const NAMES = ['you', 'bot A', 'bot B', 'bot C'];
const server = {
  tick: 0, players: new Map(), shots: [], nextShot: 0, feed: [],
  say(msg) { this.feed.unshift(msg); this.feed.length = Math.min(this.feed.length, 4); },
  join(id) {
    const s = SPAWNS[id];
    const token = 'tok' + Math.floor(rnd() * 1e9);
    this.players.set(id, { id, token, x: s.x, y: s.y, fx: id === 1 ? -1 : 1, fy: 0, hp: 100, score: 0, cooldown: 0,
      respawnIn: 0, lastSeq: -1, lastHeard: this.tick, online: true, droppedAt: 0 });
    this.say(`${NAMES[id]} joined`);
    return token;
  },
  step() {
    this.tick++;
    for (let c = 0; c < 4; c++) {
      for (const msg of up[c].receive()) {
        let p = this.players.get(c);
        if (msg.hello && !msg.token) {           // a new player (or a lost welcome): create a fresh slot
          const token = this.join(c);
          p = this.players.get(c);
          down[c].send({ welcome: true, token, x: p.x, y: p.y, fx: p.fx, fy: p.fy });
          continue;
        }
        if (!p || p.token !== msg.token) { down[c].send({ rejoin: true }); continue; }   // unknown or expired token
        if (!p.online) { p.online = true; this.say(`${NAMES[c]} reconnected`); }
        p.lastHeard = this.tick;
        for (const inp of msg.inputs) {
          if (inp.seq <= p.lastSeq) continue;
          p.lastSeq = inp.seq;
          if (p.respawnIn > 0) continue;
          move(p, inp);
          if (inp.fire && p.cooldown === 0) {
            p.cooldown = COOLDOWN;
            this.shots.push({ id: this.nextShot++, owner: c, x: p.x + p.fx * (R + 1), y: p.y + p.fy * (R + 1), vx: p.fx * SHOT_SPEED, vy: p.fy * SHOT_SPEED, life: SHOT_LIFE });
          }
        }
      }
    }
    for (const p of this.players.values()) {
      if (p.cooldown > 0) p.cooldown--;
      if (p.respawnIn > 0 && --p.respawnIn === 0) Object.assign(p, SPAWNS[p.id], { hp: 100 });
      if (p.online && this.tick - p.lastHeard >= TIMEOUT) { p.online = false; p.droppedAt = this.tick; this.say(`${NAMES[p.id]} lost connection`); }
      else if (!p.online && this.tick - p.droppedAt >= GRACE) { this.players.delete(p.id); this.say(`${NAMES[p.id]} left (slot freed)`); }
    }
    for (const s of this.shots) {
      s.x += s.vx * DT; s.y += s.vy * DT; s.life--;
      for (const p of this.players.values()) {
        if (p.id === s.owner || p.respawnIn > 0 || s.life <= 0) continue;
        if (Math.hypot(p.x - s.x, p.y - s.y) <= R + 1) {
          s.life = 0; p.hp -= DAMAGE;
          if (p.hp <= 0) {
            p.respawnIn = RESPAWN;
            const k = this.players.get(s.owner);
            if (k) k.score++;
            this.say(`${NAMES[s.owner]} eliminated ${NAMES[p.id]}`);
          }
        }
      }
    }
    this.shots = this.shots.filter((s) => s.life > 0 && s.x > 0 && s.x < AW && s.y > 0 && s.y < AH);
    if (this.tick % 3 === 0) {                     // 20 Hz snapshots
      const players = [...this.players.values()].map((p) => ({ id: p.id, x: p.x, y: p.y, hp: p.hp, score: p.score, dead: p.respawnIn > 0, online: p.online }));
      const shots = this.shots.map((s) => ({ id: s.id, x: s.x, y: s.y }));
      for (const p of this.players.values()) down[p.id].send({ t: now, ack: p.lastSeq, players, shots, feed: [...this.feed] });
    }
  },
};

// ---- clients: prediction + reconciliation for yourself, interpolation for everything else ----
const INTERP = 100;
class Client {
  constructor(id) { this.id = id; this.reset(); }
  reset() { this.lastRecv = now; this.token = null; this.seq = 0; this.pending = []; this.snaps = []; this.latest = null; this.delay = null; this.self = null; this.lastHello = -1e9; }
  step(inp) {
    for (const m of down[this.id].receive()) {
      this.lastRecv = now;
      if (m.welcome) { if (!this.token) { this.token = m.token; this.self = { x: m.x, y: m.y, fx: m.fx, fy: m.fy }; } }
      else if (m.rejoin) this.reset();             // our slot is gone: join again as a new player
      else if (this.token) this.onSnapshot(m);
    }
    if (!this.token) {                             // not in the match: say hello every 0.5 s
      if (now - this.lastHello > 500) { this.lastHello = now; up[this.id].send({ hello: true }); }
      return;
    }
    const me = this.latest?.players.find((p) => p.id === this.id);
    const full = { seq: this.seq++, ...inp };
    this.pending.push(full);
    if (this.pending.length > 120) this.pending.shift();
    if (!me?.dead) move(this.self, full);          // predict our own movement
    up[this.id].send({ token: this.token, inputs: this.pending.slice(-3) });
  }
  onSnapshot(s) {
    this.snaps.push(s); this.snaps.sort((a, b) => a.t - b.t);
    if (this.snaps.length > 20) this.snaps.shift();
    if (this.latest && s.t <= this.latest.t) return;
    this.latest = s;
    const d = now - s.t;
    this.delay = this.delay === null ? d : this.delay + (d - this.delay) * 0.05;
    const me = s.players.find((p) => p.id === this.id);
    if (!me) return;
    this.pending = this.pending.filter((i) => i.seq > s.ack);
    const auth = { x: me.x, y: me.y, fx: this.self?.fx ?? 1, fy: this.self?.fy ?? 0 };
    if (!me.dead) for (const i of this.pending) move(auth, i);   // reconcile
    this.self = auth;
  }
  view() {                                        // interpolated world at now - delay - INTERP
    const s = this.snaps;
    if (!s.length) return null;
    const t = now - this.delay - INTERP;
    let a = s[0], b = s[0];
    for (let i = 1; i < s.length; i++) if (s[i - 1].t <= t && t <= s[i].t) { a = s[i - 1]; b = s[i]; }
    if (t > s[s.length - 1].t) a = b = s[s.length - 1];
    const k = b.t > a.t ? (t - a.t) / (b.t - a.t) : 1;
    const lerp = (list, id, field) => { const o = list.find((e) => e.id === id); return o ? o[field] : null; };
    const players = b.players.map((p) => {
      const ax = lerp(a.players, p.id, 'x'), ay = lerp(a.players, p.id, 'y');
      return ax === null ? p : { ...p, x: ax + (p.x - ax) * k, y: ay + (p.y - ay) * k };
    });
    const shots = b.shots.map((sh) => {
      const ax = lerp(a.shots, sh.id, 'x'), ay = lerp(a.shots, sh.id, 'y');
      return ax === null ? sh : { ...sh, x: ax + (sh.x - ax) * k, y: ay + (sh.y - ay) * k };
    });
    return { players, shots };
  }
}
const clients = [0, 1, 2, 3].map((i) => new Client(i));

// ---- bots: wander, face the nearest player they know about, fire when roughly lined up ----
function botInput(c) {
  const v = c.view(), me = c.self;
  if (!v || !me) return { dx: 0, dy: 0, fire: false };
  const others = v.players.filter((p) => p.id !== c.id && !p.dead);
  const phase = Math.floor((now / 900) + c.id * 1.7) % 4;
  let dx = [1, 0, -1, 0][phase], dy = [0, 1, 0, -1][phase];
  let fire = false;
  if (others.length) {
    const t = others.reduce((a, b) => (Math.hypot(a.x - me.x, a.y - me.y) < Math.hypot(b.x - me.x, b.y - me.y) ? a : b));
    if (Math.abs(t.y - me.y) < 4) { dx = Math.sign(t.x - me.x); dy = 0; fire = rnd() < 0.08; }
    else if (Math.abs(t.x - me.x) < 4) { dx = 0; dy = Math.sign(t.y - me.y); fire = rnd() < 0.08; }
  }
  return { dx, dy, fire };
}

function update() {
  now += 1000 / 60;
  const dx = (keys.has('ArrowRight') || keys.has('KeyD') ? 1 : 0) - (keys.has('ArrowLeft') || keys.has('KeyA') ? 1 : 0);
  const dy = (keys.has('ArrowDown') || keys.has('KeyS') ? 1 : 0) - (keys.has('ArrowUp') || keys.has('KeyW') ? 1 : 0);
  clients[0].step({ dx, dy, fire: keys.has('Space') });
  for (let b = 1; b <= 3; b++) {
    if (b <= cfg.bots) clients[b].step(botInput(clients[b]));
    else if (clients[b].token) clients[b].reset();  // a removed bot just stops sending: the server times it out
  }
  server.step();
}

// ---- drawing: your screen (left) and the server's truth (right) ----
const COLORS = ['#ff9e40', '#4dd0e1', '#ba68c8', '#9ccc65'];
function arena(ox, oy, s, players, shots, selfId, self) {
  ctx.fillStyle = '#16213e'; ctx.fillRect(ox, oy, AW * s, AH * s);
  ctx.strokeStyle = '#22305a';
  for (let g = 0; g <= AW; g += 20) { ctx.beginPath(); ctx.moveTo(ox + g * s, oy); ctx.lineTo(ox + g * s, oy + AH * s); ctx.stroke(); }
  for (let g = 0; g <= AH; g += 20) { ctx.beginPath(); ctx.moveTo(ox, oy + g * s); ctx.lineTo(ox + AW * s, oy + g * s); ctx.stroke(); }
  ctx.fillStyle = '#fff59d';
  for (const sh of shots) { ctx.beginPath(); ctx.arc(ox + sh.x * s, oy + sh.y * s, 1.2 * s, 0, 7); ctx.fill(); }
  for (const p of players) {
    const pos = p.id === selfId && self ? self : p;
    ctx.globalAlpha = p.dead ? 0.25 : p.online === false ? 0.45 : 1;
    ctx.fillStyle = COLORS[p.id];
    ctx.beginPath(); ctx.arc(ox + pos.x * s, oy + pos.y * s, R * s, 0, 7); ctx.fill();
    ctx.fillStyle = '#300'; ctx.fillRect(ox + (pos.x - R) * s, oy + (pos.y - R - 2.5) * s, 2 * R * s, 1.2 * s);
    ctx.fillStyle = '#e53935'; ctx.fillRect(ox + (pos.x - R) * s, oy + (pos.y - R - 2.5) * s, 2 * R * s * Math.max(0, p.hp) / 100, 1.2 * s);
    if (p.online === false) { ctx.fillStyle = '#fff'; ctx.font = '9px system-ui'; ctx.textAlign = 'center'; ctx.fillText('reconnecting…', ox + pos.x * s, oy + (pos.y + R + 5) * s); }
    ctx.globalAlpha = 1;
  }
}
function draw() {
  ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
  ctx.textAlign = 'left'; ctx.fillStyle = '#fff'; ctx.font = 'bold 12px system-ui, sans-serif';
  ctx.fillText('Your screen', 4, 13);
  ctx.fillText('Server (truth)', 404, 13);
  const c = clients[0], v = c.view();
  if (v) arena(4, 20, 2.4, v.players, v.shots, 0, c.self);
  else { ctx.fillStyle = '#16213e'; ctx.fillRect(4, 20, AW * 2.4, AH * 2.4); }
  arena(404, 20, 1.2, [...server.players.values()].map((p) => ({ ...p, dead: p.respawnIn > 0 })), server.shots, -1, null);
  ctx.font = '10px ui-monospace, monospace'; ctx.fillStyle = '#cfd8dc'; ctx.textAlign = 'left';
  const scores = (c.latest?.players ?? []).map((p) => `${NAMES[p.id].padEnd(6)} ${String(p.score).padStart(2)}  hp ${String(p.hp).padStart(3)}`);
  scores.forEach((t, i) => ctx.fillText(t, 404, 152 + i * 12));
  ctx.fillStyle = '#9aa3b5';
  (c.latest?.feed ?? []).forEach((t, i) => ctx.fillText(t, 404, 208 + i * 11));
  if (c.token && now - c.lastRecv > 1000) {
    ctx.fillStyle = 'rgba(120,0,0,0.75)'; ctx.fillRect(4 + 112, 26, 160, 20);
    ctx.fillStyle = '#fff'; ctx.font = '12px system-ui'; ctx.textAlign = 'center';
    ctx.fillText(`connection problem ${((now - c.lastRecv) / 1000).toFixed(0)} s`, 4 + 192, 40);
  }
  if (!c.token) { ctx.fillStyle = '#fff'; ctx.font = '13px system-ui'; ctx.textAlign = 'center'; ctx.fillText(cfg.unplugged ? 'Cable unplugged…' : 'Joining…', 4 + 192, 140); }
  if (!active) {
    ctx.fillStyle = 'rgba(0,0,0,0.55)'; ctx.fillRect(4, 238, 384, 12);
    ctx.fillStyle = '#fff'; ctx.font = '10px system-ui, sans-serif'; ctx.textAlign = 'center';
    ctx.fillText('Click here · arrows/WASD move · Space fires', 4 + 192, 247);
  }
}
run(update, draw);
</script>

How it fits together

The client sends inputs only, never positions or hits:

js
up[this.id].send({ token: this.token, inputs: this.pending.slice(-3) });   // last 3 inputs, for loss

The server validates and applies them with the shared move(), enforcing the cooldown and ignoring dead players:

js
if (inp.seq <= p.lastSeq) continue;          // duplicate copy
p.lastSeq = inp.seq;
if (p.respawnIn > 0) continue;               // dead players can't act
move(p, inp);                                // clamps the direction itself
if (inp.fire && p.cooldown === 0) { p.cooldown = COOLDOWN; /* spawn the projectile */ }

Joining uses a tiny handshake: the client says hello, the server answers with a welcome carrying a secret token, and every later packet must carry that token. A packet with an unknown or expired token gets a rejoin reply, which is how a client that was away too long finds out its slot is gone.

Make it your own

Each of these is a good exercise, roughly in order of difficulty:

  1. Lag compensation for shots: make projectiles instant hitscan rays, keep a 250 ms history of player positions on the server, and rewind to the shooter's view time (Lag Compensation).
  2. Predicted shots: spawn your own projectile locally when you fire, give it the input's sequence number, and replace it with the server's copy when the snapshot arrives.
  3. Visual smoothing: when reconciliation corrects your position, fade the error out over 100 ms instead of snapping.
  4. Delta snapshots: send only changed players and projectiles, against the last snapshot the client acknowledged (Quantization & Delta Compression).
  5. Interest management: make the arena 4× larger and send each client only what is within 60 units (Interest Management).
  6. A real server: move the server class into Node with a WebSocket (or a WebRTC data channel) and the clients into separate browser tabs (WebSocket, WebRTC & Colyseus). The rules don't change at all, which is the point of keeping them pure.
  7. Accounts and a result: issue the connect token from a backend after a TAD sign-in, and store the final scoreboard idempotently (Accounts & Sign-In, Persistence & Player Data).

Test yourself

In the arena, why does your own circle move instantly while your projectiles appear a moment after you fire?

  1. Projectiles are slower to draw
  2. Movement is predicted locally, but projectiles are created by the server and reach you through snapshots
  3. Space is read less often than the arrow keys
  4. The bots delay them

Ben's client asks to fire on every tick. What does the server do?

  1. Fires every tick
  2. Applies one shot per cooldown period and counts the rest as rejected inputs
  3. Disconnects ben immediately
  4. Sends ben's position back

Your cable is unplugged for 5 seconds, with TIMEOUT = 3 s and GRACE = 10 s. What happens?

  1. You are removed and lose your score
  2. The server marks you offline after 3 s, keeps your slot, and you reconnect with your score when packets return
  3. Nothing at all
  4. The match ends