How to Make Online Leaderboards in Gamemaker Studio 2

In this tutorial, you will learn how to create an online highscores table for your Gamemaker Studio 2 game, completely for free.

1) Create an Altervista account

As our database, we’ll use a free service called Altervista. Altervista is normally used for blogging, but we’ll use it for storing our highscores in this case. Go to altervista.com, and hit “start now”.

How to create an account on altervista.com

Now, hit the button that says “Go on”.

Altervista registration.php, hit 'go on'

Fill out the form, and hit “Go on”.

Sign up for Altervista by filling out the form

Success! Your Altervista account has been registered. Unfortunately, now we have to play the waiting game. You’ll have to wait up to 48 hours to receive your activation email.

Altervista signup success

Altervista should send you this email right after you fill out the form:

Altervista subscription confirmation email

After the wait, you should receive an email from Altervista. Click on the link to confirm your email, and make sure to save your password and username in a safe place.

Altervista activation email

Note: if you do not receive the confirmation email within 48 hours, check your spam folder. If it’s not there, repeat enrollment.

Clicking on the “verify” link should bring you to the main dashboard. If it didn’t, click here. When you get to your dashboard, click on “file management”. We’re going to add some files that work much like scripts in Gamemaker.

Altervista go to 'file management'

Create a folder, and name it with your project’s name, then hit “New Folder”

Altervista how to create a folder

Now, open the folder by hovering over the folder and hitting “open”

Altervista: opening the folder

In the folder, create a file named “addscore”, and make sure you change the filetype to “.php” from the dropdown menu.

Altervista: creating the addscore.php file

Creating the file should bring you to a code file. This file will handle the way we add new scores to the database. Copy-paste the following code into the file, but make sure to replace the areas I highlighted with “-- --” with your own stuff.

<?php
// Connect to database
$db = new PDO('mysql:host=localhost;dbname=my_--your username--', '--your username--');

// Initialize secret key
$secret_key = "QtRzh4xS4j"; // You should replace this with your own key

// Check secret key
if($secret_key == $_POST['secret_key'])
{
  /// Correct secret key

  // Prepare statement
  $sql = "INSERT INTO --folder name--Table VALUES (NULL, :name, :score)";
  $stmt = $db->prepare($sql);
  $stmt->bindParam(':name', $name, PDO::PARAM_STR);
  $stmt->bindParam(':score', $score, PDO::PARAM_INT);

  // Get name and score from URL string
  $name = $_POST['name'];
  $score = $_POST['score'];

  // Execute statement
  $stmt->execute();
  echo '1';
}
else
{
  // Wrong secret key
  echo 'wrong key';
}
?>

IMPORTANT: Make sure you replace the stuff I marked with “– –” with your own stuff!

Now, scroll to the bottom and hit “save”.

Altervista: save addscore.php

Create a new file named “getscores”, and make sure it has the file extension of “.php”, just like last time.

Altervista: create getscores.php

Creating the file (just like the last time) should bring you to a code file. This file will return the top ten players in a formatted way. Copy-paste the below code into the file, but make sure to replace the areas I highlighted with “-- --” with your own stuff.

<?php
// Connect to database
$db = new PDO('mysql:host=localhost;dbname=my_--your username--', '--your username--');

/// Check secret key, if correct, then get names and scores

// Initialize secret key
$secret_key = "QtRzh4xS4j";

// Check secret key
if($secret_key == $_POST['secret_key'])
{
  // Get all data from the table, ordering from best to worst
  $sql = "SELECT * FROM GeoHighscoresTable ORDER BY score DESC";
  $stmt = $db->prepare($sql);
  $stmt->execute();

  /*
  Fetch the result into a nice format EXAMPLE: 1. Guest2837 100
  no_lines is the length of the list, generally, you will want a top 10
  */

  // Line number
  $line = 1;

  // Get the amount of lines
  $no_lines = $_POST['no_lines'];

  // Fetch top scores
  while($row = $stmt->fetch(PDO::FETCH_ASSOC))
  {
    // We only want the top 'no_lines'
    if($line <= $no_lines)
    {
      // Echo the top scores
      echo $line . ". " . $row['name'] . " - " . $row['score'] . "\n";
      $line += 1;
    }
  }

  // Add empty lines if no more scores are available
  if($line <= $no_lines)
  {
    for($i = $line; $i<=$no_lines; $i++)
    {
      echo $i . ". --\n";
    }
  }
}
?>

IMPORTANT: once again, ensure you replace the stuff I marked with “-- --” with your own stuff!

Now, scroll to the bottom and hit “save”.

Altervista: saving getscores.php

After that, go to the main page and hit “Activate Database”.

Altervista: how to activate a database

Hit “Get it free”.

Altervista: a free database

This should return you to the dashboard. You may now access the database. Hit “Access to PhpMyAdmin”.

How to access database in Altervista

In the admin panel, click the text on the top left that says “my_[username]”.

Altervista how to view database

Now, create a new table called “(projectName)Table”, and hit “Go”.

NOTE: Make sure you replace “(projectName)” with your own project’s name (e.g. FlappyBirdTable, or MinecraftTable)

Altervista how to view database

Fill out the table like so:

no-alignment

NOTE: Ensure you have ticked the “A_I” checkbox for the column named “id”. This ensures proper ordering.

2) Code implementation in Gamemaker

The first script we will create will be called “scr_get_online_leaderboards”. Right-click the scripts tab on the resources folder and hit “create script”. Name it “scr_get_online_leaderboards”. This script simply takes two arguments. The number of lines you want to get, and the secret key (which is in the code of your php). Just copy-paste the code below, but make sure you update the stuff I have marked with “-- --” with your own parameters.

/// @description get_online_leaderboards(name, no_lines)
/// @param lines
/// @param secret_key

// Initialize input variables
var lines = string(argument0);
var secretKey = string(argument1);

// Prepare statement
var arguments = string(string("no_lines=" + lines) + "&" + string("secret_key=" + string(secretKey)));

// Post the string
cont_leaderboards.leaderboardsStatus = http_post_string("http://ftp.--username--.altervista.org/--folder name--/getscores.php", arguments);

Awesome. The next script, named “scr_submit_score_to_leaderboards” will submit a score to Altervista, which will add the score to the database. It takes in three arguments: the player’s name, amount of points, and the secret key. As before, right-click on the script tab on the resources folder and hit “create script”. Name that script “scr_submit_score_to_leaderboards”. As before, copy-paste the code below, but still make sure you update the stuff I have marked with “-- --” with your own parameters.

/// @description send_score(name,score)
/// @param username
/// @param score
/// @param secret_key

// Initialize input variables
var name = string(argument0);
var points = string(argument1);
var secretKey = string(argument2);

// Score not above zero? (optional)
if(points <= 0) exit;

// Prepare statement
var arguments = string(string("name=" + string(name)) + "&" + string("score=" + string(points)) + "&" + string("secret_key=" + string(secretKey)));

// Send score
http_post_string("http://ftp.--username--.altervista.org/-foler name--/addscore.php", arguments);

Now that we have all the scripts set up, all we need to do now is create an object that activates those scripts! So, create an object with a name like “cont_leaderboards”.

In the create event, put the following code:

/// @description Request highscores

scr_get_online_leaderboards(10, "QtRzh4xS4j"); // Make sure you replace this with your own secret key!

In the Async - HTTP event put this code:

/// @description Receiving data from Altervista

if(ds_map_find_value(async_load, "id") == leaderboardsStatus)
{
    if(ds_map_find_value(async_load, "status") == 0)
    {
        // Set 'leaderboards'
        leaderboards = string(ds_map_find_value(async_load, "result"));

        // Check results
        if(leaderboards == "IOException") or (leaderboards == "")
        {
            // Leaderboards couldn't load...
            leaderboards = "leaderboards have failed to load";
        }
        else
        {
            /// Highscores have loaded successfully

            // Set an alarm to refresh
            alarm[0] = room_speed * 5;
        }
    }
}

And in the draw event, enter the following code (this is not required, this just draws the leaderboards).

/// @description Draw the leaderboards

// Set alignment & color
draw_set_halign(fa_center);
draw_set_valign(fa_top);
draw_set_color(c_black);

// Draw the leaderboards
draw_set_font(fnt_body);
draw_text(x, y, leaderboards);

// Reset alignment
draw_set_halign(fa_left);
draw_set_valign(fa_left);

Note: the draw event is not required, you can customize this however you’d like.

Now, add the object to your room. Whenever you want to submit a highscore, use the script “scr_submit_score_to_leaderboards()” and it should add to the highscores table. And that’s it! You should now have a working online highscores leaderboard. If you have an issue or question, feel free to ask in the comments below.

Happy coding!

Email

Comments

(Comments'd go here..)