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

forked from benjivers/val

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

Keyboard shortcuts