-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscores.php
45 lines (40 loc) · 1.09 KB
/
scores.php
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
<?php
class Scores {
private $scores = [];
public function __construct(array $players) {
Assert::type($players, 'Player');
foreach ($players as $player) {
$this->scores[] = new Score($player, 0);
}
}
public function score(Player $player, $newScore) {
foreach ($this->scores as &$score) {
if ($score->player() === $player) {
$score = new Score($player, $score->score() + $newScore);
}
}
}
public function scores() {
return $this->scores;
}
public function __toString() {
list($longestName, $longestScore) = [0, 0];
foreach ($this->scores as $score) {
$name = mb_strlen($score->player()->name());
$score = mb_strlen($score->score());
if ($name > $longestName) {
$longestName = $name;
}
if ($score > $longestScore) {
$longestScore = $score;
}
}
$s = '';
foreach ($this->scores as $score) {
$s .= str_pad($score->player()->name(), $longestName + 1);
$s .= str_pad($score->score(), $longestScore, ' ', STR_PAD_LEFT);
$s .= "\n";
}
return $s;
}
}