Last week, I did a very simple implementation of Tetris that caused Xs and Os to appear on the screen, with basic logic to handle rotations, checking the validity of moves (e.g. whether a piece can go down or be moved left or right) completion of rows, updating score and determining when a game is over. Now, we’re going to give this program a makeover. The underlying logic will be the same, but the presentation will be in… React!

Creating a React App

There are several ways to launch a React App, but the easiest path is to run the following lines of code:

Per React’s documentation, you need to have both Node Package Manager (npm) version ≥5.6 and Node (node) version ≥ 8.10. React contains a large number of files, so the download can take 10 or more minutes. Be patient… it’s worth it! And you can delete the extraneous files later.

Recall that our program last week contained two classes (Piece and Tetris), as well as a dictionary containing the seven different pieces that can appear (and be rotated) during a game of Tetris. We’re going to upgrade the simple vanilla JavaScript classes into React class components, and we’re going to flesh out the pieceObj object to contain some visual elements, such as color.

pieceObj

Each piece will have two basic visual attributes:

  • Color (ranging from red to purple)
  • Shape (represented as an array of arrays- e.g. 2x2 square, 4x1 rod)

Piece

Next, we move to our Piece class, which will be initialized with a randomly selected piece object from pieceObj and then given several additional functions for rotating, calculating borders and rendering:

Tetris

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store