Skip to main content

Command Palette

Search for a command to run...

Building Classic Games in React: Tic Tac Toe and 2048

Published
5 min read
Building Classic Games in React: Tic Tac Toe and 2048

Welcome, fellow game enthusiasts! In this blog post, we'll dive into the world of classic games and explore how to build them using React. We'll focus on two popular choices: Tic Tac Toe and 2048.

Tic Tac Toe: The Game of Strategy

Tic Tac Toe is a simple yet engaging game that requires strategic thinking. Let's break down the core logic and build a React implementation.

1. Game Board Representation:

  • We can represent the Tic Tac Toe board as a 2D array (3x3). Each cell can be either empty (null), 'X', or 'O'.
content_copyaddcompare_arrowsopen_in_fullconst board = [
  [null, null, null],
  [null, null, null],
  [null, null, null],
];

2. Player Turns:

  • We need to keep track of whose turn it is (X or O).
content_copyaddcompare_arrowsopen_in_fulllet currentPlayer = 'X';

3. Handling Moves:

  • When a player clicks on a cell, we update the board array with the player's symbol.

  • We then switch the currentPlayer to the other player.

4. Checking for a Winner:

  • After each move, we need to check if there's a winner.

  • We can do this by iterating through all possible winning combinations (rows, columns, diagonals) and checking if all cells in a combination have the same symbol.

5. Game Over:

  • If there's a winner, the game is over.

  • If the board is full and there's no winner, it's a draw.

React Implementation:

  • We can use a React component to render the game board.

  • Each cell can be a separate component that updates the board state when clicked.

  • We can use state management (e.g., useState) to track the board, current player, and game status.

Code Example (TicTacToe.js):

content_copyaddcompare_arrowsopen_in_fullimport React, { useState, useCallback, useEffect } from 'react';
import './TicTacToe.css';

// ... (X_ICON and O_ICON components)

const TicTacToe = () => {
  const [board, setBoard] = useState(Array(9).fill(null));
  const [isXNext, setIsXNext] = useState(true);
  const [gameMode, setGameMode] = useState('PVP');
  const [dialog, setDialog] = useState({ open: false, result: null });
  const [scores, setScores] = useState({ X: 0, O: 0, ties: 0 });

  useEffect(() => {
    if (gameMode === 'CPU' && !isXNext && !dialog.open) {
      setTimeout(() => computerMove(board), 500);
    }
  }, [isXNext, board, gameMode, dialog.open]);

  const checkWinner = (squares) => {
    // ... (Winning combinations logic)
  };

  const handleClick = (index) => {
    // ... (Handle player move logic)
  };

  const computerMove = useCallback((newBoard) => {
    // ... (Computer AI logic)
  }, [dialog.open]);

  const findBestMove = (board, player) => {
    // ... (Find best move for AI)
  };

  const handleCloseDialog = () => {
    // ... (Reset game logic)
  };

  return (
    <div className="tic-tac-toe">
      {/* ... (Game board, mode selection, score, and dialog components) */}
    </div>
  );
};

export default TicTacToe;

Explanation:

  • The board state holds the game board data.

  • isXNext tracks whose turn it is.

  • gameMode allows switching between player vs player (PVP) and player vs CPU modes.

  • dialog manages the game result dialog.

  • scores keeps track of the scores for X, O, and ties.

  • checkWinner checks for a winning combination.

  • handleClick handles player moves.

  • computerMove implements the AI logic for the CPU player.

  • findBestMove helps the AI find the best move.

  • handleCloseDialog resets the game.

2048: The Number Puzzle

2048 is a puzzle game where you slide numbered tiles on a grid, merging tiles with the same number. Here's the logic and a React implementation.

1. Game Grid:

  • We represent the game grid as a 2D array (4x4). Each cell can contain a number or be empty (0).
content_copyaddcompare_arrowsopen_in_fullconst grid = [
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
];

2. Generating New Tiles:

  • When the game starts, we generate a few random tiles with values of 2 or 4.

  • After each move, we generate a new tile with a probability.

3. Handling Moves:

  • When the user swipes (up, down, left, right), we shift the tiles in the corresponding direction.

  • If two tiles with the same number collide, they merge into a tile with the sum of their values.

4. Game Over:

  • The game ends when there are no more empty cells and no possible moves to merge tiles.

React Implementation:

  • We can use a React component to render the game grid.

  • Each tile can be a separate component that displays the number and handles animations.

  • We can use state management to track the grid, score, and game status.

Code Example (Game2048.js):

content_copyaddcompare_arrowsopen_in_fullimport React, { useState, useEffect } from 'react';
import './Game2048.css';

const Game2048 = () => {
  const [grid, setGrid] = useState(Array(16).fill(0));
  const [score, setScore] = useState(0);
  const [gameOver, setGameOver] = useState(false);

  useEffect(() => {
    // Generate initial tiles
    generateNewTile();
    generateNewTile();
  }, []);

  const generateNewTile = () => {
    // ... (Logic to generate a new tile randomly)
  };

  const handleSwipe = (direction) => {
    // ... (Logic to handle swipe movements and merge tiles)
  };

  const checkGameOver = () => {
    // ... (Logic to check if the game is over)
  };

  return (
    <div className="game-2048">
      {/* ... (Game grid, score display, and game over message) */}
    </div>
  );
};

export default Game2048;

Explanation:

  • The grid state holds the game grid data.

  • score tracks the player's score.

  • gameOver indicates whether the game is over.

  • generateNewTile creates a new tile randomly.

  • handleSwipe handles user swipe actions.

  • checkGameOver determines if the game is over.

Conclusion

Building classic games in React is a fun and rewarding experience. By understanding the core logic and using React's components and state management, you can create engaging and interactive games.

Next Steps:

  • Code Examples: I encourage you to explore code examples for Tic Tac Toe and 2048 in React. You can find many resources online, including GitHub repositories and tutorials.

  • Advanced Features: Once you have the basic logic in place, you can add advanced features like AI opponents, different game modes, and visual enhancements.

Happy coding!