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

              
                <!-- 
  Project 2048
Greetings to whoever has stumbled upon this project and is reading this readme. This is my first self-driven project. Its aim is to be a fully fledged 2048 browser game. The concept of the game is entirely borrowed from the popular 2048 game. 
The game logic is built using JavaScript and basic DOM manipulations, without additional frameworks/libraries. The stylesheets are rendered using SCSS. The basic HTML file only puts the skeleton of the page. The game grid is rendered within the JS logic. It supports good size responsiveness, where it would decrease the game grid and font size on smaller screens. Game interaction is performed using arrow keys for regular users, as well as swipe direction detection for touchscreens(tablets, smartphones etc.). For movement animation effect, the app uses a second grid, which comes visible only when movement is performed and only for squares that are moved. The movement is performed using simple CSS translate and transition rules and no "animation" features. There are additional visual effects for when numbers collide and add up and to display score increasement. Grid layout system is used to display the game grid. The SCSS utilizes a loop to produce class for each separate number tag, generating a distinguishable HSL background color and fluid font color, as well as corresponding font size to fit larger numbers within their element containment. 
There is a game-over effect as well as "new game" button to initiate a new game. 
-->

  <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'>New Game</button>
  </div>
  <div id="container">
    <div id="grid"></div>
    <div id="cover"></div>
  </div>
  <h1 id='gameover'>GAME OVER</h1>
  <footer>
    <div><p>coded by <span>Sylvant</span></p></div>
    <a href="https://codepen.io/Sylvant" target='_blank'>
      <svg height='32' width='32' 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/Sylvant/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/sylvant_draw/" 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>
              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css2?family=Rubik&family=Secular+One&display=swap');

html {
  box-sizing: border-box;
}

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

$mainBackground: #9cc3a9;
$secondBackground: #f5c7af; 
$secondColor: #2b5038;
$fontColor: #193824;
$transparent: hsla(0, 50%, 50%, 0);
$size: 25rem;
$gap: .8em;

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

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

a {
  min-width: 124px;
  min-height: 50px;
  display: flex;  
  align-items: center;
  justify-content: center;
  color: $secondBackground;
  &:hover, &:focus {
    color: white;
    svg {
      fill: white;
      width: 40px;
      height: 40px;
    }
  }
  &:focus {
    outline: none;
  }
  &:active {
    background-color: $fontColor;
  }
}

svg {
  fill: $secondBackground;
  margin-right: .4em;
}

footer {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: center;
  width: 100%;
  position: absolute;
  bottom: 0;
  background-color: $fontColor;
  color: $secondBackground;
  padding: 0 1em 0 1em;
  div {
    display: flex;
    min-width: 124px;
    min-height: 50px;
  }
}

@media (max-height: 700px) {
  footer {
    position: initial;
  }
}
@media (max-width: 560px) {
  footer {
    justify-content: space-evenly;
    >*{
      flex-basis: 35%;
      justify-content: flex-start;
    }
  }
}

body {
  font-family: 'Rubik', sans-serif;
  color: $fontColor;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: $mainBackground;
}

#title {
  color: $fontColor;
  font-size: 3em;
  margin: .7rem;
  padding: 0.7rem 1.5rem;
  border: $secondColor solid .3rem;
  border-radius: 1rem;
}

#panel {
  display: flex;
  max-width: 98vw;
  width: $size;
  justify-content: space-around;
  align-items: center;
}

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

#score {
  margin-left: .4em;
  padding-right: .3em;
}

#plus {
  border-radius: .4em;
  padding: .3em;
  opacity: 0;
}

#play {
  color: $fontColor;
  font-size: 1em;
  font-weight: 700;
  width: 7em;
  height: 3em;
  border: $secondColor solid .3rem;
  border-radius: .4em;
  margin: 1em;
  cursor: pointer;
  outline: none;
  transition: 0.2s;
  &:hover, &:focus {
    box-shadow: 0 0 .2em .2em lightgreen;
    border-color: green;
  }
  &:active {
    color: #0df259;
  }
}

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

@mixin grid($color) {
  padding: $gap;
  display: grid;
  grid: repeat(4, minmax(0, 1fr))/ repeat(4, minmax(0, 1fr));
  gap: $gap;
  background-color: $color;
  max-width: 98vw;
  width: $size;
  max-height: 98vw;
  height: $size;
  border-radius: $gap;
}

#grid {
  @include grid($secondColor);
}

#cover {
  position: absolute;
  top: 0;
  @include grid($transparent);
}

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


#cover .square {
  opacity: 0;
}

.square {
  background-color: $secondBackground;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: .4em;
  transform: translate(0,0);
}

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

$hue: 50;
$light: 100;
$sat: 90;
$n: 2;
@while $n<10000 {  
  $light: $light - 5;
  @if $n==32 {
    $sat: 77;
  }
  @if $n==128 {
    $hue: 60;
    $light: 70;
    $sat: 90;
  }
  @else if $n==4 {
    $light:68;
  }
  @else if $n>2048 {
    $hue: $hue + 90;
  }
  @else if $n>64 {
    $hue: $hue + 20;
  }
  @else {
    $hue: $hue - 10;
  }
  .n#{$n} {
    background-color: hsl($hue, $sat, $light);
    @if $n>1000 {
      h1 {
        font-size: 1.8rem;
      }
    }
    @if $light>60 {
      color: $secondColor;
    }
    @if $light<50 {
      color: $secondBackground;
    }
  }
  $n: $n*2;
}

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

.gameover {
  opacity: .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

//For testing purpose
//let testArr=[[2,4,2,0], [4,4,4,0], [0,4,0,0], [4,4,0,0], [4,4,2,2], [4,2,2,4], [4,0,0,4], [0,2,0,2], [0,2,4,2]]
//let testData=[0,2,16,4,2,512,64,32,4096,4,0,128,256,8,1024,2048]

//creates list of empty spots(with grid index)
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
}

//parses data in a grid of rows/columns
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
}

//check if anywhere on the grid there are repeating consecutive numbers
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()
  //console.log(`rolled random number ${twoOrFour} at index ${index}`)
}

//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){
  //console.log(`start moving cover on index ${index}`)
  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
  //console.log(`updating ${elementsToUpdate.join('|')}...`)
  elementsToUpdate.forEach(([number, index, newIndex])=>{

    //console.log(`reset cover ${index} & updating grid index ${newIndex} with number ${number}`)
    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){
  //console.log('...key has been pressed!')
  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;                                             
};

/*
// COLOR PALETTE
const body=document.body
const palette=document.createElement('div')
palette.style.display='flex'
body.appendChild(palette)
for (let i=2; i<10000; i*=2){
  let box=document.createElement('div')
  box.classList.add('square')
  box.style.width='60px'
  box.style.height='60px'
  box.classList.add('n'+i)
  let number=document.createElement('h1')
  number.textContent=i
  number.style.marginBlockEnd=0
  number.style.marginBlockStart=0
  box.appendChild(number)
  palette.appendChild(box)
}
*/
              
            
!
999px

Console