Creating a Tic-Tac-Toe game in React is a great exercise! Below is a simple implementation of a Tic-Tac-Toe game. This version includes basic functionality for two players playing against each other in a grid format, checking for wins, and resetting the game.
Tic-Tac-Toe Game Implementation
import React, { useState } from 'react';
import './App.css'; // For styling (you can customize this)
const TicTacToe = () => {
const [board, setBoard] = useState(Array(9).fill(null));
const [isXNext, setIsXNext] = useState(true);
const winner = calculateWinner(board);
const handleClick = (index) => {
if (board[index] || winner) return; // Ignore if cell is filled or there's a winner
const newBoard = [...board];
newBoard[index] = isXNext ? 'X' : 'O';
setBoard(newBoard);
setIsXNext(!isXNext);
};
const handleReset = () => {
setBoard(Array(9).fill(null));
setIsXNext(true);
};
const renderSquare = (index) => (
<button className="square" onClick={() => handleClick(index)}>
{board[index]}
</button>
);
const status = winner
? `Winner: ${winner}`
: `Next player: ${isXNext ? 'X' : 'O'}`;
return (
<div>
<h1>Tic Tac Toe</h1>
<div className="status">{status}</div>
<div className="board">
<div className="board-row">
{renderSquare(0)}
{renderSquare(1)}
{renderSquare(2)}
</div>
<div className="board-row">
{renderSquare(3)}
{renderSquare(4)}
{renderSquare(5)}
</div>
<div className="board-row">
{renderSquare(6)}
{renderSquare(7)}
{renderSquare(8)}
</div>
</div>
<button onClick={handleReset}>Reset Game</button>
</div>
);
};
// Function to calculate the winner
function 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;
}
export default TicTacToe;
Style (CSS)
You can add basic styles to make the game look nicer. Create an optional App.css file:
h1 {
text-align: center;
}
.status {
font-size: 20px;
text-align: center;
margin-bottom: 20px;
}
.board {
display: inline-block;
}
.board-row {
display: flex;
}
.square {
width: 60px;
height: 60px;
font-size: 24px;
border: 1px solid #000;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.square:hover {
background-color: #f0f0f0;
}
button {
display: block;
margin: 20px auto;
font-size: 16px;
}
How the Code Works
-
State Management:
board: An array representing the 9 squares of the Tic-Tac-Toe board. Each square can hold 'X', 'O', or null.
isXNext: A boolean to track which player's turn it is.
-
Game Logic:
- The
handleClick function updates the board and switches turns when a square is clicked, except if the square is already filled or someone has already won the game.
- The
calculateWinner function checks the board for any winning combinations.
-
Rendering:
- The
renderSquare function generates the buttons for each square.
- The game board (3x3 grid) is rendered with three rows.
- A reset button allows players to reset the game.
-
Styling: Simple CSS styles make the game visually appealing.
Running the Game
-
Set Up: Make sure you have React set up in your environment. You can use Create React App to set it up quickly.
-
Create Files:
- Create a file named
TicTacToe.js and place the game code inside.
- Create (or edit)
App.css for styling.
- In your main
App.js file, import and render the TicTacToe component.
import React from 'react';
import './App.css';
import TicTacToe from './TicTacToe';
const App = () => {
return (
<div>
<TicTacToe />
</div>
);
};
export default App;
Conclusion
This basic Tic-Tac-Toe game can be enhanced in various ways, such as adding an AI opponent, implementing a score counter, or allowing for different board sizes. Feel free to experiment and extend the game as you like!