benjivers/val Public Public: anyone can read this; the crew can change it.

Files 67bc3f098ea6832d15a90e6534b7fd9a4d872bfd
426 lines · 15.1 KB · ~4.4k tok Raw History
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; token: string; address: string; send: (data: string) => void };
35
36
let state: MatchState = newMatch();
37
const seats = new Map<string, Seat>();
38
// A session is a cookie, and a cookie costs one HTTP request — free for
39
// anyone to mint as many of as they like. The address is the one thing here
40
// a single machine cannot hand itself two of, so it is what a playing seat
41
// is actually rationed by; the session on top of it is only what lets a
42
// reload find its way back to the same seat rather than a fresh one.
43
const addressSeats = new Map<string, string>();
44
let ticks = 0;
45
let lastResult: string | null = null;
46
// The kill feed is read off the match a tick at a time; the rules keep no
47
// list of their own, and this is a view, not a rule.
48
let marks: Mark[] = marksOf(state.players);
49
let feed: Fall[] = [];
50
51
export const match = (): MatchState => state;
52
53
export const findPlayer = (id: string): Player | undefined => state.players.find((p) => p.id === id);
54
55
/**
56
 * A name nobody else in this match is using.
57
 *
58
 * The kill feed, the round log and the scoreboard all address people by
59
 * name: two players called Kit make a line that reads as a team kill this
60
 * game cannot have. The bots are dealt distinct names; a person who picks
61
 * one that is taken gets a number after it, inside the sixteen characters a
62
 * name is allowed.
63
 */
64
function freeName(want: string, exceptId: string): string {
65
  const taken = new Set(state.players.filter((p) => p.id !== exceptId).map((p) => p.name));
66
  if (!taken.has(want)) return want;
67
  for (let n = 2; n < 100; n++) {
68
    const tried = `${want.slice(0, 13)} ${n}`;
69
    if (!taken.has(tried)) return tried;
70
  }
71
  return want;
72
}
73
74
/**
75
 * Whether this address already plays under a different session. Checked
76
 * before a socket is even offered a seat, so the caller can hand it a
77
 * spectator view instead of upgrading it into a second side's vision.
78
 */
79
export function addressCapped(address: string, session: string): boolean {
80
  const holder = addressSeats.get(address);
81
  return holder !== undefined && holder !== session;
82
}
83
84
/**
85
 * Sit somebody down in the emptiest team, replacing a bot where it stands.
86
 *
87
 * Both claims go in right here, synchronously, before the caller ever opens
88
 * a socket. A websocket upgrade completes on a later tick, so two requests
89
 * arriving close together both used to read the maps before either had
90
 * written to them — one client, two seats, opposite sides, the vision of
91
 * both. Claiming inline closes that window regardless of how the two
92
 * requests were related.
93
 */
94
export function takeSeat(address: string, session: string, name: string): Player | null {
95
  const existing = seats.get(session);
96
  const held = existing ? findPlayer(existing.playerId) : undefined;
97
  if (held) {
98
    held.name = freeName(name, held.id);
99
    return held;
100
  }
101
  if (addressCapped(address, session)) return null;
102
  const humans = { red: 0, blue: 0 };
103
  for (const player of state.players) if (!player.bot) humans[player.team] += 1;
104
  const wanted = humans.red <= humans.blue ? "red" : "blue";
105
  const seat =
106
    state.players.find((p) => p.bot && p.team === wanted) ?? state.players.find((p) => p.bot);
107
  if (!seat) return null;
108
  seat.bot = false;
109
  seat.name = freeName(name, seat.id);
110
  seat.think = 0;
111
  seat.input = { mx: 0, my: 0, angle: seat.angle, fire: false, use: false, reload: false, cast: null };
112
  addressSeats.set(address, session);
113
  seats.set(session, { playerId: seat.id, token: "", address, send: () => {} });
114
  return seat;
115
}
116
117
/** The socket that actually opened fills in how to reach it and its token. */
118
export function attach(session: string, playerId: string, address: string, token: string, send: (data: string) => void): void {
119
  seats.set(session, { playerId, token, address, send });
120
}
121
122
/**
123
 * A person leaving gives the seat back to a bot, mid-round and all — but only
124
 * if this is still the socket the session is on. A reload opens the new
125
 * socket before the old one's close event arrives; without the token, that
126
 * late close would delete the reconnect's seat entry and hand a live human's
127
 * seat to a bot mid-round.
128
 */
