Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              p.text-debug This pen is supposed to overwrite the favicon, if you don't see it, <a href="https://codepen.io/jibhaine/debug/Boqmpe"  target="_blank">click here</a> 
p.text-help use the arrow keys : left/right to move, up/down to rotate, space to get the piece down
canvas#c
            
          
!
            
              body{
  width:100%;
  height:100%;
  overflow:hidden;
  background-color:#333;
}
canvas{
  position:absolute;
  left:50%;
  top:50%;
  margin-left:-8px;
  margin-top:-8px;
}
p{
  font-family:courier;
  font-size:.75em;
  margin:.75em;
  color:white;
  text-shadow:1px 1px 2px black;
}
p.text-debug{
  top:1.5em;
}
a{color:white;font:bold;}
            
          
!
            
              const
//board size in number of tiles.
  BOARD_WIDTH = 16,
  BOARD_HEIGHT = 16,
  //tiles size (each tile is a square so only one)
  TILE_SIZE = 1,
  TETRAMINOS = [{
    name: 'I',
    color: '#00FFFF',
    shape: [
      [1],
      [1],
      [1],
      [1]
    ]
  }, {
    name: 'O',
    color: '#FFD800',
    shape: [
      [1, 1],
      [1, 1]
    ]
  }, {
    name: 'T',
    color: '#B200FF',
    shape: [
      [1, 1, 1],
      [0, 1, 0]
    ]
  }, {
    name: 'S',
    color: '#4CFF00',
    shape: [
      [1, 0],
      [1, 1],
      [0, 1]
    ]
  }, {
    name: 'Z',
    color: '#FF0000',
    shape: [
      [0, 1],
      [1, 1],
      [1, 0]
    ]
  }, {
    name: 'J',
    color: '#0066ff',
    shape: [
      [0, 1],
      [0, 1],
      [1, 1]
    ]
  }, {
    name: 'L',
    color: '#FF6A00',
    shape: [
      [1, 0],
      [1, 0],
      [1, 1]
    ]
  }];
//globals
let
  canvas = document.getElementById('c'),
  context = canvas.getContext('2d'),
  board = undefined,
  collisions = undefined,
  gameSpeed = 30, //number of frames between each tick.
  frameCount = 0;
/**
 * Shape, initialized from TETRAMINOS constant.
 */
class Shape {
  constructor(x, y, baseShape) {
    this.x = x;
    this.y = y;
    this.shape = baseShape.shape.slice();
    this.color = baseShape.color;
  }
  render(context) {
    context.fillStyle = this.color;

    for (let i = 0; i < this.shape.length; i++) {
      for (let j = 0; j < this.shape[i].length; j++) {
        if (this.shape[i][j]) {
          context.fillRect(
            (this.x + i) * TILE_SIZE,
            (this.y + j) * TILE_SIZE,
            TILE_SIZE,
            TILE_SIZE
          );
        }
      }
    }
    context.fillStyle = '#000000';
  }
}
/**
 * contains fixed tiles and moving pieces
 */
