{"id":"mp-brawl","name":"Server-run arena (authoritative)","description":"A real-time arena run by press5's arena engine: the server moves everyone, checks every shot and keeps score, so nobody can cheat by editing the page. Your own movement is predicted, so it still feels instant. Rounds, a scoreboard, a blaster and a rail gun, orbs and health packs.","tags":["gaming","multiplayer","game","real-time","server"],"premium":false,"fields":[{"key":"name","label":"Game title","example":"Ember Brawl"},{"key":"tagline","label":"Tagline","example":"Server-run battles. No lag excuses."}],"preview_url":"https://demo-mp-brawl.on.press5.xyz","files":[{"path":"index.html","content":"<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">\n<title>Ember Brawl | Server-run battles. No lag excuses.</title>\n<meta name=\"description\" content=\"Ember Brawl: a free server-run multiplayer arena game in your browser. Server-run battles. No lag excuses.\">\n<meta name=\"theme-color\" content=\"#05060f\">\n<link rel=\"stylesheet\" href=\"style.css\">\n<link rel=\"icon\" href=\"thumb.svg\">\n</head>\n<body>\n<canvas id=\"game\" aria-label=\"Game\"></canvas>\n\n<div id=\"hud\" hidden>\n  <div class=\"chip\" id=\"room-chip\">Room <b id=\"room-code\">-----</b> · <span id=\"online\">1</span> playing</div>\n  <ol id=\"scores\" aria-label=\"Scoreboard\"></ol>\n  <div class=\"chip\" id=\"me-chip\"><span id=\"hp\"></span></div>\n  <div id=\"feed\" aria-live=\"polite\"></div>\n  <div class=\"chip\" id=\"round-chip\"></div>\n  <div id=\"net\" class=\"chip warn\" hidden>Reconnecting…</div>\n</div>\n\n<section id=\"menu\" class=\"overlay\">\n  <div class=\"panel\">\n    <h1>Ember Brawl</h1>\n    <p class=\"tag\">Server-run battles. No lag excuses.</p>\n    <form id=\"join\">\n      <label for=\"name\">Your name</label>\n      <input id=\"name\" maxlength=\"16\" autocomplete=\"nickname\" placeholder=\"Player\" required>\n      <button type=\"submit\" id=\"play\">Play</button>\n    </form>\n    <p class=\"help\"><b>Move</b> WASD / arrows or drag · <b>Shoot</b> click / tap / space · <b>Rail</b> right-click or E · grab <span class=\"orb-dot\"></span> orbs and <span class=\"orb-dot heal\"></span> health</p>\n    <p class=\"status\" id=\"status\" role=\"status\"></p>\n    <p class=\"small\">Multiplayer by press5 Play. Open this page in two windows to play yourself.</p>\n  </div>\n</section>\n\n<script src=\"press5-play.js\"></script>\n<script src=\"script.js\"></script>\n</body>\n</html>\n"},{"path":"press5-play.d.ts","content":"// Type definitions for the press5 Play browser SDK (protocol v2).\n// SDK:   https://play.press5.xyz/sdk/v1/press5-play.js  (global Press5Play)  or  .mjs (ES module)\n// Types: https://play.press5.xyz/sdk/v1/press5-play.d.ts\n// Docs:  https://my.press5.xyz/docs/multiplayer   Errors: https://my.press5.xyz/docs/multiplayer/errors\n//\n// Two kinds of room:\n//   relay rooms   (no \"server\" block in press5.game.json): players share state and messages, the host\n//                 player's browser runs the rules. Hold them to fair limits with a \"guard\" block.\n//   server rooms  (\"server\": { \"engine\": \"arena\" | \"turns\" | \"party\" }): press5's engine runs the rules;\n//                 the game sends inputs (arena) or actions (turns, party) and draws what comes back.\n//\n// Quick start:\n//   const play = await Press5Play.connect({ name: 'Ada' });\n//   const room = await play.quickMatch();\n//   room.setMyState({ x: 10, y: 20 });                  // relay: your own state\n//   for (const p of room.others()) draw(room.smoothState(p.id));\n\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json };\nexport type State = { [key: string]: Json };\nexport type Unsubscribe = () => void;\n\n/** An error from press5 Play. `code` is stable; `fix` says what to change; `docs` links to it. */\nexport interface PlayError extends Error {\n  code: string;\n  fix?: string;\n  docs?: string;\n  /** How long until it may work, in ms (guard_locked: the lockout left). */\n  retryMs?: number;\n}\n\n/** room.guardSmooth(target): press5 Guard corrections applied to `target` at once, drawn easing in. */\nexport interface GuardSmoother {\n  /** The value to draw for one key (the corrected value plus what is left of the ease). */\n  get(key: string): any;\n  /** A copy of the target with the eases applied: draw from this. */\n  view(out?: { [key: string]: any }): { [key: string]: any };\n  /** What is left of the ease for one key (0 when settled). */\n  offset(key: string): number;\n  /** True while any key is still easing. */\n  easing(): boolean;\n  /** Stop listening for corrections. */\n  off: Unsubscribe;\n}\n\n/** Press5Play.guardNotice(...): what to tell a player press5 Guard (or the game's owner) took out. */\nexport interface GuardNotice {\n  /** \"guard\" (removed from the room), \"guard_locked\" (locked out for a while), \"banned\" / \"guard_banned\" (by the game's owner). */\n  code: 'guard' | 'guard_locked' | 'banned' | 'guard_banned';\n  banned: boolean;\n  /** Date.now() when they may play again; 0 when not known (or banned). */\n  until: number;\n  /** ms left of the lockout. */\n  left(): number;\n  /** The line to show right now, with the countdown (\"... You can play again in 1:42.\"). */\n  text(): string;\n}\n\nexport interface ConnectOptions {\n  /** The player's name (1-24 characters; HTML characters are removed). */\n  name?: string;\n  /** Server URL. Default wss://play.press5.xyz/v1. On localhost pages only, ?play=ws://... overrides it. */\n  url?: string;\n  /** A game key (p5g_...) for native builds and local testing. Web pages on the launch pad need none. */\n  key?: string;\n  /** The game's site name, for local development only. */\n  game?: string;\n  /** How far smoothState/entities run behind, in ms (default 100). */\n  interpDelay?: number;\n  /** Use UDP/WebTransport datagrams for arena games when the browser can (default true). */\n  datagrams?: boolean;\n  /** A WebSocket implementation, outside browsers. */\n  WebSocket?: unknown;\n}\n\nexport interface Limits {\n  msgPerSec: number;\n  bytesPerSec: number;\n  maxMessage: number;\n  roomState: number;\n  playerState: number;\n  roomPlayers: number;\n}\n\nexport interface GameInfo {\n  id: string;\n  kind: 'site' | 'native';\n  title: string;\n  maxPlayers: number;\n  modes: string[];\n  tickRate: number;\n}\n\nexport interface RoomOptions {\n  /** Room size (2-64, at most the game's maxPlayers). */\n  maxPlayers?: number;\n  /** One of the game's \"modes\" in press5.game.json. */\n  mode?: string;\n  /** Up to 8 short keys; quick match only joins rooms with the same filters. Keys may not start with \"_\". */\n  filters?: { [key: string]: string | number | boolean };\n}\n\nexport interface CreateRoomOptions extends RoomOptions {\n  /** Only joinable by code (room.code): party games, playing with friends. */\n  private?: boolean;\n  /** Room meta (up to 2 KB), visible to players in the room. */\n  meta?: State;\n  /** Starting room state (relay rooms only). */\n  state?: State;\n}\n\nexport interface RoomSummary {\n  code: string;\n  mode: string;\n  players: number;\n  maxPlayers: number;\n  createdAt: number;\n  meta?: State;\n}\n\nexport interface LeaderboardEntry {\n  rank: number;\n  name: string;\n  score: number;\n  wins: number;\n  games: number;\n  best?: number;\n  /** Elo, for games with \"rated\": true. */\n  rating?: number;\n}\n\nexport interface Player {\n  id: string;\n  name: string;\n  seat: number;\n  /** This player's own state (relay rooms): what they set with setMyState. */\n  state: State;\n  /** Disconnected, holding their place while they reconnect. */\n  away: boolean;\n  joinedAt: number;\n}\n\n// ---- server rooms ---------------------------------------------------------------------------------\n\n/** arena controls, sent once a tick by the SDK. */\nexport interface ArenaInput {\n  /** Move, -1..1 each. */\n  mx?: number;\n  my?: number;\n  /** Aim direction (any length). */\n  ax?: number;\n  ay?: number;\n  /** true for the first weapon, or a weapon number. */\n  fire?: boolean | number;\n  /** Platformers (world.gravity > 0). */\n  jump?: boolean;\n}\n\nexport interface ArenaPlayer {\n  id: string;\n  name?: string;\n  x: number;\n  y: number;\n  vx?: number;\n  vy?: number;\n  ax: number;\n  ay: number;\n  hp: number;\n  dead: boolean;\n  team: number;\n  ground?: boolean;\n  score: number;\n}\n\nexport interface ArenaPickup { id: string; x: number; y: number; kind: string }\nexport interface ArenaShot { id: string; x: number; y: number; vx: number; vy: number; owner: string; weapon: number; until: number }\nexport interface ArenaRay { x: number; y: number; ax: number; ay: number; len: number; owner: string; hit: string | null; at: number }\nexport interface ArenaRound { phase: 'play' | 'end' | string; n: number; msLeft: number; teams?: number[] }\n\n/** turns: room.view */\nexport interface TurnsView {\n  ph: 'wait' | 'play' | 'end';\n  rules: string;\n  seats: string[];\n  turn: number;\n  /** Your seat (-1 when watching). */\n  you: number;\n  /** Server time the turn ends (0: no clock). */\n  deadline: number;\n  moves: number;\n  result: 0 | { winner?: number; draw?: boolean; why: string };\n  rematch: string[];\n  /** The rule pack's view: board, last move, your hand (card-table), ... see engine_reference. */\n  game: { [key: string]: Json };\n}\n\n/** party: room.view */\n/** party quiz / poll / guess: room.view */\nexport interface PartyView {\n  ph: 'lobby' | 'question' | 'reveal' | 'end';\n  mode: 'quiz' | 'poll' | 'guess';\n  n: number;\n  of: number;\n  /** Server time this phase ends. */\n  until: number;\n  /** quiz/poll: how many answered; guess: how many got it right. */\n  answered: number;\n  players: number;\n  /** Scores by player id. */\n  sc: { [id: string]: number };\n  q?: string;\n  /** quiz/poll only. */\n  choices?: string[];\n  /** quiz/poll: your choice (-1 none); guess: whether you got it and your tries so far. */\n  mine?: number | { right: boolean; tries: number };\n  /** After the reveal. quiz/poll: the right choice's index (-1 in a poll); guess: the first accepted answer. */\n  answer?: number | string;\n  /** Points each player gained this question, by id. */\n  gained?: { [id: string]: number };\n  counts?: number[];\n}\n\n/** party draw (a drawing and guessing game): room.view */\nexport interface DrawView {\n  ph: 'lobby' | 'choose' | 'draw' | 'reveal' | 'end';\n  mode: 'draw';\n  /** This turn's number, and how many turns the game has. */\n  n: number;\n  of: number;\n  /** Who draws this turn. */\n  drawer: string | null;\n  /** The drawer only, while choosing: the words to pick from (act('choose', { word })). */\n  choices?: string[];\n  /** The drawer while drawing; everyone after the reveal. */\n  word?: string;\n  /** While drawing: \"_ _ a _ _\" (letters show as time runs out). */\n  hint?: string;\n  /** Ids of players who have guessed it this turn. */\n  guessed: string[];\n  mine: { right: boolean; tries: number };\n  until: number;\n  players: number;\n  sc: { [id: string]: number };\n  gained?: { [id: string]: number };\n}\n\n/** party draw: one stroke segment (x, y from 0 to 1 of the canvas). */\nexport interface Stroke { s: [number, number][]; c: string; w: number; new: boolean }\n\nexport interface EngineInfo {\n  name: 'arena' | 'turns' | 'party';\n  version: number;\n  tickRate: number;\n  patchEvery: number;\n  /** The engine settings players may see (secrets such as quiz answers are left out). */\n  config: { [key: string]: Json };\n}\n\n// ---- events ---------------------------------------------------------------------------------------\n\nexport interface RoomEvents {\n  /** Someone joined. */\n  join: (player: Player) => void;\n  /** Someone left (reason: \"left\", \"kicked\", \"guard\", \"timeout\", ...). */\n  leave: (player: Player, reason: string) => void;\n  away: (player: Player) => void;\n  back: (player: Player) => void;\n  name: (player: Player) => void;\n  /** The host moved to another player. */\n  host: (id: string, player: Player | undefined) => void;\n  /** Relay: room state changed (keys changed, the patch). Server rooms: a new view. */\n  state: (keysOrView: string[] | { [key: string]: Json }, patch?: State) => void;\n  /** Relay: another player's state changed. */\n  playerState: (player: Player, keys: string[], patch: State) => void;\n  /** A message from room.send. */\n  message: (data: Json, from: Player | { id: string }) => void;\n  binary: (bytes: Uint8Array, from: Player | null) => void;\n  meta: (meta: State, locked: boolean) => void;\n  /**\n   * press5 Guard corrected values that broke the game's \"guard\" limits: apply them, e.g.\n   * room.on('guard', (me) => { if (me.x !== undefined) player.x = me.x; })\n   * For your own player's position, room.guardSmooth(player) does this and eases the drawing in.\n   */\n  guard: (me: State, room: State) => void;\n  /**\n   * This client left the room (reason: \"left\", \"kicked\", \"guard\", \"banned\", \"room_error\", ...).\n   * info.retryMs: after \"guard\", how long the lockout from the game lasts. Press5Play.guardNotice(reason, info)\n   * gives the message to show.\n   */\n  end: (reason: string, info: { retryMs?: number }) => void;\n  /** Any engine event (also emitted under its own name: hit, ko, spawn, pickup, round, shot, start, move, over, question, reveal, ...). */\n  event: (type: string, data: { [key: string]: Json }) => void;\n  /** party draw: the drawer drew (sent to everyone else). */\n  stroke: (stroke: Stroke) => void;\n  /** party draw: the drawing so far, for a player who joined mid-turn. */\n  canvas: (data: { strokes: Stroke[] }) => void;\n  /** party draw: a wrong guess (the chat). Right guesses arrive as \"guessed\", never with their text. */\n  guess: (data: { id: string; name: string; text: string }) => void;\n  /** party guess/draw: someone got it. */\n  guessed: (data: { id: string; name: string }) => void;\n  /** party draw: a letter was shown. */\n  hint: (data: { hint: string }) => void;\n  /** party draw: a new turn (the drawer now chooses a word). */\n  turn: (data: { drawer: string; n: number; of: number }) => void;\n  /** party draw: the drawer chose; drawing has started. */\n  drawing: (data: { drawer: string; hint: string; len: number }) => void;\n  [engineEvent: string]: (...args: any[]) => void;\n}\n\nexport interface ClientEvents {\n  error: (error: PlayError) => void;\n  reconnecting: (info: { code: number; reason: string }) => void;\n  reconnected: (info: { resumed: boolean }) => void;\n  disconnected: (reason: string) => void;\n  restart: () => void;\n  /** Arena datagrams (UDP/WebTransport) came up (true) or fell back to the WebSocket (false). */\n  datagrams: (live: boolean) => void;\n}\n\nexport declare class Emitter<E> {\n  on<K extends keyof E & string>(event: K, fn: E[K]): Unsubscribe;\n  once<K extends keyof E & string>(event: K, fn: E[K]): Unsubscribe;\n  off<K extends keyof E & string>(event: K, fn: E[K]): void;\n}\n\nexport declare class Room extends Emitter<RoomEvents> {\n  /** 6-letter code; show it so friends can joinRoom(code). */\n  readonly code: string;\n  readonly mode: string;\n  readonly private: boolean;\n  readonly locked: boolean;\n  readonly maxPlayers: number;\n  readonly filters: State;\n  readonly meta: State;\n  /** The host's player id. */\n  readonly host: string;\n  /** Relay rooms: the shared room state (only the host writes it). */\n  readonly state: State;\n  readonly players: { [id: string]: Player };\n  readonly tickRate: number;\n  /** Your player id. */\n  readonly you: string;\n  readonly id: string;\n  readonly isHost: boolean;\n  readonly me: Player | undefined;\n  readonly ended: boolean;\n  /** Server rooms only: which engine runs this room. */\n  readonly engine?: EngineInfo;\n  /** Server rooms only: the latest view from the engine (TurnsView, PartyView, or arena's raw view). */\n  readonly view: TurnsView | PartyView | DrawView | { [key: string]: Json } | null;\n  readonly client: Client;\n\n  playerList(): Player[];\n  others(): Player[];\n  player(id: string): Player | null;\n  playerBySeat(seat: number): Player | null;\n\n  // relay rooms\n  /** Your own state: merged and sent once a tick. Checked against the game's \"guard\" limits. */\n  setMyState(patch: State): void;\n  /** Room state, host only (throws not_host otherwise). */\n  setState(patch: State): void;\n  /** Another player's state about interpDelay ms in the past, smoothed between updates. */\n  smoothState(id: string): State | null;\n  /**\n   * press5 Guard corrections without the jolt: each correction is applied to `target` (your own\n   * player object) at once, and smoother.view() eases what you draw there over opts.ms (default 100).\n   * Keys: opts.keys, else any the correction names that `target` has.\n   */\n  guardSmooth(target: { [key: string]: any }, opts?: { ms?: number; keys?: string[] }): GuardSmoother;\n  /** To everyone, or to one player id or a list of ids (secrets go to one player). Counts against the guard \"messages\" limits. */\n  send(data: Json, to?: string | string[]): void;\n  sendBinary(bytes: Uint8Array | ArrayBuffer | number[], toSeat?: number): void;\n  onMessage(fn: (data: Json, from: Player | { id: string }) => void): Unsubscribe;\n  /** Messages whose data.type is `type`. */\n  onMessage(type: string, fn: (data: any, from: Player | { id: string }) => void): Unsubscribe;\n  onJoin(fn: RoomEvents['join']): Unsubscribe;\n  onLeave(fn: RoomEvents['leave']): Unsubscribe;\n  onHostChange(fn: RoomEvents['host']): Unsubscribe;\n  onStateChange(fn: RoomEvents['state']): Unsubscribe;\n  onEnd(fn: RoomEvents['end']): Unsubscribe;\n\n  // host\n  lock(): Promise<unknown>;\n  unlock(): Promise<unknown>;\n  kick(id: string): Promise<unknown>;\n  makeHost(id: string): Promise<unknown>;\n  setMeta(meta: State): Promise<unknown>;\n  leave(): Promise<void>;\n\n  // server rooms\n  /** arena: your controls (merged; the SDK sends them once a tick and predicts your movement). */\n  setInput(input: ArenaInput): void;\n  /** turns / party: an engine action, e.g. act('move', { x: 3 }), act('answer', { choice: 1 }), act('start'). */\n  act(type: string, data?: Json): Promise<Json | undefined>;\n  /** arena: your player, predicted (instant). */\n  mine(): ArenaPlayer | null;\n  /** arena: everyone else, smoothed. */\n  entities(): ArenaPlayer[];\n  pickups(): ArenaPickup[];\n  shots(): ArenaShot[];\n  /** Hitscan rays from the last 200 ms, for drawing. */\n  rays(): ArenaRay[];\n  round(): ArenaRound;\n  scores(): { [id: string]: number };\n}\n\nexport declare class Client extends Emitter<ClientEvents> {\n  readonly id: string | null;\n  readonly name: string | null;\n  readonly game: GameInfo | null;\n  readonly limits: Limits | null;\n  readonly room: Room | null;\n  readonly connected: boolean;\n  /** Round-trip time to the server, ms. */\n  readonly rtt: number;\n  /** This device's signed guest id (leaderboards know the player by it; random, not personal). */\n  readonly guest?: string;\n\n  /** Server clock in ms (use it for countdowns: deadlines and \"until\" are server times). */\n  serverTime(): number;\n  /** The fullest open room that fits, or a new one. */\n  quickMatch(opts?: RoomOptions): Promise<Room>;\n  createRoom(opts?: CreateRoomOptions): Promise<Room>;\n  /** Join by 6-letter code (case does not matter). */\n  joinRoom(code: string): Promise<Room>;\n  listRooms(opts?: RoomOptions): Promise<RoomSummary[]>;\n  setName(name: string): Promise<string>;\n  /** This game's leaderboard (server-engine games only). */\n  leaderboard(period?: 'all' | 'week' | 'day'): Promise<LeaderboardEntry[]>;\n  close(): void;\n}\n\nexport declare class Interpolator {\n  constructor(opts?: { delay?: number; size?: number; angles?: string[] });\n  push(id: string, serverTimeMs: number, values: { [key: string]: number }): void;\n  get(id: string, serverTimeMs: number): { [key: string]: number } | null;\n  remove(id: string): void;\n}\n\nexport interface Press5PlayApi {\n  readonly VERSION: string;\n  /** Connect and say hello. Rejects with a PlayError (code, message, fix, docs). */\n  connect(opts?: ConnectOptions): Promise<Client>;\n  Interpolator: typeof Interpolator;\n  Client: typeof Client;\n  Room: typeof Room;\n  Arena: unknown;\n  applyDelta(base: Json, delta: Json): Json;\n  /**\n   * What to tell a player press5 Guard took out, from room.onEnd's (reason, info) or a join error;\n   * null when it wasn't the guard.\n   */\n  guardNotice(reasonOrError: string | PlayError | null | undefined, info?: { retryMs?: number }): GuardNotice | null;\n}\n\ndeclare const Press5Play: Press5PlayApi;\nexport default Press5Play;\nexport declare const connect: Press5PlayApi['connect'];\nexport declare const VERSION: string;\n\ndeclare global {\n  /** The global from <script src=\"https://play.press5.xyz/sdk/v1/press5-play.js\">. */\n  // eslint-disable-next-line no-var\n  var Press5Play: Press5PlayApi;\n}\n"},{"path":"press5-play.js","content":"/*! press5 Play SDK v1 | multiplayer rooms for games on the press5 launch pad | MIT\n *\n *   <script src=\"press5-play.js\"></script>        (or import Press5Play from '.../press5-play.mjs')\n *   const play = await Press5Play.connect({ name: 'Ada' });\n *   const room = await play.quickMatch({ maxPlayers: 8 });\n *   room.setMyState({ x: 10, y: 20 });                 // your player's state, synced to everyone\n *   room.onMessage('chat', (data, from) => ...);       // room.send({ type: 'chat', text: 'hi' })\n *   for (const p of room.playerList()) draw(room.smoothState(p.id));\n *\n * Docs: https://my.press5.xyz/docs/multiplayer   Protocol: docs/play-protocol.md\n */\nvar Press5Play = (function () {\n  'use strict';\n  var VERSION = '2.0.0';\n  var DEFAULT_URL = 'wss://play.press5.xyz/v1';\n  var NO_RETRY = { 4001: 1, 4003: 1, 4004: 1, 4008: 1, 4010: 1 };\n\n  // ?play=, ?wt= and ?wthash= are for local testing only. On a real game page a link could otherwise send\n  // players (their guest id, inputs, hidden cards) through someone else's server.\n  function devPage() {\n    try {\n      var h = String(globalThis.location.hostname || '').toLowerCase();\n      return h === 'localhost' || h === '127.0.0.1' || h === '[::1]' || h === '::1' || /\\.localhost$/.test(h);\n    } catch (e) { return false; }\n  }\n  function devParam(name) {\n    if (!devPage()) return null;\n    try { return new URLSearchParams(globalThis.location.search).get(name); } catch (e) { return null; }\n  }\n  function safeKey(k) { return k !== '__proto__' && k !== 'constructor' && k !== 'prototype'; }\n\n  function pickUrl(opts) {\n    if (opts.url) return opts.url;\n    var q = devParam('play');\n    if (q && /^wss?:\\/\\//.test(q)) return q;\n    if (typeof globalThis.PRESS5_PLAY_URL === 'string') return globalThis.PRESS5_PLAY_URL;\n    return DEFAULT_URL;\n  }\n\n  function Emitter() { this._ev = {}; }\n  Emitter.prototype.on = function (ev, fn) {\n    (this._ev[ev] || (this._ev[ev] = [])).push(fn);\n    var self = this;\n    return function off() { self.off(ev, fn); };\n  };\n  Emitter.prototype.off = function (ev, fn) {\n    var l = this._ev[ev]; if (!l) return;\n    var i = l.indexOf(fn); if (i >= 0) l.splice(i, 1);\n  };\n  Emitter.prototype.once = function (ev, fn) {\n    var off = this.on(ev, function () { off(); fn.apply(null, arguments); });\n    return off;\n  };\n  Emitter.prototype.emit = function (ev) {\n    var l = this._ev[ev]; if (!l) return;\n    var args = Array.prototype.slice.call(arguments, 1);\n    l.slice().forEach(function (fn) {\n      try { fn.apply(null, args); } catch (e) { setTimeout(function () { throw e; }); }\n    });\n  };\n  function inherit(C) { C.prototype = Object.create(Emitter.prototype); C.prototype.constructor = C; }\n\n  function applyPatch(target, patch) {\n    var keys = [];\n    for (var k in patch) {\n      if (!Object.prototype.hasOwnProperty.call(patch, k) || !safeKey(k)) continue;\n      if (patch[k] === null) delete target[k]; else target[k] = patch[k];\n      keys.push(k);\n    }\n    return keys;\n  }\n  function merge(a, b) { a = a || {}; for (var k in b) if (Object.prototype.hasOwnProperty.call(b, k)) a[k] = b[k]; return a; }\n  // e.code: a stable code (see https://my.press5.xyz/docs/multiplayer/errors); e.fix: what to change; e.docs: a link\n  // e.retryMs: how long until it may work (guard_locked: the lockout left)\n  function PlayError(code, message, fix, docs, retryMs) { var e = new Error(message || code); e.code = code; if (fix) e.fix = fix; if (docs) e.docs = docs; if (retryMs > 0) e.retryMs = retryMs; return e; }\n  var clock = function () { return globalThis.performance && performance.now ? performance.now() : Date.now(); };\n\n  // press5 Guard took this player out: the end reason ('guard', 'banned') or a join error\n  // (guard_locked, guard_banned) -> null when it wasn't the guard, or { code, banned, until, left(), text() }.\n  // text() is the line to show right now, counting down the lockout:\n  //   room.onEnd(function (why, info) { var n = Press5Play.guardNotice(why, info); if (n) show(n); });\n  //   play.quickMatch().catch(function (e) { var n = Press5Play.guardNotice(e); if (n) show(n); });\n  function guardNotice(x, info) {\n    var code = typeof x === 'string' ? x : x && x.code;\n    if (code !== 'guard' && code !== 'banned' && code !== 'guard_locked' && code !== 'guard_banned') return null;\n    var ms = (info && info.retryMs) || (x && x.retryMs) || 0;\n    var until = ms > 0 ? Date.now() + ms : 0;\n    var banned = code === 'banned' || code === 'guard_banned';\n    return {\n      code: code, banned: banned, until: until,\n      left: function () { return until ? Math.max(0, until - Date.now()) : 0; },\n      text: function () {\n        if (banned) return 'The owner of this game has banned you from it.';\n        var head = code === 'guard_locked' ? 'press5 Guard removed you from this game a short while ago.' : 'press5 Guard removed you from the room: this game\\'s limits were broken too often.';\n        if (!until) return head;\n        var s = Math.ceil(this.left() / 1000);\n        return s ? head + ' You can play again in ' + Math.floor(s / 60) + ':' + ('0' + (s % 60)).slice(-2) + '.' : head + ' You can play again now.';\n      },\n    };\n  }\n  // errors nobody handles are still worth seeing in the console, with their fix\n  function tellConsole(e) { try { if (globalThis.console) console.warn('[press5 Play] ' + e.code + ': ' + e.message + (e.fix ? '\\n  fix: ' + e.fix : '') + (e.docs ? '\\n  ' + e.docs : '')); } catch (x) { /* no console */ } }\n\n  // ---------------------------------------------------------------------------------------------\n  // Interpolator: a short history of numeric values per key, read back slightly in the past so\n  // remote things glide between network updates instead of jumping.\n  //   var ip = new Interpolator({ delay: 100, angles: ['rot'] });\n  //   ip.push('bullet7', serverTimeMs, { x: 1, y: 2, rot: 0.3 });\n  //   var s = ip.get('bullet7', play.serverTime());\n  function Interpolator(opts) {\n    opts = opts || {};\n    this.delay = opts.delay == null ? 100 : opts.delay;\n    this.size = opts.size || 32;\n    this.angles = {}; (opts.angles || []).forEach(function (a) { this.angles[a] = 1; }, this);\n    this.tracks = {};\n  }\n  Interpolator.prototype.push = function (id, t, values) {\n    if (!safeKey(String(id))) return;\n    var tr = this.tracks[id] || (this.tracks[id] = []);\n    var snap = { t: t, v: {} };\n    var last = tr[tr.length - 1];\n    if (last) for (var k0 in last.v) snap.v[k0] = last.v[k0];\n    for (var k in values) if (safeKey(k)) snap.v[k] = values[k];\n    if (last && t <= last.t) { last.v = snap.v; return; }\n    tr.push(snap);\n    if (tr.length > this.size) tr.shift();\n  };\n  Interpolator.prototype.get = function (id, now) {\n    var tr = this.tracks[id];\n    if (!tr || !tr.length) return null;\n    var t = now - this.delay;\n    if (t <= tr[0].t) return Object.assign({}, tr[0].v);\n    for (var i = tr.length - 1; i > 0; i--) {\n      var a = tr[i - 1], b = tr[i];\n      if (t >= a.t && t <= b.t) {\n        var f = (t - a.t) / Math.max(1, b.t - a.t), out = {};\n        for (var k in b.v) {\n          var va = a.v[k], vb = b.v[k];\n          if (typeof va === 'number' && typeof vb === 'number') {\n            if (this.angles[k]) {\n              var d = ((vb - va + Math.PI) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI) - Math.PI;\n              out[k] = va + d * f;\n            } else out[k] = va + (vb - va) * f;\n          } else out[k] = f < 0.5 && va !== undefined ? va : vb;\n        }\n        return out;\n      }\n    }\n    return Object.assign({}, tr[tr.length - 1].v); // newer than anything we have: hold the last\n  };\n  Interpolator.prototype.remove = function (id) { delete this.tracks[id]; };\n\n  // ---------------------------------------------------------------------------------------------\n  // Room\n  function Room(client, snap, you) {\n    Emitter.call(this);\n    this.client = client;\n    this.you = you;\n    this.ended = false;\n    this._load(snap);\n    this._interp = new Interpolator({ delay: client.interpDelay });\n    this._out = { me: null, room: null };\n    this._flushTimer = null;\n    this._lastTs = Date.now();\n    for (var id in this.players) this._interp.push(id, this.client.serverTime(), this.players[id].state);\n    if (snap.engine) this._engineInit(snap.engine);\n  }\n  inherit(Room);\n  Room.prototype._load = function (snap) {\n    this.code = snap.code; this.mode = snap.mode; this.private = snap.private; this.locked = snap.locked;\n    this.maxPlayers = snap.maxPlayers; this.filters = snap.filters || {}; this.meta = snap.meta || {};\n    this.host = snap.host; this.state = snap.state || {}; this.tickRate = snap.tickRate || 20;\n    this.players = snap.players || {};\n  };\n  Object.defineProperty(Room.prototype, 'me', { get: function () { return this.players[this.you]; } });\n  Object.defineProperty(Room.prototype, 'id', { get: function () { return this.you; } });\n  Object.defineProperty(Room.prototype, 'isHost', { get: function () { return this.host === this.you; } });\n  Room.prototype.playerList = function () {\n    var self = this;\n    return Object.keys(this.players).map(function (k) { return self.players[k]; }).sort(function (a, b) { return a.seat - b.seat; });\n  };\n  Room.prototype.others = function () { var me = this.you; return this.playerList().filter(function (p) { return p.id !== me; }); };\n  Room.prototype.player = function (id) { return this.players[id] || null; };\n  Room.prototype.playerBySeat = function (seat) { var l = this.playerList(); for (var i = 0; i < l.length; i++) if (l[i].seat === seat) return l[i]; return null; };\n\n  // Send any JSON value to everyone else, or to one player id / a list of ids.\n  Room.prototype.send = function (data, to) {\n    var f = { t: 'send', data: data };\n    if (to !== undefined && to !== null) f.to = to;\n    this._flushNow();\n    this.client._send(f, true);\n  };\n  // Fast path: raw bytes to everyone else (or one seat). Receivers get on('binary', (bytes, player)).\n  Room.prototype.sendBinary = function (bytes, toSeat) {\n    var u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n    var out = new Uint8Array(u8.length + 1);\n    out[0] = toSeat == null ? 255 : toSeat;\n    out.set(u8, 1);\n    this._flushNow();\n    this.client._sendRaw(out);\n  };\n  // Shared state. Your own player's state: anyone may set theirs. Room state: the host only.\n  // Changes are applied here at once and sent once a tick; null removes a key.\n  Room.prototype.setMyState = function (patch) {\n    var me = this.me; if (!me) return;\n    applyPatch(me.state, patch);\n    this._out.me = merge(this._out.me, patch);\n    this._schedule();\n  };\n  Room.prototype.setState = function (patch) {\n    if (!this.isHost) throw PlayError('not_host', 'Only the host can set room state (room.isHost).');\n    applyPatch(this.state, patch);\n    this._out.room = merge(this._out.room, patch);\n    this._schedule();\n  };\n  Room.prototype._schedule = function () {\n    if (this._flushTimer || this.ended) return;\n    var self = this;\n    this._flushTimer = setTimeout(function () { self._flushTimer = null; self._flushNow(); }, Math.round(1000 / Math.min(this.tickRate, 30)));\n  };\n  Room.prototype._flushNow = function () {\n    if (this._flushTimer) { clearTimeout(this._flushTimer); this._flushTimer = null; }\n    if (!this._out.me && !this._out.room) return;\n    if (!this.client.connected) return; // kept, sent after reconnecting\n    var f = { t: 'set' };\n    if (this._out.me) f.me = this._out.me;\n    if (this._out.room && this.isHost) f.room = this._out.room;\n    this._out = { me: null, room: null };\n    if (f.me || f.room) this.client._send(f);\n  };\n  // Where a player is drawn: their state a little in the past, smoothed between updates.\n  // Your own player is returned as-is (no delay).\n  Room.prototype.smoothState = function (id) {\n    if (id === this.you) return this.me ? this.me.state : null;\n    return this._interp.get(id, this.client.serverTime()) || (this.players[id] ? this.players[id].state : null);\n  };\n  // press5 Guard corrections without the jolt. A correction (a lag spike, or a cheat, held to the\n  // game's \"guard\" limits) is applied to `target` at once, so what you send next is what the server\n  // has; what you draw eases from where it was to there over `ms` (default 100):\n  //   var smooth = room.guardSmooth(me);           // or { keys: ['x', 'y'], ms: 100 }\n  //   ... each frame: var at = smooth.view();      // draw at at.x, at.y (smooth.get('x') for one)\n  // Keys: those in opts.keys, else any the correction names that `target` already has.\n  // smooth.off() stops it. room.on('guard') still fires for anything else the game keeps.\n  Room.prototype.guardSmooth = function (target, opts) {\n    opts = opts || {};\n    var ms = opts.ms == null ? 100 : Math.max(0, +opts.ms || 0);\n    var only = null;\n    if (opts.keys) { only = {}; opts.keys.forEach(function (k) { only[k] = 1; }); }\n    var eases = {};\n    function offset(k, t) {\n      var e = eases[k]; if (!e) return 0;\n      var f = (t - e.at) / ms;\n      if (!(f < 1)) { delete eases[k]; return 0; }\n      return e.d * (1 - f) * (1 - f); // ease out: most of the way at once, settling gently\n    }\n    var off = this.on('guard', function (fix) {\n      var t = clock();\n      for (var k in fix) {\n        if (!Object.prototype.hasOwnProperty.call(fix, k) || !safeKey(k)) continue;\n        if (only ? !only[k] : !(k in target)) continue;\n        var v = fix[k];\n        if (ms > 0 && typeof v === 'number' && typeof target[k] === 'number' && isFinite(target[k])) {\n          var shown = target[k] + offset(k, t);\n          if (shown !== v) eases[k] = { d: shown - v, at: t };\n        }\n        target[k] = v;\n      }\n    });\n    return {\n      get: function (k) { var v = target[k]; return typeof v === 'number' ? v + offset(k, clock()) : v; },\n      view: function (out) {\n        out = out || {};\n        var t = clock();\n        for (var k in target) if (Object.prototype.hasOwnProperty.call(target, k)) out[k] = target[k];\n        for (var e in eases) if (typeof out[e] === 'number') out[e] += offset(e, t);\n        return out;\n      },\n      offset: function (k) { return offset(k, clock()); },\n      easing: function () { var t = clock(); for (var e in eases) if (offset(e, t)) return true; return false; },\n      off: off,\n    };\n  };\n  Room.prototype.lock = function () { return this.client._request({ t: 'lock', locked: true }); };\n  Room.prototype.unlock = function () { return this.client._request({ t: 'lock', locked: false }); };\n  Room.prototype.kick = function (id) { return this.client._request({ t: 'kick', id: id }); };\n  Room.prototype.makeHost = function (id) { return this.client._request({ t: 'host', id: id }); };\n  Room.prototype.setMeta = function (meta) { return this.client._request({ t: 'meta', meta: meta }); };\n  Room.prototype.leave = function () {\n    if (this.ended) return Promise.resolve();\n    var self = this;\n    this._flushNow();\n    return this.client._request({ t: 'leave' }).then(function () { self._end('left'); }, function () { self._end('left'); });\n  };\n  // room.onMessage(fn) gets every message; room.onMessage('chat', fn) only those whose data.type is 'chat'.\n  Room.prototype.onMessage = function (type, fn) {\n    if (typeof type === 'function') return this.on('message', type);\n    return this.on('message', function (data, from) { if (data && data.type === type) fn(data, from); });\n  };\n  Room.prototype.onJoin = function (fn) { return this.on('join', fn); };\n  Room.prototype.onLeave = function (fn) { return this.on('leave', fn); };\n  Room.prototype.onHostChange = function (fn) { return this.on('host', fn); };\n  Room.prototype.onStateChange = function (fn) { return this.on('state', fn); };\n  Room.prototype.onEnd = function (fn) { return this.on('end', fn); };\n  // info: { retryMs } when press5 Guard removed this player and locked them out of the game for a while\n  Room.prototype._end = function (reason, info) {\n    if (this.ended) return;\n    this.ended = true;\n    if (this._flushTimer) clearTimeout(this._flushTimer);\n    if (this._inputTimer) clearInterval(this._inputTimer);\n    if (this.client.room === this) this.client.room = null;\n    this.emit('end', reason, info || {});\n  };\n\n  Room.prototype._frame = function (m) {\n    var p;\n    switch (m.t) {\n      case 'patch':\n        if (m.room) { var rk = applyPatch(this.state, m.room); this.emit('state', rk, m.room); }\n        if (m.players) {\n          for (var id in m.players) {\n            if (!safeKey(id)) continue; p = this.players[id]; if (!p) continue;\n            if (id === this.you) continue; // our own state is already applied locally\n            var keys = applyPatch(p.state, m.players[id]);\n            this._interp.push(id, m.ts, m.players[id]);\n            this.emit('playerState', p, keys, m.players[id]);\n          }\n        }\n        this.emit('patch', m);\n        break;\n      case 'player_join':\n        if (!m.player || !safeKey(String(m.player.id))) break;\n        this.players[m.player.id] = m.player;\n        this._interp.push(m.player.id, this.client.serverTime(), m.player.state);\n        this.emit('join', m.player);\n        break;\n      case 'player_leave':\n        p = this.players[m.id];\n        delete this.players[m.id];\n        this._interp.remove(m.id);\n        if (p) this.emit('leave', p, m.reason);\n        break;\n      case 'guard':\n        // press5 Guard clamped a write to the game's limits: take the server's values back, and\n        // tell the game so it can move its own copy (room.on('guard', function (fix) { ... }))\n        if (m.fix && m.fix.me && this.me) applyPatch(this.me.state, m.fix.me);\n        if (m.fix && m.fix.room) applyPatch(this.state, m.fix.room);\n        this.emit('guard', (m.fix && m.fix.me) || {}, (m.fix && m.fix.room) || {});\n        break;\n      case 'player_away': p = this.players[m.id]; if (p) { p.away = true; this.emit('away', p); } break;\n      case 'player_back': p = this.players[m.id]; if (p) { p.away = false; this.emit('back', p); } break;\n      case 'player_name': p = this.players[m.id]; if (p) { p.name = m.name; this.emit('name', p); } break;\n      case 'host': this.host = m.id; this.emit('host', m.id, this.players[m.id]); if (m.id === this.you) this._flushNow(); break;\n      case 'room': this.locked = m.locked; this.meta = m.meta || {}; this.emit('meta', this.meta, this.locked); break;\n      case 'msg': this.emit('message', m.data, this.players[m.from] || { id: m.from }); break;\n      case 'state': if (this.engine) this._state(m); break;\n      case 'event': if (this.engine) this._event(m.e, m.d || {}); break;\n      default: break;\n    }\n  };\n\n  // ---------------------------------------------------------------------------------------------\n  // Server rooms (protocol v2): press5's engine owns the game; this side sends input and draws.\n  //\n  // arena movement core: an exact port of play/engines/arena/sim.js (same operations in the same\n  // order), so your own player can be predicted and agree with the server.\n  var Arena = (function () {\n    var Q = 64;\n    function snap(v) { return Math.floor(v * Q + 0.5) / Q; }\n    function clamp(v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; }\n    function approach(v, target, s) { return v < target ? Math.min(v + s, target) : Math.max(v - s, target); }\n    function moveConfig(cfg) {\n      var p = cfg.players || {}, w = cfg.world || {};\n      var speed = p.speed != null ? p.speed : 270;\n      return {\n        width: w.width != null ? w.width : 1600, height: w.height != null ? w.height : 1000, walls: w.walls || [],\n        gravity: w.gravity != null ? w.gravity : 0, maxFall: w.maxFall != null ? w.maxFall : 1400,\n        speed: speed, accel: p.accel != null ? p.accel : speed * 10, radius: p.radius != null ? p.radius : 18,\n        jump: p.jump != null ? p.jump : 620, dt: 1 / (cfg.tickRate != null ? cfg.tickRate : 30),\n      };\n    }\n    function q127(v) { var n = Number(v); if (!isFinite(n)) return 0; return Math.floor(clamp(n, -1, 1) * 127 + 0.5) / 127; }\n    function step(p, input, m) {\n      var mx = q127(input && input.mx), my = q127(input && input.my), jump = !!(input && input.jump === true);\n      var len = Math.sqrt(mx * mx + my * my);\n      if (len > 1) { mx /= len; my /= len; }\n      var dv = m.accel * m.dt, r = m.radius, i, w;\n      if (m.gravity === 0) {\n        p.vx = approach(p.vx, mx * m.speed, dv);\n        p.vy = approach(p.vy, my * m.speed, dv);\n      } else {\n        p.vx = approach(p.vx, mx * m.speed, dv);\n        p.vy = Math.min(p.vy + m.gravity * m.dt, m.maxFall);\n        if (jump && p.ground) p.vy = -m.jump;\n      }\n      p.ground = false;\n      p.x += p.vx * m.dt;\n      for (i = 0; i < m.walls.length; i++) {\n        w = m.walls[i];\n        if (p.x + r > w[0] && p.x - r < w[0] + w[2] && p.y + r > w[1] && p.y - r < w[1] + w[3]) {\n          if (p.vx > 0) p.x = w[0] - r; else if (p.vx < 0) p.x = w[0] + w[2] + r;\n          p.vx = 0;\n        }\n      }\n      p.y += p.vy * m.dt;\n      for (i = 0; i < m.walls.length; i++) {\n        w = m.walls[i];\n        if (p.x + r > w[0] && p.x - r < w[0] + w[2] && p.y + r > w[1] && p.y - r < w[1] + w[3]) {\n          if (p.vy > 0) { p.y = w[1] - r; p.ground = true; } else if (p.vy < 0) p.y = w[1] + w[3] + r;\n          p.vy = 0;\n        }\n      }\n      if (p.x < r) { p.x = r; p.vx = 0; }\n      if (p.x > m.width - r) { p.x = m.width - r; p.vx = 0; }\n      if (p.y < r) { p.y = r; p.vy = 0; }\n      if (p.y > m.height - r) { p.y = m.height - r; p.vy = 0; if (m.gravity !== 0) p.ground = true; }\n      p.x = snap(p.x); p.y = snap(p.y); p.vx = snap(p.vx); p.vy = snap(p.vy);\n      return p;\n    }\n    return { moveConfig: moveConfig, step: step, snap: snap };\n  })();\n\n  var RESERVED_EVENTS = { end: 1, join: 1, leave: 1, away: 1, back: 1, host: 1, state: 1, message: 1, meta: 1, name: 1, patch: 1, resumed: 1, binary: 1, playerState: 1, event: 1 };\n\n  function applyDelta(a, d) {\n    if (!d || typeof d !== 'object' || Array.isArray(d)) return d;\n    var out = a && typeof a === 'object' && !Array.isArray(a) ? Object.assign({}, a) : {};\n    for (var k in d) {\n      if (!Object.prototype.hasOwnProperty.call(d, k) || !safeKey(k)) continue;\n      var v = d[k];\n      if (v === null) delete out[k];\n      else if (typeof v === 'object' && !Array.isArray(v)) out[k] = applyDelta(out[k], v);\n      else out[k] = v;\n    }\n    return out;\n  }\n\n  Room.prototype._engineInit = function (info) {\n    var self = this;\n    this.engine = info;           // { name, version, tickRate, patchEvery, config }\n    this.view = null;             // the latest snapshot from the server\n    this._ctl = {};               // the controls the game set with setInput\n    this._seq = 0;\n    this._pending = [];\n    this._mine = null;            // arena: your own predicted player\n    this._ents = new Interpolator({ delay: this.client.interpDelay });\n    this._shots = {};\n    this._rays = [];\n    if (info.name === 'arena') {\n      this._move = Arena.moveConfig(Object.assign({ tickRate: info.tickRate }, info.config));\n      this._inputTimer = setInterval(function () { self._sendInput(); }, 1000 / info.tickRate);\n    }\n  };\n  Room.prototype._sendInput = function () {\n    if (!this.client.connected || this.ended) return;\n    var i = Object.assign({}, this._ctl);\n    if (i.fire) i.v = Math.round(this.client.serverTime() - this.client.interpDelay);\n    this._seq += 1;\n    this._pending.push({ s: this._seq, i: i });\n    if (this._pending.length > 120) this._pending.shift();\n    // by datagram when the fast path is live (the last 3 inputs, as packets get lost), else the websocket\n    var dg = this.client._dg;\n    if (dg && dg.live) dg.sendInputs(this._pending.slice(-3).map(function (x) { return [x.s, x.i]; }));\n    else this.client._send({ t: 'input', s: this._seq, i: i });\n    if (this._mine && !this._mine.dead) Arena.step(this._mine, i, this._move);\n    // shots fly on every screen\n    var dt = 1 / this.engine.tickRate, now = Date.now();\n    for (var id in this._shots) {\n      var s = this._shots[id];\n      s.x += s.vx * dt; s.y += s.vy * dt;\n      if (now > s.until) delete this._shots[id];\n    }\n  };\n  Room.prototype._state = function (m) {\n    // datagram states are deltas against the snapshot we acknowledged (m.b); websocket ones\n    // against the previous state. Late datagrams are kept as baselines but never wind back the view.\n    var views = this._views || (this._views = {});\n    var next;\n    if (m.full) next = m.full;\n    else if (m.b !== undefined) { if (!views[m.b]) return; next = applyDelta(views[m.b], m.d || {}); }\n    else if (m.d) next = applyDelta(this.view, m.d);\n    else next = this.view;\n    if (!next) return;\n    views[m.s] = next;\n    var keys = Object.keys(views);\n    if (keys.length > 40) delete views[keys[0]];\n    if (m.s < (this._lastS || 0)) return;\n    this._lastS = m.s;\n    this.view = next;\n    var v = this.view;\n    if (this.engine.name === 'arena' && v.p) {\n      for (var id in v.p) {\n        var e = v.p[id];\n        if (id === this.you) {\n          // reconcile: the server's word for input a, then replay what it hasn't seen yet\n          var me = { x: e[0], y: e[1], vx: e[2], vy: e[3], ground: e[9] === 1, dead: e[7] === 1 };\n          this._pending = this._pending.filter(function (x) { return x.s > m.a; });\n          if (!me.dead) for (var k = 0; k < this._pending.length; k++) Arena.step(me, this._pending[k].i, this._move);\n          this._mine = me;\n        } else {\n          this._ents.push(id, m.ts, { x: e[0], y: e[1], ax: e[4], ay: e[5] });\n        }\n      }\n    }\n    this.emit('state', v);\n  };\n  Room.prototype._event = function (e, d) {\n    if (e === 'shot') {\n      if (d.id) this._shots[d.id] = { id: d.id, x: d.x, y: d.y, vx: d.vx, vy: d.vy, owner: d.o, weapon: d.w, until: Date.now() + (d.ms || 1000) };\n      else this._rays.push({ x: d.x, y: d.y, ax: d.ax, ay: d.ay, len: d.len, owner: d.o, hit: d.hit, at: Date.now() });\n    } else if (e === 'gone') delete this._shots[d.id];\n    if (this._rays.length > 32) this._rays.shift();\n    // engine events also arrive under their own name, except names the room itself uses\n    if (!RESERVED_EVENTS[e]) this.emit(e, d);\n    this.emit('event', e, d);\n  };\n\n  // What the game calls in a server room:\n  //   room.setInput({ mx, my, ax, ay, fire, jump })  your controls; sent once a tick by the SDK\n  //   room.mine()      your player, predicted: { x, y, vx, vy, ax, ay, hp, dead, team, score }\n  //   room.entities()  everyone else, smoothed: [{ id, name, x, y, ax, ay, hp, dead, team, score }]\n  //   room.pickups(), room.shots(), room.rays(), room.round(), room.scores()\n  //   room.act(type, data)  an engine action (turns, party); resolves with the reply\n  //   room.on('hit' | 'ko' | 'spawn' | 'pickup' | 'round' | 'shot' | 'state', fn)\n  Room.prototype.setInput = function (ctl) { Object.assign(this._ctl || (this._ctl = {}), ctl); };\n  Room.prototype.act = function (type, data) {\n    return this.client._request({ t: 'act', type: type, data: data }).then(function (m) { return m.reply; });\n  };\n  Room.prototype.mine = function () {\n    var v = this.view, me = this._mine;\n    if (!v || !v.p || !v.p[this.you]) return null;\n    var e = v.p[this.you];\n    return {\n      id: this.you, x: me ? me.x : e[0], y: me ? me.y : e[1], vx: me ? me.vx : e[2], vy: me ? me.vy : e[3],\n      ax: e[4], ay: e[5], hp: e[6], dead: e[7] === 1, team: e[8], ground: me ? me.ground : e[9] === 1, score: (v.sc || {})[this.you] || 0,\n    };\n  };\n  Room.prototype.entities = function () {\n    var v = this.view, out = [];\n    if (!v || !v.p) return out;\n    var t = this.client.serverTime();\n    for (var id in v.p) {\n      if (id === this.you) continue;\n      var e = v.p[id], s = this._ents.get(id, t) || { x: e[0], y: e[1], ax: e[4], ay: e[5] };\n      var pl = this.players[id];\n      out.push({ id: id, name: pl ? pl.name : id, x: s.x, y: s.y, ax: s.ax, ay: s.ay, hp: e[6], dead: e[7] === 1, team: e[8], score: (v.sc || {})[id] || 0 });\n    }\n    return out;\n  };\n  Room.prototype.pickups = function () {\n    var v = this.view, out = [];\n    if (v && v.k) for (var id in v.k) out.push({ id: id, x: v.k[id][0], y: v.k[id][1], kind: v.k[id][2] });\n    return out;\n  };\n  Room.prototype.shots = function () { var out = []; for (var id in this._shots || {}) out.push(this._shots[id]); return out; };\n  Room.prototype.rays = function () { var now = Date.now(); return (this._rays || []).filter(function (r) { return now - r.at < 200; }); };\n  Room.prototype.round = function () { var v = this.view || {}; return { phase: v.ph, n: v.n, msLeft: v.rt, teams: v.ts }; };\n  Room.prototype.scores = function () { return (this.view && this.view.sc) || {}; };\n\n  // ---------------------------------------------------------------------------------------------\n  // Client: one connection to press5 Play.\n  function Client(opts) {\n    Emitter.call(this);\n    this.opts = opts;\n    this.url = pickUrl(opts);\n    this.name = opts.name || null;\n    this.interpDelay = opts.interpDelay == null ? 100 : opts.interpDelay;\n    this.WS = opts.WebSocket || globalThis.WebSocket;\n    if (!this.WS) throw PlayError('no_websocket', 'This environment has no WebSocket; pass { WebSocket }.');\n    this.connected = false; this.closed = false;\n    this.id = null; this.game = null; this.limits = null; this.room = null;\n    this.rtt = 0; this._offset = 0; this._bestRtt = Infinity;\n    this._rid = 0; this._pending = {}; this._queue = [];\n    this._retries = 0; this._pings = 0; this._pingTimer = null;\n  }\n  inherit(Client);\n\n  Client.prototype._open = function (resume) {\n    var self = this;\n    return new Promise(function (resolve, reject) {\n      var ws;\n      try { ws = new self.WS(self.url); } catch (e) { reject(e); return; }\n      ws.binaryType = 'arraybuffer';\n      self.ws = ws;\n      var settled = false;\n      ws.onopen = function () {\n        var hello = { t: 'hello', v: 2, sdk: 'js/' + VERSION, name: self.name || undefined };\n        if (self.opts.key) hello.key = self.opts.key;\n        if (self.opts.game) hello.game = self.opts.game;\n        if (resume) hello.resume = resume;\n        // the signed guest id leaderboards know this device by (random, not personal)\n        var guest = self.opts.guest;\n        if (!guest) try { guest = globalThis.localStorage.getItem('press5-play-guest'); } catch (e) { /* no storage */ }\n        if (guest) hello.guest = guest;\n        self._request(hello, true).then(function (w) {\n          settled = true;\n          self.connected = true; self._retries = 0;\n          self.id = w.id; self.name = w.name; self.game = w.game; self.limits = w.limits;\n          if (self._dg) { self._dg.close(); self._dg = null; }\n          if (w.udp && w.wt && self.opts.datagrams !== false) openDatagrams(self, w);\n          if (w.guest) { self.guest = w.guest; try { globalThis.localStorage.setItem('press5-play-guest', w.guest); } catch (e) { /* no storage */ } }\n          self._clockSample(w.serverTime, Date.now(), Date.now());\n          self._startPings();\n          resolve(w);\n        }, function (e) { settled = true; reject(e); });\n      };\n      ws.onmessage = function (ev) { self._onMessage(ev.data); };\n      ws.onclose = function (ev) {\n        var wasConnected = self.connected;\n        self.connected = false;\n        self._stopPings();\n        self._failPending(PlayError('disconnected', 'The connection closed.'));\n        if (!settled) { settled = true; reject(PlayError(ev.reason || 'closed', 'Could not connect to press5 Play (' + (ev.reason || ev.code) + ').')); }\n        if (wasConnected) self._dropped(ev.code, ev.reason);\n      };\n      ws.onerror = function () { /* onclose follows */ };\n    });\n  };\n\n  Client.prototype._dropped = function (code, reason) {\n    if (this.closed) return;\n    if (NO_RETRY[code]) { this._final(reason || 'closed'); return; }\n    this.emit('reconnecting', { code: code, reason: reason });\n    var self = this;\n    var delay = this._restartDelay || Math.min(5000, 250 * Math.pow(2, this._retries));\n    this._restartDelay = 0;\n    this._retries++;\n    if (this._retries > 12) { this._final('connection_lost'); return; }\n    setTimeout(function () {\n      if (self.closed) return;\n      var resume = self.room && self._resume;\n      self._open(resume).then(function (w) {\n        if (resume && !w.resumed && self.room) self.room._end('connection_lost');\n        self.emit('reconnected', { resumed: !!w.resumed });\n        var q = self._queue; self._queue = [];\n        q.forEach(function (f) { self._send(f); });\n      }, function () { self._dropped(0, 'retry'); });\n    }, delay);\n  };\n  Client.prototype._final = function (reason) {\n    this.closed = true;\n    if (this.room) this.room._end(reason);\n    this.emit('disconnected', reason);\n  };\n\n  Client.prototype._onMessage = function (data) {\n    if (typeof data !== 'string') {\n      var u8 = new Uint8Array(data);\n      if (this.room && u8.length) this.room.emit('binary', u8.subarray(1), this.room.playerBySeat(u8[0]));\n      return;\n    }\n    var m;\n    try { m = JSON.parse(data); } catch (e) { return; }\n    if (m.t === 'joined') {\n      var old = this.room;\n      if (old && old.code === m.room.code && m.resumed) {\n        old._load(m.room); old.you = m.you; this._resume = m.resume;\n        old._flushNow();\n        old.emit('resumed');\n      } else {\n        if (old) old._end('left');\n        this.room = new Room(this, m.room, m.you);\n        this._resume = m.resume;\n      }\n    } else if (m.t === 'left') {\n      if (this.room && this.room.code === m.code) this.room._end(m.reason, m.retryMs > 0 ? { retryMs: m.retryMs } : {});\n    } else if (m.t === 'server_restart') {\n      this._restartDelay = m.reconnectMs || 1000;\n      this.emit('restart');\n    } else if (this.room && m.t !== 'pong' && m.t !== 'ok' && m.t !== 'error' && m.t !== 'rooms' && m.t !== 'welcome') {\n      this.room._frame(m);\n    }\n    if (m.rid !== undefined && this._pending[m.rid]) {\n      var pr = this._pending[m.rid];\n      delete this._pending[m.rid];\n      clearTimeout(pr.timer);\n      if (m.t === 'error') pr.reject(PlayError(m.code, m.message, m.fix, m.docs, m.retryMs)); else pr.resolve(m);\n    } else if (m.t === 'error') {\n      var pe = PlayError(m.code, m.message, m.fix, m.docs, m.retryMs);\n      if (this._ev.error && this._ev.error.length) this.emit('error', pe); else tellConsole(pe);\n    }\n  };\n\n  Client.prototype._send = function (f, queueIfDown) {\n    if (!this.connected || !this.ws || this.ws.readyState !== 1) {\n      if (queueIfDown && this._queue.length < 100) this._queue.push(f);\n      return false;\n    }\n    this.ws.send(JSON.stringify(f));\n    return true;\n  };\n  Client.prototype._sendRaw = function (bytes) {\n    if (this.connected && this.ws && this.ws.readyState === 1) this.ws.send(bytes);\n  };\n  Client.prototype._request = function (f, evenIfHello) {\n    var self = this;\n    return new Promise(function (resolve, reject) {\n      if ((!self.connected && !evenIfHello) || !self.ws || self.ws.readyState !== 1) { reject(PlayError('disconnected', 'Not connected.')); return; }\n      var rid = ++self._rid;\n      f.rid = rid;\n      self._pending[rid] = { resolve: resolve, reject: reject, timer: setTimeout(function () { delete self._pending[rid]; reject(PlayError('timeout', f.t + ' timed out')); }, 10000) };\n      self.ws.send(JSON.stringify(f));\n    });\n  };\n  Client.prototype._failPending = function (e) {\n    var p = this._pending; this._pending = {};\n    for (var k in p) { clearTimeout(p[k].timer); p[k].reject(e); }\n  };\n\n  // clock: server time = local time + offset, from the ping with the shortest round trip\n  Client.prototype._clockSample = function (server, sent, got) {\n    var rtt = got - sent;\n    this.rtt = this.rtt ? this.rtt * 0.8 + rtt * 0.2 : rtt;\n    if (rtt <= this._bestRtt * 1.2 || this._pings < 3) {\n      this._bestRtt = Math.min(this._bestRtt, rtt);\n      this._offset = server - (sent + got) / 2;\n    }\n  };\n  Client.prototype.serverTime = function () { return Date.now() + this._offset; };\n  Client.prototype._startPings = function () {\n    var self = this;\n    this._stopPings();\n    var tick = function () {\n      var sent = Date.now();\n      self._request({ t: 'ping', c: sent }).then(function (m) { self._pings++; self._clockSample(m.s, sent, Date.now()); }, function () {});\n      self._pingTimer = setTimeout(tick, self._pings < 5 ? 2000 : 10000);\n    };\n    this._pingTimer = setTimeout(tick, 300);\n  };\n  Client.prototype._stopPings = function () { if (this._pingTimer) clearTimeout(this._pingTimer); this._pingTimer = null; };\n\n  // the reply's \"joined\" frame has already made client.room by the time the request resolves\n  function roomFrom(client) { return function () { return client.room; }; }\n\n  // Join the fullest open room with this mode (and filters), or start one.\n  Client.prototype.quickMatch = function (opts) { return this._request(Object.assign({ t: 'quick' }, opts || {})).then(roomFrom(this)); };\n  // A new room. { private: true } keeps it out of quick match and lists: share room.code instead.\n  Client.prototype.createRoom = function (opts) { return this._request(Object.assign({ t: 'create' }, opts || {})).then(roomFrom(this)); };\n  Client.prototype.joinRoom = function (code) { return this._request({ t: 'join', code: String(code || '').trim().toUpperCase() }).then(roomFrom(this)); };\n  Client.prototype.listRooms = function (opts) { return this._request(Object.assign({ t: 'list' }, opts || {})).then(function (m) { return m.rooms; }); };\n  // The game's leaderboard (server-engine games): period 'all' (default), 'week' or 'day'.\n  // Resolves with [{ rank, name, score, wins, games, rating? }].\n  Client.prototype.leaderboard = function (period) {\n    var base = this.url.replace(/^ws/, 'http').replace(/\\/v1\\/?$/, '');\n    return fetch(base + '/v1/games/' + encodeURIComponent(this.game.id) + '/leaderboard?period=' + (period || 'all'))\n      .then(function (r) { return r.json(); }).then(function (b) { return b.entries || []; });\n  };\n  Client.prototype.setName = function (name) { var self = this; return this._request({ t: 'name', name: name }).then(function (m) { self.name = m.name; return m.name; }); };\n  // ---------------------------------------------------------------------------------------------\n  // The fast path in browsers: WebTransport datagrams in Play's datagram format (see the protocol\n  // doc): [type][session][seq][ack][JSON][8-byte HMAC-SHA256 tag]. Used for inputs and state in\n  // server rooms; everything else stays on the websocket. Falls back silently when the browser\n  // has no WebTransport or the datagrams stop for 3 s.\n  function openDatagrams(client, w) {\n    var WT = globalThis.WebTransport, subtle = globalThis.crypto && globalThis.crypto.subtle;\n    if (!WT || !subtle) return;\n    var enc = new TextEncoder(), dec = new TextDecoder();\n    var keyRaw = Uint8Array.from(atob(w.udp.key), function (c) { return c.charCodeAt(0); });\n    var dg = { live: false, seq: 0, ack: 0, inSeq: 0, lastIn: 0, closed: false, wt: null, writer: null, key: null };\n    client._dg = dg;\n    function pack(type, payload) {\n      var body = payload === undefined ? new Uint8Array(0) : payload instanceof Uint8Array ? payload : enc.encode(JSON.stringify(payload));\n      var buf = new Uint8Array(13 + body.length);\n      var view = new DataView(buf.buffer);\n      buf[0] = type; view.setUint32(1, w.udp.session >>> 0); view.setUint32(5, (dg.seq += 1) >>> 0); view.setUint32(9, dg.ack >>> 0);\n      buf.set(body, 13);\n      return subtle.sign('HMAC', dg.key, buf).then(function (sig) {\n        var out = new Uint8Array(buf.length + 8);\n        out.set(buf, 0); out.set(new Uint8Array(sig).subarray(0, 8), buf.length);\n        return out;\n      });\n    }\n    function send(type, payload) {\n      if (dg.closed || !dg.writer) return;\n      pack(type, payload).then(function (b) { if (!dg.closed) dg.writer.write(b).catch(function () {}); });\n    }\n    function onDatagram(b) {\n      if (b.length < 21) return;\n      var body = b.subarray(0, b.length - 8);\n      subtle.sign('HMAC', dg.key, body).then(function (sig) {\n        var s = new Uint8Array(sig), diff = 0;\n        for (var i = 0; i < 8; i++) diff |= s[i] ^ b[b.length - 8 + i];\n        if (diff) return;\n        var view = new DataView(b.buffer, b.byteOffset, b.byteLength);\n        var type = b[0], ack = view.getUint32(9);\n        if (view.getUint32(1) !== (w.udp.session >>> 0)) return;\n        // Play checks the address is ours before sending anything there: echo its cookie (it rides in\n        // the seq and ack fields, so this comes before the replay check)\n        if (type === 6) { if (b.length === 21) send(7, b.slice(5, 13)); return; }\n        var seq = view.getUint32(5);\n        if (seq <= dg.inSeq) return; // old or replayed\n        dg.inSeq = seq;\n        dg.lastIn = Date.now();\n        if (type !== 3) return;\n        dg.live = true;\n        var p = JSON.parse(dec.decode(b.subarray(13, b.length - 8)));\n        var room = client.room;\n        if (!room || !room.engine) return;\n        room._state({ t: 'state', s: p.s, b: p.full ? undefined : p.b, a: ack, ts: p.ts, d: p.d, full: p.full });\n        if (room._views && room._views[p.s] && p.s > dg.ack) dg.ack = p.s;\n      });\n    }\n    dg.sendInputs = function (list) { send(2, { i: list }); };\n    dg.close = function () { dg.closed = true; dg.live = false; clearInterval(dg.timer); try { if (dg.wt) dg.wt.close(); } catch (e) { /* gone */ } };\n    subtle.importKey('raw', keyRaw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']).then(function (k) {\n      dg.key = k;\n      var hash = client.opts.wtCertHash;\n      var q = devParam('wthash'); if (q) hash = q;\n      var opts = hash ? { serverCertificateHashes: [{ algorithm: 'sha-256', value: Uint8Array.from(atob(hash), function (c) { return c.charCodeAt(0); }) }] } : undefined;\n      var url = client.opts.wtUrl || w.wt.url;\n      var qu = devParam('wt'); if (qu && /^https:\\/\\//.test(qu)) url = qu;\n      dg.wt = new WT(url, opts);\n      return dg.wt.ready;\n    }).then(function () {\n      if (dg.closed) return;\n      dg.writer = dg.wt.datagrams.writable.getWriter();\n      var reader = dg.wt.datagrams.readable.getReader();\n      (function read() { reader.read().then(function (r) { if (r.done || dg.closed) return; onDatagram(r.value); read(); }, function () {}); })();\n      // bind once a second until state flows, and keep an eye on it after\n      send(1);\n      dg.timer = setInterval(function () {\n        if (!dg.live) send(1);\n        else if (Date.now() - dg.lastIn > 3000) dg.live = false;\n      }, 1000);\n      client.emit('datagrams', true);\n    }).catch(function () { dg.live = false; client.emit('datagrams', false); });\n  }\n\n  Client.prototype.close = function () {\n    this.closed = true;\n    if (this._dg) { this._dg.close(); this._dg = null; }\n    this._stopPings();\n    if (this.room) { this.room._flushNow(); this._send({ t: 'leave' }); this.room._end('left'); }\n    if (this.ws) try { this.ws.close(1000, 'bye'); } catch (e) { /* gone */ }\n  };\n\n  // Connect and say hello. Options:\n  //   name        the player's name (1-24 characters)\n  //   url         server (default wss://play.press5.xyz/v1; on localhost pages only, ?play=ws://... overrides it)\n  //   key         a game key (p5g_...) for native builds and local testing\n  //   game        the game's site name, only for local development\n  //   interpDelay ms smoothState runs behind (default 100)\n  function connect(opts) {\n    var c = new Client(opts || {});\n    return c._open(null).then(function () { return c; });\n  }\n\n  var api = { VERSION: VERSION, connect: connect, Interpolator: Interpolator, Client: Client, Room: Room, Arena: Arena, applyDelta: applyDelta, guardNotice: guardNotice };\n  if (typeof globalThis !== 'undefined') globalThis.Press5Play = api;\n  return api;\n})();\n"},{"path":"press5.game.json","content":"{\n  \"$schema\": \"https://my.press5.xyz/schemas/press5.game.json\",\n  \"title\": \"Ember Brawl\",\n  \"description\": \"A server-run arena: move, shoot, grab orbs, win the round.\",\n  \"maxPlayers\": 12,\n  \"listed\": true,\n  \"thumbnail\": \"thumb.svg\",\n  \"tags\": [\n    \"action\",\n    \"arena\",\n    \"server\"\n  ],\n  \"server\": {\n    \"engine\": \"arena\",\n    \"version\": 1,\n    \"tickRate\": 30,\n    \"patchRate\": 20,\n    \"world\": {\n      \"width\": 1600,\n      \"height\": 1000,\n      \"walls\": [\n        [\n          380,\n          220,\n          40,\n          220\n        ],\n        [\n          1180,\n          560,\n          40,\n          220\n        ],\n        [\n          700,\n          470,\n          200,\n          40\n        ],\n        [\n          220,\n          760,\n          260,\n          30\n        ],\n        [\n          1120,\n          210,\n          260,\n          30\n        ]\n      ]\n    },\n    \"players\": {\n      \"speed\": 280,\n      \"radius\": 18,\n      \"hp\": 5,\n      \"respawnMs\": 1800\n    },\n    \"weapons\": [\n      {\n        \"id\": \"blaster\",\n        \"kind\": \"projectile\",\n        \"speed\": 760,\n        \"lifeMs\": 1000,\n        \"cooldownMs\": 200,\n        \"damage\": 1,\n        \"radius\": 5\n      },\n      {\n        \"id\": \"rail\",\n        \"kind\": \"hitscan\",\n        \"range\": 1100,\n        \"cooldownMs\": 1400,\n        \"damage\": 3\n      }\n    ],\n    \"pickups\": [\n      {\n        \"id\": \"orb\",\n        \"count\": 12,\n        \"score\": 1\n      },\n      {\n        \"id\": \"med\",\n        \"count\": 3,\n        \"score\": 0,\n        \"heal\": 2,\n        \"respawnMs\": 6000,\n        \"radius\": 11\n      }\n    ],\n    \"rounds\": {\n      \"durationS\": 180,\n      \"scoreToWin\": 30,\n      \"intermissionS\": 8\n    },\n    \"scoring\": {\n      \"ko\": 3\n    }\n  }\n}\n"},{"path":"script.js","content":"/// <reference path=\"press5-play.d.ts\" />\n// Types for the SDK (editor hints and AI tools): press5-play.d.ts. Check press5.game.json with check_game before deploying.\n// Ember Brawl: a server-run arena on press5 Play's arena engine.\n//\n// How it works (the pattern for any server-room game):\n//   - press5.game.json's \"server\" block picks the arena engine and sets it up (map, weapons,\n//     pickups, rounds). The engine is press5's code: it moves everyone, checks every shot and keeps\n//     the score. This page never decides anything; it can't cheat by being edited.\n//   - The page only sends controls: room.setInput({ mx, my, ax, ay, fire }). The SDK sends them\n//     once a tick and predicts your own movement with the same code the server runs, so it feels\n//     instant; room.mine() is that predicted you.\n//   - Everyone else comes from room.entities(), smoothed between server updates. Shots, rails,\n//     pickups, scores and the round clock come from room.shots(), room.rays(), room.pickups(),\n//     room.scores() and room.round(). Events (hit, ko, round) drive the effects and the feed.\n(function () {\n  'use strict';\n  var canvas = document.getElementById('game');\n  var ctx = canvas.getContext('2d');\n  var $ = function (id) { return document.getElementById(id); };\n  var play = null, room = null, cfg = null;\n  var keys = {}, mouse = { x: 0, y: 0, down: false, alt: false, seen: false }, touch = null;\n  var cam = { x: 800, y: 500, s: 1 };\n  var flashes = [];\n\n  try { $('name').value = localStorage.getItem('brawl-name') || ''; } catch (e) { /* private mode */ }\n  $('join').addEventListener('submit', function (ev) {\n    ev.preventDefault();\n    var name = $('name').value.trim() || 'Player';\n    try { localStorage.setItem('brawl-name', name); } catch (e) { /* private mode */ }\n    $('play').disabled = true;\n    $('status').textContent = 'Finding a match…';\n    var go = play ? play.setName(name).then(function () { return play; }) : Press5Play.connect({ name: name }).then(function (p) {\n      play = p;\n      play.on('reconnecting', function () { $('net').hidden = false; });\n      play.on('reconnected', function () { $('net').hidden = true; });\n      play.on('disconnected', function () { backToMenu('Lost the connection. Press Play to rejoin.'); });\n      return p;\n    });\n    go.then(function (p) { return p.quickMatch(); }).then(enter).catch(function (e) {\n      $('play').disabled = false;\n      var n = Press5Play.guardNotice(e);\n      if (n) showGuard(n); else $('status').textContent = 'Could not join: ' + (e.message || e);\n    });\n  });\n\n  function enter(r) {\n    room = r;\n    cfg = room.engine.config;\n    $('menu').hidden = true; $('hud').hidden = false; $('play').disabled = false; $('status').textContent = '';\n    $('room-code').textContent = room.code;\n    room.on('ko', function (d) { feed(nameOf(d.by) + ' got ' + nameOf(d.t)); });\n    room.on('hit', function (d) { if (d.t === room.id) flashes.push({ at: performance.now() }); });\n    room.on('round', function (d) {\n      if (d.phase === 'end') feed('Round over: ' + (d.ranking && d.ranking[0] ? d.ranking[0].name + ' wins' : 'no winner'));\n      else feed('Round ' + d.n + ': fight!');\n    });\n    room.onJoin(function (p) { feed(p.name + ' joined'); });\n    room.onLeave(function (p) { feed(p.name + ' left'); });\n    room.onEnd(function (why, info) {\n      if (why === 'left') return;\n      var n = Press5Play.guardNotice(why, info);\n      backToMenu(n ? '' : why === 'kicked' ? 'You were removed from the room.' : 'The match ended (' + why + ').');\n      if (n) showGuard(n);\n    });\n  }\n  function backToMenu(msg) {\n    room = null;\n    $('hud').hidden = true; $('menu').hidden = false; $('play').disabled = false;\n    $('status').textContent = msg || '';\n  }\n  // press5 Guard took us out (or the game's owner banned us): say so plainly, and count down the\n  // lockout before Play works again\n  var guardTimer = null;\n  function showGuard(n) {\n    clearInterval(guardTimer);\n    function tick() {\n      $('status').textContent = n.text();\n      var waiting = n.banned || n.left() > 0;\n      $('play').disabled = waiting;\n      if (!waiting || n.banned) clearInterval(guardTimer);\n    }\n    tick();\n    guardTimer = setInterval(tick, 1000);\n  }\n  function nameOf(id) { if (!room) return 'Someone'; if (id === room.id) return 'you'; var p = room.players[id]; return p ? p.name : 'Someone'; }\n\n  // ---- controls: turned into one input a tick by the SDK -----------------------------------\n  addEventListener('keydown', function (e) { keys[e.key.toLowerCase()] = true; if (e.key === ' ' && room) e.preventDefault(); });\n  addEventListener('keyup', function (e) { keys[e.key.toLowerCase()] = false; });\n  canvas.addEventListener('contextmenu', function (e) { e.preventDefault(); });\n  canvas.addEventListener('mousemove', function (e) { mouse.x = e.clientX; mouse.y = e.clientY; mouse.seen = true; });\n  canvas.addEventListener('mousedown', function (e) { if (e.button === 2) mouse.alt = true; else mouse.down = true; });\n  addEventListener('mouseup', function (e) { if (e.button === 2) mouse.alt = false; else mouse.down = false; });\n  canvas.addEventListener('touchstart', function (e) { var t = e.changedTouches[0]; touch = { x: t.clientX, y: t.clientY }; e.preventDefault(); }, { passive: false });\n  canvas.addEventListener('touchmove', function (e) { var t = e.changedTouches[0]; if (touch) { touch.x = t.clientX; touch.y = t.clientY; } e.preventDefault(); }, { passive: false });\n  canvas.addEventListener('touchend', function (e) { if (!e.touches.length) touch = null; });\n  function toWorld(sx, sy) { return { x: (sx - innerWidth / 2) / cam.s + cam.x, y: (sy - innerHeight / 2) / cam.s + cam.y }; }\n\n  function controls() {\n    var me = room.mine();\n    if (!me) return;\n    var mx = (keys.d || keys.arrowright ? 1 : 0) - (keys.a || keys.arrowleft ? 1 : 0);\n    var my = (keys.s || keys.arrowdown ? 1 : 0) - (keys.w || keys.arrowup ? 1 : 0);\n    var ax = me.ax, ay = me.ay, fire = false;\n    if (touch) {\n      var t = toWorld(touch.x, touch.y);\n      var dx = t.x - me.x, dy = t.y - me.y, l = Math.sqrt(dx * dx + dy * dy);\n      if (l > 20) { mx = dx / l; my = dy / l; }\n      var foe = nearest(me, 520);\n      if (foe) { ax = foe.x - me.x; ay = foe.y - me.y; fire = true; } else if (l > 20) { ax = dx; ay = dy; }\n    } else if (mouse.seen) {\n      var m = toWorld(mouse.x, mouse.y);\n      ax = m.x - me.x; ay = m.y - me.y;\n    }\n    if (mouse.down || keys[' ']) fire = true;\n    if (mouse.alt || keys.e) fire = 1; // weapon 1: the rail\n    room.setInput({ mx: mx, my: my, ax: ax, ay: ay, fire: fire });\n  }\n  function nearest(me, range) {\n    var best = null, bd = range * range;\n    room.entities().forEach(function (e) {\n      if (e.dead) return;\n      var d = (e.x - me.x) * (e.x - me.x) + (e.y - me.y) * (e.y - me.y);\n      if (d < bd) { bd = d; best = e; }\n    });\n    return best;\n  }\n\n  // ---- drawing -----------------------------------------------------------------------------\n  function resize() {\n    var dpr = Math.min(devicePixelRatio || 1, 2);\n    canvas.width = innerWidth * dpr; canvas.height = innerHeight * dpr;\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n  }\n  addEventListener('resize', resize);\n  resize();\n  function hue(id) { var p = room.players[id]; return p ? (p.seat * 67 + 20) % 360 : 0; }\n\n  function drawPlayer(id, e, name, isMe) {\n    if (!e || e.dead) return;\n    var h = hue(id), r = cfg.players.radius;\n    ctx.save();\n    ctx.translate(e.x, e.y);\n    ctx.shadowColor = 'hsl(' + h + ',100%,60%)'; ctx.shadowBlur = 18;\n    ctx.fillStyle = 'hsl(' + h + ',90%,' + (isMe ? 62 : 52) + '%)';\n    ctx.beginPath(); ctx.arc(0, 0, r, 0, Math.PI * 2); ctx.fill();\n    ctx.shadowBlur = 0;\n    var al = Math.sqrt(e.ax * e.ax + e.ay * e.ay) || 1;\n    ctx.strokeStyle = '#fff'; ctx.lineWidth = 4; ctx.lineCap = 'round';\n    ctx.beginPath(); ctx.moveTo(e.ax / al * 8, e.ay / al * 8); ctx.lineTo(e.ax / al * (r + 9), e.ay / al * (r + 9)); ctx.stroke();\n    ctx.fillStyle = '#e9ecff'; ctx.font = '600 13px system-ui, sans-serif'; ctx.textAlign = 'center';\n    ctx.fillText(name, 0, -r - 16);\n    for (var i = 0; i < cfg.players.hp; i++) { ctx.fillStyle = i < e.hp ? '#ff7a1a' : 'rgba(255,255,255,.15)'; ctx.fillRect(-cfg.players.hp * 4.5 + i * 9, -r - 11, 7, 3); }\n    ctx.restore();\n  }\n\n  function draw(now) {\n    var vw = innerWidth, vh = innerHeight;\n    ctx.fillStyle = '#05060f'; ctx.fillRect(0, 0, vw, vh);\n    if (!room || !room.view) return;\n    var W = cfg.world.width, H = cfg.world.height;\n    var me = room.mine();\n    cam.s = Math.max(0.5, Math.min(1.3, Math.min(vw / 1100, vh / 700)));\n    if (me) { cam.x += (me.x - cam.x) * 0.2; cam.y += (me.y - cam.y) * 0.2; }\n    ctx.save();\n    ctx.translate(vw / 2, vh / 2); ctx.scale(cam.s, cam.s); ctx.translate(-cam.x, -cam.y);\n    ctx.strokeStyle = 'rgba(255,122,26,.07)'; ctx.lineWidth = 1;\n    for (var gx = 0; gx <= W; gx += 50) { ctx.beginPath(); ctx.moveTo(gx, 0); ctx.lineTo(gx, H); ctx.stroke(); }\n    for (var gy = 0; gy <= H; gy += 50) { ctx.beginPath(); ctx.moveTo(0, gy); ctx.lineTo(W, gy); ctx.stroke(); }\n    ctx.strokeStyle = '#ff7a1a'; ctx.lineWidth = 4; ctx.shadowColor = '#ff7a1a'; ctx.shadowBlur = 20;\n    ctx.strokeRect(0, 0, W, H);\n    ctx.fillStyle = '#1b1530';\n    (cfg.world.walls || []).forEach(function (w) { ctx.fillRect(w[0], w[1], w[2], w[3]); ctx.strokeRect(w[0], w[1], w[2], w[3]); });\n    ctx.shadowBlur = 0;\n\n    var pulse = 1 + Math.sin(now * 5) * 0.15;\n    room.pickups().forEach(function (k) {\n      var def = cfg.pickups[k.kind];\n      ctx.fillStyle = def && def.heal ? '#6dff8a' : '#ffd84a';\n      ctx.shadowColor = ctx.fillStyle; ctx.shadowBlur = 14;\n      ctx.beginPath(); ctx.arc(k.x, k.y, (def ? def.radius : 9) * pulse, 0, Math.PI * 2); ctx.fill();\n    });\n    ctx.shadowBlur = 0;\n    room.shots().forEach(function (s) {\n      var h = hue(s.owner);\n      ctx.fillStyle = 'hsl(' + h + ',100%,75%)'; ctx.shadowColor = 'hsl(' + h + ',100%,60%)'; ctx.shadowBlur = 10;\n      ctx.beginPath(); ctx.arc(s.x, s.y, cfg.weapons[s.weapon] ? cfg.weapons[s.weapon].radius : 4, 0, Math.PI * 2); ctx.fill();\n    });\n    ctx.shadowBlur = 0;\n    room.rays().forEach(function (r) {\n      ctx.strokeStyle = 'rgba(255,240,200,' + Math.max(0, 1 - (Date.now() - r.at) / 200) + ')'; ctx.lineWidth = 3;\n      ctx.beginPath(); ctx.moveTo(r.x, r.y); ctx.lineTo(r.x + r.ax * r.len, r.y + r.ay * r.len); ctx.stroke();\n    });\n    room.entities().forEach(function (e) { drawPlayer(e.id, e, e.name, false); });\n    if (me) drawPlayer(room.id, me, 'you', true);\n    ctx.restore();\n\n    flashes = flashes.filter(function (f) { return now * 1000 - f.at < 250; });\n    if (flashes.length) { ctx.fillStyle = 'rgba(255,40,40,.18)'; ctx.fillRect(0, 0, vw, vh); }\n    hud(me);\n  }\n\n  var lastHud = 0;\n  function hud(me) {\n    var t = performance.now();\n    if (t - lastHud < 250) return;\n    lastHud = t;\n    var list = room.playerList();\n    $('online').textContent = list.length;\n    $('hp').textContent = me && me.dead ? 'RESPAWNING' : me ? new Array(Math.max(0, Math.min(20, me.hp | 0)) + 1).join('♥ ') : '';\n    var sc = room.scores();\n    var ol = $('scores');\n    ol.textContent = '';\n    list.map(function (p) { return { p: p, s: sc[p.id] || 0 }; }).sort(function (a, b) { return b.s - a.s; }).slice(0, 6).forEach(function (r) {\n      var li = document.createElement('li');\n      if (r.p.id === room.id) li.className = 'me';\n      li.textContent = r.p.name;\n      var sp = document.createElement('span'); sp.textContent = r.s; li.appendChild(sp);\n      ol.appendChild(li);\n    });\n    var rd = room.round();\n    $('round-chip').textContent = rd.phase === 'end' ? 'Next round in ' + Math.ceil(rd.msLeft / 1000) + ' s'\n      : 'Round ' + rd.n + (rd.msLeft >= 0 ? ' · ' + Math.floor(rd.msLeft / 60000) + ':' + ('0' + Math.floor(rd.msLeft / 1000) % 60).slice(-2) : '') + ' · first to ' + cfg.rounds.scoreToWin;\n  }\n\n  function feed(text) {\n    var d = document.createElement('div');\n    d.textContent = text;\n    var f = $('feed');\n    f.appendChild(d);\n    while (f.children.length > 4) f.removeChild(f.firstChild);\n    setTimeout(function () { if (d.parentNode) d.parentNode.removeChild(d); }, 4000);\n  }\n\n  function frame(t) {\n    if (room && room.view) controls();\n    draw(t / 1000);\n    requestAnimationFrame(frame);\n  }\n  requestAnimationFrame(frame);\n})();\n"},{"path":"style.css","content":":root {\n  --bg: #05060f;\n  --ink: #e9ecff;\n  --dim: #8a90b8;\n  --neon: #38f2ff;\n  --hot: #ff3dbb;\n  --gold: #ffd84a;\n  --panel: rgba(12, 14, 34, .86);\n  --font: ui-rounded, \"SF Pro Rounded\", \"Segoe UI\", system-ui, -apple-system, sans-serif;\n}\n* { box-sizing: border-box; }\nhtml, body { margin: 0; height: 100%; background: var(--bg); color: var(--ink); font-family: var(--font); overflow: hidden; touch-action: none; }\ncanvas { display: block; width: 100vw; height: 100vh; }\n\n.overlay { position: fixed; inset: 0; display: grid; place-items: center; background: radial-gradient(ellipse at center, rgba(56, 242, 255, .12), rgba(5, 6, 15, .92) 60%); padding: 16px; }\n.overlay[hidden] { display: none; }\n.panel { width: min(420px, 100%); background: var(--panel); border: 1px solid rgba(56, 242, 255, .35); border-radius: 18px; padding: 28px 24px; text-align: center; box-shadow: 0 0 40px rgba(56, 242, 255, .15), inset 0 0 30px rgba(255, 61, 187, .05); }\nh1 { margin: 0; font-size: clamp(2.2rem, 8vw, 3.2rem); letter-spacing: .04em; text-transform: uppercase; color: var(--neon); text-shadow: 0 0 12px var(--neon), 0 0 36px rgba(56, 242, 255, .5); }\n.tag { margin: 6px 0 22px; color: var(--hot); text-shadow: 0 0 10px rgba(255, 61, 187, .6); }\nform { display: grid; gap: 10px; text-align: left; }\nlabel { font-size: .85rem; color: var(--dim); }\ninput { font: inherit; font-size: 1.1rem; padding: 12px 14px; border-radius: 12px; border: 1px solid rgba(233, 236, 255, .2); background: rgba(0, 0, 0, .4); color: var(--ink); outline: none; }\ninput:focus { border-color: var(--neon); box-shadow: 0 0 0 3px rgba(56, 242, 255, .2); }\nbutton { font: inherit; font-weight: 700; font-size: 1.15rem; letter-spacing: .08em; text-transform: uppercase; padding: 13px; border: 0; border-radius: 12px; cursor: pointer; color: #05060f; background: linear-gradient(90deg, var(--neon), #7cfffb); box-shadow: 0 0 20px rgba(56, 242, 255, .45); }\nbutton:disabled { opacity: .5; cursor: wait; }\n.help { margin: 18px 0 6px; font-size: .85rem; color: var(--dim); line-height: 1.6; }\n.help b { color: var(--ink); }\n.orb-dot { display: inline-block; width: 9px; height: 9px; border-radius: 50%; background: var(--gold); box-shadow: 0 0 8px var(--gold); vertical-align: middle; }\n.status { min-height: 1.3em; color: var(--gold); margin: 8px 0 0; }\n.small { font-size: .75rem; color: var(--dim); margin: 14px 0 0; }\n\n#hud { position: fixed; inset: 0; pointer-events: none; font-size: .9rem; }\n#hud[hidden] { display: none; }\n.chip { position: absolute; background: var(--panel); border: 1px solid rgba(233, 236, 255, .12); border-radius: 999px; padding: 6px 12px; }\n.chip.warn { left: 50%; top: 50%; transform: translate(-50%, -50%); border-color: var(--gold); color: var(--gold); }\n#room-chip { left: 12px; top: 12px; }\n#room-chip b { color: var(--neon); letter-spacing: .1em; }\n#me-chip { left: 12px; bottom: 12px; color: var(--hot); letter-spacing: .2em; }\n#scores { position: absolute; right: 12px; top: 12px; margin: 0; padding: 8px 12px 8px 30px; background: var(--panel); border-radius: 12px; border: 1px solid rgba(233, 236, 255, .12); min-width: 160px; }\n#scores li { padding: 2px 0; white-space: nowrap; }\n#scores li.me { color: var(--neon); }\n#scores li span { float: right; margin-left: 14px; color: var(--gold); }\n#feed { position: absolute; left: 50%; top: 12px; transform: translateX(-50%); text-align: center; color: var(--dim); font-size: .85rem; }\n#feed div { animation: fade 4s forwards; }\n@keyframes fade { 0%, 70% { opacity: 1; } 100% { opacity: 0; } }\n@media (max-width: 600px) { #scores { font-size: .78rem; min-width: 120px; } #room-chip { font-size: .78rem; } }\n.orb-dot.heal { background: #6dff8a; box-shadow: 0 0 8px #6dff8a; }\n#round-chip { left: 50%; bottom: 12px; transform: translateX(-50%); color: var(--gold); }\n"},{"path":"thumb.svg","content":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 320 180\">\n  <defs>\n    <radialGradient id=\"bg\" cx=\"50%\" cy=\"50%\" r=\"70%\"><stop offset=\"0\" stop-color=\"#101a3a\"/><stop offset=\"1\" stop-color=\"#05060f\"/></radialGradient>\n    <filter id=\"glow\" x=\"-50%\" y=\"-50%\" width=\"200%\" height=\"200%\"><feGaussianBlur stdDeviation=\"3\" result=\"b\"/><feMerge><feMergeNode in=\"b\"/><feMergeNode in=\"SourceGraphic\"/></feMerge></filter>\n    <pattern id=\"grid\" width=\"20\" height=\"20\" patternUnits=\"userSpaceOnUse\"><path d=\"M20 0H0V20\" fill=\"none\" stroke=\"#ff7a1a\" stroke-opacity=\".12\"/></pattern>\n  </defs>\n  <rect width=\"320\" height=\"180\" fill=\"url(#bg)\"/>\n  <rect width=\"320\" height=\"180\" fill=\"url(#grid)\"/>\n  <rect x=\"8\" y=\"8\" width=\"304\" height=\"164\" rx=\"6\" fill=\"none\" stroke=\"#ff7a1a\" stroke-width=\"3\" filter=\"url(#glow)\"/>\n  <g filter=\"url(#glow)\">\n    <circle cx=\"92\" cy=\"104\" r=\"14\" fill=\"#ff7a1a\"/><line x1=\"98\" y1=\"100\" x2=\"124\" y2=\"86\" stroke=\"#fff\" stroke-width=\"4\" stroke-linecap=\"round\"/>\n    <circle cx=\"222\" cy=\"66\" r=\"14\" fill=\"#ff3dbb\"/><line x1=\"216\" y1=\"70\" x2=\"192\" y2=\"84\" stroke=\"#fff\" stroke-width=\"4\" stroke-linecap=\"round\"/>\n    <circle cx=\"246\" cy=\"132\" r=\"14\" fill=\"#8cff5a\"/>\n    <circle cx=\"150\" cy=\"76\" r=\"4\" fill=\"#ffd2a8\"/><circle cx=\"170\" cy=\"66\" r=\"4\" fill=\"#ffd2a8\"/>\n    <circle cx=\"60\" cy=\"40\" r=\"6\" fill=\"#ffd84a\"/><circle cx=\"160\" cy=\"140\" r=\"6\" fill=\"#ffd84a\"/><circle cx=\"280\" cy=\"40\" r=\"6\" fill=\"#ffd84a\"/>\n  </g>\n</svg>\n"}]}