Skip to content

Commit

Permalink
Fix events in hooks triggered by a move (#525)
Browse files Browse the repository at this point in the history
* test(core): Add test for events in hooks triggered by a move

* fix(core): Don’t cache dispatch length in Events update method

By not caching the length of the dispatch queue in `Events.update()`, 
events pushed during processing will be handled.

* test(core): Add more tests for infinite loops

* test(core): Fix mistyped hook name
  • Loading branch information
delucis authored and nicolodavis committed Nov 28, 2019
1 parent a9d4be6 commit ef4f24d
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
3 changes: 1 addition & 2 deletions src/core/events.js
Expand Up @@ -40,8 +40,7 @@ export class Events {
* @param {object} state - The state object { G, ctx }.
*/
update(state) {
const length = this.dispatch.length;
for (let i = 0; i < length; i++) {
for (let i = 0; i < this.dispatch.length; i++) {
const item = this.dispatch[i];

// If the turn already ended some other way,
Expand Down
63 changes: 63 additions & 0 deletions src/core/flow.test.js
Expand Up @@ -932,6 +932,40 @@ describe('infinite loops', () => {
client.events.endPhase();
expect(client.getState().ctx.phase).toBe('B');
});

test('loop 3', () => {
const game = {
moves: {
endTurn: (G, ctx) => {
ctx.events.endTurn();
},
},
turn: {
onBegin: (G, ctx) => ctx.events.endTurn(),
},
};
const client = Client({ game });
expect(client.getState().ctx.currentPlayer).toBe('0');
client.moves.endTurn();
expect(client.getState().ctx.currentPlayer).toBe('1');
});

test('loop 4', () => {
const game = {
moves: {
endTurn: (G, ctx) => {
ctx.events.endTurn();
},
},
turn: {
endIf: () => true,
},
};
const client = Client({ game });
expect(client.getState().ctx.currentPlayer).toBe('0');
client.moves.endTurn();
expect(client.getState().ctx.currentPlayer).toBe('1');
});
});

describe('activePlayers', () => {
Expand Down Expand Up @@ -965,3 +999,32 @@ describe('activePlayers', () => {
});
});
});

test('events in hooks triggered by moves should be processed', () => {
const game = {
turn: {
onBegin: (G, ctx) => {
ctx.events.setActivePlayers({ currentPlayer: 'A' });
},
},
moves: {
endTurn: (G, ctx) => {
ctx.events.endTurn();
},
},
};

const client = Client({ game, numPlayers: 3 });

expect(client.getState().ctx.currentPlayer).toBe('0');
expect(client.getState().ctx.activePlayers).toEqual({
'0': 'A',
});

client.moves.endTurn();

expect(client.getState().ctx.currentPlayer).toBe('1');
expect(client.getState().ctx.activePlayers).toEqual({
'1': 'A',
});
});

0 comments on commit ef4f24d

Please sign in to comment.