Pages

Saturday, January 9, 2016

Let's write a mobile game with React Native

1. Introduction

This is the first part of a tutorial that will show you how to write a cross-platform mobile game with React Native. We're going to replicate my casual game "Alpha Reflex" which can be freely downloaded from the App Store and the Play Store. The game challenges players to find randomized letters in alphabetical order as fast as possible.

React Native isn't really designed for games. There exists a myriad of better tools for professional game development: Unity, libgdx, cocos2d-x, Moai, Starling, LÖVE, etc. So why are we creating a mobile game with React Native? First off, even simple games are more fun to develop than yet another To-Do app. Games also push for a wide range of transferable skills that will help you develop other React Native apps more effectively. In this series, we'll cover native module development, 2d/3d animations, custom event handling, cross-platform considerations, and many other topics.

Source code for this tutorial can be found at https://github.com/zmxv/alpha-reflex, though I'd suggest that you follow the guide to remake the app from scratch to gain some hands-on practice.

2. App set-up

If you haven't installed the React Native command line tool, please follow the instructions at https://facebook.github.io/react-native/docs/getting-started.html to get started.

Ready? Now run $ react-native init AlphaReflex from the command line. This creates a skeleton app that displays a welcome screen.

To test the iOS app, open alpha/ios/alpha.xcodeproj in Xcode and hit ⌘+R. To run the Android version, you'll first need to either start an emulator or connect a device before executing $ react-native run-android.

Android's emulator is excruciatingly slow. Installing Intel's HAXM alleviates the pain a little bit, but you're better off with a physical test device connected to your computer. If you're using OS X, I recommend that you develop apps for iOS first and verify Android compatibility later. It'll save you a lot of time on thumb-twiddling.

Okay, now is a good time to take a snapshot of your code in a version control system. For example:

git init
git add .
git commit -m 'Initial commit'

3. Entry files

Under the app directory, you'll find two auto-generated JavaScript files: index.ios.js and index.android.js. They are the entry points for iOS and Android respectively. To reuse as much code as possible for both platforms, we should minimize the amount of logic there. I suggest that you only register an app entry class in these two files:

require('react-native').AppRegistry.registerComponent('AlphaReflex',
    () => require('./main.js'));

We then create a real, shared entry class in a main.js file:

'use strict';

var React = require('react-native');
var {
  StyleSheet,
  Text,
  View,
} = React;

var Main = React.createClass({
  render() {
    return <View style={styles.container}>
             <View style={styles.tile}>
               <Text style={styles.letter}>A</Text>
             </View>
           </View>;
  },
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#644B62',
  },
  tile: {
    width: 100,
    height: 100,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#BEE1D2',
  },
  letter: {
    color: '#333',
    fontSize: 80,
  },
});

module.exports = Main;

Main is our first custom UI component. For now, it simply displays a lonely letter tile in its render() method.

Alternatively, you may write class Main extends React.Component to declare the Main component. However, the ES6 class syntax makes it harder to define mix-ins and static properties; the code is also slightly longer. We'll therefore stick to React.createClass.

4. Flexbox

React Native's flexbox layout model borrows ideas and terms from the CSS counterpart. In our main.js file, the flex: 1 declaration stretches the container class to fill the entire screen. If you throw in a sibling <View> with the same style, each <View> will get half of the screen real estate because 1:1 equals 50%:50%. To split the screen into one-third and two-thirds parts, you'll need to style them with flex: 1 and flex: 2.

The flexDirection property controls the direction of child element flow, which is column-wise by default. Change it to 'row' if you want a horizontal arrangement.

justifyContent justifies elements along the primary flex direction; alignItems does the same job along the perpendicular axis. In the previous example, if you want to snap the letter tile to the left edge while keeping it vertically centered, you may change container's alignItems to 'flex-start' or simply comment out that line because 'flex-start' is the default value. The result is shown below:

In general, the flexbox model is quite useful for designing adaptive layouts as it frees us from manually computing the exact bounds of UI elements. Yet we'll sometimes do the calculation ourselves and embrace position: 'absolute' when it comes to dynamic layouts.

5. Resolution-independent rendering

Next, we're going to create another React Native component that renders a 4x4 grid in a resolution-independent manner. Resolution independence is a nice property that scales our UI to fit any size so it won't leave excessive whitespace on large screens. To achieve that, there're generally two strategies:

  1. Dynamically set the size of UI widgets in proportion to the target screen dimension
  2. Pick a "design size" (e.g. 640x960), hardcode the dimension and position of UI widgets inside that box, globally scale the box and its child elements to fit the screen

The second approach is easier to work with, although it may lead to blurred results on large screens. It also lacks flexibility in fixed positioning. For our game, we'll go with the first approach and calculate appropriate UI dimensions at runtime.

We can retrieve the screen size from the built-in module 'Dimensions' using ES6's destructuring assignment syntax:

var {width, height} = require('Dimensions').get('window');

which is a concise way of saying:

var width = require('Dimensions').get('window').width;
var height = require('Dimensions').get('window').height;

