Tetris

I built this Tetris clone using JavaScript, HTML and CSS in 1 week. It features classic Tetris gameplay, including scoring, levels (with speed increase), a 'ghost piece' and sound effects.

Built with:

JavaScript

CSS

HTML

DEVELOPMENT BLOG_

  • Creating and Translating the Tetrominoes

    I used JavaScript classes to create the tetrominoes, enabling me to store the information relative to each shape. Each shape consists of an array of 4 indices, which represent the starting position of each shape. The first index is the central point of the shape, which I have referred to as the anchor position throughout the code. The other 3 indices are the squares in order clockwise from the anchor position.

  • Edge Detection

    With the movement of the pieces implemented, the next phase of the project was ensuring that the pieces could not move outside of the grid or into any squares which were occupied by ‘locked’ pieces. This was perhaps the most challenging part of the project (details below).

  • Locking Pieces

    Once the pieces consistently stayed within bounds, I was then able to use setInterval to make the active pieces ‘fall’. I created separate movement functions for each type of movement (left, right, down, rotate clockwise and rotate anticlockwise) which call the test function and move the piece as long as the test passes. The moveDown function also calls a lockPiece function if the test fails.

  • Completed Lines

    With the moving, rotating, falling and locking, the next process to develop was the test for completed lines and the function to remove them. This was also a significant challenge - details below.

  • Hard Drop and Ghost Piece

    Although pressing the down arrow key would cause the piece to fall faster than the fall speed, I did not yet have a ‘hard drop’ function - which would immediately drop the piece into place. I also wanted to have a ‘ghost piece’ which shows where the piece would land if dropped. I quickly realised that these could use the same code - as both would need to calculate the piece’s lowest possible position. I tried several ways to do this, before realising that my already existing test function could serve this purpose quite neatly. I created a function that uses a while loop to test each row below the piece until it finds an illegal move, and returns the lowest ‘legal’ position of the piece. The hard drop function moves the piece to this position instantly. A render ghost function continuously adds a ‘ghost’ class to this position, which has an opacity of 20%.

  • Player Messages

    I then switched my attention to the ‘messaging area’ to the bottom right of the board. I planned to use this area to render messages relevant to the game state and alerts to game events, such as scoring points, levelling up and achieving a new high score.