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 lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>2048 Game</title>
</head>

<body>
  <h1 id="title" class='n2048'>2048</h1>
  <div id='panel'>
    <h3 id="scoreboard">Score: <span id='score'>0</span><span id='plus'></span></h3>
    <button id="play" class='n2048'>Click to start New</button>
  </div>
  <div id="container">
    <div id="grid"></div>
    <div id="cover"></div>
  </div>
  <h2 id='gameover'>GAME OVER</h2>
  <footer>
    <div class="author">
      <p>Created by <span>jahidulzaid</span></p>
    </div>
    <a href="https://codepen.io/jahidulzaid" target='_blank'>
      <svg height='42' width='42' viewBox="0 0 100 100">
        <path d="M100 34.2c-.4-2.6-3.3-4-5.3-5.3-3.6-2.4-7.1-4.7-10.7-7.1-8.5-5.7-17.1-11.4-25.6-17.1-2-1.3-4-2.7-6-4-1.4-1-3.3-1-4.8 0-5.7 3.8-11.5 7.7-17.2 11.5L5.2 29C3 30.4.1 31.8 0 34.8c-.1 3.3 0 6.7 0 10v16c0 2.9-.6 6.3 2.1 8.1 6.4 4.4 12.9 8.6 19.4 12.9 8 5.3 16 10.7 24 16 2.2 1.5 4.4 3.1 7.1 1.3 2.3-1.5 4.5-3 6.8-4.5 8.9-5.9 17.8-11.9 26.7-17.8l9.9-6.6c.6-.4 1.3-.8 1.9-1.3 1.4-1 2-2.4 2-4.1V37.3c.1-1.1.2-2.1.1-3.1 0-.1 0 .2 0 0zM54.3 12.3L88 34.8 73 44.9 54.3 32.4V12.3zm-8.6 0v20L27.1 44.8 12 34.8l33.7-22.5zM8.6 42.8L19.3 50 8.6 57.2V42.8zm37.1 44.9L12 65.2l15-10.1 18.6 12.5v20.1zM50 60.2L34.8 50 50 39.8 65.2 50 50 60.2zm4.3 27.5v-20l18.6-12.5 15 10.1-33.6 22.4zm37.1-30.5L80.7 50l10.8-7.2-.1 14.4z">
        </path>
      </svg>Codepen</a>
    <a href="https://github.com/jahidulzaid/2048" target='_blank'>
      <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32">
        <path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z">
        </path>
      </svg>Github</a>
    <a href="https://www.instagram.com/jahidulzaid/" target='_blank'>
      <svg width="32" height="32" viewBox="0 0 551.034 551.034" style="enable-background:new 0 0 551.034 551.034;">
        <path d="M386.878,0H164.156C73.64,0,0,73.64,0,164.156v222.722 c0,90.516,73.64,164.156,164.156,164.156h222.722c90.516,0,164.156-73.64,164.156-164.156V164.156 C551.033,73.64,477.393,0,386.878,0z M495.6,386.878c0,60.045-48.677,108.722-108.722,108.722H164.156 c-60.045,0-108.722-48.677-108.722-108.722V164.156c0-60.046,48.677-108.722,108.722-108.722h222.722 c60.045,0,108.722,48.676,108.722,108.722L495.6,386.878L495.6,386.878z">
        </path>
        <path d="M275.517,133C196.933,133,133,196.933,133,275.516 s63.933,142.517,142.517,142.517S418.034,354.1,418.034,275.516S354.101,133,275.517,133z M275.517,362.6 c-48.095,0-87.083-38.988-87.083-87.083s38.989-87.083,87.083-87.083c48.095,0,87.083,38.988,87.083,87.083 C362.6,323.611,323.611,362.6,275.517,362.6z">
        </path>
        <circle cx="418.306" cy="134.072" r="34.149"></circle>
      </svg>Instagram</a>
  </footer>
</body>

</html>
              
            
!

CSS

              
                @import url("https://fonts.googleapis.com/css2?family=Rubik&family=Secular+One&display=swap");
