Skip to content

Instantly share code, notes, and snippets.

@maurodaprotis
Created October 17, 2020 20:02
Show Gist options
  • Save maurodaprotis/19ea2c1dd141323c6f756e44cbdf7a07 to your computer and use it in GitHub Desktop.
Save maurodaprotis/19ea2c1dd141323c6f756e44cbdf7a07 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 decreaseMoves = assign({
movesLeft: (context) => context.movesLeft - 1
});
const assignUp = assign({
x: (context) => context.x - 1,
});
const assignDown = assign({
x: (context) => context.x + 1
});
const assignLeft = assign({
y: (context) => context.y - 1
});
const assignRight = assign({
y: (context) => context.y + 1
});
const won = ({x, y, finish}) => ( finish[0] === x && finish[1] === y)
const loose = ({ movesLeft }) => movesLeft === 0;
const isWalkable = ({ cells }) => (x, y) => (cells[x][y]?.walkable)
const canMoveUp = (context) => context.x > 0 && isWalkable(context)(context.x - 1, context.y);
const canMoveDown = (context) => context.x < context.maxX - 1 && isWalkable(context)(context.x + 1, context.y);
const canMoveLeft = (context) => context.y > 0 && isWalkable(context)(context.x, context.y - 1);
const canMoveRight = (context) => context.y < context.maxY - 1 && isWalkable(context)(context.x, context.y + 1);
const fetchMachine = Machine({
initial: "idle",
context: {
movesLeft: 10,
x: 0,
y: 0,
start: [0, 0],
finish: [2,0],
maxX: 3,
maxY: 3,
cells: {
0: { 0: { walkable: true }, 1: { walkable: true }, 2: { walkable: true } },
1: { 0: { walkable: false }, 1: { walkable: false }, 2: { walkable: true } },
2: { 0: { walkable: true }, 1: { walkable: true }, 2: { walkable: true } },
}
},
states: {
idle: {
on: {
MOVE_UP: { cond: canMoveUp, actions: assignUp, target: "moving" },
MOVE_DOWN: { cond: canMoveDown, actions: assignDown, target: "moving" },
MOVE_LEFT: { cond: canMoveLeft, actions: assignLeft, target: "moving" },
MOVE_RIGHT: { cond: canMoveRight, actions: assignRight, target: "moving" },
}
},
moving: {
entry: decreaseMoves,
on: {
'': [
{ target: 'win', cond: won },
{ target: 'loss', cond: loose },
{ target: 'idle' }
]
}
},
win: {
type: "final"
},
loss: {
type: "final"
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment