forked from kdungs/tippspiel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
97 lines (73 loc) · 2.74 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.utils import timezone
class Player(models.Model):
"""A player is a user in the context of the tippspiel."""
user = models.OneToOneField(User)
score = models.IntegerField("The player's score.", default=0)
rank = models.IntegerField("The player's rank", default=1)
def gravatar_hash(self):
from hashlib import md5
return md5(self.user.email.lower()).hexdigest()
def update_score(self):
tipps = Tipp.objects.filter(player=self)
score = 0
for tipp in tipps:
score += tipp.points()
self.score = score
def __unicode__(self):
return self.user.username
# connect signal
def create_player(sender, instance, created, **kwargs):
if created:
Player.objects.create(user=instance)
post_save.connect(create_player, sender=User)
class Team(models.Model):
"""A team in the Bundesliga"""
handle = models.CharField(max_length=3)
name = models.CharField(max_length=100)
def __unicode__(self):
return self.handle
class Match(models.Model):
"""A match between two teams."""
date = models.DateTimeField()
matchday = models.IntegerField(default=0)
team_home = models.ForeignKey(Team, related_name='+')
team_visitor = models.ForeignKey(Team, related_name='+')
score_home = models.IntegerField(default=-1)
score_visitor = models.IntegerField(default=-1)
def has_started(self):
return self.date <= timezone.now()
def __unicode__(self):
return '%s %d:%d %s' % (self.team_home.handle, self.score_home, self.score_visitor, self.team_visitor.handle)
class Tipp(models.Model):
"""A bet by a player on a match."""
player = models.ForeignKey(Player)
match = models.ForeignKey(Match)
date = models.DateTimeField()
score_home = models.IntegerField(default=0)
score_visitor = models.IntegerField(default=0)
def points(self):
sh = self.match.score_home
sv = self.match.score_visitor
th = self.score_home
tv = self.score_visitor
if -1 in [sh, sv, th, tv]:
return 0
sgn = lambda x: 0 if x==0 else x/abs(x)
points = 0
ds = sh-sv
dt = th-tv
if sgn(ds)==sgn(dt):
# correct tendency
points += 1
if ds==dt:
# correct difference
points += 1
if sh==th:
# correct result
points += 1
return points
def __unicode__(self):
return 'Tipp by %s on %s (%d:%d) (%d)' % (self.player, self.match, self.score_home, self.score_visitor, self.points())