Skip to content

Instantly share code, notes, and snippets.

@LinusBorg
Last active Oct 30, 2020
Embed
What would you like to do?
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