html {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  -webkit-box-sizing: inherit;
  box-sizing: inherit;
}

@media (max-width: 400px) {
  html {
    font-size: 14px;
  }
}

h1 {
  -webkit-margin-before: 0;
  margin-block-start: 0;
  -webkit-margin-after: 0;
  margin-block-end: 0;
  color: inherit;
}

a {
  min-width: 124px;
  min-height: 50px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  color: #f5c7af;
  text-decoration: none;
}

a:hover,
a:focus {
  color: white;
}

a:hover svg,
a:focus svg {
  fill: white;
  width: 40px;
  height: 40px;
}

a:focus {
  outline: none;
}

a:active {
  background-color: #193824;
}

svg {
  fill: #f5c7af;
  margin-right: 0.4em;
}

footer {
  display: -webkit-box;
  align-self: center;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-box-pack: end;
  -ms-flex-pack: end;
  justify-content: flex-start;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  width: 100%;
  position: absolute;
  bottom: 0;
  background-color: #193824;
  color: #f5c7af;
  padding: 0 1em 0 1em;
}

footer div {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  min-width: 124px;
  min-height: 50px;
}

@media (max-height: 700px) {
  footer {
    position: initial;
  }
}

@media (max-width: 560px) {
  footer {
    -webkit-box-pack: space-evenly;
    -ms-flex-pack: space-evenly;
    justify-content: space-evenly;
  }
  footer > * {
    -ms-flex-preferred-size: 35%;
    flex-basis: 35%;
    -webkit-box-pack: start;
    -ms-flex-pack: start;
    justify-content: flex-start;
  }
}

body {
  font-family: "Rubik", sans-serif;
  color: #0b6d9b;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  background-color: #2d312e;
}

#title {
  color: #193824;
  font-size: 3em;
  margin: 0.7rem;
  padding: 0.7rem 1.5rem;
  border: #2b5038 solid 0.3rem;
  border-radius: 1rem;
}
#author {
  display: flex;
  align-self: center;
  flex-grow: 200px;
}

#panel {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-width: 98vw;
  width: 25rem;
  -ms-flex-pack: distribute;
  justify-content: space-around;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

#scoreboard {
  padding-left: 1.4em;
  width: 12em;
}

#score {
  margin-left: 0.4em;
  padding-right: 0.3em;
}

#plus {
  border-radius: 0.4em;
  padding: 0.3em;
  opacity: 0;
}

#play {
  color: #193824;
  font-size: 1em;
  font-weight: 700;
  width: 7em;
  height: 3em;
  border: #2b5038 solid 0.3rem;
  border-radius: 0.4em;
  margin: 1em;
  cursor: pointer;
  outline: none;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

#play:hover,
#play:focus {
  -webkit-box-shadow: 0 0 0.2em 0.2em lightgreen;
  box-shadow: 0 0 0.2em 0.2em lightgreen;
  border-color: green;
}

#play:active {
  color: #0df259;
}

#container {
  position: relative;
  margin-top: 0.4em;
  margin-bottom: 1em;
}

#grid {
  padding: 0.8em;
  display: -ms-grid;
  display: grid;
  grid: repeat(4, minmax(0, 1fr)) / repeat(4, minmax(0, 1fr));
  gap: 0.8em;
  background-color: #2b5038;
  max-width: 98vw;
  width: 25rem;
  max-height: 98vw;
  height: 25rem;
  border-radius: 0.8em;
}

#cover {
  position: absolute;
  top: 0;
  padding: 0.8em;
  display: -ms-grid;
  display: grid;
  grid: repeat(4, minmax(0, 1fr)) / repeat(4, minmax(0, 1fr));
  gap: 0.8em;
  background-color: rgba(191, 64, 64, 0);
  max-width: 98vw;
  width: 25rem;
  max-height: 98vw;
  height: 25rem;
  border-radius: 0.8em;
}

@media (max-width: 400px) {
  #grid,
  #cover {
    gap: 6px;
    padding: 6px;
  }
}

#cover .square {
  opacity: 0;
}

