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="game">
  <div class="info">
    <div class="score-container">
      <div class="score-title">Your score:</div>
      <span id="score"></span>
    </div>
  </div>
  <div class="canvas" id="canvas">
    <!-- game will go here! -->
  </div>
</div>
              
            
!

CSS

              
                .game
  display: flex
  width: 600px
  margin: 50px auto
  justify-content: space-between
  font-family: monospace

.info
  
.score-container
  position: relative
  text-align: center
  font-size: 32px
  margin: 0 0 5px
  padding: 2px
  color: #444444
  &:after
    position: absolute
    line-height: 2em
    left: 100%
    top: 0
    height: 100%
    width: 50px
    content: '\01F476'
  &[data-greatestNum='8']
    &:after
      content: '\01F476'
  &[data-greatestNum='16']
    &:after
      content: '\01F476'
  &[data-greatestNum='32']
    &:after
      content: '\01F9D2'
  &[data-greatestNum='64']
    &:after
      content: '\01F466'
  &[data-greatestNum='128']
    &:after
      content: '\01F934'
  &[data-greatestNum='256']
    &:after
      content: '\01F680'
  &[data-greatestNum='512']
    &:after
      content: '\01F3C4'
  &[data-greatestNum='1024']
    &:after
      content: '\01F939'
  &[data-greatestNum='2048']
    &:after
      content: '\01F389'
  &[data-greatestNum='isTooBig']
    &:after
      content: '\01F60D'

.score-title
  font-size: 16px
  

.canvas
  > canvas
    border: 1px solid #776e65
  
              
            
!

JS

              
                let grid;
let score = 0;
let greatestNum = 0;
let isGameOver = false;

let colors = ["#eee4da", "#ede0c8", "#ffcea4", "#e8c064", "#ffab6e", "#fd9982", "#ead79c", "#76daff", "#beeaa5", "#d7d4f0", "#FFEC76", "#8bd666"];

function setup() {
  let canvas= createCanvas(400,400);
  canvas.parent('canvas');
  grid = [
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0]
  ];
  addNumber();
  addNumber();
  updateCanvas();
}

function reset() {
    score = 0;
    greatestNum = 0;
    isGameOver = false;
    grid = [
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0]
    ];
    addNumber();
    addNumber();
    updateCanvas();
}

function getColor(val) {
  let color;
  if (val > 0 && (val & (val - 1)) == 0) {
    let binar = val.toString(2);
    color = colors[(binar.length - 2) % colors.length]
  }
  return (color || '#eee4da');
}

function updateCanvas() {
  background(255);
  drawGrid();
  drawScore();
  if (isGameOver) {
    fill('rgba(255,255,255,0.75)');
    rect(0, 0, width, height);
    textAlign(CENTER, CENTER);
    textSize(36);
    textFont('monospace');
    noStroke();
    fill('#444444');
    text('Game over!'
      + String.fromCodePoint(0x1F614)
      + '\nClick to retry', 
      width/2, height/2
    );
    
  }
}

function addNumber() {
  let positions = [];
  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < 4; j++) {
      if (grid[i][j] === 0) {
        //grid[i][j] = Math.random()
        positions.push({x: i, y: j});
      }
    }
  }
  if (!positions.length) {
    return false;
  }
  let spot = random(positions);
  grid[spot.x][spot.y] = random(1) > 0.5 ? 2 : 4;
  
  if (positions.length === 1) {
    return false;
  }
  return true;
}

function checkGameOver() {
  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < 4; j++) {
      if ((j < 3 && grid[i][j] === grid[i][j+1]) || (i < 3 && grid[i][j] === grid[i+1][j])) {
        return false;
      }
    }
  }
  return true;
}

function drawGrid() {
  let w = 100;
  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < 4; j++) {
      let val = grid[i][j];
      
      strokeWeight(2);
      stroke('#776e65');
      if (val != 0) {
        fill(getColor(val));
      } else {
        noFill();
      }
      rect(i*w, j*w, w, w);
      if (val !== 0) {
        textAlign(CENTER, CENTER);
        let len = ("" + val).length - 1;
        let sizes = [64, 64, 48, 32];
        textSize(sizes[len] || 28);
        textFont('monospace');
        noStroke();
        fill('#776e65');
        text(val, i * w + w/2, j * w + w/2);
      }
      // text(i + ',' + j, i * w + w/2, j * w + w/2);
    }
  }
}

function drawScore() {
  select('#score').html(score);
  let attrVal = (greatestNum < 4096
    ? greatestNum
    : 'isTooBig'
  );
  select('.score-container').attribute('data-greatestNum', greatestNum);
}

function slide(row) {
  row = row.filter(n => !!n);
  row = combine(row);
  row = Array(4 - row.length).fill(0).concat(row);
  return row;
}

function combine(row) {
  let rowRaw = [].concat(row);
  if (row.length < 2) return row;
  let result = [];
  for (i = row.length-1; i >= 0; i--) {
    if (row[i] == row[i-1]) {
      let doubledVal = row[i]*2;
      result.unshift(doubledVal);
      score += doubledVal;
      greatestNum = (doubledVal > greatestNum ? doubledVal : greatestNum);
      row[i-1] = 0;
    } else if (row[i]) {
      result.unshift(row[i]);
    }
  }
  return result;
}

function compareRows(a, b) {
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      return true;
    }
  }
  return false;
}

function keyPressed() {
  let isChanged;
  let isArrowKey = true;
  switch (keyCode) {
   case DOWN_ARROW:
      grid.forEach((row, i, arr) => {
        let slidedRow = slide(row);
        arr[i] = slidedRow;
        if (!isChanged) {
          isChanged = compareRows(row, slidedRow);
        }
      });
      break;
    case UP_ARROW:
      grid.forEach((row, i, arr) => {
        let inputRow = [].concat(row);
        let slidedRow = slide(row.reverse()).reverse();
        arr[i] = slidedRow;
        if (!isChanged) {
          isChanged = compareRows(inputRow, slidedRow);
        }
      });
      break;
    case RIGHT_ARROW:
      for (let col = 0; col < 4; col++) { // номер колонки
        let column = [];
        for (let row = 0; row < 4; row++) { // номер строки
          column.push(grid[row][col]);
        }
        let slidedColumn = slide(column);
        for (let row = 0; row < 4; row++) { // номер строки
          grid[row][col] = slidedColumn[row];
        }
        if (!isChanged) {
          isChanged = compareRows(column, slidedColumn);
        }
      }
      break;
    case LEFT_ARROW:
      for (let col = 0; col < 4; col++) { // номер колонки
        let column = [];
        for (let row = 0; row < 4; row++) { // номер строки
          column.push(grid[row][col]);
        }
        let inputColumn = [].concat(column);
        let slidedColumn = slide(column.reverse()).reverse();
        for (let row = 0; row < 4; row++) { // номер строки
          grid[row][col] = slidedColumn[row];
        }
        if (!isChanged) {
          isChanged = compareRows(inputColumn, slidedColumn);
        }
      }
      break;
    default:
      isArrowKey = false;
  }
  if (isChanged) {
    if (!addNumber()) {
      isGameOver = checkGameOver();
    }
    updateCanvas();
  }
  if (isArrowKey) {
    return false; // prevent default behaviour
  }
}

function mouseClicked() {
  if (isGameOver) {
    reset();
  }
}
              
            
!
999px

Console