Here is the link to the actual game itself: Tetris by Truski. Once you’ve gotten a feel for the game, I invite you to right click and view the Source of the page; for the rest of the post I will be going over how everything works together to make this classic come to life through your browser!
Here are the roles for each of the files:
- Index.html holds the base framework for the document, links together the other files, and starts the game.
- Styles.css contains the styling information that gives the page visual structure and colors.
- Tetris.js provides the actual code that starts the game and gives it its heartbeat.
- Jquery-2.2.1.min.js includes helper functions that will let us edit the document and provide user control more easily.
You may notice that the bare HTML is very scarce. That’s because the file links to the other files in the
<head> tag. It is the
The Tetris Grid
The grid is simply made up of 170 (10 x 17) div blocks with the class box and an id corresponding to its coordinate. The functions
appendSwap() in Tetris.js on lines 263 and 275 properly create our Tetris grid and swap space that shows what piece we have saved.
A tetronimo, or Tetris piece, is a 4-block entity that you control. In my implementation, it is described in the class
Piece. Every piece has a base and three relative blocks that have vertical and horizontal integer offsets to the base block. The relative positions are based on the type of the tetronimo, which is randomized by the constructor.
A Piece has a plethora of methods that allows it to function as a tetronimo. It can rotate clockwise and counterclockwise, move one block-width at a time, and can draw and erase itself on the board. I encourage you to check out some of these methods to see how they all work.
The current Piece in use is drawn, erased, and redrawn repeatedly using the div ids and some helper classes to update its background. Once a piece hits the bottom or another piece, it no longer is treated as a Piece and all the blocks that formed it lose their roundness, which is an indicator used by the code to check where Pieces were placed
The Game Loop
Time urgency in end-game Tetris could really get your adrenaline rushing. This is only achievable with a constantly shortening timer that pushes pieces down and generates new ones. We use the
resetTimer() on lines 354 and 327 to see the cogs spin.
Try it Yourself
I bestow upon you a downloadable ZIP file that contains all of the source code for this project. It is completely free, but please credit me when sharing.
If you’ve already read some of it, you’ve seen that comments in the code walk you through many of the methods.
See a flaw you could correct, an optimization you could make, or a feature you can add? I challenge you to implement these modifications, and link to your version of the game in the comments below.
I’d love to see what improvements you could make. Thanks for reading, and I hope to hear from you soon!