Skip to content

Instantly share code, notes, and snippets.

@samuelsimoes
Last active May 16, 2022 05:38
Show Gist options
  • Save samuelsimoes/3234f552d732888c6b0e2f483de084f9 to your computer and use it in GitHub Desktop.
Save samuelsimoes/3234f552d732888c6b0e2f483de084f9 to your computer and use it in GitHub Desktop.
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
}
}
@ladd
Copy link

ladd commented May 18, 2020

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.

@smithdouglas404
Copy link

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