import logging import random from django.urls import reverse from django.db.models import Max from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from . import models log = logging.getLogger('picture_tournament') # Create your views here. def compare(request): if "left" not in request.session: left_pic = random_pic() request.session["left"] = left_pic.id request.session["left_count"] = 0 if "right" not in request.session: right_pic = random_pic() request.session["right"] = right_pic.id request.session["right_count"] = 0 left_pic = models.Picture.objects.get(id=request.session["left"]) right_pic = models.Picture.objects.get(id=request.session["right"]) request.session["left_count"] += 1 request.session["right_count"] += 1 context = { "left": left_pic, "right": right_pic, } return HttpResponse(render(request, 'pt/compare.html', context)) def random_pic(): max_id = models.Picture.objects.all().aggregate(Max('id'))["id__max"] log.debug("max_id = %s", max_id) while True: id = random.randint(1, max_id) pics = models.Picture.objects.filter(id=id) if len(pics) == 1: return pics[0] def left_wins(request): left = models.Picture.objects.get(id=request.session["left"]) right = models.Picture.objects.get(id=request.session["right"]) expected = 1 / (1 + 10**((right.elo - left.elo) / 400)) log.info("before: left=%f, right=%f, expected=%f", left.elo, right.elo, expected) adjust = (1 - expected) * 20 left.elo += adjust left.save() right.elo -= adjust right.save() log.info("after: left=%f, right=%f", left.elo, right.elo) log.info("counts: left=%d, right=%d", request.session["left_count"], request.session["right_count"]) if request.session["left_count"] >= 5: del request.session["left"] del request.session["right"] return HttpResponseRedirect(reverse('compare')) def right_wins(request): left = models.Picture.objects.get(id=request.session["left"]) right = models.Picture.objects.get(id=request.session["right"]) expected = 1 / (1 + 10**((left.elo - right.elo) / 400)) log.info("before: left=%f, right=%f, expected=%f", left.elo, right.elo, expected) adjust = (1 - expected) * 20 left.elo -= adjust left.save() right.elo += adjust right.save() log.info("after: left=%f, right=%f", left.elo, right.elo) log.info("counts: left=%d, right=%d", request.session["left_count"], request.session["right_count"]) if request.session["right_count"] >= 5: del request.session["right"] del request.session["left"] return HttpResponseRedirect(reverse('compare')) def refresh(request): del request.session["left"] del request.session["right"] return HttpResponseRedirect(reverse('compare')) def top(request): top = models.Picture.objects.all().order_by("-elo")[0:10] context = { "top": top } return HttpResponse(render(request, 'pt/top.html', context))