Created
January 20, 2020 04:30
-
-
Save ryanflorence/14e5ed107c8b5be51f1137bf22063fe7 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
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