1
0
Fork 0

test(minigames): add bomperator engine and registry specs

22 engine tests cover grid seeding, movement, charge fuse/detonation, chain
blasts, kick-push, round end and sudden death. 17 registry tests cover lobby,
seat lifecycle, reconnect window, dissolve below two seats, expiry sweep and XP
reward derivation.
This commit is contained in:
Jason Fraley 2026-10-16 00:32:54 -04:00
parent bfb5cea3c1
commit e29af6bc29
2 changed files with 722 additions and 0 deletions

View file

@ -0,0 +1,413 @@
import { describe, expect, it } from "vitest";
import {
BASE_SPEED_CELLS_PER_S,
BOMB_FUSE_TICKS,
CELL_COUNT,
CRATE_DENSITY,
FLAME_LIFETIME_TICKS,
GRID_H,
GRID_W,
MAX_SUDDEN_DEATH_EXPLOSIONS,
ROUND_END_HOLD_TICKS,
ROUND_TIMER_TICKS,
SPAWN_POINTS,
SUDDEN_DEATH_INTERVAL_TICKS,
applyInput,
createMatchState,
generateGrid,
idx,
tick,
type BomperatorState,
type Bomb,
type CellType,
type Dir,
type Player,
type PowerUpKind,
type SeatDescriptor,
} from "@/lib/minigames/bomperator";
/* ------------------------------------------------------------- test helpers */
/** All-open interior terrain; walls/crates are added explicitly per test. */
function blankGrid(walls: readonly (readonly [number, number])[] = []): CellType[] {
const grid: CellType[] = new Array(CELL_COUNT).fill("empty");
for (const [x, y] of walls) grid[idx(x, y)] = "solid";
return grid;
}
function mkPlayer(seat: number, x: number, y: number, over: Partial<Player> = {}): Player {
return {
seat,
userId: 100 + seat,
name: `P${seat}`,
x,
y,
dir: "down",
alive: true,
invulnerableTicks: 0,
bombsMax: 1,
range: 1,
speed: BASE_SPEED_CELLS_PER_S,
kick: false,
kills: 0,
deaths: 0,
roundsWon: 0,
inputDir: null,
wantDrop: false,
connected: true,
disconnectedAt: null,
...over,
};
}
/** A battle-phase state on a controlled grid, ready to tick. */
function battleState(
players: readonly Player[],
opts: {
grid?: CellType[];
hidden?: (PowerUpKind | null)[];
bombs?: Bomb[];
drops?: BomperatorState["drops"];
roundTimerTicks?: number;
roundTarget?: number;
} = {},
): BomperatorState {
const seats: SeatDescriptor[] = players.map((p) => ({ seat: p.seat, userId: p.userId, name: p.name }));
const base = createMatchState(seats, opts.roundTarget ?? 3, 1234);
return {
...base,
phase: "battle",
grid: opts.grid ?? blankGrid(),
hidden: opts.hidden ?? new Array(CELL_COUNT).fill(null),
players,
bombs: opts.bombs ?? [],
drops: opts.drops ?? [],
roundTimerTicks: opts.roundTimerTicks ?? ROUND_TIMER_TICKS,
};
}
function mkBomb(id: string, ownerSeat: number, x: number, y: number, over: Partial<Bomb> = {}): Bomb {
return {
id,
ownerSeat,
x,
y,
fuseTicks: BOMB_FUSE_TICKS,
range: 1,
kickable: false,
...over,
};
}
const flameAt = (state: BomperatorState, x: number, y: number) =>
state.flames.some((f) => f.x === x && f.y === y);
const bombAt = (state: BomperatorState, x: number, y: number) =>
state.bombs.find((b) => b.x === x && b.y === y);
/** A far-corner bystander so non-combat tests do not end the round on a count of one. */
function idle(seat: number): Player {
return mkPlayer(seat, GRID_W - 2, GRID_H - 2);
}
/* ------------------------------------------------------------- grid layout */
describe("bomperator engine: grid generation", () => {
it("is deterministic for a seed and differs across seeds", () => {
const a = generateGrid(42);
const b = generateGrid(42);
expect(a.grid).toEqual(b.grid);
expect(a.hidden).toEqual(b.hidden);
const c = generateGrid(999);
expect(c.grid).not.toEqual(a.grid);
});
it("lays solid borders and even/even pillars", () => {
const { grid } = generateGrid(7);
expect(grid[idx(0, 0)]).toBe("solid");
expect(grid[idx(GRID_W - 1, GRID_H - 1)]).toBe("solid");
expect(grid[idx(2, 2)]).toBe("solid"); // interior pillar
expect(grid[idx(1, 1)]).toBe("empty"); // lane
});
it("keeps every spawn cell and its escape corridor crate-free", () => {
const { grid } = generateGrid(3);
for (const spawn of SPAWN_POINTS) {
expect(grid[idx(spawn.x, spawn.y)]).toBe("empty");
for (const [dx, dy] of [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
]) {
const x = spawn.x + dx;
const y = spawn.y + dy;
if (x <= 0 || y <= 0 || x >= GRID_W - 1 || y >= GRID_H - 1) continue;
if (x % 2 === 0 && y % 2 === 0) continue; // pillar, allowed solid
expect(grid[idx(x, y)]).not.toBe("crate");
}
}
});
it("hides exactly one power-up under each crate and roughly hits density", () => {
const { grid, hidden } = generateGrid(11);
let crates = 0;
let passable = 0;
for (let i = 0; i < CELL_COUNT; i += 1) {
if (grid[i] === "crate") {
crates += 1;
expect(hidden[i]).not.toBeNull();
} else {
expect(hidden[i]).toBeNull();
}
if (grid[i] !== "solid") passable += 1;
}
// Crates should be a meaningful but not overwhelming share of open ground.
expect(crates / passable).toBeGreaterThan(0.1);
expect(crates / passable).toBeLessThan(CRATE_DENSITY + 0.25);
});
});
/* ---------------------------------------------------------------- movement */
describe("bomperator engine: movement", () => {
it("advances across an open lane and stops flush at a wall", () => {
let state = battleState([mkPlayer(0, 1, 1), idle(1)], { grid: blankGrid([[3, 1]]) });
state = applyInput(state, 0, { dir: "right" as Dir });
// 7 cells/s * 0.05s = 0.35 cells/tick; reaches the wall-adjacent cell 2 quickly.
for (let i = 0; i < 3; i += 1) state = tick(state);
expect(Math.round(state.players[0].x)).toBe(2);
// Keep ticking toward the wall at x=3; must never enter it.
for (let i = 0; i < 20; i += 1) state = tick(state);
expect(state.players[0].x).toBeLessThan(3);
expect(Math.round(state.players[0].x)).toBe(2);
});
it("blocks on a charge without kick, but a kick technician shoves it along", () => {
const bomb = mkBomb("b0", 1, 2, 1);
let blocked = battleState([mkPlayer(0, 1, 1), idle(1)], { bombs: [bomb] });
blocked = applyInput(blocked, 0, { dir: "right" as Dir });
for (let i = 0; i < 10; i += 1) blocked = tick(blocked);
expect(Math.round(blocked.players[0].x)).toBe(1);
expect(bombAt(blocked, 2, 1)).toBeDefined();
let kicker = battleState([mkPlayer(0, 1, 1, { kick: true }), idle(1)], { bombs: [bomb] });
kicker = applyInput(kicker, 0, { dir: "right" as Dir });
kicker = tick(kicker); // one shove
// The charge slid one cell ahead to x=3; the technician is still entering x=2.
expect(bombAt(kicker, 3, 1)).toBeDefined();
expect(bombAt(kicker, 2, 1)).toBeUndefined();
expect(kicker.players[0].x).toBeGreaterThan(1);
expect(kicker.players[0].x).toBeLessThan(2);
});
});
/* -------------------------------------------------------------------- slip */
describe("bomperator engine: slip (glide to rest)", () => {
it("glides forward to the next cell center after releasing mid-stride", () => {
// Off-center heading right, no active input: must complete to cell 2 and stop.
let state = battleState([mkPlayer(0, 1.4, 1, { dir: "right" as Dir }), idle(1)]);
for (let i = 0; i < 10; i += 1) state = tick(state);
expect(state.players[0].x).toBe(2);
expect(state.players[0].y).toBe(1);
expect(Number.isInteger(state.players[0].x)).toBe(true);
});
it("settles back onto the cell being left when the next cell is blocked", () => {
// Wall at x=2 ahead of a rightward slip: never enter it, rest centered on x=1.
let state = battleState([mkPlayer(0, 1.4, 1, { dir: "right" as Dir }), idle(1)], {
grid: blankGrid([[2, 1]]),
});
for (let i = 0; i < 10; i += 1) state = tick(state);
expect(state.players[0].x).toBe(1);
expect(Number.isInteger(state.players[0].x)).toBe(true);
});
it("does not glide when already centered with no input", () => {
let state = battleState([mkPlayer(0, 3, 1, { dir: "right" as Dir }), idle(1)]);
for (let i = 0; i < 5; i += 1) state = tick(state);
expect(state.players[0].x).toBe(3);
expect(state.players[0].y).toBe(1);
});
it("glides vertically and finishes perpendicular alignment before resting", () => {
// Heading down but still drifting onto the lane (x fractional): must end on a
// whole cell, never left between squares.
let state = battleState([mkPlayer(0, 5.4, 5.3, { dir: "down" as Dir }), idle(1)]);
for (let i = 0; i < 20; i += 1) state = tick(state);
expect(Number.isInteger(state.players[0].x)).toBe(true);
expect(Number.isInteger(state.players[0].y)).toBe(true);
expect(state.players[0].y).toBeGreaterThan(5.3);
});
});
/* -------------------------------------------------------------- detonation */
describe("bomperator engine: fuses and detonation", () => {
it("detonates a charge after its fuse and paints a cross flame", () => {
let state = battleState([mkPlayer(0, 7, 9), idle(1)], { bombs: [mkBomb("b0", 0, 7, 6, { range: 1 })] });
for (let i = 0; i < BOMB_FUSE_TICKS - 1; i += 1) state = tick(state);
expect(state.flames.length).toBe(0); // not yet
state = tick(state);
expect(flameAt(state, 7, 6)).toBe(true);
expect(flameAt(state, 6, 6)).toBe(true);
expect(flameAt(state, 8, 6)).toBe(true);
expect(flameAt(state, 7, 5)).toBe(true);
expect(flameAt(state, 7, 7)).toBe(true);
expect(bombAt(state, 7, 6)).toBeUndefined();
});
it("stops a flame arm at a solid wall and destroys the first crate", () => {
const grid = blankGrid([[4, 6]]);
grid[idx(2, 6)] = "crate";
let state = battleState([mkPlayer(0, 7, 9), idle(1)], { grid, hidden: hiddenWith({ "2,6": "range" }) });
state = { ...state, bombs: [mkBomb("b0", 0, 3, 6, { range: 3 })] };
for (let i = 0; i < BOMB_FUSE_TICKS; i += 1) state = tick(state);
// Left arm: crate at (2,6) burns then stops; (1,6) untouched.
expect(flameAt(state, 2, 6)).toBe(true);
expect(flameAt(state, 1, 6)).toBe(false);
// Right arm: wall at (4,6) stops before it.
expect(flameAt(state, 4, 6)).toBe(false);
// The crate is gone and its power-up is exposed as a drop.
expect(state.grid[idx(2, 6)]).toBe("empty");
expect(state.drops.some((d) => d.x === 2 && d.y === 6 && d.kind === "range")).toBe(true);
});
it("chain-detonates a neighbouring charge", () => {
let state = battleState([mkPlayer(0, 7, 9), idle(1)], {
bombs: [
mkBomb("a", 0, 5, 5, { range: 2, fuseTicks: 1 }),
mkBomb("b", 1, 6, 5, { range: 1, fuseTicks: 99 }),
],
});
state = tick(state); // 'a' pops, its arm reaches 'b', 'b' chains
expect(bombAt(state, 5, 5)).toBeUndefined();
expect(bombAt(state, 6, 5)).toBeUndefined();
expect(flameAt(state, 7, 5)).toBe(true); // reached via b's own blast
});
it("shoves a kickable charge instead of detonating it when a flame hits from behind", () => {
let state = battleState([mkPlayer(0, 7, 9), idle(1)], {
bombs: [
mkBomb("a", 0, 5, 5, { range: 3, fuseTicks: 1 }),
mkBomb("b", 1, 6, 5, { range: 1, fuseTicks: 99, kickable: true }),
],
});
state = tick(state);
// 'b' survived and slid to (8,5); only 'a' exploded.
expect(bombAt(state, 8, 5)).toBeDefined();
expect(state.events.filter((e) => e.type === "explosion")).toHaveLength(1);
});
});
/* ------------------------------------------------------------------ combat */
describe("bomperator engine: kills and pickups", () => {
it("kills an exposed technician and credits the bomb owner", () => {
let state = battleState([mkPlayer(0, 3, 5), mkPlayer(1, 6, 5)]);
state = { ...state, bombs: [mkBomb("a", 0, 6, 5, { range: 1, fuseTicks: 1 })] };
state = tick(state);
expect(state.players[1].alive).toBe(false);
expect(state.players[0].kills).toBe(1);
expect(state.players[1].deaths).toBe(1);
});
it("spares a technician still under spawn protection", () => {
let state = battleState([mkPlayer(0, 3, 5), mkPlayer(1, 6, 5, { invulnerableTicks: 5 })]);
state = { ...state, bombs: [mkBomb("a", 0, 6, 5, { range: 1, fuseTicks: 1 })] };
state = tick(state);
expect(state.players[1].alive).toBe(true);
});
it("applies a pickup when walking onto an exposed drop and it persists", () => {
let state = battleState([mkPlayer(0, 5, 5), idle(1)], { drops: [{ x: 6, y: 5, kind: "range" }] });
state = applyInput(state, 0, { dir: "right" as Dir });
for (let i = 0; i < 3; i += 1) state = tick(state);
expect(state.players[0].range).toBe(2);
expect(state.drops.length).toBe(0);
// Persists across further ticks (until the round resets).
state = tick(state);
expect(state.players[0].range).toBe(2);
});
});
/* ------------------------------------------------------- rounds and match */
describe("bomperator engine: round and match resolution", () => {
it("ends the round when one technician remains and awards it", () => {
let state = battleState([mkPlayer(0, 5, 5), mkPlayer(1, 9, 9)]);
state = { ...state, bombs: [mkBomb("a", 0, 9, 9, { range: 1, fuseTicks: 1 })] };
state = tick(state);
expect(state.phase).toBe("roundEnd");
expect(state.roundWinnerSeat).toBe(0);
expect(state.players[0].roundsWon).toBe(1);
});
it("completes the match once a technician reaches the round target", () => {
const champ = mkPlayer(0, 5, 5, { roundsWon: 2 });
let state = battleState([champ, mkPlayer(1, 9, 9)], { roundTarget: 3 });
state = { ...state, bombs: [mkBomb("a", 0, 9, 9, { range: 1, fuseTicks: 1 })] };
state = tick(state);
expect(state.phase).toBe("complete");
expect(state.matchWinnerSeat).toBe(0);
expect(state.endReason).toBe("rounds");
});
it("advances to a fresh countdown round after the end hold", () => {
let state = battleState([mkPlayer(0, 5, 5), mkPlayer(1, 9, 9)]);
state = { ...state, bombs: [mkBomb("a", 0, 9, 9, { range: 1, fuseTicks: 1 })] };
state = tick(state); // -> roundEnd
expect(state.phase).toBe("roundEnd");
const roundIndexBefore = state.roundIndex;
for (let i = 0; i < ROUND_END_HOLD_TICKS + 5 && state.phase === "roundEnd"; i += 1)
state = tick(state);
expect(state.phase).toBe("countdown");
expect(state.roundIndex).toBe(roundIndexBefore + 1);
// Fresh grid: crates exist again and everyone is alive at spawn.
expect(state.players.every((p) => p.alive)).toBe(true);
});
});
/* ------------------------------------------------------------ sudden death */
describe("bomperator engine: sudden death", () => {
it("enters sudden death when the round timer expires and spawns explosions", () => {
let state = battleState([mkPlayer(0, 1, 1), mkPlayer(1, GRID_W - 2, GRID_H - 2)], {
roundTimerTicks: 2,
});
state = tick(state); // timer 1
expect(state.suddenDeath).toBe(false);
state = tick(state); // timer 0 -> sudden death
expect(state.suddenDeath).toBe(true);
// Run past one sudden-death interval; an explosion should have fired.
for (let i = 0; i < SUDDEN_DEATH_INTERVAL_TICKS + 5; i += 1) state = tick(state);
expect(state.suddenDeathExplosions).toBeGreaterThanOrEqual(1);
});
it("calls a draw once the sudden-death explosion budget is exhausted", () => {
// Two technicians far apart with a huge timer already spent in sudden death.
let state = battleState([mkPlayer(0, 1, 1), mkPlayer(1, GRID_W - 2, GRID_H - 2)], {
roundTimerTicks: 1,
});
state = { ...state, suddenDeath: true, suddenDeathExplosions: MAX_SUDDEN_DEATH_EXPLOSIONS };
// Force the guard: keep ticking; the round must resolve rather than loop.
for (let i = 0; i < 5 && state.phase === "battle"; i += 1) state = tick(state);
expect(state.phase).not.toBe("battle");
if (state.phase === "roundEnd") expect(state.roundWinnerSeat).toBeNull();
});
});
/* ----------------------------------------------------------------- helpers */
function hiddenWith(entries: Record<string, PowerUpKind>): (PowerUpKind | null)[] {
const hidden: (PowerUpKind | null)[] = new Array(CELL_COUNT).fill(null);
for (const [key, kind] of Object.entries(entries)) {
const [x, y] = key.split(",").map(Number);
hidden[idx(x, y)] = kind;
}
return hidden;
}
// Silence unused-import lint for constants referenced only in some branches.
void FLAME_LIFETIME_TICKS;

