Add support for score ranks

This commit is contained in:
LumaLivy 2021-11-04 03:14:45 -04:00
commit 85f1afaf35

View file

@ -58,33 +58,38 @@ namespace LBPUnion.ProjectLighthouse.Controllers
// Get username
User user = await this.database.UserFromRequest(this.Request);
// Find your score, even if you aren't in the top list
List<Score> myScore = this.database.Scores
.Where(s => s.SlotId == slotId && s.Type == type && s.PlayerIdCollection.Contains(user.Username)).ToList();
// This is hella ugly but it technically assigns the proper rank to a score
// var needed for Anonymous type returned from SELECT
var rankedScores = this.database.Scores
.Where(s => s.SlotId == slotId && s.Type == type)
.OrderByDescending(s => s.Points)
.ToList()
.Select((Score s, int rank) => new { Score = s, Rank = rank + 1 });
//Split this out from pagination, so we can count totalNumScores below
IQueryable<Score> allScoresOfType = this.database.Scores
.Where(s => s.SlotId == slotId && s.Type == type);
// Find your score, since even if you aren't in the top list your score is pinned
var myScore = rankedScores
.Where(rs => rs.Score.PlayerIdCollection.Contains(user.Username))
.OrderByDescending(rs => rs.Score.Points)
.FirstOrDefault();
// Paginated viewing
IQueryable<Score> pagedScores = allScoresOfType
.OrderByDescending(s => s.Points)
var pagedScores = rankedScores
.Skip(pageStart - 1)
.Take(Math.Min(pageSize, 30));
//Calculate rank and serialize top scores
int rank = 1;
string serializedScores = Enumerable.Aggregate(pagedScores, string.Empty, (current, score) => {
score.Rank = (pageStart - 1) * pageSize + rank++;
return current + score.Serialize();
string serializedScores = Enumerable.Aggregate(pagedScores, string.Empty, (current, rs) => {
rs.Score.Rank = rs.Rank;
return current + rs.Score.Serialize();
});
string res = LbpSerializer.TaggedStringElement("scores", serializedScores, new Dictionary<string, object>() {
{"yourScore", myScore.OrderByDescending(score => score.Points).FirstOrDefault()},
{"yourRank", 0 }, // afaik, this is unused
{"totalNumScores", allScoresOfType.Count() } // This is shown as "Ranked 1/x" in the side menu if you have the global highscore
{"yourScore", myScore.Score.Points},
{"yourRank", myScore.Rank }, //This is the numerator of your position globally in the side menu.
{"totalNumScores", rankedScores.Count() } // This is the denominator of your position globally in the side menu.
});
Console.WriteLine(res);
return this.Ok(res);
}
}