Skip to content

Commit

Permalink
feat(ract): show status
Browse files Browse the repository at this point in the history
  • Loading branch information
budougumi0617 committed Oct 6, 2024
1 parent fcf6a92 commit 5df27f0
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion react/tic-tac-toe/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,16 @@ export default function Board() {
const [squares, setSquares] = useState<Array<string | null>>(
Array<string | null>(9).fill(null),
);
const winner = calculateWinner(squares);
let status: string;
if (winner) {
status = "Winner: " + winner;
} else {
status = "Next player: " + (xIsNext ? "X" : "O");
}

const handleClick = (i: number) => {
if (squares[i]) {
if (squares[i] || !!calculateWinner(squares ?? [])) {
// 入力済みのマス目をクリックした場合は何もしない
return;
}
Expand All @@ -37,6 +45,7 @@ export default function Board() {
};
return (
<>
<div className="status">{status}</div>
<div className="board-row">
<Square value={squares[0]} onSquareClick={() => handleClick(0)} />
<Square value={squares[1]} onSquareClick={() => handleClick(1)} />
Expand All @@ -55,3 +64,23 @@ export default function Board() {
</>
);
}

function calculateWinner(squares: Array<string | null>): string | null {
const lines = [
[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 i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}

0 comments on commit 5df27f0

Please sign in to comment.