Tetris

Tetris on jsfiddle

by Zonedark

HTML

<div id="everything" class="mainClass">
  <div id="control">
    <h1>Tetris</h1>
    <p>You can control the falling piece with your keyboard. <strong>Focus your mouse on the playing field in order to control the piece in JSFiddle!</strong></p>
    <p>Use <strong>Left</strong> ⇦, <strong>Down</strong> ⇩, and <strong>Right</strong> ⇨ arrow keys in your keyboard to move the piece around the playing field.</p>
    <p>You can also use  <strong>Spacebar</strong> to directly put the piece at the bottom.</p>
    <p>Use the  <strong>⇧ Up arrow</strong> to rotate the piece clockwise ↻.</p>
    <p>Press H to hide everything, and S to make it visible again. The game is paused while hidden.</p>
     <p><strong>Have fun!</strong></p>
  </div>

  <div id="tetris"></div>
</div>

CSS

#tetris {
  float: right;
  width: 50%;
}

#control {
  float: left;
  width: 50%;
}

JavaScript

// +-+-+-+-+-+-+-+-+-+ //
//                     //
//     T E T R I S     //
//                     //
// +-+-+-+-+-+-+-+-+-+ //

var Paused = false;
var SpacePressed = false;

$(document).keydown(function(e) {
  switch (e.which) {
    case 32:
      // Space
      SpacePressed = true;
      break;

    case 72:
      // H
      $(everything).hide();
      Paused = true;
      break;

    case 83:
      // S
      Paused = false;
      $(everything).show();
      break;

    default:
      return; // exit this handler for other keys
  }
  e.preventDefault(); // prevent the default action (scroll / move caret)
});

var TETRIS = {

  // ========== //
  //   Config   //
  // ========== //
  // All these parameters are configurable.
  config: {
    BlockSize: 25, // Width/height of a single block (in pixel)
    ControlKey: {
      Left: '37', // Move piece left
      Right: '39', // Move piece right
      Down: '40', // Move piece down
      RotateLeft: '38', // Rotate piece counter-clockwise
      RotateRight: '88' // Rotate piece clockwise
    },
    FieldHeight: 22, // Number of rows available in the field (in block)
    FieldWidth: 10, // Number of columns available in the field (in block)
    LevelUpRow: 10, // Number of row(s) must be cleared to get to the next level
    LevelUpSpeed: 50, // Speed increase every level up (in microsecond)
    PieceColor: { // Color of the pieces (in HTML color)
      I: 'red',
      J: 'orange',
      L: 'magenta',
      O: 'blue',
      S: 'lime',
      T: 'olive',
      Z: 'cyan'
    },
    ScoreMultiplier: 10, // Score multiplier
    StartingSpeed: 1000, // Starting interval speed (in microsecond)
    VoidColor: '#fafafa' // Color of a blank/void block (in HTML color)
  },

  // ========= //
  //   State   //
  // ========= //
  // Currently running game states.
  state: {
    shape: {},
    form: [],
    color: 'black',
    drop: false,
    rotate: 0,
    rows: 0,
    score: 0,
    level: 1,
    next: '',
    over: false,
 ...