Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created January 20, 2020 04:30
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 ryanflorence/14e5ed107c8b5be51f1137bf22063fe7 to your computer and use it in GitHub Desktop.
Save ryanflorence/14e5ed107c8b5be51f1137bf22063fe7 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
let game = Machine({
id: 'game',
initial: 'idle',
context: {
addends: [],
completions: [],
selections: []
},
states: {
idle: {
on: {
START: 'playing'
}
},
playing: {
after: {
1000: [
{
target: 'gameover',
cond: reachedMaxAddends
},
{
target: 'playing',
actions: assign({
addends: appendAddend
})
}
]
},
on: {
SELECT: [
{
target: 'playing',
cond: selectionsEqualTen,
actions: [
assign({
selections: addCompletion,
selections: []
})
]
},
{
target: 'gameover',
cond: selectionsGreaterThan10
},
{
cond: reachedMaxSelections,
target: 'gameover'
},
{
target: 'playing',
cond: selectionsLessThanTen,
actions: assign({
selections: appendSelection,
addends: removeAddend
})
}
]
}
},
gameover: {
on: {
START_OVER: {
target: 'playing',
actions: assign({
addends: [],
selections: [],
completions: []
})
}
}
}
}
})
function reachedMaxAddends(ctx) {
return ctx.addends.length === 8
}
function appendAddend(ctx, event) {
return [Math.floor(Math.random() * 10), ...ctx.addends]
}
function reachedMaxSelections(ctx, event) {
return ctx.selections === 2
}
function selectionsLessThanTen(ctx, event) {
return ctx.selections.reduce((sum, s) => sum + s, 0) < 10
}
function appendSelection(ctx, event) {
return [...ctx.selections, event.selection]
}
function removeAddend(ctx, event) {
let index = ctx.addends.indexOf(event.selection)
return ctx.addends.filter((_, i) => i !== index)
}
function selectionsGreaterThan10(ctx, event) {
return ctx.selections.reduce((s, n) => s + n, event.selection) > 10
}
function selectionsEqualTen(ctx, event) {
return ctx.selections.reduce((s, n) => s + n, event.selection) === 10
}
function addCompletion(ctx, event) {
return ctx.completions.concat(ctx.selections)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment