diff --git a/src/components/TicTacToe.tsx b/src/components/TicTacToe.tsx index 67a2d19..69e17d8 100644 --- a/src/components/TicTacToe.tsx +++ b/src/components/TicTacToe.tsx @@ -1,6 +1,6 @@ -import React, { useState } from 'react'; +import { useState } from 'react'; -const TicTacToe: React.FC = () => { +function TicTacToe() { const [board, setBoard] = useState(Array(9).fill(null)); const [currentPlayer, setCurrentPlayer] = useState('X'); @@ -13,54 +13,54 @@ const TicTacToe: React.FC = () => { } }; - const renderSquare = (index: number) => ( -
handleClick(index)} - style={{ - width: '50px', - height: '50px', - border: '1px solid black', - display: 'inline-block', - textAlign: 'center', - lineHeight: '50px', - fontSize: '24px', - cursor: 'pointer', - }} - > - {board[index]} -
- ); + const checkWinner = () => { + const winningLines = [ + [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 < winningLines.length; i++) { + const [a, b, c] = winningLines[i]; + if (board[a] && board[a] === board[b] && board[a] === board[c]) { + return board[a]; + } + } + + if (board.every((square) => square !== null)) { + return 'tie'; + } + + return null; + }; + + const winner = checkWinner(); return ( -
-
- {renderSquare(0)} - {renderSquare(1)} - {renderSquare(2)} -
-
- {renderSquare(3)} - {renderSquare(4)} - {renderSquare(5)} -
-
- {renderSquare(6)} - {renderSquare(7)} - {renderSquare(8)} -
-
- Current player: {currentPlayer} +
+
+ {board.map((square, index) => ( +
handleClick(index)} + > + {square} +
+ ))}
+ {winner && ( +
+ {winner === 'tie' ? 'It\'s a tie!' : `Player ${winner} wins!`} +
+ )}
); -}; +} export default TicTacToe;