UNPKG

@hiddentao/clockwork-engine

Version:

A TypeScript/PIXI.js game engine for deterministic, replayable games with built-in rendering

58 lines (57 loc) 1.63 kB
import alea from "alea"; export class PRNG { constructor(seed) { this.seed = ""; this.rng = alea(); if (seed) { this.reset(seed); } } reset(seed) { this.seed = seed; this.rng = alea(seed); if (PRNG.debug) { console.log(`PRNG.reset() with seed: ${seed}`); } } random() { const result = this.rng(); if (PRNG.debug) { console.log(`PRNG.random(): ${result}`); } return result; } randomInt(min, max) { const result = Math.floor(this.random() * (max - min + 1)) + min; if (PRNG.debug) { console.log(`PRNG.randomInt(${min}, ${max}): ${result}`); } return result; } randomChoice(array) { if (array.length === 0) { throw new Error("Cannot choose from empty array"); } const index = this.randomInt(0, array.length - 1); const result = array[index]; if (PRNG.debug) { console.log(`PRNG.randomChoice(array[${array.length}]): index=${index}, value=${result}`); } return result; } randomFloat(min, max) { const result = this.random() * (max - min) + min; if (PRNG.debug) { console.log(`PRNG.randomFloat(${min}, ${max}): ${result}`); } return result; } randomBoolean(threshold = 0.5) { const result = this.random() < threshold; if (PRNG.debug) { console.log(`PRNG.randomBoolean(${threshold}): ${result}`); } return result; } } PRNG.debug = false;