Create Your Own 2048 Game Online with JavaScript (Source Code)

codinglabsolution

Discover how to develop your very own 2048 game using HTML, CSS, and JavaScript. Dive into game development with our comprehensive tutorial, complete with step-by-step instructions and provided source code.


Create Your Own 2048 Game Online with JavaScript (Source Code)






Embark on a journey to create your own 2048 game online using the power of JavaScript. In this tutorial, we'll delve into the fascinating realm of game development, providing you with detailed steps and insightful explanations along the way. By the end of this tutorial, you'll have not only built your own version of the popular 2048 game but also gained valuable insights into the intricacies of web-based game development. Let's dive in and unleash your creativity!

Source Code

Step 1 (HTML Code):



Here's a breakdown of its components:


- `<!DOCTYPE html>`: Declares the document type and version of HTML.

- `<html lang="en" dir="ltr">`: Defines the document's root element with the language set to English and direction left-to-right.

- `<head>`: Contains meta-information about the HTML document, such as the character encoding and title.

  - `<meta charset="utf-8">`: Sets the character encoding to UTF-8.

  - `<title>2048 Game Online</title>`: Sets the title of the webpage.

  - `<link rel="stylesheet" href="styles.css">`: Links an external CSS file named "styles.css" to style the webpage.

  - `<script src="script.js" charset="utf-8"></script>`: Links an external JavaScript file named "script.js" to provide functionality to the webpage.

- `<body>`: Contains the content of the webpage visible to users.

  - `<div class="container">`: Serves as a container for the entire game interface.

    - `<div class="info">`: Displays information about the game, including the game title and score.

      - `<h1>2048</h1>`: Displays the title "2048".

      - `<div class="score-container">`: Container for displaying the score.

        - `<div class="score-title">score</div>`: Label for the score.

        - `<span id="score">0</span>`: Displays the current score, initially set to 0.

    - `<span id="result">Join the numbers and get to the <b>2048</b> tile!</span>`: Provides instructions or game status updates to the player.

    - `<div class="grid"></div>`: Placeholder for the game grid where the tiles will be displayed.


This HTML structure sets the foundation for building the 2048 game interface. JavaScript will handle the game logic and user interactions, while CSS will style the elements to create an appealing visual experience.

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>2048 Game Online</title> <link rel="stylesheet" href="styles.css"> <script src="script.js" charset="utf-8"></script> </head> <body> <div class="container"> <div class="info"> <h1>2048</h1> <div class="score-container"> <div class="score-title">score</div> <span id="score">0</span> </div> </div> <span id="result">Join the numbers and get to the <b>2048</b> tile!</span> <div class="grid"></div> </div> </body> </html>

Read Also :Create a Maze Game with JavaScript 


Step 2 (CSS Code):


Sure, here's a simplified breakdown of the CSS styles used for the 2048 game interface:


1. **Body Styles:**

   - Sets the background color to a light beige.

   - Uses Flexbox to horizontally center the content within the body.

   - Specifies the font family for the entire document.


2. **Heading (h1):**

   - Sets the font size to 80 pixels.

   - Adjusts the line height for proper vertical alignment.

   - Sets the text color to a dark beige.

   - Removes margin to ensure the heading is positioned flush with the container.


3. **Container Styles:**

   - Sets the width of the container to 468 pixels.

   - Adds a top margin to create space between the heading and the game grid.


4. **Game Information (Info):**

   - Displays game information side by side using Flexbox.

   - Applies space-between alignment to evenly distribute space between elements.

   - Adds a bottom margin to create space between the game information and the game grid.


5. **Game Grid (Grid):**

   - Configures the game grid to use Flexbox for layout.

   - Enables wrapping of grid items for a multi-row layout.

   - Sets the width and height of the grid to accommodate grid items.

   - Sets background color, border color, border thickness, and rounded corners for visual appeal.

   - Adds a top margin to separate the grid from the game information.


6. **Grid Items (Grid div):**

   - Specifies styles for individual grid items (tiles).

   - Sets width, height, margin, border radius, background color, text color, font weight, text alignment, font size, and line height for each tile.


7. **Score Container Styles:**

   - Styles the container for displaying the score.

   - Centers the text horizontally within the container.

   - Sets width, height, border radius, background color, and text color for the container.


