Skip to content

Instantly share code, notes, and snippets.

@colinbate
Last active June 13, 2020 20:52
Show Gist options
  • Save colinbate/5ea732933a9215a5be2d45ba62d068c9 to your computer and use it in GitHub Desktop.
Save colinbate/5ea732933a9215a5be2d45ba62d068c9 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 setRolledDice = assign({
tableDice: (ctx, ev) => ev.dice,
});
const moveToTray = assign({
tableDice: (ctx, ev) => ctx.tableDice.filter(d => d.id !== ev.die.id),
trayDice: (ctx, ev) => [...ctx.trayDice, ev.die]
});
const moveToTable = assign({
trayDice: (ctx, ev) => ctx.trayDice.filter(d => d.id !== ev.die.id),
tableDice: (ctx, ev) => [...ctx.tableDice, ev.die]
});
const decRolls = assign({
rolls: ctx => ctx.rolls - 1
});
const canRoll = (ctx, ev) => !!ctx.rolls;
const nextPlayer = assign({
currentPlayer: ctx => (ctx.currentPlayer + 1) % ctx.players.length,
rolls: 3
});
const setScore = assign({
players: (ctx, ev) => {
const p = [...ctx.players];
p[ctx.currentPlayer].scores[ev.category] = ev.value;
return p;
}
});
const yahtzeeMachine = Machine({
id: 'yahtzee',
context: {
tableDice: [],
trayDice: [],
possibleScores: {},
names: ['Player 1', 'Player 2'],
scores: [{}, {}],
currentPlayer: 0,
rolls: 3
},
type: 'parallel',
states: {
game: {
initial: 'welcome',
states: {
'welcome': {
on: {
ROLL: 'playing.rolling',
}
},
'new': {
entry: ['resetGame'],
on: {
ROLL: 'playing.rolling',
}
},
playing: {
initial: 'newturn',
states: {
newturn: {
entry: ['tallyScore'],
on: {
ROLL: 'rolling',
}
},
rolling: {
on: {
ROLLED: {
target: 'deciding',
actions: ['setRolledDice', 'decRolls', 'getPossible']
},
}
},
deciding: {
on: {
ROLL: {
target: 'rolling',
cond: 'canRoll'
},
SET_SCORE: {
target: 'checkScore',
actions: ['setScore'],
},
SET_ASIDE: {
actions: ['moveToTray']
},
PUT_BACK: {
actions: ['moveToTable']
},
}
},
checkScore: {
on: {
'': [
{
target: 'finished',
cond: 'isGameOver',
},
{
target: 'newturn',
actions: ['nextPlayer']
}
]
}
},
finished: {
type: 'final',
entry: ['tallyScore'],
}
},
on: {
START_OVER: 'new'
}
}
}
},
sidebar: {
initial: 'showScore',
states: {
showScore: {
on: {
VIEW_RULES: 'showRules',
}
},
showRules: {
on: {
VIEW_SCORE: 'showScore',
}
}
}
}
}
}, {
actions: {
setRolledDice,
moveToTable,
moveToTray,
decRolls,
nextPlayer,
setScore,
},
guards: {
canRoll
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment