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

forked from benjivers/val

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

Keyboard shortcuts