Quantcast

Jump to content

» «
Photo

Leaderboard Tutorial

14 replies to this topic
qiangqiang101
  • qiangqiang101

    I'm Not MentaL

  • Members
  • Joined: 02 Feb 2010
  • Malaysia

#1

Posted 27 February 2016 - 10:56 AM Edited by qiangqiang101, 05 March 2016 - 02:42 PM.

Leaderboard

 

8P71wBz.jpg

 

The Source Code is in VB.NET 

'Declare
    Public Shared SecretKey As String = "MY_AWESONE_SECRET_KEY"
    Public Shared AddScoreURL As String = "http://example.com/AddScore.php?" 'Don't forget the "?"
    Public Shared TopScoresURL As String = "http://example.com/TopScores.php"

'Submit Score

    Public Shared Sub SubmitScore(name As String, score As Integer)
        Try
            Dim hash As String = Md5Sum((name & score) & SecretKey) 'I use hash is to prevent Cheating
            Dim client As WebClient = New WebClient()
            client.DownloadString(Convert.ToString(AddScoreURL + "name=" & name & "&score=" & score & "&hash=") & hash)
        Catch ex As Exception
            UI.Notify(ex.Message)
        End Try
    End Sub

    Public Shared Function Md5Sum(strToEncrypt As String) As String
        Dim ue As New System.Text.UTF8Encoding()
        Dim bytes As Byte() = ue.GetBytes(strToEncrypt)
        Dim md5 As New MD5CryptoServiceProvider()
        Dim hashBytes As Byte() = md5.ComputeHash(bytes)
        Dim hashString As String = ""
        For i As Integer = 0 To hashBytes.Length - 1
            hashString += Convert.ToString(hashBytes(i), 16).PadLeft(2, "0"c)
        Next
        Return hashString.PadLeft(32, "0"c)
    End Function

'View HighScore
'I use NativeUI by Guadmaz to show a Leaderboard Menu

    Public Shared Sub LeaderboardMenu()
        Try
            topMenu = New UIMenu("Top 50", "LEADERBOARD")
            _menuPool.Add(topMenu)
            Dim Client As WebClient = New WebClient
            Dim Source As String = Client.DownloadString(TopScoresURL)
            Dim Source2 As String = Source.Remove(Source.Length - 1)
            Dim Lines() As String = Source2.Split("#"c)
            For Each s As String In Lines
                Dim result() As String = s.Split(","c)
                Dim name As String = result(0)
                Dim score As String = result(1)
                itemLeaderboard = New UIMenuItem(name)
                topMenu.AddItem(itemLeaderboard)
                With itemLeaderboard
                    .SetRightLabel(CInt(score).ToString("###,###"))
                End With
            Next
        Catch ex As Exception
            UI.Notify(ex.Message)
        End Try
        topMenu.RefreshIndex()
    End Sub

Now for the MySQL part

- Create a new MySQL Database from your DirectAdmin

- Login to phpMyAdmin

- Next, insert the following SQL:

CREATE TABLE Scores(
    name VARCHAR(10) NOT NULL DEFAULT 'Anonymous' PRIMARY KEY,
    score INT(5) UNSIGNED NOT NULL DEFAULT '0',
    ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
ENGINE=InnoDB;

- This will create a table with three variables:

  - name, which holds your player's names.

  - score, which holds each user's highest score.

  - ts, a timestamp we can use to change the order of our leaderboard.

 

Setting Up Your PHP Files

- Create a file name AddScore.php

- Change LOCAL_HOST to your server name or you can use localhost, USER_NAME to your Database User Name, PASSWORD to your Database Password and DB_NAME to your Database Name, MY_AWESONE_SECRET_KEY to your Super Super Super Secret Key.

<?php 
        //You have to fill in this information to connect to your database!
        $db = mysql_connect('LOCAL_HOST', 'USER_NAME', 'PASSWORD') or die('Failed to connect: ' . mysql_error()); 
        mysql_select_db('DB_NAME') or die('Failed to access database');

        //These are our variables.
        //We use real escape string to stop people from injecting. We handle this in Unity too, but it's important we do it here as well in case people extract our url.
        $name = mysql_real_escape_string($_GET['name'], $db); 
        $score = mysql_real_escape_string($_GET['score'], $db); 
        $hash = $_GET['hash']; 
        
        //This is the polite version of our name
        $politestring = sanitize($name);
        
        //This is your key. You have to fill this in! Go and generate a strong one.
        $secretKey="MY_AWESONE_SECRET_KEY";
        
        //We md5 hash our results.
        $expected_hash = md5($name . $score . $secretKey); 
        
        //If what we expect is what we have:
        if($expected_hash == $hash) { 
            // Here's our query to insert/update scores!
            $query = "INSERT INTO Scores
SET name = '$politestring'
   , score = '$score'
   , ts = CURRENT_TIMESTAMP
ON DUPLICATE KEY UPDATE
   ts = if('$score'>score,CURRENT_TIMESTAMP,ts), score = if ('$score'>score, '$score', score);"; 
            //And finally we send our query.
            $result = mysql_query($query) or die('Query failed: ' . mysql_error()); 
        } 

/////////////////////////////////////////////////
// string sanitize functionality to avoid
// sql or html injection abuse and bad words
/////////////////////////////////////////////////
function no_naughty($string)
{
    $string = preg_replace('/sh*t/i', 'shoot', $string);
    $string = preg_replace('/f*ck/i', 'fool', $string);
    $string = preg_replace('/asshole/i', 'animal', $string);
    $string = preg_replace('/bitches/i', 'dogs', $string);
    $string = preg_replace('/bitch/i', 'dog', $string);
    $string = preg_replace('/bastard/i', 'plastered', $string);
    $string = preg_replace('/ni**er/i', 'newbie', $string);
    $string = preg_replace('/c*nt/i', 'corn', $string);
    $string = preg_replace('/cock/i', 'rooster', $string);
    $string = preg_replace('/fa**ot/i', 'piglet', $string);

    $string = preg_replace('/suck/i', 'rock', $string);
    $string = preg_replace('/dick/i', 'deck', $string);
    $string = preg_replace('/crap/i', 'rap', $string);
    $string = preg_replace('/blows/i', 'shows', $string);

    // ie does not understand "&apos;" &#39; &rsquo;
    $string = preg_replace("/'/i", '&rsquo;', $string);
    $string = preg_replace('/%39/i', '&rsquo;', $string);
    $string = preg_replace('/&#039;/i', '&rsquo;', $string);
    $string = preg_replace('/&039;/i', '&rsquo;', $string);

    $string = preg_replace('/"/i', '&quot;', $string);
    $string = preg_replace('/%34/i', '&quot;', $string);
    $string = preg_replace('/&034;/i', '&quot;', $string);
    $string = preg_replace('/&#034;/i', '&quot;', $string);

    // these 3 letter words occur commonly in non-rude words...
    //$string = preg_replace('/fag', 'pig', $string);
    //$string = preg_replace('/ass', 'donkey', $string);
    //$string = preg_replace('/gay', 'happy', $string);
    return $string;
}

function my_utf8($string)
{
    return strtr($string,
      "/<>€悼‖垷墣?烂諔Ν嫵矊棍崕ば瘙挀斅柿巳臀咸釉曇谯贋柉槞毟洕",
      "![]YuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy");
}

function safe_typing($string)
{
    return preg_replace("/[^a-zA-Z0-9 \!\@\%\^\&\*\.\*\?\+\[\]\(\)\{\}\^\$\:\;\,\-\_\=]/", "", $string);
}

function sanitize($string)
{
    // make sure it isn't waaaaaaaay too long
    $MAX_LENGTH = 250; // bytes per chat or text message - fixme?
    $string = substr($string, 0, $MAX_LENGTH);
    $string = no_naughty($string);
    // breaks apos and quot: // $string = htmlentities($string,ENT_QUOTES);
    // useless since the above gets rid of quotes...
    //$string = str_replace("'","&rsquo;",$string);
    //$string = str_replace("\"","&rdquo;",$string);
    //$string = str_replace('#','&pound;',$string); // special case
    $string = my_utf8($string);
    $string = safe_typing($string);
    return trim($string);
}


?>
 

- Again, Create a file name TopScores.php

- Change LOCAL_HOST to your server name or you can use localhost, USER_NAME to your Database User Name, PASSWORD to your Database Password and DB_NAME to your Database Name.

<?php
    //Again, fill in your server data here!
    $db = mysql_connect('LOCAL_HOST', 'USER_NAME', 'PASSWORD') or die('Failed to connect: ' . mysql_error()); 
        mysql_select_db('DB_NAME') or die('Failed to access database');
 
     //This query grabs the top 10 scores, sorting by score and timestamp.
    $query = "SELECT * FROM Scores ORDER by score DESC, ts ASC LIMIT 10";
    $result = mysql_query($query) or die('Query failed: ' . mysql_error());
 
    //We find our number of rows
    $result_length = mysql_num_rows($result); 
    
    //And now iterate through our results
    for($i = 0; $i < $result_length; $i++)
    {
         $row = mysql_fetch_array($result);
         echo $row['name'] . "," . $row['score'] . "#"; // And output them
    }
?> 

Upload AddScore.php and TopScores.php to your Web hosting.

 

Usage:

                    If Score > PlayerHighscore Then
                        'If Score is higher than previous Highscore, then submit the new score.
                        SubmitScore(Player.Name, Score)
                    End If

Credits: Alex Rose

  • Tustin likes this

jedijosh920
  • jedijosh920

    ⭐⭐⭐⭐⭐

  • Members
  • Joined: 01 Mar 2012
  • United-States

#2

Posted 27 February 2016 - 07:18 PM

What is this even for? GTA Co-Op?


ISOFX
  • ISOFX

    Trick

  • Members
  • Joined: 31 May 2015
  • United-Kingdom

#3

Posted 27 February 2016 - 08:48 PM Edited by ISOFX, 27 February 2016 - 08:51 PM.

I'm confused, what is this?


InfamousSabre
  • InfamousSabre

    Harpocrates

  • Members
  • Joined: 03 Jan 2013

#4

Posted 27 February 2016 - 09:19 PM

Whats to be confused about? Its an example for a high score table saved to file.


ISOFX
  • ISOFX

    Trick

  • Members
  • Joined: 31 May 2015
  • United-Kingdom

#5

Posted 27 February 2016 - 11:31 PM

Whats to be confused about? Its an example for a high score table saved to file.

 

Yeah, but what could this be used in?


ikt
  • ikt

    _

  • Members
  • Joined: 02 Oct 2006
  • None

#6

Posted 28 February 2016 - 12:06 AM

Whats to be confused about? Its an example for a high score table saved to file.

 
Yeah, but what could this be used in?


Uh, any mod where you had a leaderboard? Maybe keep it local, maybe keep them online.
  • Jitnaught likes this

Tustin
  • Tustin

    Keto Friendly!

  • Members
  • Joined: 20 Dec 2013
  • Antarctica

#7

Posted 28 February 2016 - 04:27 AM Edited by Tustin, 28 February 2016 - 04:30 AM.

Pretty neat, but you should be avoiding the mysql functions because they are deprecated in the latest PHP versions. Use something like MySQLi or PDO for connecting to a database and executing queries. You can "sanitize" user inputs by using parameterized values for user input. Quick example:

<?php
$db = new PDO("mysql:host=localhost;dbname=YOUR_DB_NAME_HERE", $DB_USER, $DB_PASS);

$key = $_GET['some_random_user_input'];

//use like this
$query = $db->prepare("SELECT * FROM `users` WHERE `license` = :key");
$query->execute(array(
     "key" => $key
));
$ret = $query->fetch();

Sloppy example but that's PDO in a nutshell. I'd suggest looking into it more but that's basically the norm for database connections in PHP now. Not trying to hate on your post or anything btw, just wanted to suggest a better alternative for the PHP part :).

  • Droppy likes this

CamxxCore
  • CamxxCore

    Mark Chump

  • Members
  • Joined: 19 Oct 2013
  • Canada

#8

Posted 28 February 2016 - 06:06 PM

I can see why someone might find this useful.. but I thought this section was for documenting GTA V related functions etc.?? Feels kind of out of place.

InfamousSabre
  • InfamousSabre

    Harpocrates

  • Members
  • Joined: 03 Jan 2013

#9

Posted 28 February 2016 - 08:50 PM

I can see why someone might find this useful.. but I thought this section was for documenting GTA V related functions etc.?? Feels kind of out of place.

These are functions that work in GTA V, as shown in the screenshot. What more do you want?

  • jedijosh920 likes this

CamxxCore
  • CamxxCore

    Mark Chump

  • Members
  • Joined: 19 Oct 2013
  • Canada

#10

Posted 29 February 2016 - 05:35 AM

I can see why someone might find this useful.. but I thought this section was for documenting GTA V related functions etc.?? Feels kind of out of place.

These are functions that work in GTA V, as shown in the screenshot. What more do you want?

Seems you are missing the point. What about this post is even slightly related to GTA V?

InfamousSabre
  • InfamousSabre

    Harpocrates

  • Members
  • Joined: 03 Jan 2013

#11

Posted 29 February 2016 - 06:25 AM

I can see why someone might find this useful.. but I thought this section was for documenting GTA V related functions etc.?? Feels kind of out of place.

These are functions that work in GTA V, as shown in the screenshot. What more do you want?
Seems you are missing the point. What about this post is even slightly related to GTA V?
The very first code block. It clearly shows how he used his code to show a leaderboard in GTA V. Are you suggesting this be moved to Coding section or something? Can always just ask a mod if this is the right place. I think this seems like an appropriate subforum since it isn't a question, it's documentation on how to do a specific thing in GTA, even though the code is pretty portable for any other application without much modification.
  • leftas likes this

qiangqiang101
  • qiangqiang101

    I'm Not MentaL

  • Members
  • Joined: 02 Feb 2010
  • Malaysia

#12

Posted 02 March 2016 - 04:43 PM

What is this even for? GTA Co-Op?

for Leaderboard for Mini Game Mod like I use in Drift Streets Los Santos.


Whats to be confused about? Its an example for a high score table saved to file.

No... this is save to MySQL

 

so far I know only CamxxCore's Air Superiority Mod and My Drift Streets Los Santos Mod have a Leaderboard system.


InfamousSabre
  • InfamousSabre

    Harpocrates

  • Members
  • Joined: 03 Jan 2013

#13

Posted 02 March 2016 - 07:36 PM Edited by InfamousSabre, 03 March 2016 - 12:48 AM.

Whats to be confused about? Its an example for a high score table saved to file.

No... this is save to MySQL

 

Well you aren't saving it to RAM. Data saved on a hard disk or sent over the internet to ultimately be placed on a hard disk is known as a file.


Jitnaught
  • Jitnaught

    Grass tastes bad

  • Members
  • Joined: 24 Aug 2013
  • United-States

#14

Posted 07 April 2016 - 03:56 PM

 

Whats to be confused about? Its an example for a high score table saved to file.

No... this is save to MySQL

 

Well you aren't saving it to RAM. Data saved on a hard disk or sent over the internet to ultimately be placed on a hard disk is known as a file.

 

It sounded like you were talking about saving it to a file offline.


InfamousSabre
  • InfamousSabre

    Harpocrates

  • Members
  • Joined: 03 Jan 2013

#15

Posted 12 April 2016 - 12:30 AM Edited by InfamousSabre, 12 April 2016 - 12:34 AM.

 

 

Whats to be confused about? Its an example for a high score table saved to file.

No... this is save to MySQL

 

Well you aren't saving it to RAM. Data saved on a hard disk or sent over the internet to ultimately be placed on a hard disk is known as a file.

 

It sounded like you were talking about saving it to a file offline.

 

I didn't specify online or offline. It's a file, regardless. This method works for both. Some tweaks needed for offline, but not much.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users