Random Number Generator
Seeded random numbers: the same seed always gives the same levels, loot and daily challenges, and a bug can be replayed exactly.
Files: rng.js (the component, no dependencies) and rng.test.mjs (5 tests).
Copy rng.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createRng, dailySeed } from "./rng.js";
const rng = createRng(dailySeed()); // same for everyone today; or createRng("level-3"), createRng(12345)
const x = rng.int(0, 9); // 0..9 inclusive
const enemy = rng.pick(["slime", "bat"]);
const drop = rng.weighted([["coin", 70], ["gem", 25], ["crown", 5]]);
const levelRng = rng.fork("level"); // separate stream: adding a new random call elsewhere won't change levels
const saved = rng.state; rng.state = saved; // save and restore mid-run
API
createRng(seed) → rngseed: number or stringrng.next() → 0 ≤ n < 1rng.int(min, max) inclusive / rng.float(min, max) / rng.chance(p) / rng.sign()rng.pick(array) / rng.shuffle(array) → a new shuffled array / rng.sample(array, n) → n different itemsrng.weighted([[item, weight], ...] | [{ item, weight }, ...])rng.gaussian(mean, sd)bell curverng.fork(label) → a new rng seeded from this seed and the label (doesn't use up numbers from this one)
rng.state (get / set) / rng.seed
hashString(str) → 32-bit number / dailySeed(date) → "YYYY-MM-DD" in UTC
Algorithm: sfc32 seeded with a string hash; fast and good enough for games, not for passwords or gambling.
Engines
| Engine | Notes |
|---|---|
| Vanilla, Phaser, PixiJS, Three.js | yes. Use it instead of Math.random (Phaser’s RandomDataGenerator works too, but this one is the same in every engine). |
Tests
Node tests: same seed same numbers, different seeds differ, ranges are inclusive, rough evenness, weights, shuffle keeps items, sample has no repeats, state restore, forks are independent, daily seed in UTC.
Run them with node --test toolkit/components/rng/ (Node 20 or newer, nothing to install).