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