Tell us what’s happening:
The Tic-Tac-Toe game’s basic functionality is working but it isn’t passing any of the tests.
And my reset button resets the entire game but doesn’t pass 5 which is quite strange.
Thanks for the help in advance!
Your code so far
/* file: index.jsx */
const { useState } = React;
export function Board() {
const [square, setSquare] = useState(Array(9).fill(null));
const [nextLetter, setNextLetter] = useState(true);
function handleClick(i) {
if (square[i] || winner(square)) {
return;
}
const nextSquare = [...square]
if (nextLetter) {
nextSquare[i] = "X";
} else {
nextSquare[i] = "O"
}
setSquare(nextSquare);
setNextLetter(!nextLetter);
}
function winner(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;
}
const declareWinner = winner(square);
let message;
if (declareWinner) {
message = `Winner: ${declareWinner}`
} else {
message = `Next player: ${nextLetter ? "X" : "O"}`
}
function resetGame() {
setSquare(Array(9).fill(null));
setNextLetter(true);
message = ""
}
return (
<>
<h2 className="message">{message}</h2>
<div className="canvas">
<Square value={square[0]} handleSquareClick={() => handleClick(0)} />
<Square value={square[1]} handleSquareClick={() => handleClick(1)} />
<Square value={square[2]} handleSquareClick={() => handleClick(2)} />
<Square value={square[3]} handleSquareClick={() => handleClick(3)} />
<Square value={square[4]} handleSquareClick={() => handleClick(4)} />
<Square value={square[5]} handleSquareClick={() => handleClick(5)} />
<Square value={square[6]} handleSquareClick={() => handleClick(6)} />
<Square value={square[7]} handleSquareClick={() => handleClick(7)} />
<Square value={square[8]} handleSquareClick={() => handleClick(8)} />
<button type="button" className="reset" onClick={resetGame} ><span className="reset-button">Reset</span></button>
</div>
</>
)
};
function Square({ value, handleSquareClick }) {
return <button type="button" className="square" onClick={handleSquareClick}>
{value}
</button>
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36
Challenge Information:
Build a Tic-Tac-Toe Game - Build a Tic-Tac-Toe Game