Tell us what’s happening: A lot of test cases are still failing but the overall functionality of the code is working. The game is working as expected and it looks like I did what they asked me to do in the test cases and user story.
These are the failed test cases:
4. The first click of a button.square element should result in X being displayed within the element.
6. The second click of a button.square element should result in O being displayed within the element.
7. All subsequent clicks of a button.square element should alternate between displaying X and O within the element.
8. Clicking on an already used button.square element should result in no change.
9. Clicking on a button.square element after the game has ended should result in no change.
10. The game should display a message indicating the winner to be X or O.
11. The game should display a message indicating a draw.
Your code so far
const { useState } = React;
const winMoves = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 4, 8],
[2, 4, 6],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8]
]
function checkWinner(board) {
for (const move of winMoves) {
const [a, b, c] = move;
if (board[a] !== "" && board[a] === board[b] && board[b] === board[c]) {
return board[a];
}
}
return null;
}
export function Board() {
const [currentPlayer, setCurrentPlayer] = useState('x')
const [winner, setWinner] = useState(null);
const [board, setBoard] = useState(new Array(9).fill(""));
function handleClick(index) {
if (winner !== null) {
return;
}
if (board[index] !== "") {
return
}
const newBoard = [...board];
newBoard[index] = currentPlayer;
setBoard(newBoard);
const result = checkWinner(newBoard)
if (result !== null) {
setWinner(result)
} else {
if (!newBoard.includes("")) {
setWinner("Draw")
} else {
if (currentPlayer === 'x') {
setCurrentPlayer('o');
} else if (currentPlayer === 'o') {
setCurrentPlayer('x');
}
}
}
}
function resetGame() {
setBoard(new Array(9).fill(""));
setCurrentPlayer('X');
setWinner(null);
}
return (
<>
<h1 className="game-title">Tic Tac Toe</h1>
<div className="game-container">
<p className="next-player">{winner === null ? `Next Player: ${currentPlayer}` : winner === 'Draw' ? `It's a Draw!` : `Winner: ${winner}`}</p>
<div className="game-board">
{board.map((square, index) => (
<button
key={square+index}
className="square"
onClick={() => handleClick(index)}
>
{square}
</button>
))}
</div>
<button id="reset" onClick={resetGame}>Reset Game</button>
</div>
</>
);
}
Lesson URL (copy - paste from your browser’s address bar)