Last active
May 16, 2022 05:38
-
-
Save samuelsimoes/3234f552d732888c6b0e2f483de084f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Random = require('random-js') | |
const random = new Random(Random.engines.mt19937().autoSeed()) | |
const values = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] | |
const suits = ['d', 'h', 'c', 's'] | |
let originalDeck = | |
suits.reduce((memo, suit) => | |
[...memo, ...values.map(value => `${value}${suit}`)], [] | |
) | |
// EXAMPLE OF THE MINIMAL STATE | |
// { | |
// players: { | |
// <id> : { status: 'inGame' } | |
// }, | |
// seats: [[<position>, <id>], [<position>, <id>], | |
// playersCards: {} | |
// } | |
function shuffleAndGiveCards (state) { | |
let deck = random.shuffle([...originalDeck]) | |
originalDeck = [...deck] | |
let playersCards = {} | |
let inGamePlayersSeats = | |
state | |
.seats | |
.reduce((memo, seat) => { | |
if (state.players[seat[1]].status === 'inGame') { | |
memo.push(seat[1]) | |
} | |
return memo | |
}, []) | |
inGamePlayersSeats | |
.forEach((playerID, playerIndex) => { | |
let cardsIndex = [ | |
playerIndex, | |
(playerIndex + inGamePlayersSeats.length) | |
] | |
playersCards[playerID] = { | |
cards: [ | |
deck[cardsIndex[0]], | |
deck[cardsIndex[1]] | |
], | |
hiding: true | |
} | |
deck[cardsIndex[0]] = null | |
deck[cardsIndex[1]] = null | |
}) | |
deck = deck.filter(card => card) | |
return { | |
...state, | |
playersCards, | |
deck | |
} | |
} |
I.e., something like this would better seed mersenne twister, assuming crypto has a high quality source:
const Crypto = require('crypto')
const seed = new Uint32Array(624);
let dataView = new DataView(seed.buffer);
Crypto.randomFillSync(dataView, dataView.byteOffset, dataView.byteLength)
const random = new Random(Random.engines.mt19937().seedWithArray(seed))
This should only be done once per instance, as it is probably fairly slow.
What was the result? I agree with your assessment and wonder if the implementation of the autoseed has changed
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Are you concerned about the underlying implementation of autoSeed here? Millisecond time stamp + the output of Math.random() doesn't seem like a great seeding source. I don't know if your runtime supports
crypto.getRandomValues
, but it might be a better choice for seeding.