init basic tictactoe game

This commit is contained in:
2025-11-27 16:26:51 +05:30
commit c6c9d10476
13 changed files with 4251 additions and 0 deletions

View 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;
}