.square {
  background-color: #f5c7af;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  border-radius: 0.4em;
  -webkit-transform: translate(0, 0);
  transform: translate(0, 0);
}

.square h1 {
  font-family: "Secular One", sans-serif;
}

.n2 {
  background-color: #fef6e7;
  color: #2b5038;
}

.n4 {
  background-color: #f7c664;
  color: #2b5038;
}

.n8 {
  background-color: #f6a14c;
  color: #2b5038;
}

.n16 {
  background-color: #f47434;
}

.n32 {
  background-color: #e34a2b;
}

.n64 {
  background-color: #d91c1c;
  color: #f5c7af;
}

.n128 {
  background-color: #f7f76e;
  color: #2b5038;
}

.n256 {
  background-color: #c1f655;
  color: #2b5038;
}

.n512 {
  background-color: #7af53d;
}

.n1024 {
  background-color: #25f425;
}

.n1024 h1 {
  font-size: 1.8rem;
}

.n2048 {
  background-color: #0df259;
}

.n2048 h1 {
  font-size: 1.8rem;
}

.n4096 {
  background-color: #0b2eda;
  color: #f5c7af;
}

.n4096 h1 {
  font-size: 1.8rem;
}

.n8192 {
  background-color: #c20a85;
  color: #f5c7af;
}

.n8192 h1 {
  font-size: 1.8rem;
}

@media (max-width: 300px) {
  .square h1 {
    font-size: 1.6em;
  }
}

.gameover {
  opacity: 0.4;
}

#gameover {
  display: none;
  font-size: 4em;
  font-weight: 900;
  position: relative;
  top: -16rem;
  height: 0;
  text-align: center;
}

              
            
!

JS

              
                const container = document.getElementById("container");
const grid = document.getElementById("grid");
const cover = document.getElementById("cover");
const startBtn = document.getElementById("play");
const scoreSpan = document.getElementById("score");
const scorePlus = document.getElementById("plus");
const gameover = document.getElementById("gameover");

//create the game grid
for (let row = 0; row < 4; row++) {
  for (let col = 0; col < 4; col++) {
    const square = document.createElement("div");
    const number = document.createElement("h1");
    square.appendChild(number);
    square.classList.add("square");
    grid.appendChild(square);

    const squareCover = square.cloneNode(true);
    cover.appendChild(squareCover);
  }
}
const squares = grid.querySelectorAll(".square");
const numbers = grid.querySelectorAll(".square h1");
const squareCovers = cover.querySelectorAll(".square");
const numberCovers = cover.querySelectorAll(".square h1");
let data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let score = 0;
let stepTimer; //track if step/animation is undergoing
let step = 96; //box size in px(how much to move)
let bigFontSize = 41; //measure for grow letters effect
if (window.innerWidth < 400) {
  step = squares[0].offsetWidth + 6;
  if (window.innerWidth < 300) bigFontSize = 28;
  else bigFontSize = 36;
}
window.onresize = () => {
  if (window.innerWidth < 400) {
    step = squares[0].offsetWidth + 6;
    if (window.innerWidth < 300) bigFontSize = 28;
    else bigFontSize = 36;
  } else {
    step = 96;
    bigFontSize = 41;
  }
};
let delay = 200; //step/animation timer length in milliseconds
let elementsToUpdate = []; //queue for elements to be updated per step
let elementsToGrow = []; //elements that are result of combination

function emptySpots() {
  return data.reduce((empty, n, i) => (n === 0 ? empty.concat(i) : empty), []);
}

function rollTwoOrFour() {
  const roll = Math.random();
  if (roll > 0.9) return 4;
  return 2;
}

function dataSets(direction) {
  let sets = [];
  let counter = [0, 1, 2, 3];
  if (direction === "left" || direction === "up") counter = [3, 2, 1, 0];
  for (let i = 0; i < 4; i++) {
    let a = i;
    if (direction === "left" || direction === "right") a *= 4;
    let indices = counter.map((n) => {
      let b = n;
      if (direction === "down" || direction === "up") b *= 4;
      return a + b;
    });
    const numbers = indices.map((index) => data[index]);
    sets.push({ numbers, indices });
  }
  return sets;
}

function hasConsecutive() {
  let rows = dataSets("right");
  let cols = dataSets("down");
  for (let i = 0; i < 4; i++) {
    for (let e = 0; e < 3; e++) {
      if (
        rows[i].numbers[e] === rows[i].numbers[e + 1] ||
        cols[i].numbers[e] === cols[i].numbers[e + 1]
      )
        return true;
    }
  }
  return false;
}

function updateSquare(n, position, cover = false) {
  let square;
  let number;
  if (cover) {
    square = squareCovers[position];
    number = numberCovers[position];
  } else {
    square = squares[position];
    number = numbers[position];
  }
  square.className = "square";
  if (!n) {
    number.textContent = "";
  } else {
    square.classList.add("n" + n);
    number.textContent = n;
  }
}

function gameOver() {
  document.removeEventListener("keydown", control);
  container.removeEventListener("touchstart", handleTouchStart);
  container.removeEventListener("touchmove", handleTouchMove);

  console.log("GAME OVER");
  container.classList.add("gameover");
  gameover.style.display = "initial";
}

//rolls a new number and puts on an empty(random) spot
function rollRandomEmptySpot() {
  const empty = emptySpots();
  if (!empty.length) return;
  const randomSquare = Math.floor(Math.random() * empty.length);
  const twoOrFour = rollTwoOrFour();
  const index = empty[randomSquare];
  data[index] = twoOrFour;
  updateSquare(twoOrFour, index);
  updateSquare(twoOrFour, index, true);
  if (empty.length === 1 && !hasConsecutive()) gameOver();
}

//checks if a set of four numbers can be shifted
function canChangeSet(set, reverse = false) {
  const lastSetIndex = set.length - 1;
  if (reverse && set[lastSetIndex] === 0) {
    return canChangeSet(set.slice(0, lastSetIndex), reverse);
  }
  if (!reverse && set[0] === 0) {
    return canChangeSet(set.slice(1));
  }
  if (set.includes(0)) {
    return true;
  }
  if (!reverse) {
    for (let i = 0; i < lastSetIndex; i++) {
      if (set[i] === set[i + 1]) return true;
    }
  } else {
    for (let i = lastSetIndex; i > 0; i--) {
      if (set[i] === set[i - 1]) return true;
    }
  }
  return false;
}

function moveSquare(direction, index, steps) {
  let squareCover = squareCovers[index];
  squareCover.style.opacity = 1;
  squareCover.style.zIndex = steps + 1;
  squareCover.style.transition = "transform " + delay / 1000 + "s";
  switch (direction) {
    case "left":
      squareCover.style.transform = `translateX(-${step * steps}px)`;
      break;
    case "right":
      squareCover.style.transform = `translateX(${step * steps}px)`;
      break;
    case "up":
      squareCover.style.transform = `translateY(-${step * steps}px)`;
      break;
    case "down":
      squareCover.style.transform = `translateY(${step * steps}px)`;
  }
}

function finishBoardUpdate() {
  stepTimer = false;
  elementsToUpdate.forEach(([number, index, newIndex]) => {
    squareCovers[index].removeAttribute("style");

    updateSquare(number, newIndex);
    updateSquare(number, newIndex, true);
    updateSquare(0, index, true);
    if (elementsToGrow.includes(newIndex)) {
      let currentSize = bigFontSize;
      if (number > 1000 && bigFontSize !== 28) {
        if (bigFontSize === 41) currentSize = 36;
        else currentSize = 32;
      }
      numbers[newIndex].style.transition = "none";
      numbers[newIndex].style.fontSize = currentSize + "px";
    }
  });
  elementsToUpdate = [];
  grid.offsetHeight; //triggers document reflow to display style changes
  elementsToGrow.forEach((index) => {
    let number = numbers[index];
    number.removeAttribute("style");
    number.style.transition = "font-size 0.4s";
    number.ontransitionend = () => number.removeAttribute("style");
  });
  elementsToGrow = [];
  rollRandomEmptySpot();
}

function updateScore(n) {
  const getClassNumber = (n) => {
    for (let i = 2; i < 10000; i *= 2) {
      if (n === i) return i;
      if (n < i) return i / 2;
    }
  };
  scorePlus.className = "n" + getClassNumber(n);
  scorePlus.textContent = "+" + n;
  scorePlus.style.transition = "none";
  scorePlus.style.opacity = 1;
  grid.offsetHeight; //triggers document reflow to display style changes
  score += n;
  scoreSpan.textContent = score;
  scorePlus.style.transition = "opacity 0.5s ease-in 0.3s";
  scorePlus.style.opacity = 0;
  scorePlus.ontransitionend = () => scorePlus.removeAttribute("style");
}

function shiftDirection(direction) {
  if (stepTimer) {
    clearTimeout(stepTimer);
    finishBoardUpdate();
  }

  let sets = dataSets(direction);
  let change = false;

  for (let i = 0; i < sets.length; i++) {
    if (canChangeSet(sets[i].numbers)) {
      change = true;
      break;
    }
  }
  if (!change) return;

  let scoreToAdd = 0;
  sets.forEach(({ numbers: set, indices }) => {
    if (canChangeSet(set)) {
      let steps = 0;
      let last = 0;

      for (let i = set.length - 1; i >= 0; i--) {
        let number = set[i];
        let index = indices[i];
        if (!number) {
          steps++;
        } else {
          if (number === last) {
            last = 0;
            steps++;
            number = number * 2;
            scoreToAdd += number;
            elementsToGrow.push(indices[i + steps]);
          } else {
            last = number;
          }
          if (steps) {
            let newIndex = indices[i + steps];
            data[index] = 0;
            data[newIndex] = number;
            updateSquare(0, index); //set old position to zero
            moveSquare(direction, index, steps);
            elementsToUpdate.push([number, index, newIndex]);
          }
        }
      }
    }
  });
  if (scoreToAdd) updateScore(scoreToAdd);
  stepTimer = setTimeout(finishBoardUpdate, delay);
}

function control(e) {
  switch (e.keyCode) {
    case 37:
      shiftDirection("left");
      break;
    case 38:
      shiftDirection("up");
      break;
    case 39:
      shiftDirection("right");
      break;
    case 40:
      shiftDirection("down");
  }
}

function displayGrid() {
  //draws whole grid on the html
  data.forEach((n, i) => {
    updateSquare(n, i);
    updateSquare(n, i, true);
  });
}

function startGame() {
  console.log("Starting New Game!!!");
  data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  //data=testData
  score = 0;
  scoreSpan.textContent = score;
  container.className = ""; //clears "game over" tag
  gameover.style.display = "none";
  displayGrid();
  rollRandomEmptySpot();
  rollRandomEmptySpot();

  document.addEventListener("keydown", control);
  container.addEventListener("touchstart", handleTouchStart, false);
  container.addEventListener("touchmove", handleTouchMove, false);
}
startGame();
startBtn.addEventListener("click", startGame);

//Following touchscreen detect swipe movement is mostly borrowed by Stackoverflow
var xDown = null;
var yDown = null;

function handleTouchStart(evt) {
  const firstTouch = evt.touches[0];
  xDown = firstTouch.clientX;
  yDown = firstTouch.clientY;
}

function handleTouchMove(evt) {
  evt.preventDefault();
  if (!xDown || !yDown) return;

  var xUp = evt.touches[0].clientX;
  var yUp = evt.touches[0].clientY;
  var xDiff = xDown - xUp;
  var yDiff = yDown - yUp;

  if (Math.abs(xDiff) > Math.abs(yDiff)) {
    /*most significant*/
    if (xDiff > 0) {
      /* right swipe */
      shiftDirection("left");
    } else {
      /* left swipe */
      shiftDirection("right");
    }
  } else {
    if (yDiff > 0) {
      /* down swipe */
      shiftDirection("up");
    } else {
      /* up swipe */
      shiftDirection("down");
    }
  }
  /* reset values */
  xDown = null;
  yDown = null;
}

              
            
!
999px

Console