Implementation Details


Tetris is a pretty easy game to implement, just a simple html file with some inline css/javascript.

The only tricky part is dealing with rotation of the 7 tetrominoes.

You could try to do mathematical rotations at run time, but you will quickly discover that some of the pieces rotate around a central block (j, l, s, t and z), whilst others rotate around a point between blocks (i and o).

You could special case the 2 different behaviors, or you could accept the fact that Tetris is hard-coded to always have 7 pieces with 4 rotations and simply hard code all 28 patterns in advance.

You can avoid other special case code if you assume that all pieces are, conceptually, laid out on a 4x4 grid, where each cell is either occupied or not. Interestingly 4x4 = 16, and ‘occupied or not’ = 1 or 0.

var i = { blocks: [0x0F00, 0x2222, 0x00F0, 0x4444], color: 'cyan'   };
var j = { blocks: [0x44C0, 0x8E00, 0x6440, 0x0E20], color: 'blue'   };
var l = { blocks: [0x4460, 0x0E80, 0xC440, 0x2E00], color: 'orange' };
var o = { blocks: [0xCC00, 0xCC00, 0xCC00, 0xCC00], color: 'yellow' };
var s = { blocks: [0x06C0, 0x8C40, 0x6C00, 0x4620], color: 'green'  };
var t = { blocks: [0x0E40, 0x4C40, 0x4E00, 0x4640], color: 'purple' };
var z = { blocks: [0x0C60, 0x4C80, 0xC600, 0x2640], color: 'red'    };

We can then provide a helper method that given:

one of the pieces above a rotation direction (0-3) a location on the tetris grid … will iterate over all of the cells in the tetris grid that the piece will occupy:

function eachblock(type, x, y, dir, fn) {
  var bit, result, row = 0, col = 0, blocks = type.blocks[dir];
  for(bit = 0x8000 ; bit > 0 ; bit = bit >> 1) {
    if (blocks & bit) {
      fn(x + col, y + row);
    }
    if (++col === 4) {
      col = 0;
      ++row;
    }
  }
};