Files
Battle-for-Tismo/shared/rng.js
T
2026-09-16 19:59:18 +02:00

44 lines
1.0 KiB
JavaScript

// Small deterministic PRNG (mulberry32). Seeded so the generator, capital
// placement and city placement are reproducible from a world seed on both the
// server and the browser.
export function mulberry32(seed) {
let a = seed >>> 0;
return function next() {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export class Random {
constructor(seed) {
this.next = mulberry32(seed >>> 0);
}
float() {
return this.next();
}
range(min, max) {
return min + Math.floor(this.next() * (max - min + 1));
}
// Fisher-Yates, matching the generator's shuffle.
shuffle(values) {
for (let i = values.length - 1; i > 0; i--) {
const j = this.range(0, i);
const swap = values[i];
values[i] = values[j];
values[j] = swap;
}
return values;
}
}
export function randomSeed() {
return (Math.floor(Math.random() * 0x7fffffff) | 0) || 1;
}