Navigation

Part 3 - Saving a Score

Published on 6th November 2018

With your leaderboard created, it's time to save a score to it.

Let's assume that the player has enjoyed a round of your Instant Game, they've got a score, and you're going to save it.

The first thing to do is to create an instance of the leaderboard. In this example, the leaderboard that we created in the App Dashboard was called "globalscores".

this.facebook.on('getleaderboard', function (leaderboard)
{
    this.leaderboard = leaderboard;

}, this);

this.facebook.getLeaderboard('globalscores');

First, we set-up an event listener for the getleaderboard event. Then we call getLeaderboard, passing in the name of the leaderboard we require.

When the API call resolves our event handler will be invoked (assuming you have actually created a leaderboard called 'globalscores'). It will be passed an instance of a Leaderboard class.

This is a special type of object within the Phaser Facebook plugin that encapsulates working with a single leaderboard. Remember, a game can have as many leaderboards as you like, so it's best to keep the instances of them separate.

With an instance of the leaderboard stored locally, we can save the player's score to it:

var playerScore = 340;

this.leaderboard.setScore(playerScore);

Note that we're calling setScore on the Leaderboard instance itself, not on the Facebook plugin.

If the given score value is valid, i.e. it meets the 'Sort Order' criteria, then it will be saved and a setscore event dispatched.

When the score is saved it creates a LeaderboardScore object. Here's an example object:

score: 9999
scoreFormatted: 00:09.99
timestamp: 1542024510
rank: 1
data: 
playerName: Richard
playerPhotoURL: https://platform-lookaside.fbsbx.com/platform/instantgames/profile_pic.jpg?igpid=XXXXXXXXXXXXXXXX&height=256&width=256&ext=XXXXXXXXXX&hash=AeSAYoU03VQyDZPE
playerID: XXXXXXXXXXXXXXXX

In the object above you can see the player has a score of 9999, which is being saved to a "Time" based leaderboard, because of the scoreFormatted value. The other values, such as the rank, data and ID should be clear, and are explained in detail on the SDK LeaderboardEntry page.

Whenever you save or retrieve a player's score, this is the format of the object you get back.

You can also save data along with the score, which we'll cover in the next part.