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

Files 372b05436df22ae7f5cdcec65fdde6143ac9863f
294 lines · 9.7 KB · ~2.8k 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; 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
/** Sit somebody down in the emptiest team, replacing a bot where it stands. */
50
export function takeSeat(session: string, name: string): Player | null {
51
  const existing = seats.get(session);
52
  const held = existing ? findPlayer(existing.playerId) : undefined;
53
  if (held) {
54
    held.name = name;
55
    return held;
56
  }
57
  const humans = { red: 0, blue: 0 };
58
  for (const player of state.players) if (!player.bot) humans[player.team] += 1;
59
  const wanted = humans.red <= humans.blue ? "red" : "blue";
60
  const seat =
61
    state.players.find((p) => p.bot && p.team === wanted) ?? state.players.find((p) => p.bot);
62
  if (!seat) return null;
63
  seat.bot = false;
64
  seat.name = name;
65
  seat.think = 0;
66
  seat.input = { mx: 0, my: 0, angle: seat.angle, fire: false, use: false, reload: false, cast: null };
67
  return seat;
68
}
69
70
export function attach(session: string, playerId: string, send: (data: string) => void): void {
71
  seats.set(session, { playerId, send });
72
}
73
74
/** A person leaving gives the seat back to a bot, mid-round and all. */
75
export function release(session: string): void {
76
  const seat = seats.get(session);
77
  seats.delete(session);
78
  if (!seat) return;
79
  const player = findPlayer(seat.playerId);
80
  if (player && !stillHeld(seat.playerId)) {
81
    player.bot = true;
82
    player.think = 0;
83
    player.input.fire = false;
84
    player.input.use = false;
85
  }
86
}
87
88
const stillHeld = (playerId: string): boolean =>
89
  [...seats.values()].some((s) => s.playerId === playerId);
90
91
export const seatCount = (): number => seats.size;
92
93
// ------------------------------------------------------------- the commands
94
95
export type Command = { t: string; [key: string]: unknown };
96
97
const num = (value: unknown): number | undefined =>
98
  typeof value === "number" && Number.isFinite(value) ? value : undefined;
