rng class..

This commit is contained in:
Zutatensuppe 2020-12-21 18:34:57 +01:00
parent 3ff375dbb4
commit cbc2b88f47
12 changed files with 4762 additions and 25 deletions

View file

@ -7,9 +7,10 @@ function exists(gameId) {
return (!!GAMES[gameId]) || false
}
function createGame(id, puzzle, players, sockets, evtInfos) {
function createGame(id, rng, puzzle, players, sockets, evtInfos) {
return {
id: id,
rng: rng,
puzzle: puzzle,
players: players,
sockets: sockets,
@ -31,8 +32,8 @@ function createPlayer(id, ts) {
}
}
function newGame({id, puzzle, players, sockets, evtInfos}) {
const game = createGame(id, puzzle, players, sockets, evtInfos)
function newGame({id, rng, puzzle, players, sockets, evtInfos}) {
const game = createGame(id, rng, puzzle, players, sockets, evtInfos)
setGame(id, game)
return game
}

27
common/Rng.js Normal file
View file

@ -0,0 +1,27 @@
export class Rng {
constructor(seed) {
this.rand_high = seed || 0xDEADC0DE
this.rand_low = seed ^ 0x49616E42
}
random (min, max) {
this.rand_high = ((this.rand_high << 16) + (this.rand_high >> 16) + this.rand_low) & 0xffffffff;
this.rand_low = (this.rand_low + this.rand_high) & 0xffffffff;
var n = (this.rand_high >>> 0) / 0xffffffff;
return (min + n * (max-min+1))|0;
}
static serialize (rng) {
return {
rand_high: rng.rand_high,
rand_low: rng.rand_low
}
}
static unserialize (rngSerialized) {
const rng = new Rng(0)
rng.rand_high = rngSerialized.rand_high
rng.rand_low = rngSerialized.rand_low
return rng
}
}

View file

@ -1,11 +1,20 @@
import { Rng } from './Rng.js'
// get a unique id
export const uniqId = () => Date.now().toString(36) + Math.random().toString(36).substring(2)
// get a random int between min and max (inclusive)
export const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
export const randomInt = (
/** @type Rng */ rng,
min,
max
) => rng.random(min, max)
// get one random item from the given array
export const choice = (array) => array[randomInt(0, array.length - 1)]
export const choice = (
/** @type Rng */ rng,
array
) => array[randomInt(rng, 0, array.length - 1)]
export const throttle = (fn, delay) => {
let canCall = true
@ -21,11 +30,14 @@ export const throttle = (fn, delay) => {
}
// return a shuffled (shallow) copy of the given array
export const shuffle = (array) => {
export const shuffle = (
/** @type Rng */ rng,
array
) => {
let arr = array.slice()
for (let i = 0; i <= arr.length - 2; i++)
{
const j = randomInt(i, arr.length -1);
const j = randomInt(rng, i, arr.length -1);
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;