Skip to content

Commit

Permalink
fix players who are missing submissions
Browse files Browse the repository at this point in the history
  • Loading branch information
BrennanB committed Aug 14, 2024
1 parent e388945 commit 8a66142
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions highscores/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from datetime import datetime
from collections import Counter
from django.db.models import Avg, F
from django.db.models.functions import Coalesce

from .lib import extract_form_data, game_slug_to_submit_func
from .models import Leaderboard, Score
Expand Down Expand Up @@ -104,6 +105,50 @@ def leaderboard_combined(request: HttpRequest, game_slug: str) -> HttpResponse:

leaderboards = Leaderboard.objects.filter(game_slug=game_slug)

player_percentiles = {}
all_players = set()

for leaderboard in leaderboards:
scores = Score.objects.filter(leaderboard=leaderboard, approved=True).order_by('-score', 'time_set')
if not scores.exists():
continue
highest_score = scores.first().score

for score in scores:
percentile = (score.score / highest_score) * 100
if score.player.id not in player_percentiles:
player_percentiles[score.player.id] = {}
player_percentiles[score.player.id][leaderboard.id] = percentile
all_players.add(score.player.id)

# Ensure every player has a score for each leaderboard (0% if missing)
for player_id in all_players:
if player_id not in player_percentiles:
player_percentiles[player_id] = {}
for leaderboard in leaderboards:
if leaderboard.id not in player_percentiles[player_id]:
player_percentiles[player_id][leaderboard.id] = 0.0

average_percentiles = {player_id: sum(percentiles.values())/len(percentiles) for player_id, percentiles in player_percentiles.items()}
sorted_average_percentiles = sorted(average_percentiles.items(), key=lambda x: x[1], reverse=True)

context = []
i = 1
for player_id, avg_percentile in sorted_average_percentiles:
player = User.objects.get(id=player_id)
total_score = Score.objects.filter(player=player, leaderboard__game_slug=game_slug, approved=True).aggregate(total_score=Sum('score'))['total_score']
last_time_set = Score.objects.filter(player=player, leaderboard__game_slug=game_slug, approved=True).aggregate(last_time_set=Max('time_set'))['last_time_set']
context.append([i, {'player': player, 'average_percentile': avg_percentile, 'score': total_score, 'time_set': last_time_set}])
i += 1

return render(request, COMBINED_LEADERBOARD_PAGE, {"ls": context, "game_name": game_name})
if not Leaderboard.objects.filter(game_slug=game_slug).exists():
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

game_name = Leaderboard.objects.filter(game_slug=game_slug)[0].game

leaderboards = Leaderboard.objects.filter(game_slug=game_slug)

player_percentiles = {}

for leaderboard in leaderboards:
Expand Down

0 comments on commit 8a66142

Please sign in to comment.