Skip to content

Commit

Permalink
feat(react): record history
Browse files Browse the repository at this point in the history
  • Loading branch information
budougumi0617 committed Oct 6, 2024
1 parent 5df27f0 commit 7580b03
Showing 1 changed file with 32 additions and 7 deletions.
39 changes: 32 additions & 7 deletions react/tic-tac-toe/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@ function Square({
);
}

export default function Board() {
const [xIsNext, setXIsNext] = useState<boolean>(true);
const [squares, setSquares] = useState<Array<string | null>>(
Array<string | null>(9).fill(null),
);
export function Board({
xIsNext,
squares,
onPlay,
}: {
xIsNext: boolean;
squares: Array<string | null>;
onPlay: (nextSquares: Array<string | null>) => void;
}): JSX.Element {
const winner = calculateWinner(squares);
let status: string;
if (winner) {
Expand All @@ -40,8 +44,7 @@ export default function Board() {
} else {
nextSquares[i] = "O";
}
setSquares(nextSquares);
setXIsNext(!xIsNext);
onPlay(nextSquares);
};
return (
<>
Expand All @@ -65,6 +68,28 @@ export default function Board() {
);
}

export default function Game() {
const [xIsNext, setXIsNext] = useState<boolean>(true);
const [history, setHistory] = useState<Array<Array<string | null>>>([
Array(9).fill(null),
]);
const currentSquares = history[history.length - 1];
function handlePlay(nextSquares: Array<string | null>): void {
setHistory([...history, nextSquares]);
setXIsNext(!xIsNext);
}
return (
<div className="game">
<div className="game-board">
<Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />
</div>
<div className="game-info">
<ol>{/*TODO*/}</ol>
</div>
</div>
);
}

function calculateWinner(squares: Array<string | null>): string | null {
const lines = [
[0, 1, 2],
Expand Down

0 comments on commit 7580b03

Please sign in to comment.