Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

Behavior

Save Automatically?

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

              
                <header>
  <div class="container">
    <h1><span>2</span><span>0</span><span>4</span><span>8</span>
    </h1>
    <p class="inspired">Inspired by the original <a href="https://gabrielecirulli.github.io/2048/" target="_blank">2048</a>.</p>
  </div>
</header>
<div class="container">
  <div class="directions">
    <p><strong>HOW TO PLAY:</strong> Use your arrow keys to move the tiles. When two tiles slide into each other, they merge into one!</p>
  </div>
  <div class="scores">
    <div class="score-container best-score">
      best: 
      <div class="score">
        <div id="bestScore">0</div>
      </div>
    </div>
    <div class="score-container">
      score: 
      <div class="score">
        <div id="score">0</div>
        <div class="add" id="add"></div>
      </div>
    </div>
  </div>
  <div class="game">
    <div id="tile-container" class="tile-container"></div>
    <div class="end" id="end">Game Over<div class="monkey">🙈</div><button class="btn not-recommended__item js-restart-btn" id="try-again">Try Again</button></div>
  </div>
  
  <div class="not-recommended">
    <button class="btn not-recommended__item js-restart-btn" id="restart">Restart Game</button>
    <span class="not-recommended__annotation"></span>
  </div>
  
</div>
              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css?family=Arvo');

// https://coolors.co/f8ffe5-06d6a0-1b9aaa-ef476f-ffc43d
$gridBg: #9a9a95;
$color1: #FFC43D;
$color2: #EF476F;
$color3: #1B9AAA;
$color4: #06D6A0;
$placeholder-tile: #F8FFE5;
$font-color: #555;

$border-width: 7px;

@function setFontColor($color) {
  @if (lightness($color) > 80) {
    @return $bg;
  } @else {
    @return $placeholder-tile;
  }
}

* {
  box-sizing: border-box;
}

a {
  color: $color3;
  text-decoration: none;
  border-bottom: 1px solid currentColor;
  
  &:hover {
    color: darken($color3, 10%);
  }
  &:focus,
  &:active {
    color: darken($color3, 20%);
  }
}

body,
html {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-family: "Arvo", Helvetica, sans-serif;
  font-family: 12px;
  color: $font-color;
  background: $placeholder-tile;
}

strong {
  font-weight: bold;
}

p {
  line-height: 1.6;
}

.inspired {
  margin-top: 1em;
  font-size: 0.9rem;
  color: $gridBg;
}

header {
  color: $placeholder-tile;
  text-align: center;
  
  span {
    display: inline-block;
    box-sizing: border-box;
    width: 4rem;
    height: 4rem;
    line-height: 4rem;
    margin: 0 0.4rem;
    background: $color1;
    
    &:nth-of-type(2) {
      background: $color2;
    }
    &:nth-of-type(3) {
      background: $color3;
    }
    &:nth-of-type(4) {
      background: $color4;
    }
  }
}

h1 {
  font-size: 2.2rem;
}

.directions {
  padding: 2rem;
  border-top: 1px solid $gridBg;
  border-bottom: 1px solid $gridBg;
}

.container {
  margin: 0 auto;
  padding-bottom: 3.5rem;
  flex: 1;
  width: 100%;
  max-width: 550px;
  text-align: center;
  
  header & {
    padding: 0;
    padding: 2rem 4rem;
    max-width: 900px;
  }
}

.scores {
  display: flex;
  justify-content: center;
}

.score-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 1.8rem;
  font-size: 1.2rem;
  line-height: 1;
  color: $font-color;
  
  &.best-score {
    color: $gridBg;
  }
}

.score {
  margin-left: 1rem;
  position: relative;
  font-weight: bold;
  font-size: 1.5rem;
  vertical-align: middle;
  text-align: right;
}

.game {
  position: relative;
  margin: 0 auto;
  background: $gridBg;
  padding: $border-width;
  display: inline-block;
  border-radius: 3px;
  box-sizing: border-box;
}

.tile-container {
  border-radius: 6px;
  position: relative;
  width: 400px;
  height: 400px;
}

.tile, .background {
  display: block;
  color: $placeholder-tile;
  position: absolute;
  width: 100px;
  height: 100px;
  box-sizing: border-box;
  text-align: center;
}

.background {
  z-index: 1;
  text-align: center;
  border: $border-width solid $gridBg;
  background-color: $placeholder-tile;
}

