Files
wikideck/shared/game/rng.ts
T
claudeandClaude Opus 5.5 b5c90d2dc1 Night 1: game engine core and ENGINE_API.md, DESIGN v1 (#25)
Deterministic, off-chain rules engine in shared/game: createMatch, legalActions, applyAction, isOver, result, viewFor, serialisation, Ruleset as data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 04:22:10 +00:00

57 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Seeded, serialisable PRNG for the game engine (off-chain only).
* DESIGN.md §4: mulberry32(seed: uint32). The state is one uint32, so it
* round-trips through JSON and a match can be resumed or replayed exactly.
*/
export type RngState = number;
/** Hash a string seed (e.g. a lobby id) to a uint32 with FNV-1a. */
export function seedFromString(text: string): number {
let h = 0x811c9dc5;
for (let i = 0; i < text.length; i++) {
h ^= text.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return h >>> 0;
}
export function normalizeSeed(seed: number | string): number {
if (typeof seed === 'string') return seedFromString(seed);
if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) throw new RangeError('Seed must be a uint32 or a string');
return seed >>> 0;
}
/** Mutable wrapper over an RngState. The engine keeps `state` inside MatchState. */
export class Rng {
state: RngState;
constructor(state: RngState) { this.state = state >>> 0; }
static fromSeed(seed: number | string): Rng { return new Rng(normalizeSeed(seed)); }
/** mulberry32: float in [0, 1). */
next(): number {
this.state = (this.state + 0x6d2b79f5) >>> 0;
let t = this.state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
/** Integer in [0, n): floor(next() × n), as DESIGN.md §4 specifies. */
int(n: number): number {
if (!Number.isInteger(n) || n <= 0) throw new RangeError('Rng.int needs a positive integer bound');
return Math.floor(this.next() * n);
}
pick<T>(items: readonly T[]): T {
if (!items.length) throw new RangeError('Rng.pick on empty list');
return items[this.int(items.length)];
}
/** Fisher–Yates per DESIGN.md §4: i from n−1 down to 1, j = floor(next() × (i+1)). Returns a new array. */
shuffle<T>(items: readonly T[]): T[] {
const out = items.slice();
for (let i = out.length - 1; i > 0; i--) {
const j = this.int(i + 1);
[out[i], out[j]] = [out[j], out[i]];
}
return out;
}
}