diff --git a/src/core/reducer.js b/src/core/reducer.js index ffbc726f9..54b35e00b 100644 --- a/src/core/reducer.js +++ b/src/core/reducer.js @@ -22,6 +22,10 @@ export function createGameReducer({ game, numPlayers, multiplayer }) { numPlayers = 2; } + // Need to init PRNGState here, otherwise calls to + // Random inside setup() are using undefined. + PRNGState.set({ seed: game.seed }); + const initial = { // User managed state. G: game.setup(numPlayers), @@ -50,7 +54,7 @@ export function createGameReducer({ game, numPlayers, multiplayer }) { }; // Initialize PRNG seed. - initial.ctx._random = { seed: game.seed }; + initial.ctx._random = PRNGState.get(); const state = game.flow.init({ G: initial.G, ctx: initial.ctx }); diff --git a/src/core/reducer.test.js b/src/core/reducer.test.js index 7d99c19fb..99dedad99 100644 --- a/src/core/reducer.test.js +++ b/src/core/reducer.test.js @@ -9,6 +9,7 @@ import Game from './game'; import { createGameReducer } from './reducer'; import { makeMove, gameEvent, restore } from './action-creators'; +import { Random } from './random'; const game = Game({ moves: { @@ -151,3 +152,32 @@ test('log', () => { state = reducer(state, actionC); expect(state.log).toEqual([actionA, actionB, actionC.payload]); }); + +test('using Random inside setup()', () => { + const game1 = Game({ + seed: 'seed1', + setup: () => ({ n: Random.D6() }), + }); + + const game2 = Game({ + seed: 'seed2', + setup: () => ({ n: Random.D6() }), + }); + + const game3 = Game({ + seed: 'seed2', + setup: () => ({ n: Random.D6() }), + }); + + const reducer1 = createGameReducer({ game: game1 }); + const state1 = reducer1(undefined, makeMove()); + + const reducer2 = createGameReducer({ game: game2 }); + const state2 = reducer2(undefined, makeMove()); + + const reducer3 = createGameReducer({ game: game3 }); + const state3 = reducer3(undefined, makeMove()); + + expect(state1.G.n).not.toBe(state2.G.n); + expect(state2.G.n).toBe(state3.G.n); +});