Here is an example of building a Tic Tac Toe game in React. This example will show you how to create a Tic Tac Toe game with basic functionality.
First, create a new React component called TicTacToe
. The component will have a state object that includes an array of squares, the current player, and the winner. Here's the code for the initial component:
javascript
import React, { Component } from 'react';
class TicTacToe extends Component {
state = {
squares: Array(9).fill(null),
player: "X",
winner: null
};
render() {
return (
<div>
<h1>Tic Tac Toe</h1>
<div className="board">
{this.state.squares.map((square, index) => (
<div
key={index}
className="square"
onClick={() => this.handleSquareClick(index)}
>
{square}
</div>
))}
</div>
<p>Current player: {this.state.player}</p>
{this.state.winner && <p>Winner: {this.state.winner}</p>}
</div>
);
}
}
export default TicTacToe;
Next, let's add a function that handles a click on a square. We'll use this function to update the state object with the current player's move and check for a winner. Here's the code for the handleSquareClick
function:
javascript
handleSquareClick = (index) => {
const squares = [...this.state.squares];
if (squares[index] || this.state.winner) {
return;
}
squares[index] = this.state.player;
const winner = this.checkForWinner(squares);
this.setState({
squares,
player: this.state.player === "X" ? "O" : "X",
winner
});
};
Next, let's add a function that checks for a winner. We'll use this function to check if any player has won the game. Here's the code for the checkForWinner
function:
javascript
checkForWinner = (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;
};
Finally, let's add some styling to the component to create a Tic Tac Toe game board. Here's the CSS code for the board
and square
classes:
css
.board {
display: flex;
flex-wrap: wrap;
width: 240px;
margin: 0 auto;
}
.square {
width: 80px;
height: 80px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
font-size: 36px;
font-weight: bold;
cursor: pointer;
}
And that's it! We've created a basic Tic Tac Toe game in React. Here's the full code for
2 Comments
thank you very much,i found it useful for my assignment and it was well explained
ReplyDeleteMy Pleasure
Delete