Rewards recipe

There are a lot of different ways to setup rewards for your users but there are two key concepts to prepare:

  • Why and when are your users rewarded? At the end of the game, only when they beat a friend score, or when they beat any public score...
  • What kind of reward they are going to receive. A fixed amount of virtual coins, an amount dependent on the user level, or a list of available prizes from where to select the right reward.

Basic example

Just to simplify the example, let’s assume you are going to give a fixed amount of coins if at the end of the match to the winning user.

Create a server hook, post-save, for your game/match collection. In it you should do something like:

  1. Check who is the winner: it's better to re-calculate it on the server-side to avoid hacks.
  2. Update the user profile adding 100 virtual coins.
  3. Send a push notification to the winner congratulating him.
  4. Send a push notification to the opponent trying to re-engage him.

Let's say you have a collection called matches where an entity has the following structure:

{
	"status":{created, playing, finished},
	"u1":{

	    "uid": {string},
	    "nick":{string}},
	"u2":{

	    "uid": {string},
	    "nick":{string}
	}
}

As you can see, we have a status of the game and data from the 2 users playing the game.

Then we create a post-save server hook for the matches collection. The server hook sends a push to both users and gives a reward to the winner increasing his amount of gold. This is the code for the server hook script:

Server code script

var match = request.object;

// First check if the last move won the game
if(match.status == "finished") {

   var winner_id = request.user.id;

   if(winner_id == match.u1.uid) {

      winner = match.u1;
      loser = match.u2;

   } else {

      winner = match.u2;
      loser = match.u1;
   }

   // Send push notification to winner
   gamedonia.user.get(winner.uid, {

      success: function(userGOT) {       

         notification = new Object();
         notification.type = "wonMatch";
         notification.matchId = match.get_id();
         notification.alert = "Congratulations! You have won " + loser.nick;
         notification.badge = 1;
         gamedonia.push.send(notification, winner.uid);

         // Update the profile of the user who won the game and give him 100 gold
         userGOT.profile.gold = userGOT.profile.gold + 100;

         gamedonia.user.update(userGOT, {

            success:function(userUpdated) {

               log.info("Updated correctly");

            }

         });
      }
   });


   // Send push notification to loser
   notification = new Object();
   notification.type = "lostMatch";
   notification.matchId = match.get_id();
   notification.alert = "You lose! You have lost your match with " + winner.nick + ". Challenge him back now!";
   notification.badge = 1;
   gamedonia.push.send(notification, loser.uid);    
}