View file

@ -0,0 +1,309 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { getPayload, type Payload } from "payload";
import config from "@payload-config";
import {
INTER_ROUND_COUNTDOWN_TICKS,
MAX_SEATS,
MIN_TO_START,
RECONNECT_WINDOW_MS,
} from "@/lib/minigames/bomperator/constants";
import {
advanceForTests,
clearMatchesForTests,
createMatch,
endMatch,
forceExpireMatch,
getSnapshotFor,
joinMatch,
leaveMatch,
listMatchSummaries,
setAutoTickForTests,
startMatch,
submitInput,
} from "@/lib/minigames/bomperator/registry";
import {
awardBomperatorResult,
computeBomperatorStatsDelta,
readBomperatorStats,
xpForBomperator,
} from "@/lib/minigames/bomperator/stats";
beforeEach(() => {
setAutoTickForTests(false); // drive the sim manually; no wall-clock intervals
clearMatchesForTests();
});
afterEach(() => clearMatchesForTests());
afterAll(() => {
clearMatchesForTests();
setAutoTickForTests(true);
});
/** Bring a freshly started match out of the countdown and into battle. */
function toBattle(matchId: string): void {
advanceForTests(matchId, INTER_ROUND_COUNTDOWN_TICKS + 1);
}
describe("bomperator registry: lobby", () => {
it("seats the host and reports a waiting match", () => {
const matchId = createMatch(9001, "Host");
const summary = listMatchSummaries(9001).find((row) => row.matchId === matchId);
expect(summary?.phase).toBe("waiting");
expect(summary?.seatedCount).toBe(1);
expect(summary?.joined).toBe(true);
expect(listMatchSummaries(9002).find((row) => row.matchId === matchId)?.joined).toBe(false);
});
it("fills seats up to the cap and rejects an extra player", () => {
const matchId = createMatch(9101, "Host");
for (let seat = 1; seat < MAX_SEATS; seat += 1) joinMatch(matchId, 9101 + seat, `P${seat}`);
expect(() => joinMatch(matchId, 9999, "Overflow")).toThrow("full");
});
it("stops a user seating at two matches at once", () => {
createMatch(9201, "Host");
const second = createMatch(9202, "Other");
expect(() => joinMatch(second, 9201, "Host")).toThrow("already in another match");
});
it("lets a non-seated user read a spectator snapshot with no seat", () => {
const matchId = createMatch(9301, "Host");
const view = getSnapshotFor(matchId, 9302);
expect(view.yourSeat).toBeNull();
expect(view.players[0].name).toBe("Host");
});
});
describe("bomperator registry: start gating", () => {
it("refuses to start below the minimum and starts at the minimum", () => {
const matchId = createMatch(9401, "Host");
expect(() => startMatch(matchId, 9401)).toThrow(`at least ${MIN_TO_START}`);
joinMatch(matchId, 9402, "Guest");
const view = startMatch(matchId, 9401);
expect(view.phase).toBe("countdown");
});
it("rejects starting twice", () => {
const matchId = createMatch(9501, "Host");
joinMatch(matchId, 9502, "Guest");
startMatch(matchId, 9501);
expect(() => startMatch(matchId, 9501)).toThrow("already started");
});
});
describe("bomperator registry: input + ticking", () => {
it("applies a queued movement input over subsequent ticks", () => {
const matchId = createMatch(9601, "Host");
joinMatch(matchId, 9602, "Guest");
startMatch(matchId, 9601);
toBattle(matchId);
const before = getSnapshotFor(matchId, 9601);
expect(before.phase).toBe("battle");
expect(before.players[before.yourSeat!].x).toBeCloseTo(1, 3);
submitInput(matchId, 9601, { dir: "right" });
advanceForTests(matchId, 6);
const after = getSnapshotFor(matchId, 9601);
expect(after.players[after.yourSeat!].x).toBeGreaterThan(1.5);
});
it("rejects inputs from a non-seated user", () => {
const matchId = createMatch(9701, "Host");
joinMatch(matchId, 9702, "Guest");
startMatch(matchId, 9701);
expect(() => submitInput(matchId, 9799, { dir: "left" })).toThrow("not in this match");
});
});
describe("bomperator registry: disconnect and dissolve", () => {
it("holds a seat on leave and restores it on rejoin", () => {
const matchId = createMatch(9801, "Host");
joinMatch(matchId, 9802, "Guest");
startMatch(matchId, 9801);
toBattle(matchId);
leaveMatch(matchId, 9801);
expect(getSnapshotFor(matchId, 9802).players[0].connected).toBe(false);
joinMatch(matchId, 9801, "Host"); // rejoin within the window
expect(getSnapshotFor(matchId, 9802).players[0].connected).toBe(true);
});
it("dissolves the match once a held seat's reconnect window lapses", () => {
const matchId = createMatch(9901, "Host");
joinMatch(matchId, 9902, "Guest");
startMatch(matchId, 9901);
toBattle(matchId);
leaveMatch(matchId, 9901); // host walks away
// Advance with a clock past the reconnect window: the seat expires and the
// match drops below two active technicians.
advanceForTests(matchId, 1, Date.now() + RECONNECT_WINDOW_MS + 5_000);
const view = getSnapshotFor(matchId, 9902);
expect(view.phase).toBe("complete");
expect(view.endReason).toBe("dissolved");
});
});
describe("bomperator registry: exit paths", () => {
it("ends the match as soon as the last connected technician leaves", () => {
const matchId = createMatch(9951, "Host");
joinMatch(matchId, 9952, "Guest");
startMatch(matchId, 9951);
toBattle(matchId);
leaveMatch(matchId, 9951); // host walks; guest still connected -> alive
expect(() => getSnapshotFor(matchId, 9952)).not.toThrow();
leaveMatch(matchId, 9952); // last connected leaves -> dissolve + dispose now
expect(() => getSnapshotFor(matchId, 9952)).toThrow("Match not found.");
});
it("lets a seated technician end the drill, but not a stranger", () => {
const matchId = createMatch(9961, "Host");
joinMatch(matchId, 9962, "Guest");
startMatch(matchId, 9961);
toBattle(matchId);
expect(() => endMatch(matchId, 9999)).toThrow("Only a technician");
endMatch(matchId, 9962); // guest can end it
expect(() => getSnapshotFor(matchId, 9961)).toThrow("Match not found.");
});
});
describe("bomperator registry: disposal", () => {
it("force-expiring removes the match", () => {
const matchId = createMatch(9911, "Host");
forceExpireMatch(matchId);
expect(() => getSnapshotFor(matchId, 9911)).toThrow("Match not found.");
});
it("clearing for tests isolates subsequent specs", () => {
createMatch(9921, "Host");
clearMatchesForTests();
expect(listMatchSummaries()).toHaveLength(0);
});
});
describe("bomperator: stat math", () => {
it("reads defaults and accumulates a finished match", () => {
expect(readBomperatorStats({})).toEqual({
matchesPlayed: 0,
matchWins: 0,
roundsWon: 0,
kills: 0,
xpEarned: 0,
});
const win = computeBomperatorStatsDelta(readBomperatorStats({}), {
userId: 1,
won: true,
kills: 3,
roundsWon: 2,
});
expect(win).toEqual({
matchesPlayed: 1,
matchWins: 1,
roundsWon: 2,
kills: 3,
xpEarned: xpForBomperator(true, 3),
});
const loss = computeBomperatorStatsDelta(win, {
userId: 1,
won: false,
kills: 1,
roundsWon: 0,
});
expect(loss.matchesPlayed).toBe(2);
expect(loss.matchWins).toBe(1);
expect(loss.roundsWon).toBe(2);
expect(loss.kills).toBe(4);
});
it("scores XP as a base plus a per-kill bounty", () => {
expect(xpForBomperator(false, 0)).toBeLessThan(xpForBomperator(true, 0));
expect(xpForBomperator(true, 2) - xpForBomperator(true, 1)).toBe(
xpForBomperator(false, 1) - xpForBomperator(false, 0),
);
});
});
describe("bomperator: awards write to the profile (DB round-trip)", () => {
let payload: Payload;
const createdUserIds: number[] = [];
beforeAll(async () => {
payload = await getPayload({ config });
}, 30_000);
afterAll(async () => {
// Order matters: event logs reference the user (actor FK), profiles too.
for (const userId of createdUserIds) {
const events = await payload.find({
collection: "game-event-logs",
where: { actor: { equals: userId } },
limit: 200,
depth: 0,
overrideAccess: true,
});
for (const e of events.docs) {
await payload.delete({ collection: "game-event-logs", id: e.id, overrideAccess: true });
}
const profiles = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 50,
depth: 0,
overrideAccess: true,
});
for (const p of profiles.docs) {
await payload.delete({ collection: "profiles", id: p.id, overrideAccess: true });
}
await payload.delete({ collection: "users", id: userId, overrideAccess: true });
}
});
it("persists stats and derives chips from XP", async () => {
const username = `bomp_${Date.now().toString(36)}_${Math.floor(Math.random() * 1e6)}`;
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: `Bomp ${username}`,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
createdUserIds.push(user.id);
const result = await awardBomperatorResult(payload, "match-abc12345", [
{ userId: user.id, won: true, kills: 2, roundsWon: 1 },
]);
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const group = profileRes.docs[0]?.progression?.minigames?.bomperator;
expect(group).toMatchObject({
matchesPlayed: 1,
matchWins: 1,
roundsWon: 1,
kills: 2,
xpEarned: xpForBomperator(true, 2),
});
// Chips are auto-derived at 10 per XP, so the bank must have grown.
expect((profileRes.docs[0]?.progression?.chipBank ?? 0)).toBeGreaterThan(0);
expect(result.xpByUser[user.id]).toBe(xpForBomperator(true, 2));
});
});