99
100
/** Everything a client may ask for, validated here and nowhere else. */
101
export function command(playerId: string, message: Command): void {
102
  const player = findPlayer(playerId);
103
  if (!player || player.bot) return;
104
  switch (message.t) {
105
    case "i":
106
      setInput(player, {
107
        mx: num(message.mx),
108
        my: num(message.my),
109
        angle: num(message.a),
110
        fire: typeof message.f === "boolean" ? message.f : undefined,
111
        use: typeof message.u === "boolean" ? message.u : undefined,
112
        reload: typeof message.r === "boolean" ? message.r : undefined,
113
        cast: message.c === "c" || message.c === "q" || message.c === "e" || message.c === "x" ? message.c : undefined,
114
      });
115
      break;
116
    case "buy": {
117
      const what = String(message.what ?? "");
118
      if (isWeaponId(what)) buyWeapon(state, player, what);
119
      else if (what === "light" || what === "heavy") buyShield(state, player, what);
120
      else if (what === "c" || what === "q") buyAbility(state, player, what);
121
      break;
122
    }
123
    case "agent":
124
      if (typeof message.id === "string") pickAgent(state, player, message.id);
125
      break;
126
  }
127
}
128
129
// ------------------------------------------------------------- the snapshot
130
131
const round2 = (n: number): number => Math.round(n * 10) / 10;
132
133
export function snapshot(viewerId: string): string {
134
  const me = findPlayer(viewerId) ?? state.players[0]!;
135
  const agent = agentById(me.agent);
136
  const seen = state.players.filter((p) => visible(state, me, p));
137
  const canSee = (point: Point): boolean => !sightBlocked(me, point, state.zones);
138
139
  return JSON.stringify({
140
    t: "s",
141
    phase: state.phase,
142
    clock: round2(Math.max(0, state.clock)),
143
    round: state.round,
144
    score: state.score,
145
    attackers: state.attackers,
146
    result: state.result,
147
    me: {
148
      id: me.id,
149
      side: me.side,
150
      team: me.team,
151
      agent: me.agent,
152
      alive: me.alive,
153
      x: round2(me.x),
154
      y: round2(me.y),
155
      angle: round2(me.angle),
156
      hp: Math.round(me.hp),
157
      armour: Math.round(me.armour),
158
      credits: me.credits,
159
      weapon: me.weapon,
160
      ammo: me.ammo,
161
      reloading: me.reloadIn > 0,
162
      charges: me.charges,
163
      cooldown: { c: round2(me.cooldown.c), q: round2(me.cooldown.q), e: round2(me.cooldown.e), x: 0 },
164
      ult: me.ult,
165
      ultNeeds: agent.abilities.x.points,
166
      blind: round2(me.blind),
167
      slow: round2(me.slow),
168
      haste: round2(me.haste),
169
      spike: me.spike,
170
      planting: round2(me.planting),
171
      bot: me.bot,
172
    },
173
    players: seen.map((p) => ({
174
      id: p.id,
175
      name: p.name,
176
      agent: p.agent,
177
      x: round2(p.x),
178
      y: round2(p.y),
179
      angle: round2(p.angle),
180
      hp: Math.round(p.hp),
181
      armour: Math.round(p.armour),
182
      alive: p.alive,
183
      mate: p.side === me.side,
184
      spike: p.spike,
185
      blind: p.blind > 0,
186
      revealed: p.revealed > 0,
187
    })),
188
    zones: state.zones
189
      .filter((z) => (z.kind === "trip" ? z.side === me.side : true))
190
      .map((z) => ({ k: z.kind, x: round2(z.x), y: round2(z.y), r: z.r, f: round2(z.fuse), l: round2(z.life) })),
191
    spike: {
192
      planted: state.spike.planted,
193
      carried: state.spike.carried !== null,
194
      fuse: round2(state.spike.fuse),
195
      defuse: round2(state.spike.defuse),
196
      checkpoint: state.spike.checkpoint,
197
      // A loose spike is the attackers' business until it is armed.
198
      x: state.spike.planted || me.side === "atk" ? round2(state.spike.x) : null,
199
      y: state.spike.planted || me.side === "atk" ? round2(state.spike.y) : null,
200
    },
201
    orbs: state.orbs.filter((o) => !o.taken).map((o) => ({ x: o.x, y: o.y })),
202
    shots: state.shots.filter((s) => canSee({ x: s.x1, y: s.y1 }) || canSee({ x: s.x2, y: s.y2 })),
203
    board: state.players.map((p) => ({
204
      id: p.id,
205
      name: p.name,
206
      team: p.team,
207
      side: p.side,
208
      agent: p.agent,
209
      bot: p.bot,
210
      alive: p.alive,
211
      kills: p.kills,
212
      deaths: p.deaths,
213
      damage: Math.round(p.damageDone),
214
      credits: p.team === me.team ? p.credits : null,
215
      ult: p.ult,
216
      ultNeeds: agentById(p.agent).abilities.x.points,
217
    })),
218
    events: state.events.slice(0, 5).map((e) => e.text),
219
    // Names and a gun, never a position: the feed says what happened, not
220
    // where, so it can never be read as a call-out.
221
    feed: feed.map((f) => ({
222
      k: f.killer,
223
      v: f.victim,
224
      w: f.weapon ? WEAPONS[f.weapon].name : null,
225
      h: f.headshot,
226
      t: round2(Math.max(0, state.now - f.at)),
227
    })),
228
  });
229
}
230
231
/**
232
 * Who fell on this tick. A shot that landed this tick and started where the
233
 * killer stands is what tells a gun kill from an ability kill — the position
234
 * is used here and goes no further.
235
 */
236
function readFalls(): void {
237
  const after = marksOf(state.players);
238
  const shooters = new Set<string>();
239
  for (const shot of state.shots) {
240
    if (!shot.hit || shot.age > 0) continue;
241
    for (const player of state.players)
242
      if (Math.hypot(player.x - shot.x1, player.y - shot.y1) < 2) shooters.add(player.id);
243
  }
244
  const falls = fallsBetween(marks, after, {
245
    at: state.now,
246
    events: state.events.slice(0, 6).map((e) => e.text),
247
    shooters,
248
  });
249
  marks = after;
250
  if (falls.length) feed = [...feed, ...falls];
251
  feed = trimFeed(feed, state.now);
252
}
253
254
// ----------------------------------------------------------------- the loop
255
256
function step(): void {
257
  runBots(state, TICK);
258
  tick(state, TICK);
259
  readFalls();
260
  if (state.result && state.result !== lastResult) {
261
    lastResult = state.result;
262
    recordResult(state.result, state.score.red, state.score.blue, state.round);
263
  }
264
  if (state.result === null) lastResult = null;
265
  ticks += 1;
266
  if (ticks % BROADCAST_EVERY !== 0) return;
267
  for (const seat of seats.values()) {
268
    try {
269
      seat.send(snapshot(seat.playerId));
270
    } catch {
271
      // A socket that will not take a frame is closed already; the close
272
      // handler gives the seat back.
273
    }
274
  }
275
}
276
277
let timer: ReturnType<typeof setInterval> | null = null;
278
279
export function startArena(): void {
280
  if (timer) return;
281
  timer = setInterval(step, TICK * 1000);
282
  // The clock must never hold the process open on its own.
283
  (timer as unknown as { unref?: () => void }).unref?.();
284
}
285
286
export function stopArena(): void {
287
  if (timer) clearInterval(timer);
288
  timer = null;
289
}
290
291
/** Used by the tests: run the arena forward without waiting for real time. */
292
export function advance(seconds: number): void {
293
  for (let i = 0; i < Math.round(seconds / TICK); i++) step();
294
}
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts