Sharing Data between Players Using Game Data Service

Introduction

The GameSparks platform makes it easy for developers to be able to share game data between players. You may want to use this to implement features such as:

In this tutorial, we'll work through an example of how to share ghost race data that would allow a game to display another player's previous attempt at a track/level within a simple racing game. To do this, we'll create Event and Cloud Code scripts within the GameSparks Developer Portal and then test the configuration using the Test Harness.

Game Data Service? This tutorial assumes an understanding of the Game Data Service. We strongly recommend that you review the Game Data and the Data Explorer topics before you attempt to follow this tutorial.

Key Concepts

We'll need to create an Event which we can use to post the ghost data into GameSparks when a player completes a race on a given track. This Event will have a Cloud Code script attached to it that stores the ghost data in a Data Type using the Game Data Service. A second Event and Cloud Code script will be used to allow the game to query the ghost data collection for a given track and retrieve the player's ghost that represents the fastest time on this track.

For the purpose of this article, we'll assume that the ghost race data can be represented by the following JSON document containing an array:

[
  {
    "tick":number,
    "xPosition":number,
    "yPosition":number,
    "heading":number
  }
]

Creating the Event and Cloud Code Script for Storing Ghost Data

1. Create an Event that allows the game to submit the JSON ghost race data, the track name and the race time (how long the race took):

2. Click to Save and Close the new Event.

3. Create the Cloud Code script to store this data in a Data Type:

// Get the incoming Event Attributes
var ghostData = Spark.getData().GHOST_DATA;
var trackName = Spark.getData().TRACK;
var timeTaken = Spark.getData().TIME;

//Get playerId and timestamp to create entry name
var playerId = Spark.getPlayer().getPlayerId();
var time = new Date().toISOString();
var entryName = playerId + time;

//Create entry and get its data object
var API = Spark.getGameDataService();
var entry = API.createItem("raceData", entryName);
var data = entry.getData();

//Add new data to entry
data.ghostData = ghostData;
data.trackName = trackName;
data.timeTaken = timeTaken;
data.playerId = playerId;

//Persist and return any errors
var status = entry.persistor().persist().error();

if(status){
    Spark.setScriptError("ERROR", status);
}


Testing the Configuration for Storage Event

We will now use the Test Harness and the Data Explorer to test the configuration and check the results.

1. Navigate to the Test Harness and under Requests click Authentication. Select RegistrationRequest and submit a request to register a new player, PlayerN1:

  {
   "@class": ".RegistrationRequest",
   "displayName": "Player One",
   "password": "password",
   "userName": "playerN1"
  }

2. Now click LogEvent under Requests and select the Store race data Event we created earlier and send the following LogEventRequest.

  {
   "@class": ".LogEventRequest",
   "eventKey": "STORE_RACE_DATA",
   "GHOST_DATA": [
   {
   "tick": 1,
   "xPosition": 0,
   "yPosition": 0,
   "heading": 90
   },
   {
   "tick": 2,
   "xPosition": 10,
   "yPosition": 0,
   "heading": 92
   },
   {
   "tick": 3,
   "xPosition": 20,
   "yPosition": 0,
   "heading": 94
   }
   ],
   "TRACK": "Track1",
   "TIME": 90
  }

If successful you'll get a LogEventResponse similar to this.

  {
   "@class": ".LogEventResponse",
  }

3. Before you can query the raceData Data Type in the Data Explorer, select Configurator>Game Data. You'll first have to set up the indexing fields on the Game Data page that you want to use in your queries:

4. Now, navigate to the Data Explorer and under Data Types select to open the raceData Data Type.

5. Click Query and use the Builder to create a query rule using the indexed fields you've set up for raceData that will return a document by trackName:

6. Repeat the sending of the Store race data Event but change the data each time, especially the TIME field. This will result in several documents being stored in the raceData Data Type for PlayerN1.

7. Now register a second player, PlayerN2, by sending a RegistrationRequest and repeat the sending of the Store race data Event. Change the data each time, especially the TIME field. This will result in several documents being stored in raceData Data Type for PlayerN2.

Creating the Event and Cloud Code Script for Retrieving Ghost Data

Now we need to create an Event that allows the game to retrieve the fastest player's JSON ghost race data for a given track name.

Creating the Data Retrieval Event

1. Navigate to Configurator > Events.

2. Click to Add and a new Event.

3. Set up the Event as follows:

4. Click to Save and Close the new Event.

Adding Cloud Code to the Data Retrieval Event

Next we create the Cloud Code script to retrieve the data from the raceData Data Type and return it in the LogEventResponse.

1. Navigate to Configurator > Cloud Code > Scripts > Events.

2. Select the GET_RACE_DATA Event we created in the previous section.

3. Copy and paste the following Cloud Code into it:

// Get the incoming Event Attribute
var trackName = Spark.getData().TRACK;

//Create entry and get its data object
var API = Spark.getGameDataService();

//Construct condition and sort
var query = API.S("trackName").eq(trackName);
// Ensure the field used to sort the query results has been indexed
var sort = API.sort("timeTaken", true);

//Use condition and sort to return results
var resultsOBJ = API.queryItems("raceData", query,sort);

if(resultsOBJ.error()){
    Spark.setScriptError("ERROR", resultsOBJ.error())
}else{
    var results = resultsOBJ.cursor();
    if(results.hasNext()){
        while(results.hasNext()){
          var result = results.next();
          Spark.setScriptData(result.getId(),result.getData());
        }
    } else{
        Spark.setScriptError("ERROR", "No results found");
    }
}

4. Click to Save the Cloud Code script on the Event.

Testing the Configuration for Retrieval Event

We'll now use the Test Harness to test the configuration and check the results.

1. Navigate to the Test Harness, under Scripts click Authentication, and select AuthenticationRequest.

2. Send the AuthenticationRequest for PlayerN2 that you registered at step 7. in the previous section when testing the storage Event we set up and which should be something like this:

  {
   "@class": ".AuthenticationRequest",
   "userName": "playerN2",
   "password": "passwordN2"
  }

3. Now, click Log Event and select the Retrieve race data Event we just created and send a LogEventRequest for track 1:

  {
   "@class": ".LogEventRequest",
   "eventKey": "GET_RACE_DATA",
   "TRACK": "Track1"
  }

The response will look similar to this and should be the fastest timeTaken document from the raceData Data Type for the given track.

{
"@class": ".LogEventResponse",
"scriptData": {
  "fastestRaceData": [
    {
      "timeTaken": 90,
      "trackName": "Track1",
      "ghostData": [
        {
        "xPosition": 0,
        "heading": 90,
        "yPosition": 0,
        "tick": 1
        },
        {
        "xPosition": 10,
        "heading": 92,
        "yPosition": 0,
        "tick": 2
        },
        {
        "xPosition": 20,
        "heading": 94,
        "yPosition": 0,
        "tick": 3
      }
    ],
    "playerId": "5a687001ec34053f017895f8"
    }
  ]
}
}


Did this page help you? Please enter your feedback below. For questions about using this part of the platform, please contact support here