-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
71 lines (62 loc) · 1.91 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import Board from "./components/Board";
import History from "./components/History";
import StatusMessage from "./components/StatusMessage";
import React, { useState } from "react";
import "./styles/root.scss";
import { calculateWinner } from "./helpers";
const NEW_GAME = [{ board: Array(9).fill(null), isXNext: true }];
const App = () => {
const [history, setHistory] = useState(NEW_GAME);
const [currentMove, setCurrentMove] = useState(0);
const current = history[currentMove];
const { winner, winningSquares } = calculateWinner(current.board);
// To display the message.
const handleSquareClick = (position) => {
if (current.board[position] || winner) {
return;
}
// Update of state onClick button
setHistory((prev) => {
const last = prev[prev.length - 1];
const newBoard = last.board.map((square, pos) => {
if (pos === position) {
return last.isXNext ? "X" : "O";
}
return square;
});
return prev.concat({ board: newBoard, isXNext: !last.isXNext });
});
setCurrentMove((prev) => prev + 1);
};
const moveTo = (move) => {
setCurrentMove(move);
};
const onNewGame = () => {
setHistory(NEW_GAME);
setCurrentMove(0);
};
return (
<div className="app">
<h1>
TIC <span className="text-green">TAC</span> TOE
</h1>
<StatusMessage winner={winner} current={current} />
<Board
board={current.board}
handleSquareClick={handleSquareClick}
winningSquares={winningSquares}
/>
<button
type="button"
onClick={onNewGame}
className={`btn-reset ${winner ? "active" : ""}`}
>
Start New Game
</button>
<h2 style={{ fontWeight: "normal" }}>Current Game History</h2>
<History history={history} moveTo={moveTo} currentMove={currentMove} />
<div className="bg-balls" />
</div>
);
};
export default App;