Avatar of piotr-jelinski

piotr-jelinski's solution

to Bowling in the PHP Track

Published at Aug 12 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);
        }
    }
}

aFrame.php

<?php

declare(strict_types=1);

require_once 'iFrame.php';

abstract class aFrame implements iFrame
{
    /**
     * @var int
     */
    private $score;
    /**
     * @var bool
     */
    private $last;
    /**
     * @var iRoll
     */
    protected $firstRoll;
    /**
     * @var iRoll
     */
    protected $secondRoll;
    /**
     * @var iRoll
     */
    protected $thirdRoll;

    /**
     * @return int
     */
    abstract protected function calculateScore(): int;

    /**
     * @return int
     */
    abstract public function rollConsumption(): int;

    /**
     * @param array|iRoll[] $rolls
     * @return bool
     */
    abstract public static function rollsMatchCriteria(array $rolls): bool;

    /**
     * @return int
     */
    public function getScore(): int
    {
        return $this->score ?? $this->calculateScore();
    }

    /**
     * @param bool $last
     * @return void
     */
    public function setLast(bool $last): void
    {
        $this->last = $last;
    }

    /**
     * @return bool
     */
    public function getLast(): bool
    {
        return $this->last;
    }
}

BallRoll.php

<?php

declare(strict_types=1);

require_once 'iRoll.php';
require_once 'GameConfig.php';

class BallRoll implements iRoll
{
    public const EXCEPTION_ROLL_GREATER_THAN = 'Roll score can not be greater than %d.';
    public const EXCEPTION_ROLL_LESS_THAN = 'Roll score can not be less than %d.';

    /**
     * @var int
     */
    private $score = 0;

    /**
     * @param int $score
     * @throws Exception
     */
    public function __construct(int $score)
    {
        if ($score > GameConfig::ROLL_MAX_SCORE) {
            throw new Exception(sprintf(BallRoll::EXCEPTION_ROLL_GREATER_THAN, GameConfig::ROLL_MAX_SCORE));
        }

        if ($score < GameConfig::ROLL_MIN_SCORE) {
            throw new Exception(sprintf(BallRoll::EXCEPTION_ROLL_LESS_THAN, GameConfig::ROLL_MIN_SCORE));
        }

        $this->score = $score;
    }

    /**
     * @return int
     */
    public function getScore(): int
    {
        return $this->score;
    }
}

bowling.php

<?php

declare(strict_types=1);

require_once 'BallRoll.php';
require_once 'RollStorage.php';
require_once 'BowlingScoreCalculator.php';

class Game
{
    /**
     * @var RollStorage
     */
    private $rollStorage;
    /**
     * @var BowlingScoreCalculator
     */
    private $calculator;

    public function __construct()
    {
        $this->rollStorage = new RollStorage();
        $this->calculator = new BowlingScoreCalculator();
    }

    /**
     * @param int $pinCount
     * @return Game
     */
    public function roll(int $pinCount): Game
    {
        $this->rollStorage->push(new BallRoll($pinCount));

        return $this;
    }

    /**
     * @return int
     */
    public function score(): int
    {
        return $this->calculator->calculate($this->rollStorage->fetch());
    }
}

BowlingScoreCalculator.php

<?php

declare(strict_types=1);

require_once 'RollToFrameConverter.php';
require_once 'iFrame.php';
require_once 'GameConfig.php';

class BowlingScoreCalculator
{
    public const EXCEPTION_GAME_NOT_STARTED = 'Game has not started';
    public const EXCEPTION_INSUFFICIENT_FRAMES = 'Insufficient frames %d out of %d';
    public const EXCEPTION_EXCEEDED_FRAME_LIMIT = 'Exceeded max frame limit of %d';

    /**
     * @var iConverter
     */
    private $converter;

    public function __construct()
    {
        $this->converter = new RollToFrameConverter();
    }

    /**
     * @param int $sum
     * @param iFrame $frame
     * @return int
     */
    private function reducer(int $sum, iFrame $frame): int
    {
        return $sum + $frame->getScore();
    }

    /**
     * @param array $frames
     * @throws Exception
     * @return void
     */
    private function checkFrameRules(array $frames): void
    {
        $frameCount = count($frames);
        if ($frameCount === 0) {
            throw new Exception(BowlingScoreCalculator::EXCEPTION_GAME_NOT_STARTED);
        }

        if ($frameCount < GameConfig::FRAME_COUNT) {
            throw new Exception(sprintf(BowlingScoreCalculator::EXCEPTION_INSUFFICIENT_FRAMES, GameConfig::FRAME_COUNT - $frameCount, GameConfig::FRAME_COUNT));
        }

        if ($frameCount > GameConfig::FRAME_COUNT) {
            throw new Exception(sprintf(BowlingScoreCalculator::EXCEPTION_EXCEEDED_FRAME_LIMIT, GameConfig::FRAME_COUNT));
        }
    }

    /**
     * @param array|iRoll[] $scores
     * @return int
     */
    public function calculate(array $scores): int
    {
        $frames = $this->converter->convert($scores);
        $this->checkFrameRules($frames);

        return array_reduce($frames, [$this, 'reducer'], 0);
    }
}

GameConfig.php

<?php

declare(strict_types=1);

require_once 'StrikeFrame.php';
require_once 'SpareFrame.php';
require_once 'OpenFrame.php';

class GameConfig
{
    /**
     * required first roll points to consider frame a strike
     */
    public const STRIKE_FRAME_FIRST_ROLL_REQUIREMENT = 10;

    /**
     * required sum of 2 consecutive rolls to consider frame a spare
     */
    public const SPARE_FRAME_ROLL_SUM_REQUIREMENT = 10;

    /**
     * max sum allowed for 2 consecutive rolls (not that there are some exceptions to that)
     */
    public const ROLL_MAX_ALLOWED_SUM = 10;

    /**
     * min score for a single roll
     */
    public const ROLL_MIN_SCORE = 0;

    /**
     * max score for a single roll
     */
    public const ROLL_MAX_SCORE = 10;

    /**
     * frame limit
     */
    public const FRAME_COUNT = 10;

    /**
     * Available frames from most to least important
     */
    public const FRAMES = [
        StrikeFrame::class,
        SpareFrame::class,
        OpenFrame::class
    ];
}

iFrame.php

<?php

declare(strict_types=1);

interface iFrame
{
    /**
     * @return int
     */
    public function getScore(): int;

    /**
     * @param bool $last
     * @return void
     */
    public function setLast(bool $last): void;

    /**
     * @return bool
     */
    public function getLast(): bool;

    /**
     * @return int
     */
    public function rollConsumption(): int;

    /**
     * @param array|iRoll[] $rolls
     * @return bool
     */
    public static function rollsMatchCriteria(array $rolls): bool;
}

iRoll.php

<?php

declare(strict_types=1);

interface iRoll
{
    /**
     * @return int
     */
    public function getScore(): int;
}

NullRoll.php

<?php

declare(strict_types=1);

require_once 'iRoll.php';

class NullRoll implements iRoll
{
    /**
     * @return int
     */
    public function getScore(): int
    {
        return 0;
    }
}

OpenFrame.php

<?php

declare(strict_types=1);

require_once 'aFrame.php';
require_once 'GameConfig.php';

class OpenFrame extends aFrame
{
    /**
     * @param iRoll $firstRoll
     * @param iRoll $secondRoll
     */
    public function __construct(iRoll $firstRoll, iRoll $secondRoll)
    {
        $this->firstRoll = $firstRoll;
        $this->secondRoll = $secondRoll;
    }

    /**
     * @param int $result
     * @throws Exception
     * @return void
     */
    private function checkCalculationRules(int $result): void
    {
        if ($result > GameConfig::ROLL_MAX_ALLOWED_SUM) {
            throw new Exception(sprintf('Allowed result of %d exceeded for %s', GameConfig::ROLL_MAX_ALLOWED_SUM, OpenFrame::class));
        }
    }

    /**
     * @return int
     */
    protected function calculateScore(): int
    {
        $result = $this->firstRoll->getScore() + $this->secondRoll->getScore();
        $this->checkCalculationRules($result);

        return $result;
    }

    /**
     * @return int
     */
    public function rollConsumption(): int
    {
        return 2;
    }

    /**
     * @param array|iRoll[] $rolls
     * @return bool
     */
    public static function rollsMatchCriteria(array $rolls): bool
    {
        return true;
    }
}

RollStorage.php

<?php

declare(strict_types=1);

require_once 'iRoll.php';

class RollStorage
{
    /**
     * @var array|iRoll[]
     */
    private $rolls = [];

    /**
     * @param iRoll $roll
     * @return void
     */
    public function push(iRoll $roll): void
    {
        $this->rolls[] = $roll;
    }

    /**
     * @return array
     */
    public function fetch(): array
    {
        return $this->rolls;
    }
}

RollToFrameConverter.php

<?php

declare(strict_types=1);

require_once 'iRoll.php';
require_once 'NullRoll.php';
require_once 'iFrame.php';
require_once 'OpenFrame.php';
require_once 'GameConfig.php';

class RollToFrameConverter
{
    /**
     * @param array|iRoll[] $nextThreeRolls
     * @return string
     */
    private function determineFrameClass(array $nextThreeRolls): string
    {
        $frameClass = OpenFrame::class;
        foreach (GameConfig::FRAMES as $frameClassName) {
            if ($frameClassName::rollsMatchCriteria($nextThreeRolls)) {
                $frameClass = $frameClassName;
                break;
            }
        }

        return $frameClass;
    }

    /**
     * @param string $frameClass
     * @param bool $isLast
     * @param array|iRoll[] $nextThreeRolls
     * @return iFrame
     */
    private function getFrame(string $frameClass, bool $isLast, array $nextThreeRolls): iFrame
    {
        $frame = new $frameClass(...$nextThreeRolls);
        $frame->setLast($isLast);

        return $frame;
    }

    /**
     * @param iFrame $frame
     * @param array $source
     * @return void
     */
    private function shiftSource(iFrame $frame, array &$source): void
    {
        for ($i = 0; $i < $frame->rollConsumption(); $i++) {
            array_shift($source);
        }
    }

    /**
     * @param array|iRoll[] $source
     * @return array|iRoll[]
     */
    private function getNextThreeRolls(array $source): array
    {
        return [
            $source[0] ?? new NullRoll(),
            $source[1] ?? new NullRoll(),
            $source[2] ?? new NullRoll()
        ];
    }

    /**
     * @param array|iRoll[] $source
     * @return array|iFrame[]
     */
    public function convert(array $source): array
    {
        $frames = [];
        while (!empty($source)) {
            $nextThreeRolls = $this->getNextThreeRolls($source);
            $frame = $this->getFrame(
                $this->determineFrameClass($nextThreeRolls),
                (count($frames) === GameConfig::FRAME_COUNT - 1),
                $nextThreeRolls
            );
            $this->shiftSource($frame, $source);
            $frames[] = $frame;
        }

        return $frames;
    }
}

SpareFrame.php

<?php

declare(strict_types=1);

require_once 'aFrame.php';
require_once 'NullRoll.php';
require_once 'GameConfig.php';

class SpareFrame extends aFrame
{
    /**
     * @param iRoll $firstRoll
     * @param iRoll $secondRoll
     * @param iRoll $thirdRoll
     */
    public function __construct(iRoll $firstRoll, iRoll $secondRoll, iRoll $thirdRoll)
    {
        $this->firstRoll = $firstRoll;
        $this->secondRoll = $secondRoll;
        $this->thirdRoll = $thirdRoll;
    }

    /**
     * @param int $base
     * @throws Exception
     * @return void
     */
    private function checkCalculationRules(int $base): void
    {
        if ($base > GameConfig::ROLL_MAX_ALLOWED_SUM) {
            throw new Exception(sprintf('Allowed result of %d exceeded for %s', GameConfig::ROLL_MAX_ALLOWED_SUM, SpareFrame::class));
        }
        if ($this->getLast()) {
            if ($this->thirdRoll instanceof NullRoll) {
                throw new Exception('Bonus rolls for a spare in the last frame must be rolled before score can be calculated');
            }
        }
    }

    /**
     * @return int
     */
    protected function calculateScore(): int
    {
        $base = $this->firstRoll->getScore() + $this->secondRoll->getScore();
        $this->checkCalculationRules($base);

        return $base + $this->thirdRoll->getScore();
    }

    /**
     * @return int
     */
    public function rollConsumption(): int
    {
        return $this->getLast() ? 3 : 2;
    }

    /**
     * @param array|iRoll[] $rolls
     * @return bool
     */
    public static function rollsMatchCriteria(array $rolls): bool
    {
        [$first, $second] = $rolls;

        return (
            !($second instanceof NullRoll)
            && $first->getScore() + $second->getScore() === GameConfig::SPARE_FRAME_ROLL_SUM_REQUIREMENT
        );
    }
}

StrikeFrame.php

<?php

declare(strict_types=1);

require_once 'aFrame.php';
require_once 'NullRoll.php';
require_once 'GameConfig.php';

class StrikeFrame extends aFrame
{
    /**
     * @param iRoll $firstRoll
     * @param iRoll $secondRoll
     * @param iRoll $thirdRoll
     */
    public function __construct(iRoll $firstRoll, iRoll $secondRoll, iRoll $thirdRoll)
    {
        $this->firstRoll = $firstRoll;
        $this->secondRoll = $secondRoll;
        $this->thirdRoll = $thirdRoll;
    }

    /**
     * @param int $bonus
     * @throws Exception
     * @return void
     */
    private function checkCalculationRules(int $bonus): void
    {
        if ($this->getLast()) {
            $bothBonusesAreStrikes = $this->secondRoll->getScore() === GameConfig::STRIKE_FRAME_FIRST_ROLL_REQUIREMENT
                && $this->thirdRoll->getScore() === GameConfig::STRIKE_FRAME_FIRST_ROLL_REQUIREMENT;

            if (!$bothBonusesAreStrikes && $bonus > GameConfig::ROLL_MAX_ALLOWED_SUM) {
                throw new Exception('Max bonus rolls sum exceeded');
            }

            if ($this->secondRoll instanceof NullRoll || $this->thirdRoll instanceof NullRoll) {
                throw new Exception('Both bonus rolls for a strike in the last frame must be rolled before score can be calculated');
            }
        }
    }

    /**
     * @return int
     */
    protected function calculateScore(): int
    {
        $bonus = $this->secondRoll->getScore() + $this->thirdRoll->getScore();
        $this->checkCalculationRules($bonus);

        return $this->firstRoll->getScore() + $bonus;
    }

    /**
     * @return int
     */
    public function rollConsumption(): int
    {
        return $this->getLast() ? 3 : 1;
    }

    /**
     * @param array|iRoll[] $rolls
     * @return bool
     */
    public static function rollsMatchCriteria(array $rolls): bool
    {
        [$first] = $rolls;

        return ($first->getScore() === GameConfig::STRIKE_FRAME_FIRST_ROLL_REQUIREMENT);
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?