Mobile Zone is brought to you in partnership with:

German has posted 18 posts at DZone. View Full User Profile

Using an MBaaS in your Mobile Game (Part 2): High score tracker on the Cloud

07.29.2013
| 2980 views |
  • submit to reddit

Game developers are relying on services like Kii Cloud to get everything they need to have a robust, scalable gaming back-end that works across all the platforms that their game supports. This removes the complexity of back-end implementation, offers a soft learning curve, and allows you to focus on building your game.

In this article we continue our series to show indie game developers the value of a mobile back-end service (covering specific game-related needs such as distributed high score maintenance, user registration, game data storage and social interactions among users). If you missed Part 1 where we created a game preferences manager on the cloud please see this article.

We will again use the open source Android game “Frozen Bubble“. This is a nice game originally created for Linux with a decent Android port that doesn’t include any type of backend functionality.

Frozen Bubble screenshot

Frozen Bubble for Android screenshot

FrozenBubble maintains the high scores of a player in a local SQLite database. If you use Kii Cloud instead, not only you can keep the high scores in the cloud to perhaps later perform interesting game analytics but you also save on lines of code (keep reading). Let’s see how to manage the high scores on the cloud. First of all, the local high scores implementation requires 3 levels of abstraction: a database wrapper (with all the low level SQL commands), a Data Object layer (DAO) that serves as an intermediate layer between the the database and the rest of the world and a manager class (which effectively manages operations with high scores). Overall in order to make a high score persistent you need the following:

   /**
     * HighscoreDB - First of all, create the table
     */
   public void onCreate(SQLiteDatabase db) {
      db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, level INTEGER, name TEXT, shots INTEGER, time LONG)");
   }

    /**
     * HighscoreDB - Insert a high score record into table (low level)
     */
    public long insert(HighscoreDO hi) {
      insertStmt.bindLong(1, hi.getLevel());
      insertStmt.bindString(2, hi.getName());
      insertStmt.bindLong(3, hi.getShots());
      insertStmt.bindLong(4, hi.getTime());
      return insertStmt.executeInsert();
    }

    /**
     * HighscoreManager - Insert a high score record into table (high level)
     */
    public void endLevel(int nbBubbles) {
      long endTime  = System.currentTimeMillis();
      long duration = (endTime - startTime) + pausedTime;
      if ( duration < 0 ) duration = 0;
      lastScoreId = db.insert(new HighscoreDO(currentLevel, "anon", nbBubbles, duration));
    }

What would you think if you could reduce that into the following code snippet while taking the functionality to the cloud?

    /**
     * HighscoreManager
     * @param nbBubbles - The number of bubbles launched by the player.
     */
    public void endLevel(int nbBubbles) {
      long endTime = System.currentTimeMillis();
      long duration = (endTime - startTime) + pausedTime;
      if (duration < 0) duration = 0;

      KiiObject highscore = userBucket.object();
      highscore.set("level", currentLevel);
      highscore.set("name", "anon");
      highscore.set("shots", nbBubbles);
      highscore.set("time", duration);

      highscore.save();
      lastScoreId = highscore.toUri().hashCode();
    }

No table creation, no SQL statements, no local storage. Your object goes straight to the cloud. Beginning to feel that your life gets easier? We’re not even using a DAO object for making the object persistent (it’s not necessary as long as you know the fields that are set in the object).

So our high scores are now being sent to the cloud. How do we get them back? If you check the original local DB implementation of FrozenBubble you’ll see that the high scores are retrieved via standard SQL queries:

    /**
     * HighscoreManager - get high scores (high level)
     */
    public List getHighscore(int level, int limit) {
      return db.selectByLevel(level, limit);
    }

    /**
     * HighscoreDB - get high scores (low level)
     */
    public List selectByLevel(int level, int limit) {
      List list = new ArrayList();
      Cursor cursor = db.query(TABLE_NAME, null, "level=" + level, null, null, null, "shots asc, time asc", "" + limit);
      if (cursor.moveToFirst()) {
        do {
          list.add(new HighscoreDO(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3), cursor.getLong(4)));
        } while (cursor.moveToNext());
      }
      if ((cursor != null) && !cursor.isClosed()) {
        cursor.close();
      }
      return list;
    }

For our cloud implementation we use Kii queries:

    /**
     * HighscoreManager - get high scores
     */
    public List getHighscore(int level, int limit) {
      List highscores = new ArrayList();
      // Define query condition: fetch by level
      KiiQuery query = new KiiQuery(KiiClause.equals("level", level));
      // Sort results
      query.sortByAsc("shots");
      query.sortByAsc("time");
      // limit number of objects in result
      query.setLimit(limit);		
      // Query the bucket
      KiiQueryResult result = userBucket.query(query);
      List objList = result.getResult();
      // Iterate result and populate highscore object collection
      for (KiiObject obj : objList){
        HighscoreDO objdo = new HighscoreDO(
                  obj.toUri().hashCode(), 
                  obj.getInt("level", 0), 
                  obj.getString("name", "anon"), 
                  obj.getInt("shots", 0), 
                  obj.getLong("time", 0));
        highscores.add(objdo);
      }
      return highscores;
    }

Here we’re populating a DAO object to return it to the game visualization routines for the sake of example, but you could also provide the Kii object directly if you adapt the app accordingly. Kii queries are very powerful and easy to read; for more information please check our documentation.

If you’re curious, the end result (the high score display) looks like this:

FrozenBubble High Scores

FrozenBubble High Scores

Overall it’s very simple to work with a high score manager on Kii Cloud (and very similar to the preferences manager in the previous post). You can go ahead and check out the sample Frozen Bubble app with a HighscoreManager implementation that you can use in your own app. One word of advice: the sample uses sync calls to the cloud service which cause the game to lose some frames. Even though this is not noticeable I strongly advise you to use the asynchronous versions of these methods (e.g. save()) which return automatically and rely on a callback to tell you what happened or give you the results.

If you want to go deeper on data management with Kii Cloud please check our excellent documentation. I will keep adding back-end functionality to Frozen Bubble using Kii Cloud so stay tuned (eg. push notifications, chat, analytics, etc)

Happy coding!!

Published at DZone with permission of its author, German Viscuso.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)