How to create a simple 2048 game with Reac.js in less than 30 mins?

How to create a simple 2048 game with Reac.js in less than 30 mins?
Photo by Ben Robbins / Unsplash

Creating a simple 2048 game with React.js involves breaking down the game logic into components, managing state, and handling user interactions. Below is a step-by-step tutorial to guide you through the process:

Step 1: Set Up React App

Make sure you have Node.js and npm installed. If not, you can download and install them from here.

Open your terminal and run the following commands to create a new React app:

npx create-react-app react-2048
cd react-2048

Step 2: Create the Game Board Component

Create a new file called GameBoard.js in the src folder:

// src/GameBoard.js
import React, { useState, useEffect } from 'react';

const GameBoard = () => {
  const [board, setBoard] = useState(Array(4).fill(Array(4).fill(null)));

  useEffect(() => {
    // Initialize the game board
    // You'll implement this function later
    initializeBoard();
  }, []);

  const initializeBoard = () => {
    // Implement logic to initialize the game board
  };

  return (
    <div>
      {/* Render the game board */}
      {board.map((row, rowIndex) => (
        <div key={rowIndex} className="row">
          {row.map((cell, colIndex) => (
            <div key={colIndex} className="cell">
              {cell}
            </div>
          ))}
        </div>
      ))}
    </div>
  );
};

export default GameBoard;

Step 3: Style the Game Board

Add some basic styling to the App.css file in the src folder:

/* src/App.css */
.row {
  display: flex;
}

.cell {
  width: 80px;
  height: 80px;
  margin: 5px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
}

Step 4: Integrate GameBoard Component in App.js

Open src/App.js and replace its content with the following:

// src/App.js
import React from 'react';
import './App.css';
import GameBoard from './GameBoard';

function App() {
  return (
    <div className="App">
      <h1>2048 Game</h1>
      <GameBoard />
    </div>
  );
}

export default App;

Step 5: Implement Game Logic

Now, let's implement the game logic in GameBoard.js. Update the initializeBoard function:

// src/GameBoard.js
// ... (previous code)

const GameBoard = () => {
  const [board, setBoard] = useState(Array(4).fill(Array(4).fill(null)));

  useEffect(() => {
    initializeBoard();
  }, []);

  const initializeBoard = () => {
    const newBoard = Array.from({ length: 4 }, () => Array(4).fill(null));
    addRandomTile(newBoard);
    addRandomTile(newBoard);
    setBoard(newBoard);
  };

  const addRandomTile = (board) => {
    const emptyCells = [];
    board.forEach((row, rowIndex) => {
      row.forEach((cell, colIndex) => {
        if (cell === null) {
          emptyCells.push({ row: rowIndex, col: colIndex });
        }
      });
    });

    if (emptyCells.length > 0) {
      const randomIndex = Math.floor(Math.random() * emptyCells.length);
      const { row, col } = emptyCells[randomIndex];
      board[row][col] = Math.random() < 0.9 ? 2 : 4;
    }
  };

  return (
    <div>
      {board.map((row, rowIndex) => (
        <div key={rowIndex} className="row">
          {row.map((cell, colIndex) => (
            <div key={colIndex} className="cell">
              {cell}
            </div>
          ))}
        </div>
      ))}
    </div>
  );
};

export default GameBoard;

Step 6: Run Your App

Save your files and run the app:

npm start

Visit http://localhost:3000 in your browser to see the 2048 game in action.

Step 7: Add User Interactions (Optional)

You can enhance the game by adding keyboard controls or swipe gestures for user interactions. This involves handling events like key presses and touch events and updating the game state accordingly. Implementing user interactions goes beyond the scope of this basic tutorial, but you can explore libraries like react-swipeable for swipe gestures.

Congratulations! You've created a simple 2048 game using React.js. Feel free to expand on this foundation by adding more features, styling, and animations to make your game more engaging.








Open-source Apps

9,500+

Medical Apps

500+

Lists

450+

Dev. Resources

900+