Skip to content

Commit c12e911

Browse files
Stefan-Hankenicolodavis
authored andcommitted
Process only known moves (#151)
* allow a move to declare itself invalid by returning undefined * don't process move that is unknown to the game
1 parent 7fcdbfe commit c12e911

3 files changed

Lines changed: 27 additions & 3 deletions

File tree

src/core/game.test.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ test('basic', () => {
2525
test('processMove', () => {
2626
const testObj = { test: true };
2727
expect(game.processMove(testObj, { type: 'A' })).toEqual(testObj);
28+
expect(game.processMove(testObj, { type: 'C' })).toEqual(testObj);
2829
expect(game.processMove(testObj, { type: 'B' })).toEqual(null);
2930
});
3031

src/core/reducer.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,11 @@ export function createGameReducer({ game, numPlayers, multiplayer }) {
9898
}
9999

100100
case Actions.MAKE_MOVE: {
101+
// check whether the game knows the move at all
102+
if (!game.moveNames.includes(action.payload.type)) {
103+
return state;
104+
}
105+
101106
// Ignore the move if it isn't valid at this point.
102107
if (!game.flow.canMakeMove(state.G, state.ctx, action.payload)) {
103108
return state;
@@ -109,6 +114,11 @@ export function createGameReducer({ game, numPlayers, multiplayer }) {
109114

110115
// Process the move.
111116
let G = game.processMove(state.G, action.payload, ctxWithAPI);
117+
if (G === undefined) {
118+
// the game declared the move as invalid.
119+
return state;
120+
}
121+
112122
// Update ctx with PRNG state.
113123
const ctx = random.update(state.ctx);
114124

src/core/reducer.test.js

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,25 @@ test('_stateID is incremented', () => {
2828

2929
let state = undefined;
3030

31-
state = reducer(state, makeMove('unknown'));
31+
state = reducer(state, makeMove('A'));
3232
expect(state._stateID).toBe(1);
3333
state = reducer(state, endTurn());
3434
expect(state._stateID).toBe(2);
3535
});
3636

37+
test('when a move returns undef => treat as illegal move', () => {
38+
const game = Game({
39+
moves: {
40+
A: G => undefined, // eslint-disable-line no-unused-vars
41+
},
42+
});
43+
const reducer = createGameReducer({ game });
44+
45+
let state = reducer(state, makeMove('A'));
46+
47+
expect(state._stateID).toBe(0);
48+
});
49+
3750
test('makeMove', () => {
3851
const reducer = createGameReducer({ game });
3952

@@ -140,8 +153,8 @@ test('log', () => {
140153

141154
let state = undefined;
142155

143-
const actionA = makeMove('moveA');
144-
const actionB = makeMove('moveB');
156+
const actionA = makeMove('A');
157+
const actionB = makeMove('B');
145158
const actionC = endTurn();
146159

147160
state = reducer(state, actionA);

0 commit comments

Comments
 (0)