Farzin Nasiri
Farzin Nasiri

Reputation: 730

How to sort scores for high score board in a game

I'm writing a game in which you can have different users. Every time you play the game you submit a score. I want to have a high-score board that show the top 10 scores of all time. For instance:

A:[100,200,50]
B:[400,150,320]
C:[50,245,35]

What I want to achieve is:

B 400
B 320
C 245
A 200
B 150
A 100
A 50
C 50
C 35

Sorting the numbers themselves isn't a big problem but how can I keep track of what number is for which player? I'm using Java and I figured maybe a HashMap would be useful but I couldn't find a solution.

Basically:

  1. I already have the list of scores of each player. How should I save this data for better sorting? Is HashMap a good idea?
  2. What is the fastest algorithm I can use to do this task?
  3. If two scores are the same the alphabetical order of player names should be checked, how can I do this?

Upvotes: 1

Views: 793

Answers (1)

MWB
MWB

Reputation: 1879

You could write a class for a score and implement Comparable.

class Score implements Comparable<Score> {

    int score;
    Player player;

    Score(int score, Player player) {
        this.score = score;
        this.player = player;
    }

    @Override
    public int compareTo(Score otherScore) {
        if (this.score > otherScore.score) {
            return 1;
        } 
        else if (this.score < otherScore.score) {
            return -1;
        }
        else {
            return this.player.name.compareTo(otherScore.player.name);
        }
    }
}

This way you can just save the scores in a List and use Collections.sort().

(in the above example, I assume you have a class for Player with attribute name)

Upvotes: 3

Related Questions