The {width, height} pair is the logical resolution (e.g. 375x667 on iPhone 6) rather than the physical resolution (e.g. 750x1334 on iPhone 6), which, if you need, could be deduced by multiplying the former by the pixel density (require('react-native').PixelRatio.get()).

On iOS, height represents the full screen height; on Android, however, this value excludes the height of the status bar but includes the system navigational area at the bottom.

The rest is just basic arithmetic. Let's do it in a new component file boardview.js:

'use strict';

var React = require('react-native');
var {
  StyleSheet,
  Text,
  View,
} = React;
var {width, height} = require('Dimensions').get('window');
var SIZE = 4; // four-by-four grid
var CELL_SIZE = Math.floor(width * .2); // 20% of the screen width
var CELL_PADDING = Math.floor(CELL_SIZE * .05); // 5% of the cell size
var BORDER_RADIUS = CELL_PADDING * 2;
var TILE_SIZE = CELL_SIZE - CELL_PADDING * 2;
var LETTER_SIZE = Math.floor(TILE_SIZE * .75);

var BoardView = React.createClass({
  render() {
    return <View style={styles.container}>
             {this.renderTiles()}
           </View>;
  },

  renderTiles() {
    var result = [];
    for (var row = 0; row < SIZE; row++) {
      for (var col = 0; col < SIZE; col++) {
        var key = row * SIZE + col;
        var letter = String.fromCharCode(65 + key);
        var position = {
          left: col * CELL_SIZE + CELL_PADDING,
          top: row * CELL_SIZE + CELL_PADDING
        };
        result.push(
          <View key={key} style={[styles.tile, position]}>
            <Text style={styles.letter}>{letter}</Text>
          </View>
        );
      }
    }
    return result;
  },
});

var styles = StyleSheet.create({
  container: {
    width: CELL_SIZE * SIZE,
    height: CELL_SIZE * SIZE,
    backgroundColor: 'transparent',
  },
  tile: {
    position: 'absolute',
    width: TILE_SIZE,
    height: TILE_SIZE,
    borderRadius: BORDER_RADIUS,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#BEE1D2',
  },
  letter: {
    color: '#333',
    fontSize: LETTER_SIZE,
    backgroundColor: 'transparent',
  },
});

module.exports = BoardView;

Notice how we set a unique key property on each tile View. This practice helps React Native to detect virtual DOM changes more efficiently. Whenever you create an array of homogeneous components, remember to do this; otherwise, you'll face a prominent yellow-box warning on the screen.

We are now ready to render this component in the much simplified main.js:

'use strict';

var React = require('react-native');
var {
  StyleSheet,
  View,
} = React;

var BoardView = require('./boardview.js');

var Main = React.createClass({
  render() {
    return <View style={styles.container}>
             <BoardView/>
           </View>;
  },
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#644B62',
  },
});

module.exports = Main;

Voilà, we've just created a 4x4 grid of letters that scales nicely on both phones and tablets.

6. Custom fonts

The default system font looks legible yet unadorned; it's also inconsistent across platforms. To improve the typography, we're going to bundle a custom font with the app.

Let's do that for Android first.

  • Step 1: Create a directory android/app/src/main/assets/fonts.
  • Step 2: Drop .TTF or .OTF fonts there.
    The font files will be automatically packaged and ready for use in JavaScript.
  • Step 3: Reference the custom font name in a fontFamily property in boardview.js.
    var styles = StyleSheet.create({
      ...
      letter: {
        fontFamily: 'NukamisoLite', // <= custom font name
        ...
      },
    });
    

Now rebuild the Android app by running react-native run-android.

Let's move on to iOS.

  • Step 1: Drag and drop custom font files into the Project Navigator in XCode.
    When prompted, make sure the fonts are added to the primary build target.
  • Step 2: Select Info.plist in the Project Navigator. Click the "+" button next to "Information Property List" to add a new row. Find "Fonts provided by application" from the drop-down list.
  • Step 3: Expand the new row by clicking the triangular icon. Double-click the empty Value slot and enter the font file name without its full path.
    You may click the "+" button next to "Item 0" to add additional fonts.

Since we're using the same code base for both platforms, there's no need to edit JavaScript if you've already done step 3 for Android. Just rebuild the iOS app and check the results. (We've added a new asset to the project, so we have to rebuild rather than Cmd+R refresh.)

Full source of this part of the tutorial can be downloaded from https://github.com/zmxv/alpha-reflex/releases/tag/v0.1. The next article will discuss high-performance animations, touch event handling, and more.

(Part 2: touch event handling and property animation)

8 comments:

  1. Great post! I am looking forward to seeing next part of the tutorial. THANKS!

    ReplyDelete
  2. Thank you for the excellent tutorial. It's so helpful how you explain each aspect of the app as it gets built.

    ReplyDelete
  3. in case any of you are getting stuck in this tutorial with ES6 class syntax as I was... here is a repo: https://github.com/ericchen0121/alphaReflex

    ReplyDelete
  4. I think it has a good reaction which is very essential to us. At present people love to play mobile game. I am also. Thanks!!

    ReplyDelete
  5. Great post on a react-native game. Any plan for integrating Apple game center with your game?

    ReplyDelete