Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html>
<head>
  <title>2048 Game</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <h1>2048</h1>
  <div class="container">
    <div id="grid-container">
      <!-- Grid cells will be dynamically created here -->
    </div>
   <div id="score">Score: 0</div>
    <button id="reset-button">Reset</button>
  </div>
  
  <script src="script.js"></script>
</body>
</html>

              
            
!

CSS

              
                body {
  text-align: center;
  font-family: 'Roboto', sans-serif;
  background-color: #f3f3f3;
  color: #333;
}

h1 {
  margin-top: 20px;
  font-size: 48px;
  font-weight: bold;
}

.container {
  margin-top: 30px;
}

#grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  background-color: #faf8ef;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.cell {
  width: 100%;
  height: 100px;
  background-color: #cdc1b4;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36px;
  font-weight: bold;
  border-radius: 5px;
  transition: background-color 0.3s ease-in-out;
}

#score {
  font-size: 24px;
  margin-top: 20px;
}

#reset-button {
  font-size: 18px;
  margin-top: 20px;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #333;
  color: #fff;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}

#reset-button:hover {
  background-color: #555;
}

#reset-button:focus {
  outline: none;
}

.tile-2 {
  background-color: #eee4da;
  color: #776e65;
}

.tile-4 {
  background-color: #ede0c8;
  color: #776e65;
}

.tile-8 {
  background-color: #f2b179;
  color: #fff;
}

.tile-16 {
  background-color: #f59563;
  color: #fff;
}

.tile-32 {
  background-color: #f67c5f;
  color: #fff;
}

.tile-64 {
  background-color: #f65e3b;
  color: #fff;
}

.tile-128 {
  background-color: #edcf72;
  color: #fff;
}

.tile-256 {
  background-color: #edcc61;
  color: #fff;
}

.tile-512 {
  background-color: #edc850;
  color: #fff;
}

.tile-1024 {
  background-color: #edc53f;
  color: #fff;
}

.tile-2048 {
  background-color: #edc22e;
  color: #fff;
}

.tile-4096 {
  background-color: #3c3a32;
  color: #fff;
}

.tile-8192 {
  background-color: #3c3a32;
  color: #fff;
}

.tile-16384 {
  background-color: #3c3a32;
  color: #fff;
}

.tile-32768 {
  background-color: #3c3a32;
  color: #fff;
}

.tile-65536 {
  background-color: #3c3a32;
  color: #fff;
}

.tile-131072 {
  background-color: #3c3a32;
  color: #fff;
}

.tile-262144 {
  background-color: #3c3a32;
  color: #fff;
}

.tile-524288 {
  background-color: #3c3a32;
  color: #fff;
}

.tile-1048576 {
  background-color: #3c3a32;
  color: #fff;
}

              
            
!

