Skip to content

Commit 5fa831d

Browse files
committed
adding
1 parent 86bcd69 commit 5fa831d

File tree

1 file changed

+26
-18
lines changed

1 file changed

+26
-18
lines changed

tic-tac-toe/src/App.js

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ function App() {
66
const [xTurn, setXTurn] = useState(true);
77
const [xInput, setXInput] = useState([]);
88
const [oInput, setOInput] = useState([]);
9+
const [gameOver, setGameOver] = useState(false);
910

1011
const winnings = [
1112
[0, 1, 2],
@@ -20,26 +21,22 @@ function App() {
2021

2122
const checkWins = (array) => {
2223
return winnings.some((item) => {
23-
return item.every((index) => array.includes(index))
24-
})
24+
return item.every((index) => array.includes(index));
25+
});
2526
};
2627

2728
const handleClick = (i) => {
28-
if (xInput.includes(i) || oInput.includes(i)) return;
29-
setXTurn(!xTurn);
29+
if (xInput.includes(i) || oInput.includes(i) || gameOver) return;
3030

3131
if (xTurn) {
3232
let tempX = [...xInput, i];
3333
setXInput(tempX);
3434

3535
if (tempX.length >= 3) {
3636
let didWin = checkWins(tempX);
37-
console.log('didWin', didWin)
38-
39-
if(didWin){
40-
alert('win')
41-
setXInput([])
42-
setOInput([])
37+
if (didWin) {
38+
alert('X wins!');
39+
setGameOver(true);
4340
}
4441
}
4542
} else {
@@ -48,23 +45,33 @@ function App() {
4845

4946
if (tempO.length >= 3) {
5047
let didWin = checkWins(tempO);
51-
console.log('didWin', didWin)
52-
if(didWin){
53-
alert('win')
54-
setXInput([])
55-
setOInput([])
48+
if (didWin) {
49+
alert('O wins!');
50+
setGameOver(true);
5651
}
57-
}
52+
}
53+
}
54+
55+
if (xInput.length + oInput.length + 1 === NUMBER_OF_BOXES && !gameOver) {
56+
alert("It's a draw!");
57+
setGameOver(true);
5858
}
59+
60+
setXTurn(!xTurn);
5961
};
6062

61-
console.log(xInput, oInput)
63+
const resetGame = () => {
64+
setXInput([]);
65+
setOInput([]);
66+
setXTurn(true);
67+
setGameOver(false);
68+
};
6269

6370
const renderBoardValue = (i) => {
6471
if (xInput.includes(i)) {
6572
return "X";
6673
} else if (oInput.includes(i)) {
67-
return "0";
74+
return "O";
6875
}
6976
return "";
7077
};
@@ -87,6 +94,7 @@ function App() {
8794
<div className="App">
8895
TicTacToe
8996
<div className="board-holder">{renderBoard()}</div>
97+
{gameOver && <button onClick={resetGame}>Restart Game</button>}
9098
</div>
9199
);
92100
}

0 commit comments

Comments
 (0)