Building an online multiplayer game using React Native and Firebase: Overview

Anuj Gupta
5 min readApr 25, 2020

--

As online games are getting trending due to the current situation. I decided to create one myself. The objective was to understand how multiplayer game works. To simplify things I decided to make a tic tac toe game that can be played online. Choosing tic tac toe solved two problems. First, it limited the number of players and player’s states (More about this later) that needs to be managed and also simplified the game variables that need to be updated on every move.

Creating a local version

Before we get started on the online version of the game we need to understand the game rules and define the logic of the game which we can use later in the online version as well.

Game Logic

  1. Whose turn is it?
  2. Has anyone won or has the game tied?

Every time a player clicks on one of the grid boxes we need to check whether it is X’s turn or O’s turn and based on fill that grid and then check whether the game is over or not.

For the grid, I have take a 2D array. Initially, each grid element is initialized to an empty string.

const grid = [[null, null, null],[null, null, null],[null, null, null],];

The other variables we need are

  1. currentPlayer : To keep a track whether the current player is X or O
  2. winnerPlayer : To keep track of who won the match and can also be used to identify whether the game is over.
  3. hasGameEnded: To keep track of whether the game is over

Now the methods that are needed

  1. handleGamePlay()
// Function that's called every time the user taps on one of the grid elementconst handleGamePlay = (row, playIndex) => {const oldGameGridPlaysRowToChange = gameGridPlays[row];const newGameGridPlaysOnRow = oldGameGridPlaysRowToChange.map((play, index) => (index === playIndex ? currentPlayer : play),);const newGameGridPlays = gameGridPlays.map((rowPlays, index) =>index === row ? newGameGridPlaysOnRow : rowPlays,);const newCurrentPlayer = currentPlayer === ‘X’ ? ‘O’ : ‘X’;setGameGridPlays(newGameGridPlays);setCurrentPlayer(newCurrentPlayer);if (checkIfGameEnded(newGameGridPlays)) setHasGameEnded(true);if (hasSomeoneWon(newGameGridPlays, currentPlayer)) {setWinnerPlayer(currentPlayer);setHasGameEnded(true);}};

2. hasSomeoneWon()

// Function that checks whether someone has won
const hasSomeoneWon = (currentGameGridPlays, currentPlayer) => {
const hasSomeoneWonByRow = row =>currentGameGridPlays[row].filter(play => play === currentPlayer).length ===3;const hasSomeoneWonByColumn = column =>currentGameGridPlays.map(rowPlay => rowPlay[column] === currentPlayer).filter(winCondition => winCondition === true).length === 3;const hasSomeoneWonOnDiagonal = () => {const checkIfPlaysAreTheSame = (accumulator, currentValue) =>accumulator === currentValue ? currentValue : false;const firstRow = currentGameGridPlays[0];const secondRow = currentGameGridPlays[1];const thirdRow = currentGameGridPlays[2];const fromLeftDiagonalPlay = [firstRow[0], secondRow[1], thirdRow[2]];const fromRightDiagonalPlay = [firstRow[2], secondRow[1], thirdRow[0]];if (fromLeftDiagonalPlay.reduce(checkIfPlaysAreTheSame) ||fromRightDiagonalPlay.reduce(checkIfPlaysAreTheSame))return true;return false;};for (const currentRowOrColumn of [0, 1, 2]) {if (hasSomeoneWonByRow(currentRowOrColumn) ||hasSomeoneWonByColumn(currentRowOrColumn) ||hasSomeoneWonOnDiagonal())return true;}return false;};

So that is what is needed to implement a basic tic tac toe game. The code is self-explanatory and I want to jump into the meat of the problem. You can also keep track of the number of wins for each player

  1. firstPlayerScore : Keeps a track of the number of wins for player1
  2. secondPlayerScore : Keeps a track of the number of wins for player2

Creating the Online Version

Okay, so now talking about the online version. In the online version the state of the game resides on the server (in our case firebase) and the players get to know whenever there is a change in the state.

We will be using Firebase Realtime Database to get real time updates about state change.

So how does the Firebase structure looks like

  1. games : list of all unique games played between two players

2. users : List of all users and their active status

So here is the flow of the Online Version
1. Enter Username: A unique identification for each user

2. Update Active Status: After the user (Player A) submits his/her username and is on the Searching for players screen we update the active status of the player to be true

3. If another user (Player B) also does the same, then Player B will start Appearing in Player A’s active player list and vice versa.

4. Player A can then invite Player B, in this case, a new node is created inside the games node with the key PlayerA_PlayerB. The key is chosen in this format so that it becomes to identify the player’s username at any point in time.

5. If Player B accepts Player A’s invite then the gameStarted key inside PlayerA_PlayerB set to true and the game is started and the firebase game state is initialized

Maintaining game sync in both player’s device

  1. Whenever a player makes a move we update the corresponding game node.
  2. Both player’s devices have firebase listeners for any change.
  3. If there is a change in the game node the listener function is run and the function updates the react-native state which in turn updates the UI of the app.

What about game logic? Where does it run ?

This confused me a bit too when I was starting up with this game. Where does the game logic of deciding who the winner is run on ?. Does it run on the server? Does it run on the player’s device?

Well there are a couple of ways you could do this

  1. If you are using a backend other than firebase then you can do it on your backend
  2. For Firebase you can write cloud functions that are run every time there is a state change
  3. Third, Is to decide on a master player. It can be the player who created the game or the player who invited the other players. And run the game logic on that player.
  4. Fourth, whichever player makes the move runs the game logic and updates the state

I have used the fourth method.

Conclusion

There is a lot more to talk about like

  1. What if user leaves the game in between ?
  2. What if the player rejects the invite ?
  3. How to keep score ?
  4. How to play against computer ?

This was an overview of the app but if this article gets good response I will write a more detailed post with more code snippets. I will also be making the code opensource of my Github account soon.

The app is available on the play store and is free to play. I would really appreciate any feedback you have regarding the app.

Get Tic Tac Toe Online Multiplayer : on Play Store

Thanks for reading this article. Be sure to clap/recommend as much as you can and also share it with your friends. It means a lot to me.

Also, Let’s become friends on Twitter, Linkedin and Github.

--

--