VS 2010 Leaderboard System-VBForums
Results 1 to 7 of 7

Thread: Leaderboard System

  1. #1

    Thread Starter
    New Member
    Join Date
    Dec 2017
    Posts
    1

    Leaderboard System

    I am currently working on a game with a scoring system. After the game I want the player to insert their name. This will be saved with the score to a database. I then want the database to run a query to isolate the top 10 scores recorded. This should then be printed into a text box on a form dedicated to the leaderboards of the game. Any ideas or tips on how to use VB with access as I am currently making 0 progress individually. Any other methods or suggestions would be appreciated. Thanks

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    97,429

    Re: Leaderboard System

    There is plenty of information around about how to retrieve data from databases in VB.NET. You might start with the Database FAQ link in my signature below and check out the .NET references there.

    With regards to your query, you'll want to order your data by the score column in descending order and then get the first 10 records.

    A TextBox seems like the wrong place to put the data though, given that TextBoxes are for input as well as display. A Label seems like a more appropriate option.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,580

    Re: Leaderboard System

    A database is overkill for something like this. A simple binary file and some LINQ is all you need to implement this. Here's an example:-
    vbnet Code:
    1. Imports System.IO
    2.  
    3. Public Class Form1
    4.  
    5.     Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    6.  
    7.         'Uncomment the following to generate a list of players and scores
    8.         'and save them to a file.
    9.         '******************************************************************
    10.         ' Dim allscores As PlayerScore() = GenerateFakeData(300)
    11.         ' SaveData("C:\PlayerScores.dat", allscores)
    12.         '******************************************************************
    13.  
    14.         'Load a list of players and their scores from a binary file.
    15.         'Disable this if you have uncommented the code above
    16.         '*************************************************************
    17.         Dim allscores As PlayerScore() = LoadData("c:\playerscores.dat")
    18.         '*************************************************************
    19.  
    20.         Dim topTen As PlayerScore()
    21.  
    22.         'Select only the top ten players after sorting the list in descending order.
    23.         'In other words, we are selecting the players with the top 10 scores
    24.         topTen = allscores.OrderByDescending(Function(ps) ps.Score).Take(10).ToArray
    25.  
    26.         'Show the top ten players in a ListBox
    27.         ListBox1.Items.AddRange(topTen)
    28.  
    29.  
    30.     End Sub
    31.  
    32.     'Saves the scores of players to a file
    33.     Private Sub SaveData(ByVal fileName As String, ByVal scores As IList(Of PlayerScore))
    34.  
    35.         Using fs As New FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Read)
    36.             Using bw As New BinaryWriter(fs, System.Text.Encoding.UTF8)
    37.                 bw.Write(scores.Count)
    38.                 For Each sc As PlayerScore In scores
    39.                     bw.Write(sc.PlayerName)
    40.                     bw.Write(sc.Score)
    41.                 Next
    42.             End Using
    43.         End Using
    44.     End Sub
    45.  
    46.     'Loads the scores of players from file
    47.     Private Function LoadData(ByVal fileName As String) As PlayerScore()
    48.         Dim playerScores As New List(Of PlayerScore)
    49.  
    50.         Using fs As New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)
    51.             Using br As New BinaryReader(fs, System.Text.Encoding.UTF8)
    52.                 For i = 0 To br.ReadInt32 - 1
    53.                     Dim name As String = br.ReadString
    54.                     Dim score As Integer = br.ReadInt32
    55.  
    56.                     playerScores.Add(New PlayerScore With {.PlayerName = name, .Score = score})
    57.                 Next
    58.             End Using
    59.         End Using
    60.  
    61.  
    62.         Return playerScores.ToArray
    63.     End Function
    64.  
    65.     Private Function GenerateFakeData(ByVal numberOfPlayers As Integer) As PlayerScore()
    66.         Dim r As New Random
    67.         Dim firstNames As String() = New String() {"Kate", "John", "Harry", "Melanie", "Jake", "Johnathan", "Peter", "Alex", "Oliver", "Yohance", "Tyrell", "Peggy", "Irelia", "Kane", "Jimmy"}
    68.         Dim lastNames As String() = New String() {"Williams", "Wells", "Blackman", "Jackson", "Whitman", "Stark", "Wheeler", "Livingston"}
    69.         Dim playerScores As New List(Of PlayerScore)
    70.  
    71.  
    72.         For i = 1 To numberOfPlayers
    73.             Dim name As String = firstNames(r.Next(0, firstNames.Length)) + " " + lastNames(r.Next(0, lastNames.Length))
    74.  
    75.             Dim score As Integer = r.Next(1, 10 ^ 6)
    76.             playerScores.Add(New PlayerScore With {.PlayerName = name, .Score = score})
    77.         Next
    78.  
    79.         Return playerScores.ToArray
    80.     End Function
    81.  
    82.  
    83.     'NOTE: The following procedure is required by the Windows Form Designer
    84.     'It can be modified using the Windows Form Designer.  
    85.     'Do not modify it using the code editor.
    86.     <System.Diagnostics.DebuggerStepThrough()> _
    87.     Private Sub InitializeComponent()
    88.         Me.ListBox1 = New System.Windows.Forms.ListBox()
    89.         Me.SuspendLayout()
    90.         '
    91.         'ListBox1
    92.         '
    93.         Me.ListBox1.FormattingEnabled = True
    94.         Me.ListBox1.Location = New System.Drawing.Point(12, 12)
    95.         Me.ListBox1.Name = "ListBox1"
    96.         Me.ListBox1.Size = New System.Drawing.Size(204, 277)
    97.         Me.ListBox1.TabIndex = 0
    98.         '
    99.         'Form1
    100.         '
    101.         Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
    102.         Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
    103.         Me.ClientSize = New System.Drawing.Size(242, 312)
    104.         Me.Controls.Add(Me.ListBox1)
    105.         Me.Name = "Form1"
    106.         Me.Text = "Form1"
    107.         Me.ResumeLayout(False)
    108.  
    109.     End Sub
    110.     Friend WithEvents ListBox1 As System.Windows.Forms.ListBox
    111.  
    112.  
    113. End Class
    114.  
    115. Public Class PlayerScore
    116.  
    117.  
    118.     Public Property PlayerName As String
    119.     Public Property Score As Integer
    120.  
    121.     Public Overrides Function ToString() As String
    122.         Return Me.PlayerName + " " + Score.ToString
    123.  
    124.     End Function
    125.  
    126. End Class

    To test it, simply create a new WinForms project and use the above code as the code for Form1. Follow the instructions in the comments.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  4. #4
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    97,429

    Re: Leaderboard System

    Quote Originally Posted by Niya View Post
    A database is overkill for something like this.
    If the game is the point then maybe so, but if learning about databases is the point, or a point at least, then a simple binary file is useless.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,580

    Re: Leaderboard System

    Quote Originally Posted by jmcilhinney View Post
    If the game is the point then maybe so, but if learning about databases is the point, or a point at least, then a simple binary file is useless.
    I felt that the game was the main point of the application. Though I could be wrong.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  6. #6
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    9,223

    Re: Leaderboard System

    It all depends on how you setup your database. Personally, I'd suggest creating the database to look like this:
    Code:
    +---------+-------------+
    | user_id |   username  |
    +---------+-------------+
    |   1     |    dday9    |
    |   2     |     Niya    |
    |   3     | jmcilhinney |
    +-----------------------+
    
    +--------------+---------+-------+
    | highscore_id | user_id | score |
    +--------------+---------+-------+
    |       1      |    1    |  100  |
    |       2      |    2    |   97  |
    |       3      |    3    |  144  |
    +--------------+---------+-------+
    Then you could run your query like this:
    Code:
    SELECT
      u.`username`,
      hs.`score`
    FROM
      `highscore` AS hs
      INNER JOIN `user` AS u ON hs.`user_id` = u.`user_id`
    ORDER BY
      hs.`score`
    DESC
    LIMIT 10
    This would return the username with their respective highscore sorted from best to worst. Here is an example of the database side: Live Demo

    In regards to the Visual Basic .NET side, then all you would need to do is setup your database connections, run the query provided using a DataReader, iterate through each returned result, and finally appending the result to your control (you mentioned a TextBox, but a better solution may be a ListBox or even better a DataGridView).

  7. #7
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,297

    Re: Leaderboard System

    So, in summary:

    You may have made a mistake by using the word "database".

    A high score list for a single-player game is easy to implement as a file. Especially if you just want to keep the top 10, there's not a very good reason to deal with the extra complexity of a database.

    If you're running a game server and multiple players are talking to it at the same time, a file is not a solution. This includes Access, which is and never has been designed to handle that case, but not some other file-based databases you might choose. If you want to include "every score ever" it is also a good idea to consider a database, as the concept of sorting and filtering a file is an expensive one.

    But then once you start designing a database you have to think about your tables. You could just slap the name in each row, or you could normalize your tables like dday9 suggests in #6. That's a nice touch for professional databases, but as he demonstrated it makes the query a little more complex.

    The reason I'm laying these two things out is:

    Designing a file is a thing that doesn't take a lot of thought.

    Designing a "proper" database, even with one table, is like having two different programs that interact with each other and dramatically increases the complexity of both development and deployment. Even if you stick to something designed to be simple like SQLite, you end up juggling quite a few more things than you would if you choose a file-based implementation.

    So if you really just want "top 10 scores", and every player has their own high score list, I think a file is the best idea.idea
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.