quill/val Public Public: anyone can read this; nobody can change it.
forked from benjivers/val
workbenchthis machine
Files 607c66150cc996b915483fc27c9743896a13c0b4
| 1 | /** |
| 2 | * The arena: one match, always running, and the seats people sit in. |
| 3 | * |
| 4 | * The match ticks whether anybody is watching or not, so a visitor never |
| 5 | * arrives at a frozen board — they get the round that is happening. Taking a |
| 6 | * seat replaces a bot in place: same body, same credits, same position, so |
| 7 | * joining mid-round hands you a live player rather than a lobby. |
| 8 | * |
| 9 | * Every snapshot is built for one viewer: enemies they cannot see are not in |
| 10 | * it. The client never learns a position it has no line of sight to. |
| 11 | */ |
| 12 | |
| 13 | import { agentById, sightBlocked } from "./abilities.ts"; |
| 14 | import { runBots } from "./bots.ts"; |
| 15 | import { recordResult } from "./db.ts"; |
| 16 | import { fallsBetween, marksOf, trimFeed, type Fall, type Mark } from "./killfeed.ts"; |
| 17 | import type { Point } from "./map.ts"; |
| 18 | import { |
| 19 | buyAbility, |
| 20 | buyShield, |
| 21 | buyWeapon, |
| 22 | newMatch, |
| 23 | pickAgent, |
| 24 | setInput, |
| 25 | tick, |
| 26 | visible, |
| 27 | } from "./match.ts"; |
| 28 | import type { MatchState, Player } from "./state.ts"; |
| 29 | import { isWeaponId, WEAPONS } from "./weapons.ts"; |
| 30 | |
| 31 | export const TICK = 1 / 30; |
| 32 | const BROADCAST_EVERY = 2; |
| 33 | |
| 34 | export type Seat = { playerId: string; send: (data: string) => void }; |
| 35 | |
| 36 | let state: MatchState = newMatch(); |
| 37 | const seats = new Map<string, Seat>(); |
| 38 | let ticks = 0; |
| 39 | let lastResult: string | null = null; |
| 40 | // The kill feed is read off the match a tick at a time; the rules keep no |
| 41 | // list of their own, and this is a view, not a rule. |
| 42 | let marks: Mark[] = marksOf(state.players); |
| 43 | let feed: Fall[] = []; |
| 44 | |
| 45 | export const match = (): MatchState => state; |
| 46 | |
| 47 | export const findPlayer = (id: string): Player | undefined => state.players.find((p) => p.id === id); |
| 48 | |
| 49 | /** |
| 50 | * A name nobody else in this match is using. |
| 51 | * |
| 52 | * The kill feed, the round log and the scoreboard all address people by |
| 53 | * name: two players called Kit make a line that reads as a team kill this |
| 54 | * game cannot have. The bots are dealt distinct names; a person who picks |
| 55 | * one that is taken gets a number after it, inside the sixteen characters a |
| 56 | * name is allowed. |
| 57 | */ |
| 58 | function freeName(want: string, exceptId: string): string { |
| 59 | const taken = new Set(state.players.filter((p) => p.id !== exceptId).map((p) => p.name)); |
| 60 | if (!taken.has(want)) return want; |
| 61 | for (let n = 2; n < 100; n++) { |
| 62 | const tried = `${want.slice(0, 13)} ${n}`; |
| 63 | if (!taken.has(tried)) return tried; |
| 64 | } |
| 65 | return want; |
| 66 | } |
| 67 | |
| 68 | /** Sit somebody down in the emptiest team, replacing a bot where it stands. */ |
| 69 | export function takeSeat(session: string, name: string): Player | null { |
| 70 | const existing = seats.get(session); |
| 71 | const held = existing ? findPlayer(existing.playerId) : undefined; |
| 72 | if (held) { |
| 73 | held.name = freeName(name, held.id); |
| 74 | return held; |
| 75 | } |
| 76 | const humans = { red: 0, blue: 0 }; |
| 77 | for (const player of state.players) if (!player.bot) humans[player.team] += 1; |
| 78 | const wanted = humans.red <= humans.blue ? "red" : "blue"; |
| 79 | const seat = |
| 80 | state.players.find((p) => p.bot && p.team === wanted) ?? state.players.find((p) => p.bot); |
| 81 | if (!seat) return null; |
| 82 | seat.bot = false; |
| 83 | seat.name = freeName(name, seat.id); |
| 84 | seat.think = 0; |
| 85 | seat.input = { mx: 0, my: 0, angle: seat.angle, fire: false, use: false, reload: false, cast: null }; |
| 86 | return seat; |
| 87 | } |
| 88 | |
| 89 | export function attach(session: string, playerId: string, send: (data: string) => void): void { |
| 90 | seats.set(session, { playerId, send }); |
| 91 | } |
| 92 | |
| 93 | /** A person leaving gives the seat back to a bot, mid-round and all. */ |
| 94 | export function release(session: string): void { |
| 95 | const seat = seats.get(session); |
| 96 | seats.delete(session); |
| 97 | if (!seat) return; |
| 98 | const player = findPlayer(seat.playerId); |
| 99 | if (player && !stillHeld(seat.playerId)) { |
| 100 | player.bot = true; |
| 101 | player.think = 0; |
| 102 | player.input.fire = false; |
| 103 | player.input.use = false; |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | const stillHeld = (playerId: string): boolean => |
| 108 | [...seats.values()].some((s) => s.playerId === playerId); |
| 109 | |
| 110 | export const seatCount = (): number => seats.size; |
| 111 | |
| 112 | // ------------------------------------------------------------- the commands |
| 113 | |
| 114 | export type Command = { t: string; [key: string]: unknown }; |
| 115 | |
| 116 | const num = (value: unknown): number | undefined => |
| 117 | typeof value === "number" && Number.isFinite(value) ? value : undefined; |
| 118 | |
| 119 | /** Everything a client may ask for, validated here and nowhere else. */ |
| 120 | export function command(playerId: string, message: Command): void { |
| 121 | const player = findPlayer(playerId); |
| 122 | if (!player || player.bot) return; |
| 123 | switch (message.t) { |
| 124 | case "i": |
| 125 | setInput(player, { |
| 126 | mx: num(message.mx), |
| 127 | my: num(message.my), |
| 128 | angle: num(message.a), |
| 129 | fire: typeof message.f === "boolean" ? message.f : undefined, |
| 130 | use: typeof message.u === "boolean" ? message.u : undefined, |
| 131 | reload: typeof message.r === "boolean" ? message.r : undefined, |
| 132 | cast: message.c === "c" || message.c === "q" || message.c === "e" || message.c === "x" ? message.c : undefined, |
| 133 | }); |
| 134 | break; |
| 135 | case "buy": { |
| 136 | const what = String(message.what ?? ""); |
| 137 | if (isWeaponId(what)) buyWeapon(state, player, what); |
| 138 | else if (what === "light" || what === "heavy") buyShield(state, player, what); |
| 139 | else if (what === "c" || what === "q") buyAbility(state, player, what); |
| 140 | break; |
| 141 | } |
| 142 | case "agent": |
| 143 | if (typeof message.id === "string") pickAgent(state, player, message.id); |
| 144 | break; |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // ------------------------------------------------------------- the snapshot |
| 149 | |
| 150 | const round2 = (n: number): number => Math.round(n * 10) / 10; |
| 151 | |
| 152 | export function snapshot(viewerId: string): string { |
| 153 | const me = findPlayer(viewerId) ?? state.players[0]!; |
| 154 | const agent = agentById(me.agent); |
| 155 | const seen = state.players.filter((p) => visible(state, me, p)); |
| 156 | const canSee = (point: Point): boolean => !sightBlocked(me, point, state.zones); |
| 157 | |
| 158 | return JSON.stringify({ |
| 159 | t: "s", |
| 160 | phase: state.phase, |
| 161 | clock: round2(Math.max(0, state.clock)), |
| 162 | round: state.round, |
| 163 | score: state.score, |
| 164 | attackers: state.attackers, |
| 165 | result: state.result, |
| 166 | me: { |
| 167 | id: me.id, |
| 168 | side: me.side, |
| 169 | team: me.team, |
| 170 | agent: me.agent, |
| 171 | alive: me.alive, |
| 172 | x: round2(me.x), |
| 173 | y: round2(me.y), |
| 174 | angle: round2(me.angle), |
| 175 | hp: Math.round(me.hp), |
| 176 | armour: Math.round(me.armour), |
| 177 | credits: me.credits, |
| 178 | weapon: me.weapon, |
| 179 | ammo: me.ammo, |
| 180 | reloading: me.reloadIn > 0, |
| 181 | charges: me.charges, |
| 182 | cooldown: { c: round2(me.cooldown.c), q: round2(me.cooldown.q), e: round2(me.cooldown.e), x: 0 }, |
| 183 | ult: me.ult, |
| 184 | ultNeeds: agent.abilities.x.points, |
| 185 | blind: round2(me.blind), |
| 186 | slow: round2(me.slow), |
| 187 | haste: round2(me.haste), |
| 188 | spike: me.spike, |
| 189 | planting: round2(me.planting), |
| 190 | bot: me.bot, |
| 191 | }, |
| 192 | players: seen.map((p) => ({ |
| 193 | id: p.id, |
| 194 | name: p.name, |
| 195 | agent: p.agent, |
| 196 | x: round2(p.x), |
| 197 | y: round2(p.y), |
| 198 | angle: round2(p.angle), |
| 199 | hp: Math.round(p.hp), |
| 200 | armour: Math.round(p.armour), |
| 201 | alive: p.alive, |
| 202 | mate: p.side === me.side, |
| 203 | spike: p.spike, |
| 204 | blind: p.blind > 0, |
| 205 | revealed: p.revealed > 0, |
| 206 | })), |
| 207 | zones: state.zones |
| 208 | .filter((z) => (z.kind === "trip" ? z.side === me.side : true)) |
| 209 | .map((z) => ({ k: z.kind, x: round2(z.x), y: round2(z.y), r: z.r, f: round2(z.fuse), l: round2(z.life) })), |
| 210 | spike: { |
| 211 | planted: state.spike.planted, |
| 212 | carried: state.spike.carried !== null, |
| 213 | fuse: round2(state.spike.fuse), |
| 214 | defuse: round2(state.spike.defuse), |
| 215 | checkpoint: state.spike.checkpoint, |
| 216 | // A loose spike is the attackers' business until it is armed. |
| 217 | x: state.spike.planted || me.side === "atk" ? round2(state.spike.x) : null, |
| 218 | y: state.spike.planted || me.side === "atk" ? round2(state.spike.y) : null, |
| 219 | }, |
| 220 | orbs: state.orbs.filter((o) => !o.taken).map((o) => ({ x: o.x, y: o.y })), |
| 221 | shots: state.shots.filter((s) => canSee({ x: s.x1, y: s.y1 }) || canSee({ x: s.x2, y: s.y2 })), |
| 222 | board: state.players.map((p) => ({ |
| 223 | id: p.id, |
| 224 | name: p.name, |
| 225 | team: p.team, |
| 226 | side: p.side, |
| 227 | agent: p.agent, |
| 228 | bot: p.bot, |
| 229 | alive: p.alive, |
| 230 | kills: p.kills, |
| 231 | deaths: p.deaths, |
| 232 | damage: Math.round(p.damageDone), |
| 233 | credits: p.team === me.team ? p.credits : null, |
| 234 | ult: p.ult, |
| 235 | ultNeeds: agentById(p.agent).abilities.x.points, |
| 236 | })), |
| 237 | events: state.events.slice(0, 5).map((e) => e.text), |
| 238 | // Names and a gun, never a position: the feed says what happened, not |
| 239 | // where, so it can never be read as a call-out. |
| 240 | feed: feed.map((f) => ({ |
| 241 | k: f.killer, |
| 242 | v: f.victim, |
| 243 | w: f.weapon ? WEAPONS[f.weapon].name : null, |
| 244 | h: f.headshot, |
| 245 | t: round2(Math.max(0, state.now - f.at)), |
| 246 | })), |
| 247 | }); |
| 248 | } |
| 249 | |
| 250 | /** |
| 251 | * Who fell on this tick. A shot that landed this tick and started where the |
| 252 | * killer stands is what tells a gun kill from an ability kill — the position |
| 253 | * is used here and goes no further. |
| 254 | */ |
| 255 | function readFalls(): void { |
| 256 | const after = marksOf(state.players); |
| 257 | const shooters = new Set<string>(); |
| 258 | for (const shot of state.shots) { |
| 259 | if (!shot.hit || shot.age > 0) continue; |
| 260 | for (const player of state.players) |
| 261 | if (Math.hypot(player.x - shot.x1, player.y - shot.y1) < 2) shooters.add(player.id); |
| 262 | } |
| 263 | const falls = fallsBetween(marks, after, { |
| 264 | at: state.now, |
| 265 | events: state.events.slice(0, 6).map((e) => e.text), |
| 266 | shooters, |
| 267 | }); |
| 268 | marks = after; |
| 269 | if (falls.length) feed = [...feed, ...falls]; |
| 270 | feed = trimFeed(feed, state.now); |
| 271 | } |
| 272 | |
| 273 | // ----------------------------------------------------------------- the loop |
| 274 | |
| 275 | function step(): void { |
| 276 | runBots(state, TICK); |
| 277 | tick(state, TICK); |
| 278 | readFalls(); |
| 279 | if (state.result && state.result !== lastResult) { |
| 280 | lastResult = state.result; |
| 281 | recordResult(state.result, state.score.red, state.score.blue, state.round); |
| 282 | } |
| 283 | if (state.result === null) lastResult = null; |
| 284 | ticks += 1; |
| 285 | if (ticks % BROADCAST_EVERY !== 0) return; |
| 286 | for (const seat of seats.values()) { |
| 287 | try { |
| 288 | seat.send(snapshot(seat.playerId)); |
| 289 | } catch { |
| 290 | // A socket that will not take a frame is closed already; the close |
| 291 | // handler gives the seat back. |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | let timer: ReturnType<typeof setInterval> | null = null; |
| 297 | |
| 298 | export function startArena(): void { |
| 299 | if (timer) return; |
| 300 | timer = setInterval(step, TICK * 1000); |
| 301 | // The clock must never hold the process open on its own. |
| 302 | (timer as unknown as { unref?: () => void }).unref?.(); |
| 303 | } |
| 304 | |
| 305 | export function stopArena(): void { |
| 306 | if (timer) clearInterval(timer); |
| 307 | timer = null; |
| 308 | } |
| 309 | |
| 310 | /** Used by the tests: run the arena forward without waiting for real time. */ |
| 311 | export function advance(seconds: number): void { |
| 312 | for (let i = 0; i < Math.round(seconds / TICK); i++) step(); |
| 313 | } |