Last active
October 10, 2020 09:17
-
-
Save saneef/b8d236e4b8da49f90ee15428f4f6e874 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
const ROLL_DELAY = 500; //ms; | |
const faceIndices = [0,1,2,3]; | |
function getRandomInt (min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
const pickFromArray = (items) => items[Math.floor(Math.random() * items.length)]; | |
const tickCallBackHandler = (context, event) => (cb) => { | |
const sendTicks = () => cb({ | |
type: 'ROLL', | |
next: pickFromArray(faceIndices) | |
}); | |
sendTicks(); | |
const id = setInterval(sendTicks, ROLL_DELAY); | |
return () => clearInterval(id) | |
}; | |
const diceRollerMachine = Machine({ | |
id: "dice-roller", | |
type: 'parallel', | |
states: { | |
roller: { | |
initial: 'idle', | |
states: { | |
idle: { | |
on: { | |
START_ROLLING: "rolling" | |
}, | |
}, | |
rolling: { | |
invoke: { | |
id: 'tickCallback', | |
src: tickCallBackHandler | |
}, | |
after: { | |
RANDOM_DELAY: "idle" | |
}, | |
} | |
} | |
}, | |
dice: { | |
initial: 'one', | |
states: { | |
one: { | |
on: { | |
ROLL: [ | |
{target: 'two', cond: 'isFaceOne'}, | |
{target: 'three', cond: 'isFaceTwo'}, | |
{target: 'four', cond: 'isFaceThree'}, | |
{target: 'five'} | |
] | |
}, | |
}, | |
two: { | |
on: { | |
ROLL: [ | |
{target: 'one', cond: 'isFaceOne'}, | |
{target: 'three', cond: 'isFaceTwo'}, | |
{target: 'four', cond: 'isFaceThree'}, | |
{target: 'six'} | |
] | |
}, | |
}, | |
three: { | |
on: { | |
ROLL: [ | |
{target: 'one', cond: 'isFaceOne'}, | |
{target: 'two', cond: 'isFaceTwo'}, | |
{target: 'five', cond: 'isFaceThree'}, | |
{target: 'six'} | |
] | |
}, | |
}, | |
four: { | |
on: { | |
ROLL: [ | |
{target: 'one', cond: 'isFaceOne'}, | |
{target: 'two', cond: 'isFaceTwo'}, | |
{target: 'five', cond: 'isFaceThree'}, | |
{target: 'six'} | |
] | |
}, | |
}, | |
five: { | |
on: { | |
ROLL: [ | |
{target: 'one', cond: 'isFaceOne'}, | |
{target: 'three', cond: 'isFaceTwo'}, | |
{target: 'four', cond: 'isFaceThree'}, | |
{target: 'six'} | |
] | |
}, | |
}, | |
six: { | |
on: { | |
ROLL: [ | |
{target: 'two', cond: 'isFaceOne'}, | |
{target: 'three', cond: 'isFaceTwo'}, | |
{target: 'four', cond: 'isFaceThree'}, | |
{target: 'five'} | |
] | |
}, | |
} | |
} | |
} | |
} | |
}, { | |
delays: { | |
RANDOM_DELAY: (context, event) => getRandomInt(2000, 10000) | |
}, | |
guards: { | |
isFaceOne: (context, event) => event.next === 0, | |
isFaceTwo: (context, event) => event.next === 1, | |
isFaceThree: (context, event) => event.next === 2, | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment