Skip to content

Instantly share code, notes, and snippets.

@kdgerona
Created October 9, 2020 23:05
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 kdgerona/0bae49d220549ef7befdcd548178b9f8 to your computer and use it in GitHub Desktop.
Save kdgerona/0bae49d220549ef7befdcd548178b9f8 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const context = {
inserted_coins: 0,
min_coins: 5,
total_coins: 0,
game_time_ms: 5000,
total_game_time_ms: 0,
max_machine_lifetime: 10000,
}
const fetchMachine = Machine({
context,
id: 'arcade_machine',
initial: 'active',
states: {
active: {
initial: 'idle',
states: {
idle: {
on: {
INPUT: {
target: 'checkCoins',
actions: ['insertCoin']
},
},
},
checkCoins: {
// always: [
// {
// target: 'waitForPlayerResponse',
// cond: 'isMinCoinReached',
// },
// {
// target: 'idle',
// }
// ]
on: {
"": [
{
target: 'waitForPlayerResponse',
cond: 'isMinCoinReached',
},
{
target: 'idle',
}
]
}
},
waitForPlayerResponse: {
on: {
START_GAME: 'playing',
}
},
playing: {
invoke: {
id: 'gameService',
src: 'gameService',
},
entry: 'deductCoinsAndSumTotalCoins',
on: {
GAME_OVER: 'gameOver',
}
},
gameOver: {
entry: 'sumTotalGameTime',
on: {
PLAY_AGAIN: [
{
target: 'idle',
cond: 'isOperational'
},
{
target: '#broken'
}
],
}
},
},
},
broken: {
id: 'broken',
type: 'final'
}
}
}, {
actions: {
insertCoin: assign({ inserted_coins: ({ inserted_coins = 0, min_coins }) => {
console.log(`*** INSERT COINS *** ${inserted_coins}/${min_coins}\n`)
return inserted_coins + 1;
}
}),
deductCoinsAndSumTotalCoins: assign((context) => {
const { inserted_coins, min_coins, total_coins} = context;
const deduct_coins = inserted_coins - min_coins;
const sum_total_coins = total_coins + min_coins;
console.log("*** Press play button to start game. ***\n");
return {
inserted_coins: deduct_coins,
total_coins: sum_total_coins,
}
}),
sumTotalGameTime: assign((context) => {
const { game_time_ms, total_game_time_ms } = context;
const sum_total_game_time = total_game_time_ms + game_time_ms;
console.log("*** Game over! ***\n");
console.log("*** Press play again button to start playing, again. ***\n");
return {
total_game_time_ms: sum_total_game_time,
}
}),
},
guards: {
isMinCoinReached: (context, event) => context.inserted_coins >= context.min_coins,
isOperational: (context) => context.total_game_time_ms <= context.max_machine_lifetime,
},
services: {
gameService: (context) => (send) => {
const { game_time_ms } = context;
console.log('*** Game Started *** \n');
setTimeout(() => {
send('GAME_OVER')
}, game_time_ms)
}
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment