Win an Ipad
  Developer   Tutorials   Beginners’ tutorial ...   Creating a high scor ...
Lesson 8

Creating a high scores leaderboard

Leader board, also called high score table, is a table which provides information about a few highest scores archived in the game. Sometimes, it may provide also information about the player that achieved the score. This tutorial shows how can be simple leader board created in Moscrif. It will save achieved scores, time and date of the achievement.

Data saving

To remember data even when the application is turned off, the data must be saved to some file to the device drive and not only to the RAM memory.  Probably, the most effective way how to save and manage data is using some database engine. Moscrif offers support for SQLite database engine.

Firstly, create a new empty database file called leaderboard with one table. The table is called also leaderboard and has three columns: id, score and date. The table can be made using the Moscrif database editor. Click twice to the database file and in structure tap click onto add table. In the following dialog create three columns:

  • id – Not null, integer, primary key
  • score – numeric
  • date – text

Image: creating the table

Before we can start coding our application it is needed to add sqlite library to the project in the project properties window.

Image: adding Sqlite library

In Moscrif all the sqlite features are included in the Database class. We use an instance of the Database class in a Leaderboard class which is used to manage the leaderborad. In the constructor we open the database file:

Example: opening the database file

class Leaderboard
{
    // maximum reports in the table
    const maxRecords = 10;     function this()
    {
        // open databse file
        this._database = Database.open("app://leaderboard.db");
    }

Once the level ends we need to write a new score to the database. To achieve this, an insert method is called. The insert method adds a new row to the database. If there are more rows in the database than is the allowed maximum, the record with the lowest score is removed.

Example: adding a new record to the database

function insert(score)
{
    // current time and date
    var d = new Date();
    // insert row
    this._database.exec("INSERT INTO leaderboard VALUES (null, " + score + ", '" + d.hour + ":" + d.minute + " " + d.day + "." + d.month + "." + d.year + "');");
    // number of rows
    var data = this._database.exec("SELECT Count(*) FROM leaderboard");
    // if there are more rows as it is required
    if (data["Count(*)"] > maxRecords) {
        // delete row with the lowest score
        this._database.exec("DELETE from leaderboard WHERE id = (SELECT id FROM leaderboard ORDER BY score ASC LIMIT 1);");
    }
}

To show the largest scores the getTable method is called. The getTable returns an array with elements representing the rows in the table. Every object has members with same names as are names of columns in the database, which contains values in the corresponding columns.

Example: getting data from the database

function getTable()
{
    var table = new Array();
    // select data from the table
    var data = this._database.exec("SELECT * from leaderboard ORDER BY score DESC;");     // if there are no data -> return
    if (!data)
        return;     // push one row to the table
    do {
        table.push(data.rowAsObject());
    } while (data.next());     return table;
}

Highest score scene

The score is showed in scene which requires the table from the database and shows the results in the table on the screen.

Example: showing the highest score table

include "lib://game2d/scene.ms" class ScoreScene : Scene
{
    function init()
    {
        super.init();         // get access to the highscore table
        this._table = new Leaderboard().getTable();         // paint used for text
        this._textPaint = new Paint();
        this._textPaint.color = 0xffdddddd;
        this._textPaint.textSize = System.width / 30;         this.add(new Label({
            text        : "High score",
            x           : System.width / 2,
            y           : System.height / 10,
            color       : 0xffffffff,
            textSize    : System.width / 20
        }));         this._back = new TextButton({text:"Back", x:System.width/2, y:9*System.height/10, frameWidth : 100, frameHeight : 100});
        this._back.onClick = function() {
            Game.instance.pop(new SlideToBottom());
        }
        this.add(this._back);     }     function draw(canvas)
    {
        // custom drawings         for (var i = 0; i < this._table.length; i++) {
            canvas.drawText((i+1).toString() + ".", System.width / 20, System.height / 15 * i + System.height / 5, this._textPaint);
            canvas.drawText(this._table[i].score + " points", System.width / 5, System.height / 15 * i + System.height / 5, this._textPaint);
            canvas.drawText(this._table[i].date, System.width / 2, System.height / 15 * i + System.height / 5, this._textPaint);
        }         // call (optional) default drawings         super.draw(canvas);
    }
}

Summary

As seen, creating a leaderboard for your game is pretty straightforward. You can easily reuse the code above and adjust it to your needs.

 Working with JSON   Creating a high scor ...   Moscrif for JavaScri ... 
Tutorial details and chapters
Technology:
iOS, Android
Difficulty:
Beginner
Completion:
30 min
Beginners’ tutorial series chapters