JS

              
                document.addEventListener("DOMContentLoaded", () => {
  const gridContainer = document.getElementById("grid-container");
  const scoreDisplay = document.getElementById("score");
  const resetButton = document.getElementById("reset-button");
  
  let grid = [];
  let score = 0;

  // Create the initial grid
  function createGrid() {
    for (let i = 0; i < 4; i++) {
      grid[i] = [];
      for (let j = 0; j < 4; j++) {
        grid[i][j] = 0;
      }
    }
  }

  // Add a new number (2 or 4) to an empty cell
  function addNewNumber() {
    const availableCells = [];
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (grid[i][j] === 0) {
          availableCells.push({ row: i, col: j });
        }
      }
    }
    if (availableCells.length > 0) {
      const randomCell = availableCells[Math.floor(Math.random() * availableCells.length)];
      const newValue = Math.random() < 0.9 ? 2 : 4;
      grid[randomCell.row][randomCell.col] = newValue;
    }
  }

  // Update the grid view
  function updateGrid() {
    gridContainer.innerHTML = "";
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        const cellValue = grid[i][j];
        const cellDiv = document.createElement("div");
        cellDiv.className = "cell";
        cellDiv.textContent = cellValue > 0 ? cellValue : "";
        cellDiv.style.backgroundColor = getCellColor(cellValue);
        gridContainer.appendChild(cellDiv);
      }
    }
    scoreDisplay.textContent = "Score: " + score;
  }

  // Get the background color for a cell based on its value
  function getCellColor(value) {
    switch (value) {
      case 2: return "#EEE4DA";
      case 4: return "#EDE0C8";
      case 8: return "#F2B179";
      case 16: return "#F59563";
      case 32: return "#F67C5F";
      case 64: return "#F65E3B";
      case 128: return "#EDCF72";
      case 256: return "#EDCC61";
      case 512: return "#EDC850";
      case 1024: return "#EDC53F";
      case 2048: return "#EDC22E";
      default: return "#CDC1B4";
    }
  }

  // Check if the game is over
  function isGameOver() {
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (grid[i][j] === 0) {
          return false;
        }
        if (i < 3 && grid[i][j] === grid[i + 1][j]) {
          return false;
        }
        if (j < 3 && grid[i][j] === grid[i][j + 1]) {
          return false;
        }
      }
    }
    return true;
  }

  // Reset the game
  function resetGame() {
    createGrid();
    addNewNumber();
    addNewNumber();
    score = 0;
    updateGrid();
  }

  // Handle keyboard events
  function handleKeyPress(event) {
    if (event.keyCode >= 37 && event.keyCode <= 40) {
      event.preventDefault();
      if (!isGameOver()) {
        const direction = event.keyCode - 37; // 0: left, 1: up, 2: right, 3: down
        moveTiles(direction);
        if (!isGameOver()) {
          addNewNumber();
        }
        updateGrid();
      }
    }
  }

  // Handle touch events
  let touchStartX = 0;
  let touchStartY = 0;
  let touchEndX = 0;
  let touchEndY = 0;

  function handleTouchStart(event) {
    touchStartX = event.touches[0].clientX;
    touchStartY = event.touches[0].clientY;
  }

  function handleTouchMove(event) {
    event.preventDefault();
  }

  function handleTouchEnd(event) {
    touchEndX = event.changedTouches[0].clientX;
    touchEndY = event.changedTouches[0].clientY;

    const deltaX = touchEndX - touchStartX;
    const deltaY = touchEndY - touchStartY;

    if (Math.abs(deltaX) > Math.abs(deltaY)) {
      if (deltaX > 0) {
        // Swipe right
        if (!isGameOver()) {
          moveTiles(2); // 2: right
          if (!isGameOver()) {
            addNewNumber();
          }
          updateGrid();
        }
      } else {
        // Swipe left
        if (!isGameOver()) {
          moveTiles(0); // 0: left
          if (!isGameOver()) {
            addNewNumber();
          }
          updateGrid();
        }
      }
    } else {
      if (deltaY > 0) {
        // Swipe down
        if (!isGameOver()) {
          moveTiles(3); // 3: down
          if (!isGameOver()) {
            addNewNumber();
          }
          updateGrid();
        }
      } else {
        // Swipe up
        if (!isGameOver()) {
          moveTiles(1); // 1: up
          if (!isGameOver()) {
            addNewNumber();
          }
          updateGrid();
        }
      }
    }
  }

  // Move the tiles in the given direction
  function moveTiles(direction) {
    let moved = false;
    let merged = false;
    const prevGrid = JSON.parse(JSON.stringify(grid));

    for (let i = 0; i < 4; i++) {
      if (direction === 0) {
        // Move tiles left
        for (let j = 1; j < 4; j++) {
          if (grid[i][j] !== 0) {
            let k = j;
            while (k > 0 && grid[i][k - 1] === 0) {
              grid[i][k - 1] = grid[i][k];
              grid[i][k] = 0;
              k--;
              moved = true;
            }
            if (k > 0 && grid[i][k - 1] === grid[i][k] && !merged) {
              grid[i][k - 1] *= 2;
              grid[i][k] = 0;
              score += grid[i][k - 1];
              merged = true;
              moved = true;
            }
            merged = false;
          }
        }
      } else if (direction === 1) {
        // Move tiles up
        for (let j = 1; j < 4; j++) {
          if (grid[j][i] !== 0) {
            let k = j;
            while (k > 0 && grid[k - 1][i] === 0) {
              grid[k - 1][i] = grid[k][i];
              grid[k][i] = 0;
              k--;
              moved = true;
            }
            if (k > 0 && grid[k - 1][i] === grid[k][i] && !merged) {
              grid[k - 1][i] *= 2;
              grid[k][i] = 0;
              score += grid[k - 1][i];
              merged = true;
              moved = true;
            }
            merged = false;
          }
        }
      } else if (direction === 2) {
        // Move tiles right
        for (let j = 2; j >= 0; j--) {
          if (grid[i][j] !== 0) {
            let k = j;
            while (k < 3 && grid[i][k + 1] === 0) {
              grid[i][k + 1] = grid[i][k];
              grid[i][k] = 0;
              k++;
              moved = true;
            }
            if (k < 3 && grid[i][k + 1] === grid[i][k] && !merged) {
              grid[i][k + 1] *= 2;
              grid[i][k] = 0;
              score += grid[i][k + 1];
              merged = true;
              moved = true;
            }
            merged = false;
          }
        }
      } else if (direction === 3) {
        // Move tiles down
        for (let j = 2; j >= 0; j--) {
          if (grid[j][i] !== 0) {
            let k = j;
            while (k < 3 && grid[k + 1][i] === 0) {
              grid[k + 1][i] = grid[k][i];
              grid[k][i] = 0;
              k++;
              moved = true;
            }
            if (k < 3 && grid[k + 1][i] === grid[k][i] && !merged) {
              grid[k + 1][i] *= 2;
              grid[k][i] = 0;
              score += grid[k + 1][i];
              merged = true;
              moved = true;
            }
            merged = false;
          }
        }
      }
    }

    if (moved) {
      if (JSON.stringify(grid) !== JSON.stringify(prevGrid)) {
        addNewNumber();
      }
    }
  }

  // Initialize the game
  function init() {
    createGrid();
    addNewNumber();
    addNewNumber();
    updateGrid();
    resetButton.addEventListener("click", resetGame);
    document.addEventListener("keydown", handleKeyPress);
    document.addEventListener("touchstart", handleTouchStart);
    document.addEventListener("touchmove", handleTouchMove);
    document.addEventListener("touchend", handleTouchEnd);
  }

  init();
});


              
            
!
999px

Console