Jump to content
    1. Welcome to GTAForums!

    1. GTANet.com

    1. GTA Online

      1. Los Santos Drug Wars
      2. Updates
      3. Find Lobbies & Players
      4. Guides & Strategies
      5. Vehicles
      6. Content Creator
      7. Help & Support
    2. Red Dead Online

      1. Blood Money
      2. Frontier Pursuits
      3. Find Lobbies & Outlaws
      4. Help & Support
    3. Crews

    1. Grand Theft Auto Series

      1. Bugs*
      2. St. Andrews Cathedral
    2. GTA VI

    3. GTA V

      1. Guides & Strategies
      2. Help & Support
    4. GTA IV

      1. The Lost and Damned
      2. The Ballad of Gay Tony
      3. Guides & Strategies
      4. Help & Support
    5. GTA San Andreas

      1. Classic GTA SA
      2. Guides & Strategies
      3. Help & Support
    6. GTA Vice City

      1. Classic GTA VC
      2. Guides & Strategies
      3. Help & Support
    7. GTA III

      1. Classic GTA III
      2. Guides & Strategies
      3. Help & Support
    8. Portable Games

      1. GTA Chinatown Wars
      2. GTA Vice City Stories
      3. GTA Liberty City Stories
    9. Top-Down Games

      1. GTA Advance
      2. GTA 2
      3. GTA
    1. Red Dead Redemption 2

      1. PC
      2. Help & Support
    2. Red Dead Redemption

    1. GTA Mods

      1. GTA V
      2. GTA IV
      3. GTA III, VC & SA
      4. Tutorials
    2. Red Dead Mods

      1. Documentation
    3. Mod Showroom

      1. Scripts & Plugins
      2. Maps
      3. Total Conversions
      4. Vehicles
      5. Textures
      6. Characters
      7. Tools
      8. Other
      9. Workshop
    4. Featured Mods

      1. Design Your Own Mission
      2. OpenIV
      3. GTA: Underground
      4. GTA: Liberty City
      5. GTA: State of Liberty
    1. Rockstar Games

    2. Rockstar Collectors

    1. Off-Topic

      1. General Chat
      2. Gaming
      3. Technology
      4. Movies & TV
      5. Music
      6. Sports
      7. Vehicles
    2. Expression

      1. Graphics / Visual Arts
      2. GFX Requests & Tutorials
      3. Writers' Discussion
      4. Debates & Discussion
    1. Announcements

    2. Support

    3. Suggestions

Leaderboard Tutorial


qiangqiang101
 Share

Recommended Posts

qiangqiang101

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 ScoresSET name = '$politestring'   , score = '$score'   , ts = CURRENT_TIMESTAMPON 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 "'" ' ’    $string = preg_replace("/'/i", '’', $string);    $string = preg_replace('/%39/i', '’', $string);    $string = preg_replace('/'/i', '’', $string);    $string = preg_replace('/&039;/i', '’', $string);    $string = preg_replace('/"/i', '"', $string);    $string = preg_replace('/%34/i', '"', $string);    $string = preg_replace('/&034;/i', '"', $string);    $string = preg_replace('/"/i', '"', $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("'","’",$string);    //$string = str_replace("\"","”",$string);    //$string = str_replace('#','£',$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

Edited by qiangqiang101
Link to comment
Share on other sites

 

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.

Link to comment
Share on other sites

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 :).

Edited by Tustin
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

InfamousSabre

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?

  • Like 1
Link to comment
Share on other sites

 

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?

Link to comment
Share on other sites

InfamousSabre

 

 

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.
Link to comment
Share on other sites

qiangqiang101

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.

Link to comment
Share on other sites

InfamousSabre

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.

Edited by InfamousSabre
Link to comment
Share on other sites

  • 1 month later...

 

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.

Link to comment
Share on other sites

InfamousSabre

 

 

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.

Edited by InfamousSabre
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • 1 User Currently Viewing
    0 members, 0 Anonymous, 1 Guest

×
×
  • Create New...

Important Information

By using GTAForums.com, you agree to our Terms of Use and Privacy Policy.