Skip to content

Instantly share code, notes, and snippets.

@kwiss
Last active May 8, 2020 23:14
Show Gist options
  • Save kwiss/2de03f29fa99639b873b2ab05c0f04db to your computer and use it in GitHub Desktop.
Save kwiss/2de03f29fa99639b873b2ab05c0f04db to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const { cancel } = actions;
const incrementPlayer = assign({
currentPlayer: (context) => {
const currentPlayer =
context.currentPlayer === 4 ? 1 : context.currentPlayer + 1;
return currentPlayer;
},
});
const incrementTurn = assign({
currentTurn: (context) => {
const currentTurn =
context.currentPlayer === 1
? context.currentTurn + 1
: context.currentTurn;
return currentTurn;
},
});
const sendIncrementAfter10Second = send('TIMER', {
delay: 10000,
id: 'incrementTimer', // give the event a unique ID
});
const cancelTimer = cancel('incrementTimer');
const gameIsOver = (context) => {
return context.currentTurn === 10 && context.currentPlayer === 4;
};
const gameMachine = Machine(
{
id: 'game',
initial: 'idle',
context: {
currentPlayer: 0,
currentTurn: 0,
},
states: {
idle: {
on: {
START: {
target: 'autoIncrementing',
actions: ['start', 'notify'],
},
},
},
autoIncrementing: {
entry: sendIncrementAfter10Second,
on: {
'': {
target: 'end',
cond: 'gameIsOver',
},
TIMER: {
target: 'autoIncrementing',
actions: ['incrementPlayer', 'incrementTurn', 'notify'],
},
INCREMENT: {
target: 'autoIncrementing',
actions: [
cancelTimer,
'incrementPlayer',
'incrementTurn',
'notify',
],
},
},
},
end: {},
},
},
{
actions: {
incrementPlayer,
incrementTurn,
notify: (context, event) => {
console.log(context);
console.log(event);
},
},
guards: { gameIsOver },
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment