Created
March 1, 2020 23:32
-
-
Save arjunyel/16876d36525fcf711b1a36bb6470d731 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or 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
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const TicTacToe = Machine( | |
{ | |
initial: "playing", | |
context: { | |
board: Array(9).fill(null), | |
moves: 0, | |
player: "x", | |
winner: undefined | |
}, | |
states: { | |
playing: { | |
on: { | |
"": [ | |
{ target: "winner", cond: "checkWin" }, | |
{ target: "draw", cond: "checkDraw" } | |
], | |
PLAY: [ | |
{ | |
target: "playing", | |
cond: "isValidMove", | |
actions: "updateBoard" | |
} | |
] | |
} | |
}, | |
winner: { | |
onEntry: "setWinner" | |
}, | |
draw: {} | |
}, | |
on: { | |
RESET: { | |
target: "playing", | |
actions: "resetGame" | |
} | |
} | |
}, | |
{ | |
actions: { | |
updateBoard: assign({ | |
board: (ctx, e) => { | |
const updatedBoard = [...ctx.board]; | |
updatedBoard[e.value] = ctx.player; | |
return updatedBoard; | |
}, | |
moves: ctx => ctx.moves + 1, | |
player: ctx => (ctx.player === "x" ? "o" : "x") | |
}), | |
resetGame: assign({ | |
board: Array(9).fill(null), | |
moves: 0, | |
player: "x", | |
winner: undefined | |
}), | |
setWinner: assign({ | |
winner: ctx => (ctx.player === "x" ? "o" : "x") | |
}) | |
}, | |
guards: { | |
checkWin: ctx => { | |
const { board } = ctx; | |
const winningLines = [ | |
[0, 1, 2], | |
[3, 4, 5], | |
[6, 7, 8], | |
[0, 3, 6], | |
[1, 4, 7], | |
[2, 5, 8], | |
[0, 4, 8], | |
[2, 4, 6] | |
]; | |
for (let line of winningLines) { | |
const xWon = line.every(index => { | |
return board[index] === "x"; | |
}); | |
if (xWon) { | |
return true; | |
} | |
const oWon = line.every(index => { | |
return board[index] === "o"; | |
}); | |
if (oWon) { | |
return true; | |
} | |
} | |
}, | |
checkDraw: ctx => ctx.moves === 9, | |
isValidMove: (ctx, e) => { | |
return ctx.board[e.value] === null; | |
} | |
} | |
} | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment