Bash.tv → GitHub → itch.io

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

rng.state (get / set) / rng.seed

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).