129
export function release(session: string, token: string): void {
130
  const seat = seats.get(session);
131
  if (!seat || seat.token !== token) return;
132
  seats.delete(session);
133
  if (addressSeats.get(seat.address) === session) addressSeats.delete(seat.address);
134
  const player = findPlayer(seat.playerId);
135
  if (player && !stillHeld(seat.playerId)) {
136
    player.bot = true;
137
    player.think = 0;
138
    player.input.fire = false;
139
    player.input.use = false;
140
  }
141
}
142
143
/**
144
 * Test-only hygiene: give back whatever this address currently holds. The
145
 * arena is one match shared by the whole test run, over real HTTP, from one
146
 * loopback address — this is how a test that needs that address free gets it
147
 * free, rather than depending on every other test in the file to clean up
148
 * after itself.
149
 */
150
export function releaseAddress(address: string): void {
151
  const session = addressSeats.get(address);
152
  if (session !== undefined) release(session, seats.get(session)?.token ?? "");
153
}
154
155
const stillHeld = (playerId: string): boolean =>
156
  [...seats.values()].some((s) => s.playerId === playerId);
157
158
export const seatCount = (): number => seats.size;
159
160
// -------------------------------------------------------------- spectators
161
162
// A connection that never carried a session the page minted gets no side and
163
// no seat: only the public state everyone already sees on the page itself.
164
const spectators = new Map<string, (data: string) => void>();
165
166
export function spectatorSnapshot(): string {
167
  return JSON.stringify({
168
    t: "s",
169
    spectator: true,
170
    phase: state.phase,
171
    clock: round2(Math.max(0, state.clock)),
172
    round: state.round,
173
    score: state.score,
174
    attackers: state.attackers,
175
    result: state.result,
176
    events: state.events.slice(0, 5).map((e) => e.text),
177
  });
178
}
179
180
export function watch(token: string, send: (data: string) => void): void {
181
  spectators.set(token, send);
182
  send(spectatorSnapshot());
183
}
184
185
export function unwatch(token: string): void {
186
  spectators.delete(token);
187
}
188
189
// ------------------------------------------------------------- the commands
190
191
export type Command = { t: string; [key: string]: unknown };
192
193
const num = (value: unknown): number | undefined =>
194
  typeof value === "number" && Number.isFinite(value) ? value : undefined;
195
196
/** Everything a client may ask for, validated here and nowhere else. */
197
export function command(playerId: string, message: Command): void {
198
  const player = findPlayer(playerId);
199
  if (!player || player.bot) return;
200
  switch (message.t) {
201
    case "i":
202
      setInput(player, {
203
        mx: num(message.mx),
204
        my: num(message.my),
205
        angle: num(message.a),
206
        fire: typeof message.f === "boolean" ? message.f : undefined,
207
        use: typeof message.u === "boolean" ? message.u : undefined,
208
        reload: typeof message.r === "boolean" ? message.r : undefined,
209
        cast: message.c === "c" || message.c === "q" || message.c === "e" || message.c === "x" ? message.c : undefined,
210
      });
211
      break;
212
    case "buy": {
213
      const what = String(message.what ?? "");
214
      if (isWeaponId(what)) buyWeapon(state, player, what);
215
      else if (what === "light" || what === "heavy") buyShield(state, player, what);
216
      else if (what === "c" || what === "q") buyAbility(state, player, what);
217
      break;
218
    }
219
    case "agent":
220
      if (typeof message.id === "string") pickAgent(state, player, message.id);
221
      break;
222
  }
223
}
224
225
// ------------------------------------------------------------- the snapshot
226
227
const round2 = (n: number): number => Math.round(n * 10) / 10;
228
229
export function snapshot(viewerId: string): string {
230
  const me = findPlayer(viewerId) ?? state.players[0]!;
231
  const agent = agentById(me.agent);
232
  const seen = state.players.filter((p) => visible(state, me, p));
233
  const canSee = (point: Point): boolean => !sightBlocked(me, point, state.zones);
234
235
  return JSON.stringify({
236
    t: "s",
237
    phase: state.phase,
238
    clock: round2(Math.max(0, state.clock)),
239
    round: state.round,
240
    score: state.score,
241
    attackers: state.attackers,
242
    result: state.result,
243
    me: {
244
      id: me.id,
245
      side: me.side,
246
      team: me.team,
247
      agent: me.agent,
248
      alive: me.alive,
249
      x: round2(me.x),
250
      y: round2(me.y),
251
      angle: round2(me.angle),
252
      hp: Math.round(me.hp),
253
      armour: Math.round(me.armour),
254
      credits: me.credits,
255
      weapon: me.weapon,
256
      ammo: me.ammo,
257
      reloading: me.reloadIn > 0,
258
      charges: me.charges,
259
      cooldown: { c: round2(me.cooldown.c), q: round2(me.cooldown.q), e: round2(me.cooldown.e), x: 0 },
260
      ult: me.ult,
261
      ultNeeds: agent.abilities.x.points,
262
      blind: round2(me.blind),
263
      slow: round2(me.slow),
264
      haste: round2(me.haste),
265
      spike: me.spike,
266
      planting: round2(me.planting),
267
      // Your own two ways of being held still, so the browser's prediction
268
      // of your own body runs at the speed the server is about to use.
269
      defusing: me.defusing > 0,
270
      bot: me.bot,
271
    },
272
    players: seen.map((p) => ({
273
      id: p.id,
274
      name: p.name,
275
      agent: p.agent,
276
      x: round2(p.x),
277
      y: round2(p.y),
278
      angle: round2(p.angle),
279
      hp: Math.round(p.hp),
280
      armour: Math.round(p.armour),
281
      alive: p.alive,
282
      mate: p.side === me.side,
283
      spike: p.spike,
284
      blind: p.blind > 0,
285
      revealed: p.revealed > 0,
286
    })),
287
    zones: state.zones
288
      .filter((z) => (z.kind === "trip" ? z.side === me.side : true))
289
      .map((z) => ({ k: z.kind, x: round2(z.x), y: round2(z.y), r: z.r, f: round2(z.fuse), l: round2(z.life) })),
290
    spike: {
291
      planted: state.spike.planted,
292
      carried: state.spike.carried !== null,
293
      fuse: round2(state.spike.fuse),
294
      defuse: round2(state.spike.defuse),
295
      checkpoint: state.spike.checkpoint,
296
      // A loose spike is the attackers' business until it is armed.
297
      x: state.spike.planted || me.side === "atk" ? round2(state.spike.x) : null,
298
      y: state.spike.planted || me.side === "atk" ? round2(state.spike.y) : null,
299
    },
300
    orbs: state.orbs.filter((o) => !o.taken).map((o) => ({ x: o.x, y: o.y })),
301
    shots: state.shots.filter((s) => canSee({ x: s.x1, y: s.y1 }) || canSee({ x: s.x2, y: s.y2 })),
302
    board: state.players.map((p) => ({
303
      id: p.id,
304
      name: p.name,
305
      team: p.team,
306
      side: p.side,
307
      agent: p.agent,
308
      bot: p.bot,
309
      alive: p.alive,
310
      kills: p.kills,
311
      deaths: p.deaths,
312
      damage: Math.round(p.damageDone),
313
      credits: p.team === me.team ? p.credits : null,
314
      ult: p.ult,
315
      ultNeeds: agentById(p.agent).abilities.x.points,
316
    })),
317
    events: state.events.slice(0, 5).map((e) => e.text),
318
    // Names and a gun, never a position: the feed says what happened, not
319
    // where, so it can never be read as a call-out.
320
    feed: feed.map((f) => ({
321
      k: f.killer,
322
      v: f.victim,
323
      w: f.weapon ? WEAPONS[f.weapon].name : null,
324
      h: f.headshot,
325
      t: round2(Math.max(0, state.now - f.at)),
326
    })),
327
  });
328
}
329
330
/**
331
 * Who fell on this tick. A shot that landed this tick and started where the
332
 * killer stands is what tells a gun kill from an ability kill — the position
333
 * is used here and goes no further.
334
 */
