Building a Turn-Based Multiplayer Game with GameSparks and Unity: Part 2

In the previous part of this tutorial we’ve covered GameSparks basic concepts, including the configuration of matchmaking and setting up the Challenges. Today we will further explore the Cloud Code and implement our server-side game logic.

As you probably remember, Cloud Code is essentially JavaScript and most of the good practices translate well if you have used JavaScript before.

Game Logic Cloud Code

Start out with creating a new GameSparks module, which is a script that you can later use in any other Cloud Code scripts.

There are many ways to structure your code in JavaScript, but we’ll present how to use the module design pattern (don’t confuse with a GameSparks module) to create a board object.

Module design pattern uses closures to encapsulate private fields of the object, only exposing a public interface. If you don’t come from a JavaScript background, and you’ve used classical object oriented programming languages so far, this might be confusing. If you want to improve your understanding of JavaScript concepts later, I recommend reading a book called JavaScript: The Good Parts.

The board will be represented by a flattened, two-dimensional array of fields. Every element will be a number of the piece on that field. 0 is an empty field, 1 is a piece owned by player one, and 2 is a piece owned by player two. This is the only thing that will be persistently stored in the Challenge data as JSON and sent to the Unity client.

First create a new module and call it Board.

Find Modules subfolder in the Cloud Code configurator.
Fig. 1: Modules folder in Cloud Code configurator. Click the plus sign to add a new Module.

Inside define three constants, representing piece types.

Now define createBoard function which creates and returns a new object.

In JavaScript you can nest functions inside other functions. You can use it to your advantage. Inside createBoard you can define any number of variables. Thanks to the closure they will be accessible by all inner functions, but will be inaccessible from the outside. Add fields variable, which we’ll use to store the board representation, as well as some constants which will come in handy later.

Add getField and setField helper functions to calculate the index and retrieve the piece at position (x, y).

Board Initialization

Before being able to use the fields array we need to initialize it with empty fields. Add initialize, createFields and save functions and call initialize just before the return statement.

Each created Challenge object is serialized and stored in a NoSQL database. You can append your custom data using setScriptData function. You can later retrieve that data with the use of getScriptData function. Since our board object will be recreated every time the Cloud Code is being executed, we need to check if the fields array has been already created for this challenge. If not, it has to be created and saved to the script data.

Move Logic

Add tryMove function along with its helper isPositionValid. We want to expose both functions as public, so let’s also add references to them in the returned object.

tryMove function will return true or false, depending on whether the move was valid or not.

Win Conditions

Last thing we need in the public interface is a function that checks for win conditions. We can simplify the problem by correctly assuming that a winning chain always contains a piece put on the board during the last move. This way we don’t have to check every horizontal, vertical and diagonal.

All our checks will use countRecursivelyInDirection function.

It is a function meant to be used recursively. xDelta and yDelta parameters indicate a direction in which the next piece is checked. If it is a different piece, the counting stops, as the chain is broken there. If it is the same piece as the original one, the counter is incremented and the next field is checked in the same direction recursively.

Now we just need to add functions that check for winning chains in all possible directions, starting at given coordinates. Add checkWinConditions function along with its helpers: checkHorizontal, checkVertical, checkFirstDiagonal and checkSecondDiagonal. Don’t forget to add checkWinConditions to the public interface and save the GameSparks module.

Add following code to GlobalMessages/ChallengeStartedMessage:

Move Challenge Event

It’s time to use your newly created Board module. First let’s create an Event that will be sent by players when they make a move.

Go to Configurator/Events and click Add button. Fill in the form as shown in the image below, adding two Attributes which will be X and Y coordinates of the move.

Short Code should be "Move", add two Number attributes: "X" and "Y".
Fig. 2: Move Event configuration.

Click ‘Save and Close’ button.

Go to Configurator/CloudCode. Move event makes sense only in a context of a Challenge, and we need a reference to that Challenge, so we could access its script data. That’s why we need to use a Challenge Event interceptor. Select ChallengeEvents/Move which corresponds to the Event you have just created.

Find Challenge Events Subfolder in the Cloud Code configurator.
Fig. 3: Move script in the Cloud Code Configurator.

Paste in the following code:

First line allows  us to use the previously created Board module in this script. Any needed Request data is retrieved from the Sparks object. After that, we create a board object and try to put a piece on the board. If the move was successful, player’s turn is consumed and all players receive a ChallengeTurnTakenMessage. Then we check for win conditions. After the Challenge is won, the winner is sent a ChallengeWonMessage and the loser is sent a ChallengeLostMessage.


Open the Test Harness, authenticate two players and find a match to create a Challenge as before. Then try to send a LogChallengeEvent (Move) request. One of the players will be unable to do this (one cannot move if it’s not his or her turn). The other one should be able to affect the fields array in the script data.

Request and Response JSON.
Fig. 4: Test Harness – player one has sent a Move Challenge Event and has received an error Response because it wasn’t his turn.
Request and Message JSON.
Fig. 5: Test Harness – player two has sent a Move Challenge Event and has received a ChallengeTurnTakenMessage, which indicates that the move was valid.
Field JSON. First field value is set to 2.
Fig. 6: State of the board after the first move. We can see a piece belonging to player two which has been placed on the first field of the board.


This concludes the GameSparks part of this tutorial. You can already play the game using the Test Harness, however, it might be difficult to see how the board looks in two dimensions. In the next part we’ll create a new Unity project and set up authentication and matchmaking scenes, in preparation for the final part of the tutorial in which we’ll implement the gameplay.

How to Use Unity’s Resources Folder
Unity has several kinds of special folders. One of them is the Resources folder. Simple concept...
Understanding the Importance of Using Multiple Cameras in Unity
From what I observe, many Unity users do not grasp the concept of using multiple Unity cameras...
[Tutorial] – Create a Procedurally Generated Terrain for a 2D Infinite Runner Game in Unity
Have you ever been thinking of creating infinite runner game with the Unity? This kind of games...
Call The Knights!
We are here for you.
Please contact us with regards to a Unity project below.

The Knights appreciate your decision!
Expect the first news soon!
hire us!