Created
January 18, 2024 04:58
-
-
Save SydBal/08dd8be15dd412b9d85c381f01daa63c to your computer and use it in GitHub Desktop.
React TicTacToe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.ticTacToeDisplay { | |
text-align: center; | |
margin: 20px; | |
} | |
.board { | |
display: grid; | |
grid-template-columns: repeat(3, 100px); | |
grid-template-rows: repeat(3, 100px); | |
gap: 5px; | |
margin: 20px auto; | |
} | |
.cell { | |
display: flex; | |
align-items: center; | |
justify-content: center; | |
font-size: 24px; | |
border: 1px solid #ccc; | |
cursor: pointer; | |
} | |
.playerX { | |
color: #f00; | |
} | |
.playerO { | |
color: #00f; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
const TicTacToe = () => { | |
const [board, setBoard] = useState(Array(9).fill(null)); | |
const [isPlayerXNext, setIsPlayerXNext] = useState(true); | |
const [winner, setWinner] = useState(null); | |
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 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; | |
}; | |
const handleClick = (index) => { | |
if (!board[index] && !winner) { | |
const newBoard = [...board]; | |
newBoard[index] = isPlayerXNext ? "X" : "O"; | |
setBoard(newBoard); | |
setIsPlayerXNext(!isPlayerXNext); | |
const currentWinner = calculateWinner(newBoard); | |
if (currentWinner) { | |
setWinner(currentWinner); | |
} | |
} | |
}; | |
const handleReset = () => { | |
setBoard(Array(9).fill(null)); | |
setIsPlayerXNext(true); | |
setWinner(null); | |
}; | |
const renderBoard = () => { | |
return ( | |
<div className="board"> | |
{board.map((value, index) => ( | |
<div key={index} className="cell" onClick={() => handleClick(index)}> | |
{value} | |
</div> | |
))} | |
</div> | |
); | |
}; | |
return ( | |
<div className="localTicTacToeDisplay"> | |
<h2>Local Tic Tac Toe</h2> | |
{renderBoard()} | |
{winner && <p>Winner: {winner}</p>} | |
<button onClick={handleReset}>Reset Game</button> | |
</div> | |
); | |
}; | |
export default TicTacToe; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment