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

forked from benjivers/val

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

Keyboard shortcuts