A while ago, I decided to put together my JavaScript knowledge towards the task of implementing a simple game, taking input from the user and maintaining a game state. The game I picked was one of the classics, simple but compelling: Tetris.
I won't explain the mechanics of the gameplay here, since every reader of this will have played many hours of Tetris before. What I will explain is one way to implement those mechanics, and I hope to introduce JavaScript along the way.
Each of the pieces in Tetris is a tetromino: a unique arrangement of 4 blocks. It can be mathematically proven that there are only seven possible tetrominoes on a 2-dimensional surface: seven ways to arrange 4 blocks. Of course, you can also rotate each of the 7 kinds of tetromino, and they'll look different from each of the compass points. So, there are 28 total possible "tetromino configurations".
Each shape has been given a name here, and all 4 of its rotational states are shown. If you rotate a shape on the top row, around the centre point of the grid, you'll go through rotation states 2, 3, and 4, before getting back to the top row.
The other major part of Tetris is the well: the space into which the blocks fall. The simplest way to think of the well in Tetris is as an empty grid. As blocks fall, they get added to the well, and new blocks are introduced.
When a piece is introduced to the well, the logic of the game runs like this:
The game logic itself is rather simple; the complexities arise in checking for space around the piece, and checking for full rows in the well.