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

forked from benjivers/val

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

Keyboard shortcuts