335
function readFalls(): void {
336
  const after = marksOf(state.players);
337
  const shooters = new Set<string>();
338
  for (const shot of state.shots) {
339
    if (!shot.hit || shot.age > 0) continue;
340
    for (const player of state.players)
341
      if (Math.hypot(player.x - shot.x1, player.y - shot.y1) < 2) shooters.add(player.id);
342
  }
343
  const falls = fallsBetween(marks, after, {
344
    at: state.now,
345
    events: state.events.slice(0, 6).map((e) => e.text),
346
    shooters,
347
  });
348
  marks = after;
349
  if (falls.length) feed = [...feed, ...falls];
350
  feed = trimFeed(feed, state.now);
351
}
352
353
// ----------------------------------------------------------------- the loop
354
355
/**
356
 * Nobody watching, nothing happens.
357
 *
358
 * The arena used to tick around the clock, so bots played out rounds for an
359
 * empty room — burning a share of a small box's CPU and filling the record
360
 * with matches no one saw. The world now freezes when the last connection
361
 * goes and carries on from exactly where it stopped when someone arrives, so
362
 * a visitor never finds a score that ran up while they were away.
363
 *
364
 * A spectator counts as somebody: watching is watching.
365
 */
366
const attended = (): boolean => seats.size > 0 || spectators.size > 0;
367
368
/** How many connections the arena is playing for: seats plus watchers. */
369
export const attendance = (): number => seats.size + spectators.size;
370
371
function step(): void {
372
  runBots(state, TICK);
373
  tick(state, TICK);
374
  readFalls();
375
  if (state.result && state.result !== lastResult) {
376
    lastResult = state.result;
377
    recordResult(state.result, state.score.red, state.score.blue, state.round);
378
  }
379
  if (state.result === null) lastResult = null;
380
  ticks += 1;
381
  if (ticks % BROADCAST_EVERY !== 0) return;
382
  for (const seat of seats.values()) {
383
    try {
384
      seat.send(snapshot(seat.playerId));
385
    } catch {
386
      // A socket that will not take a frame is closed already; the close
387
      // handler gives the seat back.
388
    }
389
  }
390
  for (const send of spectators.values()) {
391
    try {
392
      send(spectatorSnapshot());
393
    } catch {
394
      // Same story: the close handler drops it from the set.
395
    }
396
  }
397
}
398
399
let timer: ReturnType<typeof setInterval> | null = null;
400
401
/**
402
 * One beat of real time. The gate lives here rather than inside `step` so the
403
 * tests can still drive the simulation directly with `advance` — a test is an
404
 * attendance of its own, and making it prove otherwise would only teach the
405
 * suite to work around the rule.
406
 */
407
export function beat(): void {
408
  if (attended()) step();
409
}
410
411
export function startArena(): void {
412
  if (timer) return;
413
  timer = setInterval(beat, TICK * 1000);
414
  // The clock must never hold the process open on its own.
415
  (timer as unknown as { unref?: () => void }).unref?.();
416
}
417
418
export function stopArena(): void {
419
  if (timer) clearInterval(timer);
420
  timer = null;
421
}
422
423
/** Used by the tests: run the arena forward without waiting for real time. */
424
export function advance(seconds: number): void {
425
  for (let i = 0; i < Math.round(seconds / TICK); i++) step();
426
}
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts