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

forked from benjivers/val

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

Keyboard shortcuts