ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# LukeCarrier's solution

## to Bowling in the PHP Track

Published at Sep 08 2019 · 0 comments
Instructions
Test suite
Solution

Score a bowling game.

Bowling is a game where players roll a heavy ball to knock down pins arranged in a triangle. Write code to keep track of the score of a game of bowling.

## Scoring Bowling

The game consists of 10 frames. A frame is composed of one or two ball throws with 10 pins standing at frame initialization. There are three cases for the tabulation of a frame.

• An open frame is where a score of less than 10 is recorded for the frame. In this case the score for the frame is the number of pins knocked down.

• A spare is where all ten pins are knocked down by the second throw. The total value of a spare is 10 plus the number of pins knocked down in their next throw.

• A strike is where all ten pins are knocked down by the first throw. The total value of a strike is 10 plus the number of pins knocked down in the next two throws. If a strike is immediately followed by a second strike, then the value of the first strike cannot be determined until the ball is thrown one more time.

Here is a three frame example:

Frame 1 Frame 2 Frame 3
X (strike) 5/ (spare) 9 0 (open frame)

Frame 1 is (10 + 5 + 5) = 20

Frame 2 is (5 + 5 + 9) = 19

Frame 3 is (9 + 0) = 9

This means the current running total is 48.

The tenth frame in the game is a special case. If someone throws a strike or a spare then they get a fill ball. Fill balls exist to calculate the total of the 10th frame. Scoring a strike or spare on the fill ball does not give the player more fill balls. The total value of the 10th frame is the total number of pins knocked down.

For a tenth frame of X1/ (strike and a spare), the total value is 20.

For a tenth frame of XXX (three strikes), the total value is 30.

## Requirements

Write code to keep track of the score of a game of bowling. It should support two operations:

• `roll(pins : int)` is called each time the player rolls a ball. The argument is the number of pins knocked down.
• `score() : int` is called only at the very end of the game. It returns the total score for that game.

## Running the tests

1. Go to the root of your PHP exercise directory, which is `<EXERCISM_WORKSPACE>/php`. To find the Exercism workspace run

`````` % exercism debug | grep Workspace
``````
2. Get PHPUnit if you don't have it already.

`````` % wget --no-check-certificate https://phar.phpunit.de/phpunit.phar
% chmod +x phpunit.phar
``````
3. Execute the tests:

`````` % ./phpunit.phar bowling/bowling_test.php
``````

## Source

The Bowling Game Kata at but UncleBob http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### bowling_test.php

``````<?php

/**
* Translated from original source:
* http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata
*/
class GameTest extends PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass() : void
{
require_once 'bowling.php';
}

/** @var Game */
private \$game;

public function setUp() : void
{
\$this->game = new Game();
}

public function testShouldBeAbleToScoreAGameWithAllZeros() : void
{
\$this->rollMany(20, 0);

\$this->assertEquals(0, \$this->game->score());
}

public function testShouldBeAbleToScoreAGameWithNoStrikesOrSpares() : void
{
\$this->game->roll(3);
\$this->game->roll(6);
\$this->game->roll(3);
\$this->game->roll(6);
\$this->game->roll(3);
\$this->game->roll(6);
\$this->game->roll(3);
\$this->game->roll(6);
\$this->game->roll(3);
\$this->game->roll(6);
\$this->game->roll(3);
\$this->game->roll(6);
\$this->game->roll(3);
\$this->game->roll(6);
\$this->game->roll(3);
\$this->game->roll(6);
\$this->game->roll(3);
\$this->game->roll(6);
\$this->game->roll(3);
\$this->game->roll(6);

\$this->assertEquals(90, \$this->game->score());
}

public function testASpareFollowedByZerosIsWorthTenPoints() : void
{
\$this->game->roll(6);
\$this->game->roll(4);
\$this->rollMany(18, 0);

\$this->assertEquals(10, \$this->game->score());
}

public function testPointsScoredInTheRollAfterASpareAreCountedTwice() : void
{
\$this->game->roll(6);
\$this->game->roll(4);
\$this->game->roll(3);
\$this->rollMany(17, 0);

\$this->assertEquals(16, \$this->game->score());
}

public function testConsecutiveSparesEachGetAOneRollBonus() : void
{
\$this->game->roll(5);
\$this->game->roll(5);
\$this->game->roll(3);
\$this->game->roll(7);
\$this->game->roll(4);
\$this->rollMany(15, 0);

\$this->assertEquals(31, \$this->game->score());
}

public function testASpareInTheLastFrameGetsAOneRollBonusThatIsCountedOnce() : void
{
\$this->rollMany(18, 0);
\$this->game->roll(7);
\$this->game->roll(3);
\$this->game->roll(7);

\$this->assertEquals(17, \$this->game->score());
}

public function testAStrikeEarnsTenPointsInFrameWithASingleRoll() : void
{
\$this->game->roll(10);
\$this->rollMany(18, 0);

\$this->assertEquals(10, \$this->game->score());
}

public function testPointsScoredInTheTwoRollsAfterAStrikeAreCountedTwiceAsABonus() : void
{
\$this->game->roll(10);
\$this->game->roll(5);
\$this->game->roll(3);
\$this->rollMany(16, 0);

\$this->assertEquals(26, \$this->game->score());
}

public function testConsecutiveStrikesEachGetTheTwoRollBonus() : void
{
\$this->game->roll(10);
\$this->game->roll(10);
\$this->game->roll(10);
\$this->game->roll(5);
\$this->game->roll(3);
\$this->rollMany(12, 0);

\$this->assertEquals(81, \$this->game->score());
}

public function testAStrikeInTheLastFrameGetsATwoRollBonusThatIsCountedOnce() : void
{
\$this->rollMany(18, 0);
\$this->game->roll(10);
\$this->game->roll(7);
\$this->game->roll(1);

\$this->assertEquals(18, \$this->game->score());
}

public function testRollingASpareWithTheTwoRollBonusDoesNotGetABonusRoll() : void
{
\$this->rollMany(18, 0);
\$this->game->roll(10);
\$this->game->roll(10);
\$this->game->roll(10);

\$this->assertEquals(30, \$this->game->score());
}

public function testAStrikeWithTheOneRollBonusAfterASpareInTheLastFrameDoesNotGetABonus() : void
{
\$this->rollMany(18, 0);
\$this->game->roll(7);
\$this->game->roll(3);
\$this->game->roll(10);

\$this->assertEquals(20, \$this->game->score());
}

public function testStrikesWithTheTwoRollBonusDoNotGetBonusRolls() : void
{
\$this->rollMany(18, 0);
\$this->game->roll(10);
\$this->game->roll(7);
\$this->game->roll(3);

\$this->assertEquals(20, \$this->game->score());
}

public function testAllStrikesIsAPerfectGame() : void
{
\$this->rollMany(12, 10);

\$this->assertEquals(300, \$this->game->score());
}

public function testRollsCanNotScoreNegativePoints() : void
{
\$this->expectException(Exception::class);

\$this->game->roll(-1);
}

public function testARollCanNotScoreMoreThan10Points() : void
{
\$this->expectException(Exception::class);
\$this->game->roll(11);
\$this->rollMany(19, 0);

\$this->game->score();
}

public function testTwoRollsInAFrameCanNotScoreMoreThan10Points() : void
{
\$this->expectException(Exception::class);
\$this->game->roll(5);
\$this->game->roll(6);
\$this->rollMany(18, 0);

\$this->game->score();
}

public function testTwoBonusRollsAfterAStrikeInTheLastFrameCanNotScoreMoreThan10Points() : void
{
\$this->expectException(Exception::class);

\$this->rollMany(18, 0);
\$this->game->roll(10);
\$this->game->roll(5);
\$this->game->roll(6);

\$this->game->score();
}

public function testAnUnstartedGameCanNotBeScored() : void
{
\$this->expectException(Exception::class);

\$this->game->score();
}

public function testAnIncompleteGameCanNotBeScored() : void
{
\$this->expectException(Exception::class);
\$this->game->roll(0);
\$this->game->roll(0);

\$this->game->score();
}

public function testAGameWithMoreThanTenFramesCanNotBeScored() : void
{
\$this->expectException(Exception::class);
\$this->rollMany(21, 0);

\$this->game->score();
}

public function testBonusRollsForAStrikeInTheLastFrameMustBeRolledBeforeScoreCanBeCalculated() : void
{
\$this->expectException(Exception::class);
\$this->rollMany(18, 0);
\$this->game->roll(10);

\$this->game->score();
}

public function testBothBonusRollsForAStrikeInTheLastFrameMustBeRolledBeforeScoreCanBeCalculated() : void
{
\$this->expectException(Exception::class);
\$this->rollMany(18, 0);
\$this->game->roll(10);
\$this->game->roll(10);

\$this->game->score();
}

public function testBonusRollForASpareInTheLastFrameMustBeRolledBeforeScoreCanBeCalculated() : void
{
\$this->expectException(Exception::class);
\$this->rollMany(18, 0);
\$this->game->roll(7);
\$this->game->roll(3);

\$this->game->score();
}

private function rollStrike() : void
{
\$this->game->roll(10);
}

private function rollSpare() : void
{
\$this->rollMany(2, 5);
}

private function rollMany(\$n, \$pins) : void
{
for (\$i = 0; \$i < \$n; \$i++) {
\$this->game->roll(\$pins);
}
}
}``````
``````<?php

declare(strict_types=1);

const NUM_FRAMES = 10;
const NUM_PINS = 10;

interface Frame
{
public function index(): int;
public function score(): int;
public function validate(): void;
}

abstract class BaseFrame implements Frame
{
protected \$index;
protected \$rolls = [];

public function __construct(\$index, \$rolls)
{
\$this->index = \$index;
\$this->rolls = \$rolls;
}

public function index(): int
{
return \$this->index;
}

public function score(): int
{
return array_sum(\$this->rolls);
}

public function validate(): void
{
if (array_sum(\$this->rolls) > NUM_PINS) {
throw new InvalidFrameException(\$this, 'sum of rolls in a frame must be <= 10');
}
}
}

class OpenFrame extends BaseFrame implements Frame
{
public function __construct(\$index, \$firstRoll, \$secondRoll)
{
parent::__construct(\$index, [\$firstRoll, \$secondRoll]);
}
}

class SpareFrame extends BaseFrame implements Frame
{
protected \$nextRoll;

public function __construct(\$index, \$firstRoll, \$secondRoll)
{
parent::__construct(\$index, [\$firstRoll, \$secondRoll]);
}

public function nextRoll(\$roll): void
{
\$this->nextRoll = \$roll;
}

public function score(): int
{
return parent::score() + \$this->nextRoll;
}
}

class StrikeFrame extends BaseFrame implements Frame
{
protected \$nextRolls = [];

public function __construct(\$index)
{
parent::__construct(\$index, [10]);
}

public function nextRolls(\$firstRoll, \$secondRoll): void
{
\$this->nextRolls = [\$firstRoll, \$secondRoll];
}

public function score(): int
{
return parent::score() + array_sum(\$this->nextRolls);
}
}

class FinalFrame extends BaseFrame implements Frame
{
protected \$fillBallRolls = [];

public function __construct(\$rolls)
{
if (\$rolls[0] === NUM_PINS) {
\$frameRolls = [\$rolls[0]];
\$this->fillBallRolls = array_slice(\$rolls, 1);
} else {
\$frameRolls = [\$rolls[0], \$rolls[1]];
\$this->fillBallRolls = array_slice(\$rolls, 2);
}
parent::__construct(10, \$frameRolls);
}

public function score(): int
{
\$bonusScore = 0;
if (\$this->rolls[0] === NUM_PINS) {
\$bonusScore = \$this->fillBallRolls[0] + \$this->fillBallRolls[1];
} elseif (array_sum(\$this->rolls) === NUM_PINS) {
\$bonusScore = \$this->fillBallRolls[0];
}

return parent::score() + \$bonusScore;
}

public function validate(): void
{
parent::validate();

\$numFillBalls = count(\$this->fillBallRolls);
if (\$this->rolls[0] === NUM_PINS) {
if (\$numFillBalls !== 2) {
throw new InvalidFrameException(\$this, 'bonus frame rolled strike; expected 2 fill balls');
}
if (\$this->fillBallRolls[0] !== NUM_PINS && array_sum(\$this->fillBallRolls) > NUM_PINS) {
throw new InvalidFrameException(\$this, 'bonus frame rolled > 10');
}
} elseif (array_sum(\$this->rolls) === NUM_PINS) {
if (\$numFillBalls !== 1) {
throw new InvalidFrameException(\$this, 'bonus frame rolled spare; expected 1 fill ball');
}
} elseif (\$numFillBalls > 0) {
throw new InvalidFrameException(\$this, 'no bonus frame but fill balls found');
}
}
}

class InvalidRollException extends InvalidArgumentException
{
protected \$roll;
protected \$pins;

public function __construct(int \$roll, int \$pins, string \$error)
{
\$this->roll = \$roll;
\$this->pins = \$pins;

parent::__construct(sprintf('Roll %d of %d pins is invalid: %s', \$roll, \$pins, \$error));
}
}

class MissingFrameException extends Exception
{}

class InvalidFrameException extends Exception
{
protected \$frame;

public function __construct(Frame \$frame, string \$error)
{
\$this->frame = \$frame;

parent::__construct(sprintf('Frame %d is invalid: %s', \$frame->index(), \$error));
}
}

class FrameIterator implements Iterator
{
protected \$rolls;
protected \$position;
protected \$frameIndex;
protected \$currentFrame;

public function __construct(\$rolls)
{
\$this->rolls = \$rolls;
\$this->rewind();
}

public function rewind(): void
{
\$this->frameIndex = 1;
\$this->position = 0;
\$this->currentFrame = null;
}

protected function makeCurrentFrame(): void
{
if (\$this->frameIndex === NUM_FRAMES) {
\$frame = new FinalFrame(array_slice(\$this->rolls, \$this->position));
\$this->position = count(\$this->rolls);
} elseif (\$this->rolls[\$this->position] === NUM_PINS) {
\$frame = new StrikeFrame(\$this->frameIndex);
if (array_key_exists(\$this->position + 2, \$this->rolls)) {
\$frame->nextRolls(\$this->rolls[\$this->position + 1], \$this->rolls[\$this->position + 2]);
} elseif (array_key_exists(\$this->position + 1, \$this->rolls)) {
\$frame->nextRolls(\$this->rolls[\$this->position + 1], null);
}
} elseif (array_key_exists(\$this->position + 1, \$this->rolls)) {
\$firstPins = \$this->rolls[\$this->position];
\$secondPins = \$this->rolls[\$this->position + 1];
\$framePins = \$firstPins + \$secondPins;
\$this->position++;

if (\$framePins === NUM_PINS) {
\$frame = new SpareFrame(\$this->frameIndex, \$firstPins, \$secondPins);
if (array_key_exists(\$this->position + 1, \$this->rolls)) {
\$frame->nextRoll(\$this->rolls[\$this->position + 1]);
}
} else {
\$frame = new OpenFrame(\$this->frameIndex, \$firstPins, \$secondPins);
}
}

\$frame->validate();
\$this->currentFrame = \$frame;
}

public function current(): Frame
{
if (\$this->currentFrame === null) {
\$this->makeCurrentFrame();
}

return \$this->currentFrame;
}

public function key()
{
return \$this->position;
}

public function next()
{
\$this->frameIndex++;
\$this->position++;
\$this->currentFrame = null;
}

public function valid()
{
return array_key_exists(\$this->position, \$this->rolls);
}
}

class Game
{
protected \$rolls = [];

public function roll(int \$pins): void
{
if (\$pins < 0) {
throw new InvalidRollException(count(\$this->rolls) + 1, \$pins, 'cannot roll negative pin count');
} elseif (\$pins > NUM_PINS) {
throw new InvalidRollException(count(\$this->rolls) + 1, \$pins, 'cannot roll more than 10 pins');
}
\$this->rolls[] = \$pins;
}

public function score(): int
{
\$frameScores = [];
\$frames = new FrameIterator(\$this->rolls);
foreach (\$frames as \$frame) {
\$frameScores[\$frame->index()] = \$frame->score();
}

if (count(\$frameScores) < NUM_FRAMES) {
throw new MissingFrameException();
}

return array_sum(\$frameScores);
}
}``````