92 lines
2.2 KiB
Java
92 lines
2.2 KiB
Java
package com.rubenvandeven.emotionhero;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.reflect.TypeToken;
|
|
|
|
import java.lang.reflect.Array;
|
|
import java.util.ArrayList;
|
|
import java.util.Collections;
|
|
import java.util.Comparator;
|
|
import java.util.Date;
|
|
|
|
/**
|
|
* Created by ruben on 19/08/16.
|
|
*/
|
|
|
|
public class Highscores extends ArrayList<Highscore>{
|
|
|
|
|
|
public static Highscores fromJson(String json) {
|
|
Gson gson = new Gson();
|
|
return gson.fromJson(json, Highscores.class);
|
|
}
|
|
|
|
public String toJson() {
|
|
Gson gson = new Gson();
|
|
return gson.toJson(this);
|
|
}
|
|
|
|
/**
|
|
* Check if given highscore is highest score in this set.
|
|
* @param score
|
|
* @return
|
|
*/
|
|
public boolean isHighest(Highscore score) {
|
|
for(Highscore s: this) {
|
|
if(s == score) // to allow comparison of items that are already in the set
|
|
continue; // skip if it wants to compare with self.
|
|
|
|
if(s.score > score.score) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Get the n highest scores
|
|
*/
|
|
public Highscores getTopN(int n) {
|
|
Collections.sort(this, new Comparator<Highscore>() {
|
|
@Override
|
|
public int compare(Highscore score1, Highscore score2)
|
|
{
|
|
// return highest first
|
|
return score1.score > score2.score ? -1 : score1.score == score2.score ? 0 : 1;
|
|
}
|
|
});
|
|
|
|
Highscores scores = new Highscores();
|
|
for (int i = 0; i < n; i++) {
|
|
scores.add(this.get(i));
|
|
}
|
|
return scores;
|
|
}
|
|
|
|
/**
|
|
* Get the n highest scores
|
|
*/
|
|
public Highscores getLast(Integer n) {
|
|
Collections.sort(this, new Comparator<Highscore>() {
|
|
@Override
|
|
public int compare(Highscore score1, Highscore score2)
|
|
{
|
|
// return newest first
|
|
return score1.time.before(score2.time) ? -1 : score1.time == score2.time ? 0 : 1;
|
|
}
|
|
});
|
|
|
|
if(n == null) { // no limit
|
|
return this;
|
|
}
|
|
|
|
Highscores scores = new Highscores();
|
|
for (int i = 0; i < n; i++) {
|
|
scores.add(this.get(i));
|
|
}
|
|
return scores;
|
|
}
|
|
|
|
|
|
}
|