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

Files 0da7ffcb37d59bc652a0ef6ea8768f5a4ee103ff
718 lines · 26.8 KB · ~7.8k tok Raw History
1
/**
2
 * The match: one round loop, server-authoritative, and the only place a
3
 * number changes.
4
 *
5
 * `tick(state, dt)` is the whole game — call it with a fixed step and it
6
 * runs without a clock, a socket or a browser, which is how the tests play
7
 * whole rounds in a millisecond. Inputs arrive as intent (a direction, an
8
 * angle, a held key); nothing a client says is taken as a position.
9
 */
10
11
import { cast, castable, agentById, buyableSlots, flashDuration, sightBlocked, SLOTS } from "./abilities.ts";
12
import { emptyTrack } from "./engine/aim.ts";
13
import { BODY_R, moveSpeed, RUN } from "./engine/glide.ts";
14
import { award, clampCredits, roundReward, spend, START_CREDITS } from "./economy.ts";
15
import {
16
  blockedCircle,
17
  clearPaths,
18
  moveCircle,
19
  orbSpots,
20
  rayHitWall,
21
  segmentPoint,
22
  siteAt,
23
  spawnCells,
24
  type Point,
25
} from "./map.ts";
26
import { emptyInput, type Input, type MatchState, type Player, type Side, type Slot, type Team } from "./state.ts";
27
import { applyDamage, damage, shotSpread, SHIELD, WEAPONS, zoneFromMiss, type WeaponId } from "./weapons.ts";
28
29
// A body's size and the step-and-slide are shared with the browser, which
30
// predicts your own movement between snapshots: `src/engine/glide.ts` is the
31
// one copy. How fast that body moves is decided here alone, by `speedOf`,
32
// and sent as a number — see the note on it.
33
export const PLAYER_R = BODY_R;
34
export const RUN_SPEED = RUN;
35
export const BUY_TIME = 14;
36
export const ROUND_TIME = 100;
37
export const PLANT_TIME = 4;
38
export const FUSE_TIME = 45;
39
export const DEFUSE_TIME = 7;
40
export const DEFUSE_CHECKPOINT = 3.5;
41
export const END_TIME = 5;
42
export const OVER_TIME = 12;
43
export const SWAP_AFTER = 12;
44
export const WIN_ROUNDS = 13;
45
export const ROSTER = 5;
46
export const SPIKE_REACH = 46;
47
48
const TEAMS: Team[] = ["red", "blue"];
49
50
/** Deterministic randomness: the same seed plays the same round. */
51
export function random(state: MatchState): number {
52
  state.seed = (state.seed + 0x6d2b79f5) | 0;
53
  let t = state.seed;
54
  t = Math.imul(t ^ (t >>> 15), t | 1);
55
  t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
56
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
57
}
58
59
const say = (state: MatchState, text: string): void => {
60
  state.events.unshift({ text, age: 0 });
61
  state.events.length = Math.min(state.events.length, 12);
62
};
63
64
export const sideOf = (state: MatchState, team: Team): Side =>
65
  team === state.attackers ? "atk" : "def";
66
67
export const teammates = (state: MatchState, side: Side): Player[] =>
68
  state.players.filter((p) => p.side === side);
69
70
export const aliveOn = (state: MatchState, side: Side): Player[] =>
71
  state.players.filter((p) => p.side === side && p.alive);
72
73
const BOT_NAMES = [
74
  "Ash", "Bex", "Cade", "Dune", "Enzo", "Fay", "Gus", "Hale", "Ivo", "Juno",
75
  "Kit", "Lux", "Mox", "Nell", "Orla", "Pike", "Quill", "Rio", "Sage", "Tove",
76
];
77
78
/**
79
 * Twenty names, shuffled, dealt to the ten seats — drawn without replacement.
80
 *
81
 * A name is how a person is addressed: in the kill feed, in the round log, on
82
 * the scoreboard. Two bots called Kit make "Kit killed Kit", which reads as a
83
 * team kill that this game cannot even have. Picking each name independently
84
 * collided in most matches — a uniform pick over twenty names for ten seats
85
 * is a birthday problem, and no arithmetic spacing survives adding a uniform
86
 * term to it. Shuffling once and dealing cannot collide at all.
87
 */
88
export function dealNames(state: MatchState, count = TEAMS.length * ROSTER): string[] {
89
  const bag = BOT_NAMES.slice();
90
  for (let i = bag.length - 1; i > 0; i--) {
91
    const j = Math.floor(random(state) * (i + 1));
92
    const swap = bag[i]!;
93
    bag[i] = bag[j]!;
94
    bag[j] = swap;
95
  }
96
  return bag.slice(0, Math.min(count, bag.length));
97
}
98
99
/**
100
 * One seat. The name is dealt by the caller so a whole roster is drawn
101
 * without replacement; on its own it falls back to the seat's own slot,
102
 * which is distinct for every seat in a match too.
103
 */
104
export function makePlayer(
105
  state: MatchState,
106
  team: Team,
107
  index: number,
108
  name = BOT_NAMES[(TEAMS.indexOf(team) * ROSTER + index) % BOT_NAMES.length]!,
109
): Player {
110
  const agent = ["ember", "veil", "sable", "mender", "rook"][index % 5]!;
111
  return {
112
    id: `bot-${team}-${index}`,
113
    name: `${name}`,
114
    bot: true,
115
    agent,
116
    team,
117
    side: sideOf(state, team),
118
    x: 0,
119
    y: 0,
120
    angle: 0,
121
    hp: 100,
122
    armour: 0,
123
    alive: true,
124
    credits: START_CREDITS,
125
    weapon: "classic",
126
    ammo: WEAPONS.classic.magazine,
127
    reloadIn: 0,
128
    fireIn: 0,
129
    charges: { c: 0, q: 0, e: 1, x: 0 },
130
    cooldown: { c: 0, q: 0, e: 0, x: 0 },
131
    ult: 0,
132
    blind: 0,
133
    slow: 0,
134
    haste: 0,
135
    revealed: 0,
136
    spike: false,
137
    planting: 0,
138
    defusing: 0,
139
    kills: 0,
140
    deaths: 0,
141
    assists: 0,
142
    damageDone: 0,
143
    input: emptyInput(),
144
    goal: null,
145
    think: 0,
146
    aim: emptyTrack(),
147
    flashedAt: -99,
148
    spray: 0,
149
    joinedAt: 0,
150
  };
151
}
152
153
export function newMatch(seed = Date.now() % 100000): MatchState {
154
  const state: MatchState = {
155
    id: `m${seed.toString(36)}${Math.floor(seed / 7) % 997}`,
156
    phase: "buy",
157
    clock: BUY_TIME,
158
    round: 1,
159
    score: { red: 0, blue: 0 },
160
    attackers: "red",
161
    lossStreak: { red: 0, blue: 0 },
162
    players: [],
163
    zones: [],
164
    nextZone: 1,
165
    spike: { carried: null, x: 0, y: 0, planted: false, fuse: 0, site: null, defuse: 0, checkpoint: 0 },
166
    orbs: orbSpots().map((p) => ({ ...p, taken: false })),
167
    shots: [],
168
    events: [],
169
    result: null,
170
    last: null,
171
    seed,
172
    now: 0,
173
  };
174
  const names = dealNames(state);
175
  for (const team of TEAMS)
176
    for (let i = 0; i < ROSTER; i++)
177
      state.players.push(makePlayer(state, team, i, names[state.players.length]));
178
  startRound(state, true);
179
  say(state, "Round 1 — buy phase");
180
  return state;
181
}
182
183
/** A fresh match on the same seats: an ended match never parks. */
184
export function resetMatch(state: MatchState): void {
185
  const fresh = newMatch((state.seed + 7919) % 100000);
186
  fresh.players = state.players;
187
  fresh.attackers = state.attackers === "red" ? "blue" : "red";
188
  for (const player of fresh.players) {
189
    player.kills = 0;
190
    player.deaths = 0;
191
    player.assists = 0;
192
    player.damageDone = 0;
193
    player.ult = 0;
194
    player.credits = START_CREDITS;
195
    player.weapon = "classic";
196
  }
197
  Object.assign(state, fresh);
198
  startRound(state, true);
199
  say(state, "New match — round 1");
200
}
201
202
function placeAtSpawn(state: MatchState, player: Player, index: number): void {
203
  const cells = spawnCells(player.side);
204
  const spot = cells[index % cells.length]!;
205
  player.x = spot.x + (random(state) - 0.5) * 20;
206
  player.y = spot.y + (random(state) - 0.5) * 20;
207
  const centre = player.side === "atk" ? { x: 1200, y: 400 } : { x: 1200, y: 1200 };
208
  player.angle = Math.atan2(centre.y - player.y, centre.x - player.x);
209
}
210
211
export function startRound(state: MatchState, first = false): void {
212
  clearPaths();
213
  state.phase = "buy";
214
  state.clock = BUY_TIME;
215
  state.zones = [];
216
  state.shots = [];
217
  state.spike = { carried: null, x: 0, y: 0, planted: false, fuse: 0, site: null, defuse: 0, checkpoint: 0 };
218
  state.orbs = orbSpots().map((p) => ({ ...p, taken: false }));
219
220
  const byTeam: Record<Team, number> = { red: 0, blue: 0 };
221
  for (const player of state.players) {
222
    player.side = sideOf(state, player.team);
223
    // A gun survives the round its owner does; armour never does.
224
    if (!player.alive || first) player.weapon = "classic";
225
    player.armour = 0;
226
    player.hp = 100;
227
    player.alive = true;
228
    player.ammo = WEAPONS[player.weapon].magazine;
229
    player.reloadIn = 0;
230
    player.fireIn = 0;
231
    player.blind = 0;
232
    player.slow = 0;
233
    player.haste = 0;
234
    player.revealed = 0;
235
    player.spike = false;
236
    player.planting = 0;
237
    player.defusing = 0;
238
    player.spray = 0;
239
    player.goal = null;
240
    player.think = 0;
241
    player.aim = emptyTrack();
242
    // A new round is a new entry: the team's flash spacing starts clear.
243
    player.flashedAt = -99;
244
    // Basics are bought fresh every round; the signature comes back free.
245
    player.charges = { c: 0, q: 0, e: 1, x: 0 };
246
    player.cooldown = { c: 0, q: 0, e: 0, x: 0 };
247
    if (first) player.credits = START_CREDITS;
248
    placeAtSpawn(state, player, byTeam[player.team]++);
249
    // The keys are let go of, but the facing the spawn gave is kept as the
250
    // input's own: an empty input's angle is zero, and the next tick copies
251
    // the input's angle onto the player, so a round used to point everybody
252
    // at the site and then swing them east a tick later — a camera that
253
    // jumped twice in the first hundred milliseconds of every round.
254
    player.input = { ...emptyInput(), angle: player.angle };
255
  }
256
  giveSpike(state);
257
}
258
259
function giveSpike(state: MatchState): void {
260
  const attackers = aliveOn(state, "atk");
261
  if (attackers.length === 0) return;
262
  const carrier = attackers[Math.floor(random(state) * attackers.length)]!;
263
  carrier.spike = true;
264
  state.spike.carried = carrier.id;
265
  state.spike.x = carrier.x;
266
  state.spike.y = carrier.y;
267
}
268
269
/** Buying is refused server-side: no credits, no gun, no argument. */
270
export function buyWeapon(state: MatchState, player: Player, id: WeaponId): boolean {
271
  if (state.phase !== "buy") return false;
272
  const cost = WEAPONS[id].cost;
273
  const paid = spend(player.credits, cost);
274
  if (!paid.ok) return false;
275
  player.credits = paid.credits;
276
  player.weapon = id;
277
  player.ammo = WEAPONS[id].magazine;
278
  return true;
279
}
280
281
export function buyShield(state: MatchState, player: Player, kind: "light" | "heavy"): boolean {
282
  if (state.phase !== "buy") return false;
283
  const shield = SHIELD[kind];
284
  if (player.armour >= shield.armour) return false;
285
  const paid = spend(player.credits, shield.cost);
286
  if (!paid.ok) return false;
287
  player.credits = paid.credits;
288
  player.armour = shield.armour;
289
  return true;
290
}
291
292
export function buyAbility(state: MatchState, player: Player, slot: Slot): boolean {
293
  if (state.phase !== "buy" || !buyableSlots.includes(slot)) return false;
294
  const ability = agentById(player.agent).abilities[slot];
295
  if (player.charges[slot] >= ability.charges) return false;
296
  const paid = spend(player.credits, ability.cost);
297
  if (!paid.ok) return false;
298
  player.credits = paid.credits;
299
  player.charges[slot] += 1;
300
  return true;
301
}
302
303
export function pickAgent(state: MatchState, player: Player, agent: string): boolean {
304
  if (state.phase !== "buy" || player.charges.c > 0 || player.charges.q > 0) return false;
305
  player.agent = agent;
306
  return true;
307
}
308
309
// ---------------------------------------------------------------- the tick
310
311
export function tick(state: MatchState, dt: number): void {
312
  state.now += dt;
313
  for (const shot of state.shots) shot.age += dt;
314
  state.shots = state.shots.filter((s) => s.age < 0.12);
315
  for (const event of state.events) event.age += dt;
316
317
  if (state.phase === "over") {
318
    state.clock -= dt;
319
    if (state.clock <= 0) resetMatch(state);
320
    return;
321
  }
322
  if (state.phase === "end") {
323
    state.clock -= dt;
324
    if (state.clock <= 0) nextRound(state);
325
    return;
326
  }
327
328
  state.clock -= dt;
329
  if (state.phase === "buy") {
330
    for (const player of state.players) movePlayer(state, player, dt, true);
331
    if (state.clock <= 0) {
332
      state.phase = "live";
333
      state.clock = ROUND_TIME;
334
      say(state, "Round live");
335
    }
336
    return;
337
  }
338
339
  for (const player of state.players) {
340
    if (player.blind > 0) player.blind = Math.max(0, player.blind - dt);
341
    if (player.slow > 0) player.slow = Math.max(0, player.slow - dt);
342
    if (player.haste > 0) player.haste = Math.max(0, player.haste - dt);
343
    if (player.revealed > 0) player.revealed = Math.max(0, player.revealed - dt);
344
    for (const slot of SLOTS)
345
      if (player.cooldown[slot] > 0) {
346
        player.cooldown[slot] = Math.max(0, player.cooldown[slot] - dt);
347
        // The signature charge comes back on its own when the wait is over.
348
        if (player.cooldown[slot] === 0) player.charges[slot] = Math.max(player.charges[slot], 1);
349
      }
350
    player.spray = Math.max(0, player.spray - dt * 6);
351
    if (!player.alive) continue;
352
    movePlayer(state, player, dt, false);
353
    useAbility(state, player);
354
    shoot(state, player, dt);
355
    spikeWork(state, player, dt);
356
    orbs(state, player);
357
  }
358
359
  if (state.spike.planted) state.spike.fuse = Math.max(0, state.spike.fuse - dt);
360
  zones(state, dt);
361
  endConditions(state);
362
}
363
364
/**
365
 * How fast this player moves right now — every reason the match has to speed
366
 * a body up, slow it down or hold it still, in one number.
367
 *
368
 * The browser used to rebuild this from four snapshot fields, which was this
369
 * function written twice and correct only until a fifth reason was added.
370
 * The snapshot carries the answer instead (`me.speed` in `src/arena.ts`), so
371
 * a new rule that stops you arrives as a zero and the prediction stops with
372
 * it without knowing why. Add a reason here and nothing else needs telling.
373
 */
