From e17c55a29d5a5fe2d0afc1b5abe442e195bd2851 Mon Sep 17 00:00:00 2001 From: djmil Date: Mon, 31 Jul 2023 17:56:11 +0200 Subject: [PATCH] geme status --- src/App.css | 4 ++++ src/App.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/App.css b/src/App.css index 28425e9..1685faa 100644 --- a/src/App.css +++ b/src/App.css @@ -28,3 +28,7 @@ body { content: ''; display: table; } + +.status { + margin-bottom: 10px; +} \ No newline at end of file diff --git a/src/App.js b/src/App.js index 494c5f2..39a8bc3 100644 --- a/src/App.js +++ b/src/App.js @@ -18,6 +18,9 @@ function App() { const [squares, setSquares] = useState(Array(9).fill(null)); function handleClick(i) { + if (squares[i] || calculateWinner(squares)) { + return; + } const nextSquares = squares.slice(); if (xIsNext) { nextSquares[i] = "X"; @@ -28,8 +31,17 @@ function App() { setXIsNext(!xIsNext); } + const winner = calculateWinner(squares); + let status; + if (winner) { + status = "Winner: " + winner; + } else { + status = "Next player: " + (xIsNext ? "X" : "O"); + } + return ( <> +
{status}
handleClick(0)}/> handleClick(1)}/> @@ -50,3 +62,23 @@ function App() { } export default App; + +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