Tell us what’s happening:
Tests 5-11 fail. The game works fine (as far as I can tell). Usually when tests fail I have an idea what to work on, here I have no clue.
I’d greatly appreciate any help. Thanks
Your code so far
<!-- file: index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Tic-Tac-Toe</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.26.5/babel.min.js"></script>
<script
data-plugins="transform-modules-umd"
type="text/babel"
src="index.jsx"
></script>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="root"></div>
<script
data-plugins="transform-modules-umd"
type="text/babel"
data-presets="react"
data-type="module"
>
import { Board } from './index.jsx';
ReactDOM.createRoot(document.getElementById('root')).render(<Board />);
</script>
</body>
</html>
/* file: styles.css */
.square {
width: 50px;
height: 50px;
}
#container {
display: flex;
flex-wrap: wrap;
width: 180px;
}
/* file: index.jsx */
const { useState } = React;
export function Board() {
const [player, setPlayer] = useState("X");
const [board, setBoard] = useState(new Array(9).fill(""));
const [winner, setWinner] = useState("");
const [turns, setTurns] = useState(0);
function checkWon(newBoard) {
const winCombos = [[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 combo of winCombos) {
if (newBoard[combo[0]] && newBoard[combo[0]] === newBoard[combo[1]] && newBoard[combo[1]] === newBoard[combo[2]]) {
setWinner(newBoard[combo[0]]);
return;
}
}
}
function switchPlayer() {
if (player === "X") setPlayer("O");
else setPlayer("X");
}
function handleClick(e) {
const newBoard = [...board];
newBoard[e.target.name] = player;
setBoard(newBoard);
checkWon(newBoard);
switchPlayer();
setTurns(prevTurns => prevTurns + 1);
}
function handleReset() {
setPlayer("X");
setBoard(new Array(9).fill(""));
setWinner("");
setTurns(0);
}
return (<>
<h1>Tic Tac Toe</h1>
<p>{winner ? ("Winner: " + winner) : turns < 9 ? ("Next player: " + player) : ("It's a draw!")}</p>
<div id="container">
{board.map((content, index) => {
return <button className="square" key={index} name={index} onClick={handleClick} disabled={winner || content}>{content}</button>
})}
</div>
<br />
<button id="reset" onClick={handleReset}>Reset</button>
</>)
}
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:142.0) Gecko/20100101 Firefox/142.0
Challenge Information:
Build a Tic-Tac-Toe Game - Build a Tic-Tac-Toe Game
https://www.freecodecamp.org/learn/full-stack-developer/lab-tic-tac-toe/build-a-tic-tac-toe-game