Skip to content

Instantly share code, notes, and snippets.

@LinusBorg
Last active October 30, 2020 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LinusBorg/6c4ae64f95ceb9f59e4bc91e88644d9c to your computer and use it in GitHub Desktop.
Save LinusBorg/6c4ae64f95ceb9f59e4bc91e88644d9c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const fetchMachine = Machine({
id: 'memoryGame',
initial: 'idle',
context: {
cards: [1,1,2,2,3,3,4,4],
matchedValues: [],
flippedIdxs: [],
},
states: {
idle: {
on: {
FLIP: {
target: 'flippedFirst',
// cond: 'notOpen'
}
}
},
flippedFirst: {
entry: 'addFlipped',
on: {
FLIP: {
target: 'flippedSecond',
cond: 'notOpen'
}
}
},
flippedSecond: {
entry: 'compareCards',
exit: 'resetFlippedIdxs',
after: {
2000: [
{ target: 'won', cond: 'allMatched' },
{ target: 'idle' }
]
}
},
won: {
type: 'final'
}
}
},
{
actions: {
addFlipped: assign({
flippedIdxs: (ctx, evt) => ctx.flippedIdx.push(evt.index)
}),
resetFlippedIdxs: assign({
flippedIdxs: () => [],
}),
compareCards: assign(({cards, flippedIdxs, matchedValues }) => {
if (cards[flippedIdxs[0]] === cards[flippedIdxs[1]]) {
return {
matchedValues: matchedValues.push(cards[flippedIdxs[0]])
}
}
})
},
guards: {
notMatched: (ctx, evt) => !ctx.matchedValues.includes(ctx.cards[evt.index]) && !ctx.flippedIdxs.includes(evt.index),
allMatched: (ctx) => ctx.matchedValues.length === 4
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment