Skip to content

Instantly share code, notes, and snippets.

@mysiar
Created September 20, 2016 05:10
Show Gist options
  • Save mysiar/45df217fe7b522ed339a9197c5061344 to your computer and use it in GitHub Desktop.
Save mysiar/45df217fe7b522ed339a9197c5061344 to your computer and use it in GitHub Desktop.
Bowling Game
class BowlingGame {
private $rolls = array();
private $currentRoll = 0;
public function __construct() {
for ($i = 0; $i < 21; $i++) {
$this->rolls[$i] = 0;
}
}
public function roll($pins) {
$this->rolls[$this->currentRoll++] = $pins;
}
/* R0 R1 R2 R3 R4 R5 R6 R7 R8 R9
* | 0 1 | 2 3 | 4 5 | 6 7 | 8 9 | 10 11 | 12 13 | 14 15 | 16 17 | 18 19 20
*/
public function score() {
$score = 0;
$rollNumber = 0; // roll number in round - even numbers - first, odd - second
for ($round = 0; $round < 10; $round++) {
if ($this->isStrike($rollNumber)) { // strike
$score += 10 + $this->rolls[$rollNumber + 1] + $this->rolls[$rollNumber + 2];
$rollNumber++;
}
else if ($this->isSpare($rollNumber)) { // spare
$score += 10 + $this->rolls[$rollNumber + 2];
$rollNumber += 2;
}
else {
$score += $this->rolls[$rollNumber] + $this->rolls[$rollNumber + 1];
$rollNumber += 2;
}
}
return $score;
}
private function isSpare($rollNumber) {
if ($this->rolls[$rollNumber] + $this->rolls[$rollNumber + 1] == 10) {
return TRUE;
}
else {
return FALSE;
}
}
private function isStrike($rollNumber) {
if ($this->rolls[$rollNumber] == 10) {
return TRUE;
}
else {
return FALSE;
}
}
public function getRolls() {
return $this->rolls;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment