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

              
                <div class="container">
  <header>
    <h1>Use the arrow keys to slide & add to <span>2048</span></h1>
    <div class="score-wrapper">
      <div class="score-container">
        <div class="score-title">score</div>
        <span id="score">0</span>
      </div>
      <div id="result"></div>
    </div>
  </header>
  <div class="board">
    <div class="grid"></div>
    <button id="move-up">
      <svg width="40" length="40" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 11l7-7 7 7M5 19l7-7 7 7"></path>
      </svg>
    </button>
    <button id="move-left">
      <svg width="40" length="40" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 19l-7-7 7-7m8 14l-7-7 7-7"></path>
      </svg>
    </button>
    <button id="move-right">
      <svg width="40" length="40" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 5l7 7-7 7M5 5l7 7-7 7"></path>
      </svg>
    </button>
    <button id="move-down">
      <svg width="40" length="40" class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 13l-7 7-7-7m14-8l-7 7-7-7"></path>
      </svg>
    </button>
  </div>
  <footer>
    Made by <br />
    <a href="https://twitter/_moodybones">Mel Jones</a>
  </footer>
</div>
              
            
!

CSS

              
                * {
  box-sizing: border-box;
  margin: 0;
}

body {
  background: #eeeeee;
  font-family: sans-serif;
  color: rgb(53, 53, 53);
  display: grid;
  align-items: center;
  justify-content: center;
}

.container {
  display: flex;
  flex-direction: column;
}
header {
  display: flex;
  justify-content: space-between;
  margin-top: 2rem;
  padding: 0 0.5rem;
}
h1 {
  align-self: flex-end;
  text-transform: uppercase;
  font-size: 1rem;
  margin: 0;
  width: min-content;
  line-height: 1.5;
  /*   font-weight: normal; */
}
h1 span {
  font-size: 3rem;
  letter-spacing: 1px;
}

@keyframes bounce-heading {
  0% {
    transform: scale(0.8);
  }
  100% {
    transform: scale(1);
  }
}

.board {
  display: grid;
  gap: 0;
  grid-template-columns: 1fr auto 1fr;
  grid-template-rows: 1fr auto 1fr;
  grid-template-areas:
    ". up ."
    "left squares right"
    ". down .";
}

.board button {
  all: unset;
  border: none;
  cursor: pointer;
  text-align: center;
  /* background: rgb(53, 53, 53); */
}
.board button svg {
  width: 30px;
  height: auto;
  transition: all 0.5s ease-in-out;
}
.board button:hover svg {
  transform: scale(1.25);
}

/* .board button:focus {
  outline: 6px dotted white;
} */

#move-up {
  grid-area: up;
}
#move-left {
  grid-area: left;
}
#move-right {
  grid-area: right;
}
#move-down {
  grid-area: down;
}

.grid {
  grid-area: squares;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(4, 1fr);
  grid-gap: 0.5rem;
  padding: 0.5rem;
  border-radius: 0.2rem;
  background: white;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

/* selects all divs inside of .grid */
.grid div {
  padding: 0 0.02em;
  display: grid;
  align-items: center;
  justify-content: center;
  min-width: 50px;
  min-height: 50px;
  background: #f6e58d;
  letter-spacing: 1px;
  font-size: 1rem;
  font-weight: bold;
  border-radius: 0.05rem;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
}

.score-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}
.score-container {
  background: rgb(53, 53, 53);
  background-image: radial-gradient(
    circle at top right,
    rgb(87, 87, 87),
    rgb(53, 53, 53),
    rgb(87, 87, 87),
    rgb(53, 53, 53)
  );
  color: white;
  width: max-content;
  height: max-content;
  padding: 0.5em 0.4em 0.2em;
  border-radius: 0.3rem;
  margin-bottom: 0.5rem;
  font-size: 1rem;
  letter-spacing: 2px;
  text-transform: uppercase;
  text-align: center;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
  background-size: 200%;
  animation: bg-animation 20s infinite alternate;
}

@keyframes bg-animation {
  0% {
    background-position: left;
  }
  100% {
    background-position: right;
  }
}

.score-title {
  margin-bottom: 0.1em;
}
#score {
  font-size: 2rem;
  font-weight: bold;
}

footer {
  padding: 4rem 0.75rem 2rem;
  font-size: 0.9rem;
  line-height: 1.5;
  letter-spacing: 1px;
  text-transform: uppercase;
  text-align: center;
}

footer a {
  color: inherit;
  text-decoration: none;
  font-weight: bold;
  transition: opacity 0.1s ease-in-out;
}

footer a:hover {
  opacity: 75%;
}

/* footer a:focus {
  outline: 6px dotted white;
} */

@media (min-width: 370px) {
  .board {
    gap: 0.5em;
  }
  .grid {
    grid-gap: 0.7rem;
    padding: 0.7rem;
  }
  .grid div {
    min-width: 60px;
    min-height: 60px;
    font-size: 1.2rem;
  }
  .container {
    min-width: 360px;
    width: 100%;
  }
}

@media (min-width: 500px) {
/*   .grid {
    grid-gap: 0.7rem;
    padding: 0.7rem;
  } */
  .grid div {
    min-width: 80px;
    min-height: 80px;
    font-size: 1.8rem;
  }
/*   .container {
    min-width: 360px;
    width: 100%;
  } */
  board {
    gap: 1rem;
  }
}

              
            
!

JS

              
                document.addEventListener("DOMContentLoaded", () => {
  const gridDisplay = document.querySelector(".grid");
  const scoreDisplay = document.getElementById("score");
  const resultDisplay = document.getElementById("result");
  const upButton = document.getElementById("move-up");
  const leftButton = document.getElementById("move-left");
  const rightButton = document.getElementById("move-right");
  const downButton = document.getElementById("move-down");
  const width = 4;
  let squares = [];
  let score = 0;

  // create a 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 number randomly
  function generate() {
    let randomNumber = Math.floor(Math.random() * squares.length);
    if (squares[randomNumber].innerHTML == 0) {
      // it will only set the value to 2 if the innerHTML is 0
      squares[randomNumber].innerHTML = 2;
      checkForGameOver();
    } else generate(); // otherwise it will rerun the function
  }

  // swipe right to
  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)
        ]; // parse to number

        let filteredRow = row.filter((num) => num); // save the squares with numbers in a new array

        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];
      }
    }
  }
  // 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)
        ]; // parse to number

        let filteredRow = row.filter((num) => num); // save the squares with numbers in a new array

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

  // swipe down
  function moveDown() {
    // loop over first 4 elements
    // and check the squares below
    for (let i = 0; i < 4; i++) {
      // console.log(i)
      let totalOne = squares[i].innerHTML;
      // console.log(totalOne, 'totalOne')
      let totalTwo = squares[i + width].innerHTML;
      // console.log(totalTwo, 'totalTwo')
      let totalThree = squares[i + width * 2].innerHTML;
      // console.log(totalThree, 'totalThree')
      let totalFour = squares[i + width * 3].innerHTML;
      // console.log(totalFour, 'totalFour')
      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);
      console.log(column, "down column");
      console.log(filteredColumn, "down filteredColumn");
      console.log(zeros, "down zeros");
      console.log(newColumn, "down newColumn");

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

  // swipe up
  function moveUp() {
    // loop over first 4 elements
    // and check the squares below
    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);
      // console.log(column, 'down column')
      // console.log(filteredColumn, 'down filteredColumn')
      // console.log(zeros, 'down zeros')
      // console.log(newColumn, 'down newColumn')

      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() {
    // we don't need to check for the 15th square right square or it will break
    for (let i = 0; i < 15; i++) {
      // check if square is the same as it's right neighbour
      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() {
    // there are no squares below 13, 14, 15 or 16 because there are no sqaures below them
    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 keycodes
  function control(e) {
    if (e.key === "ArrowRight") {
      keyRight();
    } else if (e.key === "ArrowLeft") {
      keyLeft();
    } else if (e.key === "ArrowDown") {
      keyDown();
    } else if (e.key === "ArrowUp") {
      keyUp();
    }
  }
  document.addEventListener("keyup", control);
  upButton.addEventListener("click", keyUp);
  leftButton.addEventListener("click", keyLeft);
  rightButton.addEventListener("click", keyRight);
  downButton.addEventListener("click", keyDown);

  function keyRight() {
    moveRight();
    combineRow();
    moveRight();
    generate();
  }
  function keyLeft() {
    moveLeft();
    combineRow();
    moveLeft();
    generate();
  }
  function keyDown() {
    moveDown();
    combineColumn();
    moveDown();
    generate();
  }
  function keyUp() {
    moveUp();
    combineColumn();
    moveUp();
    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!'
        resultDisplay.innerHTML =
          '<svg width="40" height="40" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>';
        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) {
      // resultDisplay.innerHTML = 'You Lose!'
      resultDisplay.innerHTML =
        '<svg width="40" height="40" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>';
      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 = "#f2f2f2";
      else if (squares[i].innerHTML == 2)
        squares[i].style.backgroundColor = "#f6e58d";
      else if (squares[i].innerHTML == 4)
        squares[i].style.backgroundColor = "#ffbe76";
      else if (squares[i].innerHTML == 8)
        squares[i].style.backgroundColor = "#686de0";
      else if (squares[i].innerHTML == 16)
        squares[i].style.backgroundColor = "#7ed6df";
      else if (squares[i].innerHTML == 32)
        squares[i].style.backgroundColor = "#e056fd";
      else if (squares[i].innerHTML == 64)
        squares[i].style.backgroundColor = "#ED4C67";
      else if (squares[i].innerHTML == 128)
        squares[i].style.backgroundColor = "#58B19F";
      else if (squares[i].innerHTML == 256)
        squares[i].style.backgroundColor = "#25CCF7";
      else if (squares[i].innerHTML == 512)
        squares[i].style.backgroundColor = "#D6A2E8";
      else if (squares[i].innerHTML == 1024)
        squares[i].style.backgroundColor = "#9AECDB";
      else if (squares[i].innerHTML == 2048)
        squares[i].style.backgroundColor = "#EAB543";
    }
  }
  addColours();

  var myTimer = setInterval(addColours, 50);
});

              
            
!
999px

Console