From d3f8ad21a1d8f640f10276c2251ee784e579ff2b Mon Sep 17 00:00:00 2001 From: Paul Trowbridge Date: Sun, 18 Apr 2021 22:38:28 -0400 Subject: [PATCH] determine a winner --- src/index.js | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index ca2029d..6f0fe35 100644 --- a/src/index.js +++ b/src/index.js @@ -22,7 +22,12 @@ function Square(props){ handleClick(i) { const squares = this.state.squares.slice(); squares[i] = this.state.xIsNext ? 'X' : 'O'; - this.setState({squares: squares,xIsNext: !this.state.xIsNext}); + this.setState( + { + squares: squares, + xIsNext: !this.state.xIsNext + } + ); } renderSquare(i) { @@ -39,7 +44,13 @@ function Square(props){ } render() { - const status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O'); + const winner = calculateWinner(this.state.squares); + let status; + if (winner) { + status = 'Winner: ' + winner; + } else { + status = 'Next Player: ' + (this.state.xIsNext ? 'X' : 'O') + } return (
@@ -87,3 +98,22 @@ function Square(props){ document.getElementById('root') ); + function calculateWinner(squares) { + const lines = [ + [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 i = 0; i < lines.length; i++) { + const [a, b, c] = lines[i]; + if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { + return squares[a]; + } + } + return null; + } \ No newline at end of file