Skip to content

Instantly share code, notes, and snippets.

@danielkcz
Last active January 6, 2020 18:20
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 danielkcz/ee35535f09d3baa69bd6d3f7cafad437 to your computer and use it in GitHub Desktop.
Save danielkcz/ee35535f09d3baa69bd6d3f7cafad437 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const tickEvent = (gear) => ({ type: 'TICK', gear })
const trainMachine = Machine(
{
id: 'train',
initial: 'inactive',
context: {
position: {
x: 0,
y: 0,
},
power: 0,
speed: 0,
tickStream: null,
},
on: {
ACTIVATE: '.active',
DEACTIVATE: '.inactive',
},
states: {
inactive: {
invoke: ctx => ctx.tickStream.map(tickEvent),
on: {
TICK: { actions: ['slowDown', 'updatePosition'], cond: 'isMoving' },
},
},
active: {
invoke: ctx => ctx.tickStream.map(tickEvent),
on: {
TICK: {
actions: ['updatePower', 'updateSpeed', 'updatePosition'],
},
},
},
},
},
{
actions: {
updatePower: assign({
power: (_, ev) => {
switch (ev.gear) {
case 'neutral':
return 0
case 'forward':
return 1
case 'reverse':
return -1
}
},
}),
updateSpeed: assign({
speed: ctx => Phaser.Math.Clamp(ctx.speed + ctx.power, -1, 3),
}),
updatePosition: assign({ position: ctx => {} }),
slowDown: assign({ speed: ctx => Phaser.Math.MinSub(ctx.speed, 0.1, 0) }),
},
guards: {
isMoving: (ctx) => ctx.speed !== 0,
},
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment