Home

Published

- 3 min read

How to create a tic tac toe game in react.js

img of How to create a tic tac toe game in react.js

Intro

If you love to learn to react by creating cool stuff, this post is for you. I’m building a simple tic-tac-toe game using React. This is not the first time I’ve created this game, I had already made this game when I was learning programming at an early stage in C++ language. But that was built on a console and This time I’m using React.js to build the game with the user interface.

Step 1: Creating the game component

Now inside the src/components/game.jsx. We will add two state variables, status and gameData, status will be used to carry the status of the game e.g. Who is currently playing, Finishing the game, and showing the winner. gameData variable will store the values in 9 cells that are initially nulled and the current player of the game (X or O).

   import React, { useState } from 'react'

export const Game = () => {
	const [status, setStatus] = useState('Current Player : X ')
	const [gameData, setGameData] = useState({
		squares: Array(9).fill(null),
		xIsNext: false
	})
	return <div></div>
}

Step 2: Design UI and cells

   import React from 'react'

export const Game = () => {
  ......

  const Square = ({squareIndex}) =>  {
    return (
      <button className="square" onClick={() => handleClick(squareIndex)}>
      {
        // Display Cell value at given index
        gameData.squares[squareIndex]
      }
    </button>
    );
  }
  return (
   <div>
      <div className="status">{status}</div>
        <div className="board-row">
          <Square squareIndex={0} />
          <Square squareIndex={1} />
          <Square squareIndex={2} />
        </div>
      <div className="board-row">
        <Square squareIndex={3} />
        <Square squareIndex={4} />
        <Square squareIndex={5} />
      </div>
      <div className="board-row">
        <Square squareIndex={6} />
        <Square squareIndex={7} />
        <Square squareIndex={8} />
      </div>
    </div>
  )
}

Step 3: Implement the Click function

   const handleClick = (i) => {
	const squares = gameData.squares.slice()
	if (calculateWinner(squares) || squares[i]) {
		return
	}
	squares[i] = gameData.xIsNext ? 'O' : 'X'
	setGameData({
		squares,
		xIsNext: !gameData.xIsNext
	})
	setStatus('Current Player: ' + (gameData.xIsNext ? 'X' : 'O'))
	const winner = calculateWinner(squares)
	if (winner) {
		setStatus('Game Over! : ' + winner + ' is winner')
	}
}

Step 4: Writing algorithm to check the winner on every state/click

   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
}

The function calculateWinner is a logic of checking the winner at each stage. It accepts the current values in the cell array and matches the pattern defined in lines a variable. This variable is a 2-dimensional which is looped and compared with either row, column, or diagonal values If the values are saved in the condition. It will return the value (X or O) which is matching to the pattern otherwise it will return a null value. Here is the output of the code