-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameWithUseState.js
66 lines (58 loc) · 1.57 KB
/
GameWithUseState.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
import React, { useState } from 'react';
import Board from './Board';
import { calculateWinner } from '../utils/calculateWinner';
const Game = () => {
const [history, setHistory] = useState([{
squares: Array(9).fill(null),
}]);
const [stepNumber, setStepNumber] = useState(0);
const [xIsNext, setXIsNext] = useState(true);
const currentBoard = history[stepNumber];
const winner = calculateWinner(currentBoard.squares);
const handleClick = (i) => {
const newHistory = history.slice(0, stepNumber + 1);
const newSquares = [...currentBoard.squares];
if (winner || newSquares[i]) {
return;
}
newSquares[i] = xIsNext ? 'X' : 'O';
setHistory([...newHistory, { squares: newSquares }]);
setStepNumber(newHistory.length);
setXIsNext(!xIsNext);
};
const jumpTo = (step) => {
setStepNumber(step);
setXIsNext((step % 2) === 0);
};
const moves = history.map((step, move) => {
const desc = move ?
`Go to move #${move}` :
'Go to game start';
return (
<li key={move}>
<button onClick={() => jumpTo(move)}>{desc}</button>
</li>
);
});
let status;
if (winner) {
status = `Winner: ${winner}`;
} else {
status = `Next player: ${xIsNext ? 'X' : 'O'}`;
}
return (
<div className="game">
<div className="game-board">
<Board
squares={currentBoard.squares}
onClick={i => handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
};
export default Game;