Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix random setup #134

Merged
merged 4 commits into from
Mar 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});