rook/val Public Public: anyone can read this; nobody can change it.

forked from benjivers/val

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

Keyboard shortcuts