import { useState, useEffect } from 'react'; import { X, Circle, RotateCcw } from 'lucide-react'; export default function TicTacToe() { // Game state const [board, setBoard] = useState(Array(9).fill(null)); const [isXNext, setIsXNext] = useState(true); const [winner, setWinner] = useState(null); const [xMoves, setXMoves] = useState([]); const [oMoves, setOMoves] = useState([]); const [gameHistory, setGameHistory] = useState([]); // Handle cell click const handleClick = (index) => { // Return if cell is already filled or game is won if (winner || board[index] !== null) return; const currentPlayer = isXNext ? 'X' : 'O'; const currentMoves = isXNext ? xMoves : oMoves; const newBoard = [...board]; // If player already has 3 pieces on the board, remove the oldest one if (currentMoves.length >= 3) { const oldestMoveIndex = currentMoves[0]; newBoard[oldestMoveIndex] = null; if (isXNext) { setXMoves(xMoves.slice(1).concat(index)); } else { setOMoves(oMoves.slice(1).concat(index)); } } else { // Add the new move if (isXNext) { setXMoves([...xMoves, index]); } else { setOMoves([...oMoves, index]); } } // Place the new piece newBoard[index] = currentPlayer; setBoard(newBoard); // Add to game history setGameHistory([...gameHistory, { board: newBoard.slice(), player: currentPlayer, position: index }]); // Check for winner const gameWinner = calculateWinner(newBoard); if (gameWinner) { setWinner(gameWinner); } else { // Switch turns setIsXNext(!isXNext); } }; // Reset the game const resetGame = () => { setBoard(Array(9).fill(null)); setIsXNext(true); setWinner(null); setXMoves([]); setOMoves([]); setGameHistory([]); }; // Calculate winner const calculateWinner = (squares) => { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], // rows [0, 3, 6], [1, 4, 7], [2, 5, 8], // columns [0, 4, 8], [2, 4, 6] // diagonals ]; 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; }; // Get status message const getStatus = () => { if (winner) { return `Winner: ${winner}`; } else { return `Next player: ${isXNext ? 'X' : 'O'}`; } }; // Render a cell const renderCell = (index) => { return ( ); }; return (

Tic Tac Toe

Each player can only have 3 pieces on the board. When you place a 4th piece, your oldest piece disappears.

{getStatus()}
{Array(9).fill(null).map((_, index) => (
{renderCell(index)}
))}
X pieces: {xMoves.length}/3
O pieces: {oMoves.length}/3
{gameHistory.length > 0 && (

Game History

    {gameHistory.map((move, index) => (
  • Move {index + 1}: Player {move.player} placed at position {move.position + 1}
  • ))}
)}
); }