]> git.sesse.net Git - foosball/blob - foosball.pm
Make a constant out of 455.
[foosball] / foosball.pm
1 use strict;
2 use warnings;
3 use DBI;
4
5 package foosball;
6
7 sub db_connect {
8         my $dbh = DBI->connect("dbi:Pg:dbname=foosball;host=127.0.0.1", "foosball", "cleanrun", {AutoCommit => 0});
9         $dbh->{RaiseError} = 1;
10         return $dbh;
11 }
12
13 sub find_single_rating {
14         my ($dbh, $username, $limit) = @_;
15         my ($age, $rating, $rd) = $dbh->selectrow_array('SELECT EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP-ratetime)), rating, rd FROM single_rating WHERE username=? '.$limit.' ORDER BY ratetime DESC LIMIT 1',
16                 undef, $username);
17         $rd = apply_aging($rd, $age / 86400.0);
18         return ($rating, $rd);
19 }
20
21 sub find_double_rating {
22         my ($dbh, $username, $limit) = @_;
23         my ($age, $rating, $rd) = $dbh->selectrow_array('SELECT EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP-ratetime)), rating, rd FROM double_rating WHERE username=? '.$limit.'ORDER BY ratetime DESC LIMIT 1',
24                 undef, $username);
25         $rd = apply_aging($rd, $age / 86400.0);
26         return ($rating, $rd);
27 }
28
29 sub create_user_if_not_exists {
30         my ($dbh, $username) = @_;
31         my $count = $dbh->selectrow_array('SELECT count(*) FROM users WHERE username=?',
32                 undef, $username);
33         return if ($count > 0);
34         $dbh->do('INSERT INTO users (username) VALUES (?)',
35                 undef, $username);
36         $dbh->do('INSERT INTO single_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,1500.0,350.0)',
37                 undef, $username);
38         $dbh->do('INSERT INTO double_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,1500.0,350.0)',
39                 undef, $username);
40         return $dbh;
41 }
42
43 # 10-9 is 0.60
44 # 10-0 is 1.00
45 sub find_score {
46         my ($score1, $score2) = @_;
47         if ($score1 == 10) {
48                 # yay, a win
49                 return 0.60 + 0.40 * (9.0-$score2)/9.0;
50         }
51         if ($score2 == 10) {
52                 # a loss
53                 return 0.40 - 0.40 * (9.0-$score1)/9.0;
54         }
55         die "Nobody won?";
56 }
57
58 # c=8 => RD=50 moves to RD=350 over approx. five years
59 our $c = 8;
60
61 sub apply_aging {
62         my ($rd, $age) = @_;
63         $rd = sqrt($rd*$rd + $c * $c * ($age / 86400.0));
64         $rd = 350.0 if ($rd > 350.0);
65         return $rd;
66 }
67
68 sub calc_rating {
69         my ($rating1, $rd1, $rating2, $rd2, $score1, $score2) = @_;
70         my $result = `/srv/foosball.sesse.net/foorank $rating1 $rd1 $rating2 $rd2 $score1 $score2`;
71         chomp $result;
72         my ($newr1, $newrd1) = split / /, $result;
73
74         $newrd1 = 30.0 if ($newrd1 < 30.0);
75
76         return ($newr1, $newrd1);
77 }
78
79 1;