0

I am making a game app and I want to list user's scores descending. I could list scores descending in the leaderboard so far, but what if the users scores are equal? Then I want whoever completed the game in less time to go up in that list. I would like to list users like that : if scores of the user is equal, which user has more time left he will go up

Here is my code :

   val query: Query = FirebaseFirestore.getInstance()
        .collection("Scores")
        .orderBy("score",Query.Direction.DESCENDING)
        .limit(50)

    val options: FirestoreRecyclerOptions<LeaderModel> = FirestoreRecyclerOptions.Builder<LeaderModel>()
        .setQuery(query, LeaderModel::class.java)
        .build()


    adapter = FBRecyclerAdapter(options)
    binding?.recyclerViewLeaderBoard?.adapter = adapter

Any help would be appreciated. Thank you!

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

1

but what if the users scores are equal?

If two users have the same score, you should implement a mechanism to differentiate them.

Then I want whoever completed the game in less time to go up in that list.

To achieve this you should add a new .orderBy() call like this:

val query: Query = FirebaseFirestore.getInstance()
    .collection("Scores")
    .orderBy("score", Query.Direction.DESCENDING)
    .orderBy("time", Query.Direction.DESCENDING) //Newly added
    .limit(50)

This means that you should add a new property inside each document that exists in the "Scores" collection that can hold the time in which a user has completed the game.

Firestore--root
  |
  --- Scores (collection)
       |
       --- $scoreId (document)
             |
             --- score: 100
             |
             --- time: 30 //Time in seconds

In order to make it work, don't also forget to create an index, as explained in my answer from the following post:

Firestore whereEqualTo, orderBy and limit(1) not working

So your index should be on the following fields:

score Descending time Descending
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193