A Tetris Game Using React and Redux

Use React, Redux, Immutable to code Tetris.


] to play!


Interface preview

This is the normal speed of recording, you can see it has a smooth experience.

Responsive

Not only refers to the screen adaptation, but the change of input depending on your platform, use of the keyboard in the PC and in the phone using the touch as input:

Data persistence

What’s the worst can happen when you’re playing stand-alone games? Power outage. The state is stored in the localStorage by subscribing to store.subscribe, which records exactly all the state. Web page refreshes, the program crashes, the phone is dead, just re-open the connection and you can continue playing.

Redux state preview (Redux DevTools extension)

Redux manages all the state that should be stored, which is a guarantee to be persisted as mentioned above.


+ Redux, together with Immutable.js.

1. What is Immutable.js?

Immutable is data that can not be changed once it is created. Any modification or addition to or deletion of an Immutable object returns a new Immutable object.

Acquaintance:

Let’s look at the following code:

function keyLog(touchFn) {
  let data = { key: 'value' };
  f(data);
  console.log(data.key); // Guess what will be printed?
}

If we do not look at f, and do not know what it did to data, we can not confirm what will be printed. But if data is Immutable, you can be sure that data haven’t changed and value is printed:

function keyLog(touchFn) {
  let data = Immutable.Map({ key: 'value' });
  f(data);
  console.log(data.get('key'));  // value
}

JavaScript uses a reference assignment, meaning that the new object simply refers to the original object, changing the new will also affect the old:

foo = {a: 1};  bar = foo;  bar.a = 2;
foo.a // 2

Although this can save memory, when the application is complex, it can result in the state not being controllable, posing a big risk. The advantages of saving memory, in this case, become more harm than good.

With Immutable.js the same doesn’t happen:

foo = Immutable.Map({ a: 1 });  bar = foo.set('a', 2);
foo.get('a') // 1

Concise:

In Redux, it’s a good practice to return a new object (array) to each reducer, so we often see code like this:

// reducer
...
return [
   ...oldArr.slice(0, 3),
   newValue,
   ...oldArr.slice(4)
];

In order modify one item in the array and return the new object (array), the code has this strange appearance above, and it becomes worse the deeper the data structure. Let’s take a look at Immutable.js’s approach:

// reducer
...
return oldArr.set(4, newValue);

Isn’t it simpler?

About “===”:

We know that === operator for the Object and Array compares the reference to the address of the object rather than its “value comparison”, such as:

{a:1, b:2, c:3} === {a:1, b:2, c:3}; // false
[1, 2, [3, 4]] === [1, 2, [3, 4]]; // false

To achieve the above we could only deepCopy and deepCompare to traverse the objects, but this is not only cumbersome it also harms performance.

Let’s check Immutable.js approach!

map1 = Immutable.Map({a:1, b:2, c:3});
map2 = Immutable.Map({a:1, b:2, c:3});
Immutable.is(map1, map2); // true

// List1 = Immutable.List([1, 2, Immutable.List[3, 4]]);
List1 = Immutable.fromJS([1, 2, [3, 4]]);
List2 = Immutable.fromJS([1, 2, [3, 4]]);
Immutable.is(List1, List2); // true

It’s smooth like a breeze blowing.

React has a big trick when it comes to performance tuning. It uses shouldComponentUpdate() to check (as the name says) if the component should be re-rendered, it returns true by default, which always executes the render() method followed by the Virtual DOM comparison.

If we don’t return a new object when making state updates, we would have to use deepCopy and deepCompare to calculate if the new state is equal to the previous one, the consumption of the performance is not worth it. With Immutable.js, it’s easy to compare deep structures using the method above.

For Tetris, imagine that the board is a two-dimensional array. The square that can be moved is shape (also a two-dimensional array) + coordinates. The superposition of the board and the box is composed of the final result of Matrix. The properties above are built by Immutable.js, through its comparison method, you can easily write shouldComponentUpdate. Source Code:/src/components/matrix/index.js#L35

Immutable learning materials:


2. How to use Immutable.js in Redux

Goal: state -> Immutable. Important plug-ins: gajus/redux-immutable Will be provided by the original Redux combineReducers provided by the above plug-ins:

// rootReducers.js
// import { combineReducers } from 'redux'; // The old method
import { combineReducers } from 'redux-immutable'; // The new method

import prop1 from './prop1';
import prop2 from './prop2';
import prop3 from './prop3';

const rootReducer = combineReducers({
  prop1, prop2, prop3,
});


// store.js
// Create a store method and the same general
import { createStore } from 'redux';
import rootReducer from './reducers';

const store = createStore(rootReducer);
export default store;

