How to build a tic-tac-toe game using react
Tic-tac-toe is the most popular game on the internet. Most of us very well know this game. It gives us lots of fun to play this game. And we can also play this game with friends. This game is available offline and online. It is best to pass the time.
In this article, we will learn how to build a tic-tac-toe game using react. As we know, to improve skills we should build projects. A project like this gives you the best understanding of core concepts. To create this project basic knowledge of react js is required. You should be aware of some react js core concepts such as react hook, props, ES6 features, etc.
I also provide react source code for you or you can see the full code on the GitHub repository.
The logic of the tic-tac-toe game
This tic-tac-toe game contains nine boxes in a 3×3 box. And a heading that displays turns. This heading tells which player should play. Two players can play this game. The player who has the first move is ×. And the player who has the second move is ○. Players will move one by one. The player who fills boxes vertically, diagonally, and horizontally wins. If the match draws reload the window to restart it. This game is easy and has basic logic. It does not take too hard to understand it.
Installation
This project is created using vite, react, and tailwindcss. So, to start with it install react using vite, and don't forget about tailwindcss. You can also install react using react webpack. Vite is used to increasing the speed of the app. If you don't want vite for your project you can skip it.
Folder structure
It doesn't contain a complex structure. If you are familiar with react you can
understand it easily.
This app contains only two files Boxes.jsx
and
App.jsx
.
-
App.jsx
contains the logic of the tic-tac-toe game and it is the main file of the app. -
Boxes.jsx
has the code of the box which calls in the main file.
Adding code to the App.jsx
file
Copy the source code below and paste it into the
App.jsx
file. We will understand it later.
Source code of App.jsx
file
import React from "react"; import { useState } from "react"; import Boxes from "./Boxes"; const GameScreen = () => { const [state, setState] = useState(Array(9).fill(null)); const [isXTurn, setIsXTurn] = useState(true); const checkWinner = () => { const winnerLogic = [ [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 logic of winnerLogic) { const [a, b, c] = logic; // console.log(logic); if (state[a] !== null && state[a] === state[b] && state[a] === state[c]) { return state[a]; } } return false; }; const isWinner = checkWinner(); // console.log(isWinner); const handleEvent = (index) => { if (state[index] !== null) { return; } const copyState = [...state]; copyState[index] = isXTurn ? "x" : "o"; setState(copyState); setIsXTurn(!isXTurn); }; console.log(isWinner); return ( <div className="w-screen max-w-7xl min-h-screen flex justify-center flex-col items-center select-none"> <h1 className="text-[#ff9a9e] font-bold text-2xl mb-5 "> {isXTurn ? "X" : "O"}'s Turn! </h1> <div className=" w-60 h-60 sm:w-96 sm:h-96 bg-gradient-to-br from-[#ff9a9e] to-[#ffaa93] grid grid-cols-3 grid-rows-3 gap-1 overflow-hidden place-items-stretch relative rounded-lg"> {isWinner ? ( <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 flex justify-center items-center flex-col text-center "> <h1 className="text-white font-bold text-4xl sm:text-5xl">{`${isWinner} won!`}</h1> <button className="w-fit h-fit p-2 bg-white rounded-md mt-3 font-semibold text-[#f1a894]" onClick={() => { setState(Array(9).fill(null)); }} > Play Again </button> </div> ) : ( <> <Boxes value={state[0]} onClick={() => handleEvent(0)} /> <Boxes value={state[1]} onClick={() => handleEvent(1)} /> <Boxes value={state[2]} onClick={() => handleEvent(2)} /> <Boxes value={state[3]} onClick={() => handleEvent(3)} /> <Boxes value={state[4]} onClick={() => handleEvent(4)} /> <Boxes value={state[5]} onClick={() => handleEvent(5)} /> <Boxes value={state[6]} onClick={() => handleEvent(6)} /> <Boxes value={state[7]} onClick={() => handleEvent(7)} /> <Boxes value={state[8]} onClick={() => handleEvent(8)} /> </> )} </div> </div> ); }; export default GameScreen;
Understanding the code
The jsx section of this tic-tac-toe project has three main elements heading, game container, and winner screen.
Here heading displays which player should move. It uses a state variable named
isXTrurn
. If isXTrurn
is true it displays, it is an "X" player turn or
if isXTrurn
is false it displays, it is an "O" turn.
The game container contains boxes that come from the
Boxes.jsx
file. We call Boxes components nine times that make
nine boxes in the game container. In every box, two props are passed. First is
a value (X or O) and a function named "handleEvent". This function accepts the
index value of the clicked box and passes an array into the state variable
named "state". It also changes the turn of the player. Basically, this
function is responsible for filling the boxes with "X" and "O".
The winner screen displays when any one player wins the game. The function
checkWinner
is used here to display the winner screen. If any one
player wins the game this function returns the player's name or if the match
is drawn then it returns false. If the function returns the player name then
the winner displays on the winner screen.
Let's see how the checkWinner
function works. This function has
an array that contains all of the patterns of game winnings. Then it checks
the winner and returns the winner's name if any one player wins.
It is time to add the code to the boxes.
Adding code to the Boxes.jsx
file
Boxes.jsx
file.
const Boxes = (props) => { return ( <> <div onClick={props.onClick} className=" bg-white grid place-items-center text-5xl font-semibold text-[#ff9a9e]" > {props.value} </div> </> ); }; export default Boxes;
Understanding the source code
The component in this file has the code of the box which calls in the game container. This component accepts props that come from the main file.
Conclusion
Well, this is pretty tough for a beginner. But once you try it, it becomes easy. This project can clear your basic concepts of react js. You can also add it to your portfolio. It definitely increases your impression.
This tic-tac-toe game also improves your logic-building and coding skills. There is a lot of fun in this project. And you can also play this game with your friends.
Thank you!