Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 

Repository files navigation

tictactoe

import React, { useState } from "react";

const TicTacToe = () => { const [board, setBoard] = useState(Array(9).fill(null)); const [isXNext, setIsXNext] = useState(true);

const calculateWinner = (squares) => { 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 line of lines) { const [a, b, c] = line; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } return null; };

const handleClick = (index) => { if (board[index] || calculateWinner(board)) return; const newBoard = board.slice(); newBoard[index] = isXNext ? "X" : "O"; setBoard(newBoard); setIsXNext(!isXNext); };

const winner = calculateWinner(board); const status = winner ? Winner: ${winner} : Next player: ${isXNext ? "X" : "O"};

const resetGame = () => { setBoard(Array(9).fill(null)); setIsXNext(true); };

return (

Tic-Tac-Toe

{status}
{board.map((value, index) => ( <button key={index} className="w-16 h-16 text-xl font-bold flex items-center justify-center border border-gray-500" onClick={() => handleClick(index)} > {value} ))}
Restart Game
); };

export default TicTacToe;

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors