Building Your Own 2048 Game: Complete Instructions

Building Your Own 2048 Game: Complete Instructions

·

6 min read

BuyMeACoffee

Project:- 11/500 2048 Game project.

Description

2048 is a single-player sliding block puzzle game. The objective of the game is to slide numbered tiles on a grid to combine them and create a tile with the number 2048. Players can continue to play the game after reaching the 2048 tile, creating tiles with larger numbers.

Features

  • Tile Movement: Slide tiles up, down, left, or right to combine tiles of the same number.

  • Scoring System: Keep track of the player's score, which increases as tiles are combined.

  • Game Over Detection: Detect when no more moves are possible and display a game over message.

Technologies Used

  • JavaScript: Implements game logic and interactivity.

  • HTML: Structures the game's layout.

  • CSS: Styles the game's appearance.

Setup

Follow these instructions to set up and run the 2048 game project:

  1. Clone the Repository:

     git clone https://github.com/deepakkumar55/ULTIMATE-JAVASCRIPT-PROJECT.git
     cd Games/4-2048_game
    
  2. Open the Project: Open the index.html file in your preferred web browser to start the game.

  3. Play the Game: Use the arrow keys to move the tiles. Combine tiles with the same number to reach the 2048 tile.

Contribution

Contributions to the 2048 game project are welcome. Follow these steps to contribute:

  1. Fork the Repository: Click the "Fork" button on the repository's GitHub page to create a copy of the repository under your GitHub account.

  2. Clone Your Fork:

     git clone https://github.com/your-username/ULTIMATE-JAVASCRIPT-PROJECT.git
     cd Games/4-2048_game
    
  3. Create a Branch: Create a new branch for your feature or bug fix.

     git checkout -b feature-name
    
  4. Make Changes: Make your changes to the codebase. Ensure your code follows the project's style guidelines.

  5. Commit Changes: Commit your changes with a descriptive commit message.

     git commit -m "Description of the changes"
    
  6. Push Changes: Push your changes to your forked repository.

     git push origin feature-name
    
  7. Create a Pull Request: Open a pull request from your fork's branch to the main repository's main branch. Provide a clear description of your changes and the purpose of the pull request.

Code

Here's a simple implementation of the 2048 game using JavaScript, HTML, and CSS.

HTML

Create an index.html file with the following content:

<!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="styles.css">
</head>
<body>
    <div class="game-container">
        <div id="score">Score: 0</div>
        <div class="grid" id="grid">
            <!-- Grid cells will be dynamically generated by JavaScript -->
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS

Create a styles.css file with the following content:

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #faf8ef;
    font-family: Arial, sans-serif;
}

.game-container {
    text-align: center;
}

#score {
    font-size: 24px;
    margin-bottom: 10px;
}

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

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

.grid-cell[data-value="2"] {
    background-color: #eee4da;
}

.grid-cell[data-value="4"] {
    background-color: #ede0c8;
}

.grid-cell[data-value="8"] {
    background-color: #f2b179;
    color: #f9f6f2;
}

/* Add more styles for other tile values as needed */

JavaScript

Create a script.js file with the following content:

document.addEventListener("DOMContentLoaded", () => {
    const gridDisplay = document.querySelector("#grid");
    const scoreDisplay = document.querySelector("#score");
    let squares = [];
    let score = 0;

    // Create the playing board
    function createBoard() {
        for (let i = 0; i < 16; i++) {
            let square = document.createElement("div");
            square.classList.add("grid-cell");
            square.innerHTML = 0;
            gridDisplay.appendChild(square);
            squares.push(square);
        }
        generate();
        generate();
    }

    // Generate a new number in a random empty square
    function generate() {
        let randomNumber = Math.floor(Math.random() * squares.length);
        if (squares[randomNumber].innerHTML == 0) {
            squares[randomNumber].innerHTML = 2;
            squares[randomNumber].setAttribute('data-value', 2);
            checkForGameOver();
        } else generate();
    }

    // Swipe right
    function moveRight() {
        for (let i = 0; i < 16; i++) {
            if (i % 4 === 0) {
                let totalOne = squares[i].innerHTML;
                let totalTwo = squares[i + 1].innerHTML;
                let totalThree = squares[i + 2].innerHTML;
                let totalFour = squares[i + 3].innerHTML;
                let row = [
                    parseInt(totalOne),
                    parseInt(totalTwo),
                    parseInt(totalThree),
                    parseInt(totalFour)
                ];

                let filteredRow = row.filter(num => num);
                let missing = 4 - filteredRow.length;
                let zeros = Array(missing).fill(0);
                let newRow = zeros.concat(filteredRow);

                squares[i].innerHTML = newRow[0];
                squares[i + 1].innerHTML = newRow[1];
                squares[i + 2].innerHTML = newRow[2];
                squares[i + 3].innerHTML = newRow[3];
                updateTileData(i, i + 1, i + 2, i + 3);
            }
        }
    }

    // Swipe left
    function moveLeft() {
        for (let i = 0; i < 16; i++) {
            if (i % 4 === 0) {
                let totalOne = squares[i].innerHTML;
                let totalTwo = squares[i + 1].innerHTML;
                let totalThree = squares[i + 2].innerHTML;
                let totalFour = squares[i + 3].innerHTML;
                let row = [
                    parseInt(totalOne),
                    parseInt(totalTwo),
                    parseInt(totalThree),
                    parseInt(totalFour)
                ];

                let filteredRow = row.filter(num => num);
                let missing = 4 - filteredRow.length;
                let zeros = Array(missing).fill(0);
                let newRow = filteredRow.concat(zeros);

                squares[i].innerHTML = newRow[0];
                squares[i + 1].innerHTML = newRow[1];
                squares[i + 2].innerHTML = newRow[2];
                squares[i + 3].innerHTML = newRow[3];
                updateTileData(i, i + 1, i + 2, i + 3);
            }
        }
    }

    // Swipe down
    function moveDown() {
        for (let i = 0; i < 4; i++) {
            let totalOne = squares[i].innerHTML;
            let totalTwo = squares[i + 4].innerHTML;
            let totalThree = squares[i + 8].innerHTML;
            let totalFour = squares[i + 12].innerHTML;
            let column = [
                parseInt(totalOne),
                parseInt(totalTwo),
                parseInt(totalThree),
                parseInt(totalFour)
            ];

            let filteredColumn = column.filter(num => num);
            let missing = 4 - filteredColumn.length;
            let zeros = Array(missing).fill(0);
            let newColumn = zeros.concat(filteredColumn);

            squares[i].innerHTML = newColumn[0];
            squares[i + 4].innerHTML = newColumn[1];
            squares[i + 8].innerHTML = newColumn[2];
            squares[i + 12].innerHTML = newColumn[3];
            updateTileData(i, i + 4, i + 8, i + 12);
        }
    }

    // Swipe up
    function moveUp() {
        for (let i = 0; i < 4; i++) {
            let totalOne = squares[i].innerHTML;
            let totalTwo =

 squares[i + 4].innerHTML;
            let totalThree = squares[i + 8].innerHTML;
            let totalFour = squares[i + 12].innerHTML;
            let column = [
                parseInt(totalOne),
                parseInt(totalTwo),
                parseInt(totalThree),
                parseInt(totalFour)
            ];

            let filteredColumn = column.filter(num => num);
            let missing = 4 - filteredColumn.length;
            let zeros = Array(missing).fill(0);
            let newColumn = filteredColumn.concat(zeros);

            squares[i].innerHTML = newColumn[0];
            squares[i + 4].innerHTML = newColumn[1];
            squares[i + 8].innerHTML = newColumn[2];
            squares[i + 12].innerHTML = newColumn[3];
            updateTileData(i, i + 4, i + 8, i + 12);
        }
    }

    // Combine rows
    function combineRow() {
        for (let i = 0; i < 15; i++) {
            if (squares[i].innerHTML === squares[i + 1].innerHTML) {
                let combinedTotal = parseInt(squares[i].innerHTML) + parseInt(squares[i + 1].innerHTML);
                squares[i].innerHTML = combinedTotal;
                squares[i + 1].innerHTML = 0;
                score += combinedTotal;
                scoreDisplay.innerHTML = `Score: ${score}`;
                updateTileData(i, i + 1);
            }
        }
        checkForWin();
    }

    // Combine columns
    function combineColumn() {
        for (let i = 0; i < 12; i++) {
            if (squares[i].innerHTML === squares[i + 4].innerHTML) {
                let combinedTotal = parseInt(squares[i].innerHTML) + parseInt(squares[i + 4].innerHTML);
                squares[i].innerHTML = combinedTotal;
                squares[i + 4].innerHTML = 0;
                score += combinedTotal;
                scoreDisplay.innerHTML = `Score: ${score}`;
                updateTileData(i, i + 4);
            }
        }
        checkForWin();
    }

    // Assign functions to keycodes
    function control(e) {
        if (e.keyCode === 39) {
            keyRight();
        } else if (e.keyCode === 37) {
            keyLeft();
        } else if (e.keyCode === 38) {
            keyUp();
        } else if (e.keyCode === 40) {
            keyDown();
        }
    }
    document.addEventListener("keyup", control);

    function keyRight() {
        moveRight();
        combineRow();
        moveRight();
        generate();
    }

    function keyLeft() {
        moveLeft();
        combineRow();
        moveLeft();
        generate();
    }

    function keyDown() {
        moveDown();
        combineColumn();
        moveDown();
        generate();
    }

    function keyUp() {
        moveUp();
        combineColumn();
        moveUp();
        generate();
    }

    function checkForWin() {
        for (let i = 0; i < squares.length; i++) {
            if (squares[i].innerHTML == 2048) {
                scoreDisplay.innerHTML = "You win!";
                document.removeEventListener("keyup", control);
            }
        }
    }

    function checkForGameOver() {
        let zeros = 0;
        for (let i = 0; i < squares.length; i++) {
            if (squares[i].innerHTML == 0) {
                zeros++;
            }
        }
        if (zeros === 0) {
            scoreDisplay.innerHTML = "Game Over!";
            document.removeEventListener("keyup", control);
        }
    }

    function updateTileData(...indices) {
        indices.forEach(index => {
            squares[index].setAttribute('data-value', squares[index].innerHTML);
        });
    }

    createBoard();
});

Get in Touch

If you have any questions or need further assistance, feel free to open an issue on GitHub or contact us directly. Your contributions and feedback are highly appreciated!


Thank you for your interest in the 2048 Game project. Together, we can build a more robust and feature-rich application. Happy coding!

💰 You can help me by Donating

BuyMeACoffee