geme status

This commit is contained in:
djmil 2023-07-31 17:56:11 +02:00
parent 09b5009dfd
commit e17c55a29d
2 changed files with 36 additions and 0 deletions

View File

@ -28,3 +28,7 @@ body {
content: '';
display: table;
}
.status {
margin-bottom: 10px;
}

View File

@ -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 (
<>
<div className="status">{status}</div>
<div className="board-row">
<Square value={squares[0]} onSquareClick={() => handleClick(0)}/>
<Square value={squares[1]} onSquareClick={() => 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;
}