8. **Score Display (#score):**

   - Sets the font size of the score display.


9. **Score Title Styles (.score-title):**

   - Sets the font size of the score title.


These CSS styles work together to create a visually appealing and functional layout for the 2048 game interface.

body { background-color: #faf8ef; display: flex; justify-content: center; font-family: "Clear Sans", "Helvetica Neue"; } h1 { font-size: 80px; line-height: 0.7; color: #776E65; margin: 0px; } .container { width: 468px; margin-top: 10px; } .info { display: flex; justify-content: space-between; margin-bottom: 20px; } .grid{ display: flex; flex-wrap: wrap; width: 456px; height: 456px; background-color: #BBADA0; border: 7px solid #BBADA0; border-radius: 6px; margin-top: 20px; } .grid div { width: 100px; height: 100px; margin: 7px; border-radius: 3px; background-color: #EEE4DA; color: #afa192; font-weight: bold; text-align: center; font-size: 60px; line-height: 1.6; } .score-container { text-align: center; width: 70px; height: 60px; border-radius: 3px; background-color: #8f7a66; color: #FFFFFF; } #score { font-size: 30px; } .score-title { font-size: 16px; }


Step 3 (JavaScript Code):


This JavaScript code controls the functionality of the 2048 game. Here's a breakdown of what each part does:


1. Event Listener:

   - Listens for the `DOMContentLoaded` event, which fires when the initial HTML document has been completely loaded and parsed.


2. Variable Declarations:

   - `gridDisplay`, `scoreDisplay`, and `resultDisplay` store references to specific elements in the HTML document.

   - `squares` is an array that will hold references to each square tile on the game board.

   - `width` defines the width of the game board (4x4 grid).

   - `score` keeps track of the player's score.


3. Create Board Function:

   - Generates the initial game board by creating 16 square tiles (4x4 grid) and appending them to the grid display element.

   - Initializes two tiles with a value of 2.


4. Generate Function:

   - Randomly selects an empty square tile and assigns it a value of 2.

   - Checks for game over conditions after generating a new tile.


5. Move Functions (moveRight, moveLeft, moveUp, moveDown):

   - Implements tile movement logic for each direction by iterating over the grid.

   - Combines adjacent tiles with the same value if they collide during movement.

   - Generates a new tile after each move.


6. Combine Functions (combineRow, combineColumn):

   - Combines adjacent tiles in a row or column if they have the same value.

   - Updates the score accordingly.


7. Control Function:

   - Listens for keyup events and executes corresponding move functions based on the pressed arrow key.


8. Key Functions (keyRight, keyLeft, keyUp, keyDown):

   - Wrapper functions for move functions that handle key presses.


9. Win and Game Over Check Functions (checkForWin, checkForGameOver):

   - Checks for a winning condition (reaching 2048) or a game over condition (no empty tiles).


10. Clear Function:

   - Clears the timer used for adding colors to tiles.


11. Add Colors Function (addColours):

   - Applies background colors to tiles based on their value.


12. Timer and Interval (myTimer):

   - Periodically updates tile colors using the `addColours` function.


This code creates the core game mechanics for the 2048 game, allowing players to move tiles, combine them, track their score, and win or lose the game.


document.addEventListener('DOMContentLoaded', () =>  {
  const gridDisplay = document.querySelector('.grid')
  const scoreDisplay = document.getElementById('score')
  const resultDisplay = document.getElementById('result')
  let squares = []
  const width = 4
  let score = 0

  //create the playing board
  function createBoard() {
    for (let i=0; i < width*width; i++) {
      square = document.createElement('div')
      square.innerHTML = 0
      gridDisplay.appendChild(square)
      squares.push(square)
    }
    generate()
    generate()
  }
  createBoard()

  //generate a new number
  function generate() {
    randomNumber = Math.floor(Math.random() * squares.length)
    if (squares[randomNumber].innerHTML == 0) {
      squares[randomNumber].innerHTML = 2
      checkForGameOver()
    } else generate()
  }

  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]
      }
    }
  }

  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]
      }
    }
  }


  function moveUp() {
    for (let i=0; i < 4; i++) {
      let totalOne = squares[i].innerHTML
      let totalTwo = squares[i+width].innerHTML
      let totalThree = squares[i+(width*2)].innerHTML
      let totalFour = squares[i+(width*3)].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 +width].innerHTML = newColumn[1]
      squares[i+(width*2)].innerHTML = newColumn[2]
      squares[i+(width*3)].innerHTML = newColumn[3]
    }
  }

  function moveDown() {
    for (let i=0; i < 4; i++) {
      let totalOne = squares[i].innerHTML
      let totalTwo = squares[i+width].innerHTML
      let totalThree = squares[i+(width*2)].innerHTML
      let totalFour = squares[i+(width*3)].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 +width].innerHTML = newColumn[1]
      squares[i+(width*2)].innerHTML = newColumn[2]
      squares[i+(width*3)].innerHTML = newColumn[3]
    }
  }

  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
      }
    }
    checkForWin()
  }

  function combineColumn() {
    for (let i =0; i < 12; i++) {
      if (squares[i].innerHTML === squares[i +width].innerHTML) {
        let combinedTotal = parseInt(squares[i].innerHTML) + parseInt(squares[i +width].innerHTML)
        squares[i].innerHTML = combinedTotal
        squares[i +width].innerHTML = 0
        score += combinedTotal
        scoreDisplay.innerHTML = score
      }
    }
    checkForWin()
  }

  //assign functions to keyCodes
  function control(e) {
    if(e.keyCode === 37) {
      keyLeft()
    } else if (e.keyCode === 38) {
      keyUp()
    } else if (e.keyCode === 39) {
      keyRight()
    } else if (e.keyCode === 40) {
      keyDown()
    }
  }
  document.addEventListener('keyup', control)

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

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

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

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

  //check for the number 2048 in the squares to win
  function checkForWin() {
    for (let i=0; i < squares.length; i++) {
      if (squares[i].innerHTML == 2048) {
        resultDisplay.innerHTML = 'You WIN'
        document.removeEventListener('keyup', control)
        setTimeout(() => clear(), 3000)
      }
    }
  }

  //check if there are no zeros on the board to lose
  function checkForGameOver() {
    let zeros = 0
    for (let i=0; i < squares.length; i++) {
      if (squares[i].innerHTML == 0) {
        zeros++
      }
    }
    if (zeros === 0) {
      resultDisplay.innerHTML = 'You LOSE'
      document.removeEventListener('keyup', control)
      setTimeout(() => clear(), 3000)
    }
  }

  //clear timer
  function clear() {
    clearInterval(myTimer)
  }


  //add colours
  function addColours() {
    for (let i=0; i < squares.length; i++) {
      if (squares[i].innerHTML == 0) squares[i].style.backgroundColor = '#afa192'
      else if (squares[i].innerHTML == 2) squares[i].style.backgroundColor = '#eee4da'
      else if (squares[i].innerHTML  == 4) squares[i].style.backgroundColor = '#ede0c8'
      else if (squares[i].innerHTML  == 8) squares[i].style.backgroundColor = '#f2b179'
      else if (squares[i].innerHTML  == 16) squares[i].style.backgroundColor = '#ffcea4'
      else if (squares[i].innerHTML  == 32) squares[i].style.backgroundColor = '#e8c064'
      else if (squares[i].innerHTML == 64) squares[i].style.backgroundColor = '#ffab6e'
      else if (squares[i].innerHTML == 128) squares[i].style.backgroundColor = '#fd9982'
      else if (squares[i].innerHTML == 256) squares[i].style.backgroundColor = '#ead79c'
      else if (squares[i].innerHTML == 512) squares[i].style.backgroundColor = '#76daff'
      else if (squares[i].innerHTML == 1024) squares[i].style.backgroundColor = '#beeaa5'
      else if (squares[i].innerHTML == 2048) squares[i].style.backgroundColor = '#d7d4f0'
    }
}
addColours()

