,

Tutorial: Building TicTacToe Game with React and GatsbyJS

Posted by


In this tutorial, we will be building a Tic Tac Toe game using React and GatsbyJS. Tic Tac Toe is a classic two-player game where players take turns placing either an ‘X’ or an ‘O’ on a 3×3 grid. The goal of the game is to get three of your symbols in a row either horizontally, vertically, or diagonally.

Before we get started, make sure you have Node.js installed on your computer. You can download it from the official Node.js website.

Step 1: Set up a new Gatsby site
To get started, let’s create a new Gatsby site by running the following command in your terminal:

npx gatsby new tictactoe

This command will create a new Gatsby site in a folder named ‘tictactoe’. Navigate into the folder by running:

cd tictactoe

Step 2: Install dependencies
Next, we need to install some dependencies for our project. Run the following command in your terminal:

npm install react react-dom gatsby react-helmet

Step 3: Create the Tic Tac Toe game component
Now that we have set up our project, let’s create a new component for our Tic Tac Toe game. Inside the src folder, create a new file called TicTacToe.js and add the following code:

import React, { useState } from 'react';

const TicTacToe = () => {
  const [board, setBoard] = useState(Array(9).fill(null));
  const [isXNext, setIsXNext] = useState(true);
  const winner = calculateWinner(board);

  const handleClick = (i) => {
    const newBoard = board.slice();

    if (winner || newBoard[i]) {
      return;
    }

    newBoard[i] = isXNext ? 'X' : 'O';
    setBoard(newBoard);
    setIsXNext(!isXNext);
  };

  const renderSquare = (i) => {
    return (
      <button className="square" onClick={() => handleClick(i)}>
        {board[i]}
      </button>
    );
  };

  const status = winner
    ? `Winner: ${winner}`
    : `Next player: ${isXNext ? 'X' : 'O'}`;

  return (
    <div>
      <div className="status">{status}</div>
      <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>
  );
};

export default TicTacToe;

function calculateWinner(board) {
  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 (board[a] && board[a] === board[b] && board[a] === board[c]) {
      return board[a];
    }
  }

  return null;
}

This code creates the TicTacToe component that will handle the game logic and rendering of the game board. It uses the useState hook to manage the game state, such as the current board state, the player who is currently playing (‘X’ or ‘O’), and the winner of the game. The handleClick function is called when a player clicks on a square on the game board, updating the board state accordingly.

Step 4: Create the game stylesheet
Next, let’s create a CSS file for styling our game. Inside the src folder, create a new file called styles.css and add the following CSS code:

.square {
  background: #fff;
  border: 1px solid #999;
  float: left;
  font-size: 24px;
  font-weight: bold;
  line-height: 34px;
  height: 34px;
  margin-right: -1px;
  margin-top: -1px;
  padding: 0;
  text-align: center;
  width: 34px;
}

.board-row:after {
  clear: both;
  content: "";
  display: table;
}

Step 5: Update the layout component
Finally, update the layout.js file in the src folder to include the TicTacToe component. Import the TicTacToe component at the top of the file and add it to the layout like this:

import React from 'react';
import { Helmet } from 'react-helmet';
import TicTacToe from './TicTacToe';

import './styles.css';

const Layout = ({ children }) => (
  <>
    <Helmet title="Tic Tac Toe Game" />
    <div>{children}</div>
    <div>
      <TicTacToe />
    </div>
  </>
);

export default Layout;

Step 6: Start the development server
To see your Tic Tac Toe game in action, start the development server by running the following command in your terminal:

gatsby develop

Open your browser and navigate to http://localhost:8000 to see your Tic Tac Toe game in action. You can click on the squares to place your ‘X’ or ‘O’ and try to win the game!

Congratulations! You have successfully built a Tic Tac Toe game using React and GatsbyJS. You can further customize and enhance the game by adding features such as keeping score, highlighting the winning squares, or adding a reset button. Have fun playing and experimenting with your new game!

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x