.tile {
  opacity: 0;
  z-index: 2;
  background: $color1;
  color: setFontColor($color1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.8rem;
  align-items: center;
  transition: 110ms ease-in-out;
  border-radius: 3px;
  border: $border-width solid $gridBg;
  box-sizing: border-box;
  
  &--4 {
    background: $color2;
    color: setFontColor($color2);
  }
  
  &--8 {
    background: $color3;
    color: setFontColor($color3);
  }
  
  &--16 {
    background: $color4;
    color: setFontColor($color4);
  }
  
  &--32 {
    background: lighten($color2, 10%);
    color: setFontColor(lighten($color2, 10%));
  }
  
  &--64 {
    background: lighten($color3, 10%);
    color: setFontColor(lighten($color3, 10%));
  }
  
  &--128 {
    background: lighten($color4, 10%);
    color: setFontColor(lighten($color4, 10%));
  }
  
  &--256 {
    background: lighten($color1, 10%);
    color: setFontColor(lighten($color1, 10%));
  }
  
  &--512 {
    background: darken($color2, 10%);
    color: setFontColor(lighten($color2, 10%));
  }
  
  &--1024 {
    background: darken($color3, 10%);
    color: setFontColor(lighten($color3, 10%));
  }
  
  &--2048 {
    background: darken($color4, 10%);
    color: setFontColor(lighten($color4, 10%));
  }
  
  &--pop {
    animation: pop 0.3s ease-in-out;
    animation-fill-mode: forwards;
  }
  
  &--shrink {
    animation: shrink 0.5s ease-in-out;
    animation-fill-mode: forwards;
  }
}

.add {
  position: absolute;
  opacity: 0;
  left: 120%;
  top: 0;
  font-size: 1rem;
  color: $color3;
  
  &.active {  
    animation: add 0.8s ease-in-out;
  }
}

@keyframes add {
  0% {
    opacity: 1;
    top: 0;
  }
  100% {
    opacity: 0;
    top: -100%;
  }
}

@keyframes pop {
  0% {
    transform: scale(0.5);
    opacity: 0;
  }
  90% {
    transform: scale(1.1);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes shrink {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(0.9);
    opacity: 0.9;
  }
}

.end {
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba($font-color, 0.9);
  color: white;
  font-size: 2rem;
  transition: opacity 0.3s ease-in-out;
  
  btn {
    margin-top: 1rem;
  }
  
  &.active {
    opacity: 1;
    z-index: 1000;
  }
}

.monkey {
  font-size: 3rem;
  margin: 1rem 0;
}

.btn {
  font-family: inherit;
  font-size: 1rem;
  border: none;
  background: $color3;
  letter-spacing: 1px;
  color: white;
  font-weight: 300;
  padding: 0.9em 1.5em;
  border-radius: 3px;
  border: 1px solid transparent;
  cursor: pointer;
  
  &:hover {
    background-color: darken($color3, 10%);
  }
  
  &:active {
    background-color: darken($color3, 20%);
  }
  
  &:focus {
    box-shadow: 0 0 10px  darken($color3, 20%) inset;
    outline: none;
  }
}

.not-recommended {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 3rem;
  
  & * + * {
    margin-left: 10px;
  }
  
  &__item + .not-recommended__annotation:before {
    font-size: 30px;
    content: "😐";
  }
  &__item:hover + .not-recommended__annotation:before {
    content: "😟";
  }
  &__item:focus + .not-recommended__annotation:before {
    content: "😄";
  }
  &__item:active + .not-recommended__annotation:before {
    content: "😨";
  }
  
}
              
            
!

JS

              
                let game = null;
let bestScore = 0;
const scoreDiv = document.getElementById('score');
const bestScoreDiv = document.getElementById('bestScore');
const addDiv = document.getElementById('add');
const endDiv = document.getElementById('end');
const size = 4;
let nextId = 1;
let score = 0;

function initGame() {
  game = Array(size*size).fill(null); // 4 x 4 grid, represented as an array
  initBestScore();
}

function initBestScore() {
  bestScore = localStorage.getItem('bestScore') || 0;
  bestScoreDiv.innerHTML = bestScore;
}

function updateDOM(before, after) {
  const newElements = getNewElementsDOM(before, after);
  const existingElements = getExistingElementsDOM(before, after);
  const mergedTiles = getMergedTiles(after);
  removeElements(mergedTiles);
  drawGame(newElements, true);
  drawGame(existingElements);
}

function removeElements(mergedTiles) {
  for (let tile of mergedTiles) {
    for (let id of tile.mergedIds) {
      const currentElm = document.getElementById(id);
      positionTile(tile, currentElm);
      currentElm.classList.add('tile--shrink');
      setTimeout(() => {
        currentElm.remove();
      }, 100);
    }
  }
}

function getMergedTiles(after) {
  return after.filter((tile) => tile && tile.mergedIds);
}

function getNewElementsDOM(before, after) {
  const beforeIds = before.filter((tile) => tile).map((tile) => tile.id);
  const newElements = after.filter((tile) => {
    return tile && beforeIds.indexOf(tile.id) === -1;
  });
  return newElements;
}

function getExistingElementsDOM(before, after) {
  const beforeIds = before.filter((tile) => tile).map((tile) => tile.id);
  const existingElements = after.filter((tile) => {
    return tile && beforeIds.indexOf(tile.id) !== -1;
  });
  return existingElements;
}

function drawBackground() {
  const tileContainer = document.getElementById('tile-container');
  tileContainer.innerHTML = '';
  for (let i = 0; i < game.length; i++) {
    const tile = game[i];
    const tileDiv = document.createElement('div');
    const x = i % size;
    const y = Math.floor(i / size);
    tileDiv.style.top = `${y*100}px`;
    tileDiv.style.left = `${x*100}px`;
    
    tileDiv.classList.add("background"); 
    tileContainer.appendChild(tileDiv);
  }
}

function positionTile(tile, elm) {
  const x = tile.index % size;
  const y = Math.floor(tile.index / size);
  elm.style.top = `${y*100}px`;
  elm.style.left = `${x*100}px`;
}

function drawGame(tiles, isNew) {
  const tileContainer = document.getElementById('tile-container');
  for (let i = 0; i < tiles.length; i++) {
    const tile = tiles[i];
    if (tile) {
      if (isNew) {
        const tileDiv = document.createElement('div');
        positionTile(tile, tileDiv);
        tileDiv.classList.add('tile', `tile--${tile.value}`);
        tileDiv.id = tile.id;
        setTimeout(() => {
          tileDiv.classList.add("tile--pop");
        }, tile.mergedIds ? 1 : 150);
        tileDiv.innerHTML = `<p>${tile.value}</p>`;    
        tileContainer.appendChild(tileDiv);
      } else {
        const currentElement = document.getElementById(tile.id);
        positionTile(tile, currentElement);
      }
    }
  }
}

function gameOver() {
  if (game.filter((number)=>number===null).length === 0) {
    const sameNeighbors = game.find((tile, i)=>{
      const isRightSame = game[i+1] && (i+1)%4 !== 0 ? tile.value === game[i+1].value : false;
      const isDownSame = game[i+4] ? tile.value === game[i+4].value : false;
      if (isRightSame || isDownSame) {
        return true;
      }
      return false;
    });
    return !sameNeighbors;
  }
}

function generateNewNumber() {
  // 0.9 probability of 2, 0.1 probability of 4
  const p = Math.random() * 100;
  return (p <= 90) ? 2 : 4;
}

function addRandomNumber() {
  // Adds either a 2 or a 4 to an empty position in the game array
  const emptyCells = game.map((_, index) => index)
    .filter((index) => game[index] === null);
  if (emptyCells.length === 0) { return; }
  const newPos = emptyCells[Math.floor(Math.random() * emptyCells.length)];
  const newObj = {
    id: nextId++,
    index: newPos,
    value: generateNewNumber()
  };
  game.splice(newPos, 1, newObj);
}

function getIndexForPoint(x, y) {
  return y*size + x;
}

function reflectGrid(grid) {
  let reflectedGame = Array(size*size).fill(0);
  for (let row = 0; row < size; row++) {
    for (let col = 0; col < size; col++) {
      const index1 = getIndexForPoint(col, row);
      const index2 = getIndexForPoint(size-col-1, row);
      reflectedGame[index1] = grid[index2];
    }
  }
  return reflectedGame;
} 

function rotateLeft90Deg(grid) {
  let rotatedGame = Array(size*size).fill(0);
  for (let row = 0; row < size; row++) {
    for (let col = 0; col < size; col++) {
      const index1 = getIndexForPoint(col, row);
      const index2 = getIndexForPoint(size-1-row, col);
      rotatedGame[index1] = grid[index2];
    }
  }
  return rotatedGame;
} 

function rotateRight90Deg(grid) {
  let rotatedGame = Array(size*size).fill(0);
  for (let row = 0; row < size; row++) {
    for (let col = 0; col < size; col++) {
      const index1 = getIndexForPoint(col, row);
      const index2 = getIndexForPoint(row,size-1-col);
      rotatedGame[index1] = grid[index2];
    }
  }
  return rotatedGame;
}

/*
For any cell whose neighbor to the right is empty, move that cell
to the right. For any cell whose neighbor to the right is equal
to the same value, combine the values together (e.g. 2+2 = 4)
*/
function shiftGameRight(gameGrid) {
  // reflect game grid
  let reflectedGame = reflectGrid(gameGrid);
  // shift left
  reflectedGame = shiftGameLeft(reflectedGame);
  // reflect back
  return reflectGrid(reflectedGame);
}

function shiftGameLeft(gameGrid) {
  let newGameState = [];
  let totalAdd = 0;
  // for rows
  for (let i = 0; i < size; i++) {
    // for columns
    const firstPos = 4*i;
    const lastPos = (size)+4*i;
    const currentRow = gameGrid.slice(firstPos,lastPos);
    const filteredRow = currentRow.filter((row)=>row);
    for (let row of filteredRow) {
      delete row.mergedIds;
    }
    
    for (let j = 0; j < filteredRow.length - 1; j++) {
      if (filteredRow[j].value === filteredRow[j+1].value) {
        const sum = filteredRow[j].value * 2;
        filteredRow[j] = {
          id: nextId++,
          mergedIds: [filteredRow[j].id, filteredRow[j+1].id],
          value: sum
        };
        filteredRow.splice(j+1,1);
        score += sum;
        totalAdd += sum;
      }
    }
    while(filteredRow.length < size) {
      filteredRow.push(null);
    };
    newGameState = [...newGameState, ...filteredRow];
  }
  
  if (totalAdd > 0) {
    scoreDiv.innerHTML = score;
    addDiv.innerHTML = `+${totalAdd}`;
    addDiv.classList.add('active');
    setTimeout(function() {
      addDiv.classList.remove("active");
    }, 800); 
    if (score > bestScore) {
      localStorage.setItem('bestScore', score);
      initBestScore();
    }
  }
  return newGameState;
}

function shiftGameUp(gameGrid) {
  let rotatedGame = rotateLeft90Deg(gameGrid);
  rotatedGame = shiftGameLeft(rotatedGame);
  return rotateRight90Deg(rotatedGame);
}

function shiftGameDown(gameGrid) {
  let rotatedGame = rotateRight90Deg(gameGrid);
  rotatedGame = shiftGameLeft(rotatedGame);
  return rotateLeft90Deg(rotatedGame);
}

const buttons = document.querySelectorAll(".js-restart-btn");
const length = buttons.length;
for (let i = 0; i < length; i++) {
    if (document.addEventListener) {
        buttons[i].addEventListener("click", function() {
            newGameStart();
        });
    } else {
        buttons[i].attachEvent("onclick", function() {
            newGameStart();
        });
    };
};

document.addEventListener("keydown", handleKeypress);
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);

let xDown = null;       
let yDown = null;

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

function handleTouchMove(evt) {
  const prevGame = [...game];
  if ( !xDown || !yDown ) {
    return;
  }
  const xUp = evt.touches[0].clientX;
  const yUp = evt.touches[0].clientY;

  const xDiff = xDown - xUp;
  const yDiff = yDown - yUp;

  if ( Math.abs(xDiff) > Math.abs(yDiff) ) {
    if ( xDiff > 0 ) {
      game = shiftGameLeft(game);
    } else {
      game = shiftGameRight(game);
    }                       
  } else {
    if ( yDiff > 0 ) {
      game = shiftGameUp(game);
    } else { 
      game = shiftGameDown(game);
    }                                                                 
  }
  game = game.map((tile, index) => {
    if (tile) {
      return {
        ...tile,
        index
      };
    } else {
      return null;
    }
  });
  if (_.isEqual(prevGame, game)) return;
  addRandomNumber();
  updateDOM(prevGame, game);
  if (gameOver()) {
    setTimeout(() => {
      endDiv.classList.add('active');
    }, 800);
    return;
  }
  xDown = null;
  yDown = null;                                             
};

function handleKeypress(evt) {
  var modifiers = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
  var whichKey= event.which;
  
  const prevGame = [...game];
  
  if (!modifiers) {
    event.preventDefault();
    switch (whichKey) {
      case 37:
        game = shiftGameLeft(game);
        break;
      case 38:
        game = shiftGameUp(game);
        break;
      case 39:
        game = shiftGameRight(game);
        break;
      case 40:
        game = shiftGameDown(game);
        break;
    }
    game = game.map((tile, index) => {
      if (tile) {
        return {
          ...tile,
          index
        };
      } else {
        return null;
      }
    });
    if (_.isEqual(prevGame, game)) return;
    addRandomNumber();
    updateDOM(prevGame, game);
    if (gameOver()) {
      setTimeout(() => {
        endDiv.classList.add('active');
      }, 800);
      return;
    }
  }
}

function newGameStart() {
  document.getElementById('tile-container').innerHTML = '';
  endDiv.classList.remove('active');
  score = 0;
  scoreDiv.innerHTML = score;
  initGame();
  drawBackground();
  const previousGame = [...game];
  addRandomNumber();
  addRandomNumber();
  updateDOM(previousGame, game);
}

newGameStart();

              
            
!
999px

Console