var myTimer = setInterval(addColours, 50)

})

Final Output:


#JavaScript #GameDevelopment #WebDevelopment #2048Game #HTML #CSS #SourceCode

Source Code : Download files

Conclusion:


In conclusion, by following the provided JavaScript source code and accompanying HTML and CSS files, you can create your own 2048 game online. The source code provides the essential functionality for generating the game board, handling user input, updating the score, and checking for win or loss conditions.


To create your own 2048 game, you can use this source code as a foundation and further customize it according to your preferences. You can enhance the game with additional features such as animations, sound effects, or different themes. Additionally, you can optimize the code for better performance or add multiplayer functionality to make the game more interactive.


By understanding and modifying the provided source code, you can develop your JavaScript skills and gain hands-on experience in game development. Get creative and enjoy the process of building your very own 2048 game online!


Tags: #JavaScript #GameDevelopment #WebDevelopment #2048Game #HTML #CSS #SourceCode

إرسال تعليق

ملفات تعريف الارتباط
نستخدم ملفات تعريف الارتباط (Cookies) لفهم كيفية استخدامك لموقعنا وتحسين تجربتك في المحتوى والإعلانات. باستمرارك في تصفح الموقع، فإنك توافق على استخدامنا لملفات تعريف الارتباط وفقًا لسياسة الخصوصية لدينا.
أُووبس!
يبدو أن هناك خطأ ما في اتصالك بالإنترنت. يرجى الاتصال بالإنترنت وبدء التصفح مرة أخرى.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.