BlueGit

projects-timfalken-com meteors

Files

meteors / src / rng.js

rng.js

rng.js 874 B Download Raw
1'use strict';
2
3/**
4 * Seedable mulberry32 RNG, so the game core stays deterministic in tests
5 * and (later) for multiplayer replays.
6 */
7function createRng (seed)
8{
9 var a = (seed >>> 0) || 1;
10 return function rng ()
11 {
12 a |= 0;
13 a = a + 0x6D2B79F5 | 0;
14 var t = Math.imul(a ^ a >>> 15, 1 | a);
15 t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
16 return ((t ^ t >>> 14) >>> 0) / 4294967296;
17 };
18}
19
20function pickIndex (rng, count)
21{
22 var n = count | 0;
23 if (n <= 0)
24 { return 0; }
25 return Math.floor(rng() * n) % n;
26}
27
28function pickFrom (rng, list)
29{
30 if (!list || !list.length)
31 { return undefined; }
32 return list[pickIndex(rng, list.length)];
33}
34
35var Rng = {
36 create: createRng,
37 pickIndex: pickIndex,
38 pickFrom: pickFrom
39};
40
41if (typeof module !== 'undefined' && module.exports)
42{ module.exports = Rng; }
43else if (typeof globalThis !== 'undefined')
44{ globalThis.Rng = Rng; }