class Board {
  constructor() {
    //moving piece
    this.currentShape = {};
    //array of colors (non-moving shapes)
    this.tiles = [];
    this.initialize();
  }
  initialize() {
    for (let x = 0; x < BOARD_WIDTH; x++) {
      this.tiles[x] = [];
      for (let y = 0; y < BOARD_HEIGHT; y++) {
        this.tiles[x][y] = 0;
      }
    }
  }
  render() {
    context.fillStyle = '#000000';
    context.fillRect(0, 0,
      BOARD_WIDTH * TILE_SIZE,
      BOARD_HEIGHT * TILE_SIZE
    )
    //draw already placed tiles
    for (let x = 0; x < BOARD_WIDTH; x++) {
      for (let y = 0; y < BOARD_HEIGHT; y++) {
        if(this.tiles[x][y]){
          context.fillStyle = this.tiles[x][y];
          context.fillRect(
            x * TILE_SIZE,
            y * TILE_SIZE,
            TILE_SIZE,
            TILE_SIZE
          ); 
        }
      }
    }
    //Draw current moving shape
    this.currentShape.render(context);
  }
  fixShape() {
    for (let x = 0; x < this.currentShape.shape.length; x++) {
      for (let y = 0; y < this.currentShape.shape[0].length; y++) {
        if (this.currentShape.shape[x][y] !== 0) {
          //fix shape in tiles array
          this.tiles[this.currentShape.x + x][this.currentShape.y + y] = this.currentShape.color;
        }
      }
    }
  }
  detectFullLines() {
    let fullLineIndexes = [];
    for (let y = 0; y < BOARD_HEIGHT; y++) {
      let isFull = true;
      for (let x = 0; x < BOARD_WIDTH; x++) {
        if(this.tiles[x][y] == 0){
          isFull = false;
        }
      }
      if(isFull){
        fullLineIndexes.push(y);
      }
    }
    for(let index of fullLineIndexes){
      this.collapseLine(index);
    }
  }
  collapseLine(index){
    for (let y = index; y > 0; y--) {
      for (let x = 0; x < BOARD_WIDTH; x++) {
        this.tiles[x][y] = this.tiles[x][y-1];
      }
    }
  }
}

/**
 * Uses the Board.tiles to check for collisions.
 * Principle : create a new shape at future potential position and check for collision/out of bounds
 */
class CollisionDetector {
  constructor(currentBoard) {
    this.board = currentBoard;
    this.nextShape = {};
  }
  /**
   * clone currentShape to nextShape
   */
  initNextShape() {
    Object.assign(this.nextShape, this.board.currentShape);
    //avoid keeping reference of nested shape array.
    Object.assign(this.nextShape.shape, this.board.currentShape.shape);
  }
  /**
   * for each plain cell of the shape, check if an existing tiles exists at the position
   */
  willItCollide() {
    let collisionOccured = false;
    for (let x = 0; x < this.nextShape.shape.length; x++) {
      for (let y = 0; y < this.nextShape.shape[0].length; y++) {
        if (this.nextShape.shape[x][y] !== 0 && this.board.tiles[this.nextShape.x + x][this.nextShape.y + y] !== 0) {
          //bingo !
          collisionOccured = true;
        }
      }
    }
    return collisionOccured;
  }
  /**
  * for each cell of the shape, checks if we are still inside
  */
  willBeOutOfBounds(){
    let outOfBounds = false;
    for (let x = 0; x < this.nextShape.shape.length; x++) {
      for (let y = 0; y < this.nextShape.shape[0].length; y++) {
        if(this.nextShape.shape[x][y] !== 0){
          //real position
          let i = this.nextShape.x + x;
          let j = this.nextShape.y + y;
          outOfBounds &= i < 0 && i >= BOARD_WIDTH && j < 0 && j >= BOARD_HEIGHT;
        }
      }
    }
    
    return outOfBounds;
  }
  canMoveDown() {
    let reachedTheBottom = (this.board.currentShape.shape[0].length + this.board.currentShape.y < BOARD_HEIGHT);
    this.initNextShape();
    this.nextShape.y++;
    return reachedTheBottom && !this.willItCollide();
  }
  canMoveLeft() {
    let reachedLeftBorder = (this.board.currentShape.x > 0);
    this.initNextShape();
    this.nextShape.x--;
    return reachedLeftBorder && !this.willItCollide();
  }
  canMoveRight() {
    let reachedRightBorder = (this.board.currentShape.x + this.board.currentShape.shape.length < BOARD_WIDTH);
    this.initNextShape();
    this.nextShape.x++;
    return reachedRightBorder && !this.willItCollide();
  }
  canRotateLeft() {
    this.initNextShape();
    this.nextShape.shape = Rotator.toTheLeft(this.nextShape.shape);
    return !this.willBeOutOfBounds() && !this.willItCollide();
  }
  canRotateRight() {
    this.initNextShape();
    this.nextShape.shape = Rotator.toTheRight(this.nextShape.shape);
    return !this.willBeOutOfBounds() && !this.willItCollide();
  }
}

/**
 * Utility methods to rotate an array.
 */
class Rotator{
  
