How Tetris Version 2 Improves Over Version 1
Posted on: June 14, 2023
For the past two weeks, I have been building a second version of my Tetris game (Tetris v2) using JavaScript. In this blog post, I will explain how it is different to the first version (Tetris v1) and why it is better.
Implemention Differences
Tetris v1 was built when I first start learning ReactJs, so it is implemented using pure ReactJs. In order to monitor how the Tetris board changes every time the Tetris piece moves, a lot of state management hooks like useState
and useEffect
is used for each component, causing the code lines very messy and hard to read. Especially when updating the Tetris board, I would need to make a copy of the Tetris board object before altering it or passing it into a function, to prevent directly passing its reference instead of its value which would lead to some weird behaviours.
Therefore I made Tetris v2, an better version. All game elements such as Game, Board, Piece and Cell are implemented using pure JavaScript. This approach is more flexible and can connect to any of your preferred UI building tools such as ReactJs or VueJs to build the UI. I used ReactJs to build my UI but has much less states to maintain than Tetris v1. This is because Tetris v2 has a Game class, that has full control of the whole game including generating and moving a piece then updating a board. Therefore I only need to create a Game object and add keyboard controls in App.js
then call game.run()
to play the game.
The other three classes Board, Piece and Cell have similar behaviours as in Tetris v1, but in Tetris v1 Piece class belongs to Board. Whereas in Tetris v2 I have separated Piece from Board to follow the SOLID principles, so only Game class knows information about Piece and Board.
The way to generate a Piece object is very different. In Tetirs v1 piece initial coordinates are hard coded which is less fleible. I notice Tetris pieces are always the same, each piece has its unique shape and colour, only its coordinates change during the game. So in Tetris v2 I hard coded its shape and colour, and passed in board's width and height to calculate its initial coordinates. Thus different board size is allowed like displaying pieces on the Hold Grid and the Queue Grid, more importantly only one place of code to maintain.
In Tetris v2, I also used a mixture of sync and async functions. It allows the board to perform some changes before the next piece is dropped. In this way the code is neater and more readable.
Feature Differences
-
No Button: Tetris v2 has no button on the UI to control the Tetris piece, instead users can use keyboard on desktops or swipe to move the piece on mobile devices.
-
Piece Ghost: A piece ghost is added to indicate the piece's landing position when it reached the bottom of the board.
-
Hold Function: The Hold function is added, to hold the unwanted piece temporarily.
-
Longer Queue: The Queue is now longer, displaying five pieces.