/
Game.php
49 lines (42 loc) · 1.17 KB
/
Game.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
46
47
48
49
<?php
namespace marcusjian\BowlingGame;
class Game
{
private array $rolls = [];
public function bulkRoll(int ...$pins): void
{
foreach ($pins as $pin) {
$this->roll($pin);
}
}
public function roll(int $pin): void
{
$this->rolls[] = $pin;
}
public function score(): int
{
$score = 0;
$cursor = 0;
for ($frame = 0; $frame < 10; $frame++) {
if ($this->isStrike($cursor)) {
$score += (10 + $this->rolls[$cursor+1] + $this->rolls[$cursor+2]);
$cursor++;
} elseif ($this->isSpare($cursor)) {
$score += (10 + $this->rolls[$cursor+2]);
$cursor += 2;
} else {
$score += $this->rolls[$cursor] + $this->rolls[$cursor+1];
$cursor += 2;
}
}
return $score;
}
protected function isSpare(int $cursor): bool
{
return 10 === $this->rolls[$cursor] + $this->rolls[$cursor + 1];
}
protected function isStrike(int $cursor): bool
{
return $this->rolls[$cursor] == 10;
}
}