init basic tictactoe game
This commit is contained in:
52
src/tictactoe/TicTacToe.tsx
Normal file
52
src/tictactoe/TicTacToe.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import { useState } from "react";
|
||||
import Board from "./Board";
|
||||
|
||||
export default function TicTacToe() {
|
||||
const [board, setBoard] = useState(Array(9).fill(null));
|
||||
const [xIsNext, setXIsNext] = useState(true);
|
||||
|
||||
const winner = calculateWinner(board);
|
||||
|
||||
function handleSquareClick(i: number) {
|
||||
if (board[i] || winner) return;
|
||||
|
||||
const newBoard = board.slice();
|
||||
newBoard[i] = xIsNext ? "X" : "O";
|
||||
|
||||
setBoard(newBoard);
|
||||
setXIsNext(!xIsNext);
|
||||
}
|
||||
|
||||
function reset() {
|
||||
setBoard(Array(9).fill(null));
|
||||
setXIsNext(true);
|
||||
}
|
||||
|
||||
const status = winner
|
||||
? `Winner: ${winner}`
|
||||
: `Next player: ${xIsNext ? "X" : "O"}`;
|
||||
|
||||
return (
|
||||
<div className="game-container">
|
||||
<h1>Tic Tac Toe</h1>
|
||||
<div className="status">{status}</div>
|
||||
<Board squares={board} onClick={handleSquareClick} />
|
||||
<button className="reset-btn" onClick={reset}>Reset</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- winner logic ---
|
||||
function calculateWinner(sq: any[]) {
|
||||
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 [a,b,c] of lines) {
|
||||
if (sq[a] && sq[a] === sq[b] && sq[a] === sq[c]) {
|
||||
return sq[a];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user