Through the new combineReducers the store object will be stored as an Immutable.js object, the container will be slightly different, but this is what we want:

const mapStateToProps = (state) => ({
  prop1: state.get('prop1'),
  prop2: state.get('prop2'),
  prop3: state.get('prop3'),
  next: state.get('next'),
});
export default connect(mapStateToProps)(App);

3. Web Audio Api

There are many different sound effects in the game, but in fact we keep only a reference to a sound file: /build/music.mp3. With the help of Web Audio Api, you can play audio in millisecond precision, with a high frequency, which is not possible with the <audio> tag. Press the arrow keys to move the box while the game is in progress, you can hear high-frequency sound.

WAA is a new set of relatively independent interface system, the audio file has a higher processing power and more professional built-in audio effects, is the W3C recommended interface, can deal with professional “sound speed, volume, environment, sound visualization, High-frequency, sound to ” and other needs. The following figure describes the use of WAA process.

Where Source represents an audio source, Destination represents the final output. Multiple Sources compose the Destination. Source Code:/src/unit/music.js. To achieve ajax loading mp3, and to WAA, control the playback process.

WAA is supported in the latest 2 versions of each browser(CanIUse)

IE and Android lack support though.

Web Audio Api learning materials:


4. Game on the experience of optimization

  • Experience:
    • Press the arrow keys to move vertically and horizontally. The trigger frequency is different, the game can define the trigger frequency, instead of the original event frequency, the source code:/src/unit/event.js ;
    • Left and right to move the delay can drop the speed, but when moving in the wall smaller delay; in the speed of 6 through the delay will ensure a complete horizontal movement in a row;
    • The touchstart and mousedown events are also registered for the button for responsive games. When touchstart occurs, mousedown is not triggered, and when mousedown occurs, the mouseup simulator mouseup will also be listened to as mouseup, since the mouse-removed event element can not fire. Source Code:/src/components/keyboard/index.js;
    • The visibilitychange event, when the page is hidden\switch, the game will not proceed, switch back and it will continue, the focus state has also been written into the Redux. So when playing with the phone and the phone has a call, the progress of the game will be saved; PC open the game do not hear any other gameover, which is a bit like ios application switch;
    • In the game any time you refresh the page, (such as the closing the tab or the end of the game) can restore the current state;
    • The only pictures used in the game are , all the rest is CSS;
    • Game compatible with Chrome, Firefox, IE9 +, Edge, etc .;
  • Rules:
    • You can specify the initial board (ten levels) and speed (six levels) before the start of the game;
    • 100 points for 1 line, 300 points for 2 lines, 700 points for 3 lines, 1500 points for 4 lines;
    • The drop speed of the box increases with the number of rows eliminated (one level for every 20 lines);

5. Experience in Development

  • shouldComponentUpdate is written for all react components, which on the phone causes a significant performance improvement. For Large and medium-sized applications when facing performance problems, try writing your own shouldComponentUpdate, it will most probably help you.
  • Stateless Functional Components(Stateless Functional Components has no lifecycle hooks. And because all components need to write the life cycle hook shouldComponentUpdate, they are not used.
  • In the webpack.config.js devServer attribute is written host: '0.0.0.0', but you can be use in the development any other ip, not limited to localhost;
  • Redux in the store not only connect to the method passed to container, you can jump out of the component, in other documents out to do flow control (dispatch), the source code:/src/control/states.js
  • Dealing with persistence in React + Redux is very convenient, as long as the redux state of storage, reducers do read in each of the initialization time.
  • By configuring .eslintrc.js and webpack.config.js, the ESLint test is integrated in the project. Using ESLint allows coding to be written to specifications, effectively controlling code quality. Code that does not conform to the specifications can be found through the IDE and the console at development time (or build time). reference:Airbnb React/JSX Style Guide

6. Summary

  • As a React hand application, in the realization of the process found a small “box” or a lot of details can be optimized and polished, this time is a test of a front-end engineers and the skill of the time carefully.
  • Optimization of the direction of both React itself, such as what state is stored by the Redux, which states to the state of the component like; and out of the framework of the product can have a lot of features to play, in order to meet your needs, these will be natural propulsion technology development of.
  • An application from scratch, the function slowly accumulate bit by bit, it will build into a high-rise, do not fear it difficult to have the idea to knock on it. ^_^

7. Flowchart


8. Development

Install

npm install

Run

npm start

The browser will go to http://127.0.0.1:8080/

multi-language

In the i18n.json is the configuration for the multi-language environment. You can change the language by passing the url parameter lan like this: https://github.com/BestCryptoKnight/react-tetris

Build

npm run build

Will build the application in the build folder.

GitHub

View Github