Last active
December 30, 2019 09:37
-
-
Save JulianG/729222e4b7eb4636294ef0fa273cc4fd to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const initialContext = { | |
cards: [ | |
{ type: 1, collected: false }, | |
{ type: 1, collected: false }, | |
{ type: 2, collected: false }, | |
{ type: 2, collected: false }, | |
{ type: 3, collected: false }, | |
{ type: 3, collected: false }, | |
{ type: 4, collected: false }, | |
{ type: 4, collected: false } | |
], | |
pairs: [], | |
firstSelected: null, | |
secondSelected: null | |
} | |
const isFinished = (c) => c.cards.every(c => c.collected) | |
const isNotFinished = (c) => !isFinished(c) | |
const memoryGameMachine = Machine( | |
{ | |
id: 'memory', | |
initial: 'idle', | |
context: initialContext, | |
states: { | |
idle: { | |
on: { | |
SELECT: { | |
target: 'oneSelected', | |
actions: ['selectFirst'] | |
} | |
} | |
}, | |
oneSelected: { | |
on: { | |
SELECT: { | |
target: 'twoSelected', | |
actions: ['selectSecond'] | |
} | |
} | |
}, | |
twoSelected: { | |
on: { | |
CONTINUE: 'comparing' | |
} | |
}, | |
comparing: { | |
entry: 'compareSelections', | |
on: { | |
'': [ | |
{ | |
target: 'finished', | |
cond: isFinished | |
}, | |
{ | |
target: 'idle', | |
cond: isNotFinished | |
} | |
] | |
} | |
}, | |
finished: { | |
type: 'final' | |
} | |
} | |
}, | |
{ | |
actions: { | |
compareSelections: assign((context) => { | |
const { firstSelected, secondSelected, pairs } = context | |
if (firstSelected.type === secondSelected.type) { | |
pairs.push(firstSelected, secondSelected) | |
firstSelected.collected = true | |
secondSelected.collected = true | |
} | |
context.firstSelected = context.secondSelected = null | |
return context | |
}), | |
selectFirst: assign((context, e) => { | |
context.firstSelected = context.cards[e.index] | |
return context | |
}), | |
selectSecond: assign((context, e) => { | |
context.secondSelected = context.cards[e.index] | |
return context | |
}) | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment