Skip to content

Commit

Permalink
Fix random setup (#134)
Browse files Browse the repository at this point in the history
* set seed before calling setup()

* drop console.log; drop unnecessary condition

* fix PRNGState initialization
  • Loading branch information
Stefan-Hanke authored and nicolodavis committed Mar 9, 2018
1 parent c50d5ea commit ed09f51
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/core/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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 });

Expand Down
30 changes: 30 additions & 0 deletions src/core/reducer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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);
});

0 comments on commit ed09f51

Please sign in to comment.