374
export function speedOf(state: MatchState, player: Player): number {
375
  // The phases whose tick returns before it moves anybody, and the dead.
376
  if (state.phase === "end" || state.phase === "over" || !player.alive) return 0;
377
  return moveSpeed({
378
    haste: player.haste > 0,
379
    slow: player.slow > 0,
380
    stopped: player.planting > 0 || player.defusing > 0,
381
    heavy: player.weapon === "operator",
382
  });
383
}
384
385
function movePlayer(state: MatchState, player: Player, dt: number, penned: boolean): void {
386
  if (!player.alive) return;
387
  const input = player.input;
388
  if (Number.isFinite(input.angle)) player.angle = input.angle;
389
  let mx = input.mx;
390
  let my = input.my;
391
  const len = Math.hypot(mx, my);
392
  if (len > 1) {
393
    mx /= len;
394
    my /= len;
395
  }
396
  const speed = speedOf(state, player) * dt;
397
  if (speed === 0 || (mx === 0 && my === 0)) return;
398
  let next = moveCircle(player.x, player.y, mx * speed, my * speed, PLAYER_R);
399
  // In the buy phase nobody leaves their own spawn.
400
  if (penned) {
401
    const cells = spawnCells(player.side);
402
    const near = cells.reduce((best, c) => (Math.hypot(c.x - next.x, c.y - next.y) < Math.hypot(best.x - next.x, best.y - next.y) ? c : best));
403
    if (Math.hypot(near.x - next.x, near.y - next.y) > 120) return;
404
  }
405
  // Walls put down by abilities are as solid as the map's.
406
  for (const zone of state.zones) {
407
    if (!zone.solid || zone.fuse > 0) continue;
408
    const gap = Math.hypot(next.x - zone.x, next.y - zone.y);
409
    if (gap < zone.r + PLAYER_R) {
410
      const push = zone.r + PLAYER_R - gap;
411
      const angle = gap === 0 ? 0 : Math.atan2(next.y - zone.y, next.x - zone.x);
412
      const shoved = { x: next.x + Math.cos(angle) * push, y: next.y + Math.sin(angle) * push };
413
      if (!blockedCircle(shoved.x, shoved.y, PLAYER_R)) next = shoved;
414
      else next = { x: player.x, y: player.y };
415
    }
416
  }
417
  player.x = next.x;
418
  player.y = next.y;
419
}
420
421
function useAbility(state: MatchState, player: Player): void {
422
  const slot = player.input.cast;
423
  if (slot === null) return;
424
  player.input.cast = null;
425
  if (state.phase !== "live" || player.blind > 0.8) return;
426
  if (cast(state, player, slot)) {
427
    const ability = agentById(player.agent).abilities[slot];
428
    if (slot === "x") say(state, `${player.name} used ${ability.name}`);
429
  }
430
}
431
432
function shoot(state: MatchState, player: Player, dt: number): void {
433
  player.fireIn = Math.max(0, player.fireIn - dt);
434
  if (player.reloadIn > 0) {
435
    player.reloadIn -= dt;
436
    if (player.reloadIn <= 0) {
437
      player.ammo = WEAPONS[player.weapon].magazine;
438
      player.reloadIn = 0;
439
    }
440
    return;
441
  }
442
  const weapon = WEAPONS[player.weapon];
443
  if (player.input.reload && player.ammo < weapon.magazine) {
444
    player.input.reload = false;
445
    player.reloadIn = weapon.reload;
446
    return;
447
  }
448
  if (!player.input.fire || player.fireIn > 0) return;
449
  if (!weapon.auto) player.input.fire = false;
450
  if (player.ammo <= 0) {
451
    player.reloadIn = weapon.reload;
452
    return;
453
  }
454
  player.ammo -= 1;
455
  player.fireIn = 1 / weapon.rate;
456
  player.spray = Math.min(6, player.spray + 1);
457
458
  const moving = Math.hypot(player.input.mx, player.input.my) > 0.1 ? 1 : 0;
459
  // Blind aim is a guess: the shot goes somewhere near where you were looking.
460
  const wobble = player.blind > 0 ? 0.5 : 0;
461
  const spread = shotSpread(player.weapon, moving) + player.spray * 0.006 + wobble;
462
  const angle = player.angle + (random(state) - 0.5) * 2 * spread;
463
  const from: Point = { x: player.x, y: player.y };
464
  const wall = rayHitWall(from, angle, weapon.range);
465
  let stop = wall;
466
  // A wall an ability put up stops bullets too; smoke does not.
467
  for (const zone of state.zones) {
468
    if (!zone.solid || zone.fuse > 0) continue;
469
    const near = segmentPoint(from, wall, zone);
470
    if (near.dist <= zone.r && near.travel < Math.hypot(stop.x - from.x, stop.y - from.y))
471
      stop = { x: from.x + Math.cos(angle) * near.travel, y: from.y + Math.sin(angle) * near.travel };
472
  }
473
474
  let best: { target: Player; travel: number; miss: number } | null = null;
475
  for (const other of state.players) {
476
    if (!other.alive || other.side === player.side || other.id === player.id) continue;
477
    const near = segmentPoint(from, stop, other);
478
    if (near.dist > PLAYER_R || near.travel < 1) continue;
479
    if (best === null || near.travel < best.travel) best = { target: other, travel: near.travel, miss: near.dist };
480
  }
481
482
  const end = best ? { x: from.x + Math.cos(angle) * best.travel, y: from.y + Math.sin(angle) * best.travel } : stop;
483
  state.shots.push({ x1: from.x, y1: from.y, x2: end.x, y2: end.y, hit: best !== null, age: 0 });
484
  if (!best) return;
485
486
  const zone = zoneFromMiss(best.miss, PLAYER_R);
487
  const dealt = damage(player.weapon, zone, best.travel);
488
  hurt(state, best.target, dealt, player, zone === "head" ? "headshot" : "");
489
}
490
491
function hurt(state: MatchState, target: Player, amount: number, from: Player | null, note: string): void {
492
  if (!target.alive) return;
493
  const before = target.hp + target.armour;
494
  const after = applyDamage(target.hp, target.armour, amount);
495
  target.hp = after.hp;
496
  target.armour = after.armour;
497
  if (from) from.damageDone += Math.max(0, before - (target.hp + target.armour));
498
  if (target.hp > 0) return;
499
  target.alive = false;
500
  target.deaths += 1;
501
  target.planting = 0;
502
  // A defuse dies with the defender, back to the half-way checkpoint.
503
  if (target.defusing > 0) {
504
    target.defusing = 0;
505
    state.spike.defuse = state.spike.checkpoint;
506
  }
507
  if (target.spike) {
508
    target.spike = false;
509
    state.spike.carried = null;
510
    state.spike.x = target.x;
511
    state.spike.y = target.y;
512
  }
513
  if (from && from.side !== target.side) {
514
    from.kills += 1;
515
    from.credits = award(from.credits, 200);
516
    from.ult = Math.min(10, from.ult + 1);
517
    say(state, `${from.name} ${note === "headshot" ? "headshot" : "killed"} ${target.name}`);
518
  } else {
519
    say(state, `${target.name} died`);
520
  }
521
}
522
523
function spikeWork(state: MatchState, player: Player, dt: number): void {
524
  const spike = state.spike;
525
  if (player.side === "atk" && !spike.planted) {
526
    if (!spike.carried && !player.spike && Math.hypot(player.x - spike.x, player.y - spike.y) < SPIKE_REACH) {
527
      player.spike = true;
528
      spike.carried = player.id;
529
      say(state, `${player.name} picked up the spike`);
530
    }
531
    if (player.spike) {
532
      spike.x = player.x;
533
      spike.y = player.y;
534
      const site = siteAt(player.x, player.y);
535
      if (player.input.use && site) {
536
        player.planting += dt;
537
        if (player.planting >= PLANT_TIME) {
538
          spike.planted = true;
539
          spike.site = site;
540
          spike.fuse = FUSE_TIME;
541
          spike.carried = null;
542
          player.spike = false;
543
          player.planting = 0;
544
          player.ult = Math.min(10, player.ult + 1);
545
          for (const mate of teammates(state, "atk")) mate.credits = award(mate.credits, 300);
546
          say(state, `${player.name} planted on ${site}`);
547
        }
548
      } else player.planting = 0;
549
    }
550
    return;
551
  }
552
  if (player.side === "def" && spike.planted) {
553
    const close = Math.hypot(player.x - spike.x, player.y - spike.y) < SPIKE_REACH;
554
    if (player.input.use && close) {
555
      spike.defuse += dt;
556
      player.defusing = spike.defuse;
557
      // Half way is a checkpoint: the next defender starts from there.
558
      if (spike.defuse >= DEFUSE_CHECKPOINT && spike.checkpoint === 0) {
559
        spike.checkpoint = DEFUSE_CHECKPOINT;
560
        say(state, `${player.name} is half way through the defuse`);
561
      }
562
    } else if (player.defusing > 0) {
563
      player.defusing = 0;
564
      spike.defuse = spike.checkpoint;
565
    }
566
  }
567
}
568
569
function orbs(state: MatchState, player: Player): void {
570
  for (const orb of state.orbs)
571
    if (!orb.taken && Math.hypot(player.x - orb.x, player.y - orb.y) < 40) {
572
      orb.taken = true;
573
      player.ult = Math.min(10, player.ult + 1);
574
      say(state, `${player.name} took an ult orb`);
575
    }
576
}
577
578
function zones(state: MatchState, dt: number): void {
579
  for (const zone of state.zones) {
580
    if (zone.fuse > 0) {
581
      zone.fuse -= dt;
582
      if (zone.fuse > 0) continue;
583
      if (zone.kind === "flash") {
584
        // Pop: everyone inside its radius with a sight line to it, blinded by
585
        // how far their back was turned and how close they stood. Smoke
586
        // between them and it saves them.
587
        for (const player of state.players) {
588
          if (!player.alive) continue;
589
          const blocked = sightBlocked(zone, player, state.zones);
590
          const blind = flashDuration(zone.damage, player, zone, player.angle, blocked, zone.r);
591
          if (blind > 0) player.blind = Math.max(player.blind, blind);
592
        }
593
      }
594
      continue;
595
    }
596
    zone.life -= dt;
597
    zone.beat -= dt;
598
    if (zone.kind === "molly" && zone.beat <= 0) {
599
      zone.beat = 0.5;
600
      const owner = state.players.find((p) => p.id === zone.owner) ?? null;
601
      for (const player of state.players)
602
        if (player.alive && player.side !== zone.side && Math.hypot(player.x - zone.x, player.y - zone.y) <= zone.r)
603
          hurt(state, player, Math.round(zone.damage / 2), owner, "");
604
    }
605
    if (zone.kind === "dart" && zone.beat <= 0 && zone.pulses > 0) {
606
      zone.beat = 1.6;
607
      zone.pulses -= 1;
608
      for (const player of state.players)
609
        if (player.alive && player.side !== zone.side && Math.hypot(player.x - zone.x, player.y - zone.y) <= zone.r && !sightBlocked(zone, player, state.zones))
610
          player.revealed = Math.max(player.revealed, 2);
611
    }
612
    if (zone.kind === "heal" && zone.beat <= 0) {
613
      zone.beat = 0.5;
614
      const target = state.players.find((p) => p.id === zone.owner);
615
      if (target && target.alive) {
616
        target.hp = Math.min(100, target.hp + zone.damage / 6);
617
        zone.x = target.x;
618
        zone.y = target.y;
619
      }
620
    }
621
    if (zone.kind === "trip" && zone.life > 0) {
622
      const caught = state.players.find(
623
        (p) => p.alive && p.side !== zone.side && Math.hypot(p.x - zone.x, p.y - zone.y) <= zone.r,
624
      );
625
      if (caught) {
626
        caught.revealed = Math.max(caught.revealed, 4);
627
        caught.slow = Math.max(caught.slow, 3);
628
        zone.life = 0;
629
        say(state, `${caught.name} tripped a wire`);
630
      }
631
    }
632
    // Blackout: a smoke that carries a slow (marked with negative damage).
633
    if (zone.kind === "smoke" && zone.damage < 0)
634
      for (const player of state.players)
635
        if (player.alive && player.side !== zone.side && Math.hypot(player.x - zone.x, player.y - zone.y) <= zone.r)
636
          player.slow = Math.max(player.slow, 0.5);
637
  }
638
  state.zones = state.zones.filter((z) => z.life > 0 || z.fuse > 0);
639
}
640
641
function endConditions(state: MatchState): void {
642
  const spike = state.spike;
643
  if (spike.planted && spike.defuse >= DEFUSE_TIME) return finishRound(state, "def", "Spike defused");
644
  if (aliveOn(state, "def").length === 0) return finishRound(state, "atk", "Defenders eliminated");
645
  if (aliveOn(state, "atk").length === 0 && !spike.planted)
646
    return finishRound(state, "def", "Attackers eliminated");
647
  if (spike.planted) {
648
    if (spike.fuse <= 0) return finishRound(state, "atk", "Spike detonated");
649
  } else if (state.clock <= 0) return finishRound(state, "def", "Time out");
650
}
651
652
function finishRound(state: MatchState, winners: Side, why: string): void {
653
  const winningTeam: Team = winners === "atk" ? state.attackers : state.attackers === "red" ? "blue" : "red";
654
  const losingTeam: Team = winningTeam === "red" ? "blue" : "red";
655
  state.score[winningTeam] += 1;
656
  state.lossStreak[losingTeam] += 1;
657
  state.lossStreak[winningTeam] = 0;
658
  for (const player of state.players) {
659
    const won = player.team === winningTeam;
660
    player.credits = clampCredits(
661
      player.credits + roundReward(won, state.lossStreak[player.team], state.spike.planted && player.side === "atk"),
662
    );
663
  }
664
  state.phase = "end";
665
  state.clock = END_TIME;
666
  state.last = { round: state.round, winner: winningTeam, why };
667
  say(state, `${why} — ${winningTeam} take round ${state.round} (${state.score.red}–${state.score.blue})`);
668
  if (state.score[winningTeam] >= WIN_ROUNDS) {
669
    state.phase = "over";
670
    state.clock = OVER_TIME;
671
    state.result = `${winningTeam} win ${state.score.red}–${state.score.blue}`;
672
    say(state, `Match over — ${state.result}. A new one starts in ${OVER_TIME} seconds.`);
673
  }
674
}
675
676
function nextRound(state: MatchState): void {
677
  state.round += 1;
678
  // Sides swap once twelve rounds are behind us.
679
  if (state.round === SWAP_AFTER + 1) {
680
    state.attackers = state.attackers === "red" ? "blue" : "red";
681
    say(state, "Sides swap");
682
  }
683
  startRound(state);
684
  say(state, `Round ${state.round} — buy phase`);
685
}
686
687
/** What one player is allowed to see: their own side, and what light reaches. */
688
export function visible(state: MatchState, viewer: Player, other: Player): boolean {
689
  if (other.id === viewer.id || other.side === viewer.side) return true;
690
  if (!other.alive) return false;
691
  if (other.revealed > 0) return true;
692
  if (viewer.blind > 0) return false;
693
  // A dead player watches the round out through their team's eyes, not
694
  // through the walls: what a living team mate can see, and nothing more.
695
  // Otherwise dying and staying connected would be a wallhack to call out.
696
  if (!viewer.alive)
697
    return state.players.some(
698
      (mate) => mate.side === viewer.side && mate.alive && mate.blind <= 0 && !sightBlocked(mate, other, state.zones),
699
    );
700
  return !sightBlocked(viewer, other, state.zones);
701
}
702
703
/** Wraps to (-pi, pi]: a client's own claim of where it looks, kept in range
704
 * rather than left to grow without bound and lose precision against it. */
705
const normalizeAngle = (angle: number): number => ((angle + Math.PI * 3) % (Math.PI * 2)) - Math.PI;
706
707
export function setInput(player: Player, input: Partial<Input>): void {
708
  const target = player.input;
709
  if (typeof input.mx === "number" && Number.isFinite(input.mx)) target.mx = Math.max(-1, Math.min(1, input.mx));
710
  if (typeof input.my === "number" && Number.isFinite(input.my)) target.my = Math.max(-1, Math.min(1, input.my));
711
  if (typeof input.angle === "number" && Number.isFinite(input.angle)) target.angle = normalizeAngle(input.angle);
712
  if (typeof input.fire === "boolean") target.fire = input.fire;
713
  if (typeof input.use === "boolean") target.use = input.use;
714
  if (typeof input.reload === "boolean") target.reload = input.reload;
715
  if (input.cast === "c" || input.cast === "q" || input.cast === "e" || input.cast === "x") target.cast = input.cast;
716
}
717
718
export { castable, agentById };
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts