]> git.localhorst.tv Git - alttp.git/blob - app/Models/Tournament.php
show placements on user profile
[alttp.git] / app / Models / Tournament.php
1 <?php
2
3 namespace App\Models;
4
5 use App\Events\ParticipantChanged;
6 use Illuminate\Database\Eloquent\Factories\HasFactory;
7 use Illuminate\Database\Eloquent\Model;
8
9 class Tournament extends Model
10 {
11         use HasFactory;
12
13
14         public function getRunners() {
15                 $runners = [];
16                 foreach ($this->participants as $participant) {
17                         if (in_array('runner', $participant->roles)) {
18                                 $runners[] = $participant;
19                         }
20                 }
21                 return $runners;
22         }
23
24         public function updatePlacement() {
25                 $runners = [];
26                 foreach ($this->participants as $p) {
27                         if ($p->isRunner()) {
28                                 $p->score = 0;
29                                 $runners[] = $p;
30                         } else {
31                                 $p->updatePlacement(null, null);
32                         }
33                 }
34                 if (empty($runners)) {
35                         return;
36                 }
37                 foreach ($this->rounds as $round) {
38                         foreach ($runners as $p) {
39                                 $result = $p->findResult($round);
40                                 if ($result) {
41                                         $p->score += $result->score;
42                                 }
43                         }
44                 }
45
46                 usort($runners, [Participant::class, 'compareScore']);
47                 $reversed = array_reverse($runners);
48                 $placement = count($runners);
49                 $skipped = 0;
50                 $lastScore = $runners[0]->score;
51                 foreach ($runners as $p) {
52                         if ($p->score > $lastScore) {
53                                 $placement -= $skipped;
54                                 $skipped = 1;
55                                 $lastScore = $p->score;
56                         } else {
57                                 ++$skipped;
58                         }
59                         $p->updatePlacement($p->score, $placement);
60                 }
61         }
62
63
64         public function participants() {
65                 return $this->hasMany(Participant::class);
66         }
67
68         public function protocols() {
69                 return $this->hasMany(Protocol::class)->orderBy('created_at', 'DESC');
70         }
71
72         public function rounds() {
73                 return $this->hasMany(Round::class)->orderBy('number', 'DESC');
74         }
75
76 }