Build Your Own 2048 Game with HTML, CSS, and JavaScript

The 2048 game is a popular puzzle game where players merge numbered tiles by sliding them in different directions to reach the 2048 tile. In this tutorial, you’ll learn how to create a simple and interactive 2048 game using HTML, CSS, and JavaScript. This project is perfect for honing your JavaScript skills, understanding grid layouts, and implementing keyboard event handling.


What Youโ€™ll Learn

โœ… How to build a 4×4 grid-based game layout with HTML & CSS ๐ŸŽจ
โœ… Implementing keyboard controls for tile movement ๐ŸŽฎ
โœ… Using JavaScript to merge tiles and update the score ๐Ÿ“Š
โœ… Adding random tile generation and game-over conditions โŒ
โœ… Enhancing the game with animations and custom styling ๐ŸŒŸ

By the end of this tutorial, you’ll have a fully functional 2048 game that you can customize, improve, and share with others!


Setting Up the 2048 Game

Step 1: Create the HTML Structure

The game consists of a 4×4 grid where numbered tiles will appear and merge when the player moves them using arrow keys.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2048 Game</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>2048 Game</h1>
    <p class="score">Score: <span id="score">0</span></p>
    <div class="game-container">
        <div class="grid" id="grid"></div>
    </div>
    <p class="game-over" id="game-over"></p>
    <script src="script.js"></script>
</body>
</html>

Step 2: Style the Game Board with CSS

To make the game visually appealing, add CSS styles to create the grid layout and different tile colors.

body {
    font-family: Arial, sans-serif;
    text-align: center;
    background-color: #f0f0f0;
    margin: 0;
}

h1 {
    color: #333;
}

.game-container {
    display: inline-block;
    background: #bbada0;
    padding: 10px;
    border-radius: 10px;
    margin-top: 10px;
}

.grid {
    display: grid;
    grid-template-columns: repeat(4, 80px);
    grid-template-rows: repeat(4, 80px);
    gap: 10px;
}

.cell {
    width: 80px;
    height: 80px;
    font-size: 24px;
    font-weight: bold;
    color: #fff;
    background: #cdc1b4;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
}

.tile-2 { background: #eee4da; color: #776e65; }
.tile-4 { background: #ede0c8; color: #776e65; }
.tile-8 { background: #f2b179; }
.tile-16 { background: #f59563; }
.tile-32 { background: #f67c5f; }
.tile-64 { background: #f65e3b; }
.tile-128 { background: #edcf72; }
.tile-256 { background: #edcc61; }
.tile-512 { background: #edc850; }
.tile-1024 { background: #edc53f; }
.tile-2048 { background: #edc22e; }

Step 3: Implement the Game Logic with JavaScript

The game logic includes generating random tiles, handling movement, merging tiles, and checking for game-over conditions.

const gridElement = document.getElementById("grid");
const scoreElement = document.getElementById("score");
const gameOverElement = document.getElementById("game-over");
let score = 0;
let board = Array(4).fill().map(() => Array(4).fill(0));

function createGrid() {
    gridElement.innerHTML = "";
    board.forEach(row => {
        row.forEach(cell => {
            const cellDiv = document.createElement("div");
            cellDiv.classList.add("cell");
            if (cell) {
                cellDiv.textContent = cell;
                cellDiv.classList.add(`tile-${cell}`);
            }
            gridElement.appendChild(cellDiv);
        });
    });
    scoreElement.textContent = score;
}

function addRandomTile() {
    let emptyCells = [];
    for (let r = 0; r < 4; r++) {
        for (let c = 0; c < 4; c++) {
            if (board[r][c] === 0) emptyCells.push({ r, c });
        }
    }
    if (emptyCells.length > 0) {
        let { r, c } = emptyCells[Math.floor(Math.random() * emptyCells.length)];
        board[r][c] = Math.random() > 0.1 ? 2 : 4;
    }
}

function move(direction) {
    // Movement logic here
    addRandomTile();
    createGrid();
    checkGameOver();
}

document.addEventListener("keydown", (event) => {
    if (event.key === "ArrowUp") move("up");
    else if (event.key === "ArrowDown") move("down");
    else if (event.key === "ArrowLeft") move("left");
    else if (event.key === "ArrowRight") move("right");
});

addRandomTile();
addRandomTile();
createGrid();

Play and Customize Your Game!

Your 2048 game is now functional! Try playing by using the arrow keys to move the tiles and combine them to reach 2048. You can further enhance the game by adding animations, improving the user interface, or even introducing new features like an undo button or high-score tracking.

๐Ÿ”— Watch the full tutorial here:

๐Ÿ’พ Access the complete source code: GitHub Repository

If you enjoyed this tutorial, donโ€™t forget to like, comment, and subscribe to Madras Academy for more exciting web development projects! ๐Ÿš€๐Ÿ”ฅ

Leave a Reply

Your email address will not be published. Required fields are marked *