-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.js
62 lines (61 loc) · 1.61 KB
/
actions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { assign } from 'xstate';
export default {
createDeck: assign({
deck: () => [...Array(4).keys()].map(color =>
[...Array(13).keys()].map(value =>
({ value, color}))
).flat()
}),
resetBoard: assign({
board: c => c.players.map(() => [])
}),
shuffleDeck: assign({
deck: c => c.deck.sort(() => Math.random() - 0.5)
}),
dealDeck: assign({
deck: [],
players: c => c.players.map((player, pi) => {
const deckSliceSize = c.deck.length / c.players.length;
return {
...player,
hand: c.deck.slice(deckSliceSize * pi, deckSliceSize * (1 + pi))
}
})
}),
resetCurrentPlayer: assign(c => {
c.currentPlayerId = 0;
}),
setNextPlayer: assign({
currentPlayerId: c => {
const nextPlayerId = c.currentPlayerId + 1;
return nextPlayerId < c.players.length ? nextPlayerId : 0;
}
}),
play: assign(c => {
const { players } = c;
const card = players[c.currentPlayerId].hand.pop();
c.board[c.currentPlayerId].push(card);
return c;
}),
electRoundWinner: assign({
roundWinnerId: c => {
const lastCards = c.board.map(stack => stack.slice(-1)[0].value);
return lastCards.indexOf(Math.max(...lastCards));
}
}),
collectBoard: assign({
players: c => {
c.players[c.roundWinnerId].folds = [
...c.players[c.roundWinnerId].folds,
...c.board.flat()
];
return c.players;
}
}),
electGameWinner: assign({
gameWinnerId: c => {
const cardsCounts = c.players.map(p => p.folds.length);
return cardsCounts.indexOf(Math.max(...cardsCounts));
}
})
};