  /**
   * Transpose bi-dimensional array
   */
  static transpose(m){
    let result = new Array(m[0].length);
    for (let i = 0; i < m[0].length; i++) {
      result[i] = new Array(m.length - 1);
      for (let j = m.length - 1; j > -1; j--) {
        result[i][j] = m[j][i];
      }
    }
    return result;
  }
  /**
   * rotate : transpose then reverse,
   * @see http://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array
   */
  static toTheLeft(m) {
    return this.transpose(m).reverse();;
  }
  /**
   *  reverse, then transpose
   */
  static toTheRight(m) {
    return this.transpose(m.reverse());
  }
}

let
  /**
   * Creates a new random tetramino.
   */
  shapeFactory = () => {
    let i = Math.floor(Math.random() * TETRAMINOS.length);
    //console.log('new shape from base : ',TETRAMINOS[i]);
    //new random tetramino at the top center.
    return new Shape(BOARD_WIDTH / 2 - 1, 0, TETRAMINOS[i]);
  },
  /**
   * game logic.
   */
  tick = () => {
    if (collisions.canMoveDown()) {
      //go down
      board.currentShape.y++;
      board.detectFullLines();
    } else {
      board.fixShape();
      board.currentShape = shapeFactory();
      //end of game if the new shape can't go down
      if (!collisions.canMoveDown()) {
        initialize();
      }
    }
    faviconize();
  },
  animate = () => {
    board.render();
    //todo extract in a setInterval or wathever, this makes the speed go batsheetcray
    if (frameCount % gameSpeed == 0) {
      tick();
    }
    frameCount++;
    requestAnimationFrame(animate);
  },
  initialize = () => {
    canvas.width = BOARD_WIDTH * TILE_SIZE;
    canvas.height = BOARD_HEIGHT * TILE_SIZE;
    frameCount = 0;
    board = new Board();
    board.currentShape = shapeFactory();
    collisions = new CollisionDetector(board);
    animate();
    //remove the fullscreen link if we are in debug view
    if(/(.*)\/debug(.*)/g.test(document.location)){
      document.querySelector('.text-debug').style.display = 'none';
    }
  },
  
  keyHandler = (event) => {
    let e = event || window.event;
    // up arrow
    if (e.keyCode == '38') {
      if (collisions.canRotateLeft()) {
        board.currentShape.shape = Rotator.toTheLeft(board.currentShape.shape);
      }
    }
    // down arrow
    else if (e.keyCode == '40') {
      if (collisions.canRotateRight()) {
        board.currentShape.shape = Rotator.toTheRight(board.currentShape.shape);
      }

    }
    // left arrow
    else if (e.keyCode == '37') {
      if (collisions.canMoveLeft()) {
        board.currentShape.x--;
      }
    } 
    // right arrow
    else if (e.keyCode == '39') {
      if (collisions.canMoveRight()) {
        board.currentShape.x++;
      }
    } 
    //space bar
    else if (e.keyCode == '32' || e.keyCode == ' ') {

      while (collisions.canMoveDown()) {
        //go down
        board.currentShape.y++;
      }
    }

  },
  /**
   * Creates a favicon element and add it ot the dom.
   */
  linkFactory = () => {
    let link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    document.getElementsByTagName('head')[0].appendChild(link);
    return link;
  },
  /**
   * converts canvas to dataUrl image and sets it as a favicon
   */
  faviconize = () => {
    let link = document.querySelector("link[rel='shortcut icon']");
    if (!link) {
      link = linkFactory();
    }
    link.href = canvas.toDataURL("image/x-icon");

  };

document.addEventListener('DOMContentLoaded', initialize);
document.addEventListener('keydown', keyHandler);


//polyfill for Object.assign taken from here : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
if (typeof Object.assign != 'function') {
  Object.assign = function(target) {
    'use strict';
    if (target == null) {
      throw new TypeError('Cannot convert undefined or null to object');
    }

    target = Object(target);
    for (var index = 1; index < arguments.length; index++) {
      var source = arguments[index];
      if (source != null) {
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
    }
    return target;
  };
}
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console