Android Tutorial How to add highscore code

Hey fellow B4Aers, I was wondering if any one has a code snippet for storing highscores in a app. I have been searching and nothing. I just need that first shove and i can take off from there (hopefully). Just something simple not to a remote site or nothing just a small database on the phone to hold 10 names and scores and how to reset them if there becomes a higher one. Thanks in advance.
 

Kamac

Active Member
Licensed User
Longtime User
It is the best to create it yourself. It isn't hard. What you must do is:
1. Save some name and score to a file. (eg. highscores.txt)
2. When user opens higscore menu, do this:
2.1. Load all names and scores to some list/array (depends on your fancies)
2.2. Find out ex. top three scores, you can use that formula:
B4X:
[COLOR="Green"]'For loading scores, not names.
'This is in case you'd use list.[/COLOR]
[COLOR="RoyalBlue"]Dim[/COLOR] holder [COLOR="RoyalBlue"]as [/COLOR][COLOR="SeaGreen"]int[/COLOR]
[COLOR="RoyalBlue"]Dim[/COLOR] top1 [COLOR="RoyalBlue"]as[/COLOR] [COLOR="SeaGreen"]int[/COLOR]
[COLOR="RoyalBlue"]For[/COLOR] n=[COLOR="Sienna"]0[/COLOR] to highscores.lenght
    holder = highscores.Get(n)
    [COLOR="RoyalBlue"]If[/COLOR] holder > top1 [COLOR="RoyalBlue"]Then[/COLOR]
        top1 = holder
    [COLOR="RoyalBlue"]End If[/COLOR]
[COLOR="RoyalBlue"]Next[/COLOR]

Actually, this is just something that would get the highest score from the list.

2.3. Display scores by using labels/scrollviews or anything else suitable.


This is all. I recommend you to skip highscores until you gain deeper knowledge of programming :(. I'd do something simplier on your place! :)

That might be a newbie question, but that's advanced solution. You can aswell show only the highest score you've reached, but until you figure that out, it'll be stupid to you just copy&paste code. You'll learn nothing this way.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Here is an implementation that uses SQL library and DBUtils:

B4X:
Sub process_globals
   Dim SQL As SQL
   Dim NumberOfScores As Int
   'size of board
   NumberOfScores = 10
   Dim LowestScore As Int
End Sub

Sub Globals

End Sub
Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
      CreateDatabase
   End If
   
   'test
   ResetScores
   AddScore("a", 123)
   AddScore("sda", 123)
   AddScore("aa", 334)
   AddScore("gra", 123)
   AddScore("wa", 123)
   AddScore("gb", 1)
   AddScore("gea", 123)
   LogScores
   AddScore("ea", 123)
   AddScore("ga", 122)
   AddScore("da", 123)
   AddScore("ag", 23)
   AddScore("wwa", 5)
   AddScore("fa", 423)
   AddScore("age", 2)
   LogScores
End Sub

Sub CreateDatabase
   SQL.Initialize(File.DirInternal, "highscore.db", True)
   'create the tables if they do not exist
   Dim fields As Map
   fields.Initialize
   fields.Put("name", DBUtils.DB_TEXT)
   fields.Put("score", DBUtils.DB_INTEGER)
   DBUtils.CreateTable(SQL, "main", fields, "")
   LowestScore = GetLowestScore
End Sub

Sub ResetScores
   'delete all scores
   SQL.ExecNonQuery("DELETE FROM main")
   LowestScore = GetLowestScore
End Sub

Sub AddScore(Name As String, Score As Int)
   If Score <= LowestScore Then
      Log("Name=" & Name & ", Score=" & Score & ", Score is too low!")
   Else
      SQL.ExecNonQuery2("INSERT INTO main (name, score) VALUES(?, ?)", Array As Object(Name, Score))
      SQL.ExecNonQuery2("DELETE FROM main WHERE score <= ?", Array As Object(LowestScore))
      LowestScore = GetLowestScore
   End If
End Sub

Sub GetLowestScore As Int
   If SQL.ExecQuerySingleResult("SELECT count(*) FROM main") < NumberOfScores Then Return 0
   Dim table As List
   table = DBUtils.ExecuteMemoryTable(SQL, "SELECT score FROM main ORDER BY score DESC", Null, 0)
   Dim s() As String
   s = table.Get(NumberOfScores - 1)
   Return s(0)
End Sub

Sub LogScores
   Dim table As List
   table = DBUtils.ExecuteMemoryTable(SQL, "SELECT name, score FROM main ORDER BY score DESC", Null, 0)
   Dim s() As String
   For i = 0 To table.Size - 1
      s = table.Get(i)
      Log("Name=" & s(0) & ", Score=" & s(1))
   Next
End Sub
Sub Activity_Resume

End Sub
Sub Activity_Pause (UserClosed As Boolean)

End Sub

In order to run it you should copy DBUtils.bas from DBUtils: Basic4android Search: DBUtils
You will also need to reference SQL library.

Check the logs while running it to see it working.
 
Top