Avatar of artemkorsakov

artemkorsakov's solution

to Bowling in the Java Track

Published at Feb 14 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

You can run all the tests for an exercise by entering

$ gradle test

in your terminal.

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.

BowlingTest.java

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.junit.Assert.assertEquals;

public class BowlingTest {
    private BowlingGame game;

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Before
    public void setup() {
        game = new BowlingGame();
    }

    private void playGame(int[] rolls) {
        for (int pins : rolls) {
            game.roll(pins);
        }
    }

    @Test
    public void shouldBeAbleToScoreAGameWithAllZeros() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);
        assertEquals(0, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void shouldBeAbleToScoreAGameWithNoStrikesOrSpares() {
        int[] rolls = {3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6};

        playGame(rolls);
        assertEquals(90, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void aSpareFollowedByZerosIsWorthTenPoints() {
        int[] rolls = {6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);
        assertEquals(10, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void pointsScoredInTheRollAfterASpareAreCountedTwice() {
        int[] rolls = {6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);
        assertEquals(16, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void consecutiveSparesEachGetAOneRollBonus() {
        int[] rolls = {5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);
        assertEquals(31, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void aSpareInTheLastFrameGetsAOneRollBonusThatIsCountedOnce() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7};

        playGame(rolls);
        assertEquals(17, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void aStrikeEarnsTenPointsInFrameWithASingleRoll() {
        int[] rolls = {10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);
        assertEquals(10, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void pointsScoredInTheTwoRollsAfterAStrikeAreCountedTwiceAsABonus() {
        int[] rolls = {10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);
        assertEquals(26, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void consecutiveStrikesEachGetTheTwoRollBonus() {
        int[] rolls = {10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);
        assertEquals(81, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void aStrikeInTheLastFrameGetsATwoRollBonusThatIsCountedOnce() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1};

        playGame(rolls);
        assertEquals(18, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void rollingASpareWithTheTwoRollBonusDoesNotGetABonusRoll() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3};

        playGame(rolls);
        assertEquals(20, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void strikesWithTheTwoRollBonusDoNotGetBonusRolls() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10};

        playGame(rolls);
        assertEquals(30, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void aStrikeWithTheOneRollBonusAfterASpareInTheLastFrameDoesNotGetABonus() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10};

        playGame(rolls);
        assertEquals(20, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void allStrikesIsAPerfectGame() {
        int[] rolls = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10};

        playGame(rolls);
        assertEquals(300, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void rollsCanNotScoreNegativePoints() {
        int[] rolls = {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Negative roll is invalid");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void aRollCanNotScoreMoreThan10Points() {
        int[] rolls = {11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Pin count exceeds pins on the lane");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void twoRollsInAFrameCanNotScoreMoreThan10Points() {
        int[] rolls = {5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Pin count exceeds pins on the lane");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void bonusRollAfterAStrikeInTheLastFrameCanNotScoreMoreThan10Points() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 0};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Pin count exceeds pins on the lane");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void twoBonusRollsAfterAStrikeInTheLastFrameCanNotScoreMoreThan10Points() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5, 6};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Pin count exceeds pins on the lane");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void twoBonusRollsAfterAStrikeInTheLastFrameCanScoreMoreThan10PointsIfOneIsAStrike() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6};

        playGame(rolls);

        assertEquals(26, game.score());
    }

    @Ignore("Remove to run test")
    @Test
    public void theSecondBonusRollsAfterAStrikeInTheLastFrameCanNotBeAStrikeIfTheFirstOneIsNotAStrike() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6, 10};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Pin count exceeds pins on the lane");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void secondBonusRollAfterAStrikeInTheLastFrameCanNotScoreMoreThan10Points() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 11};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Pin count exceeds pins on the lane");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void anUnstartedGameCanNotBeScored() {
        int[] rolls = new int[0];

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Score cannot be taken until the end of the game");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void anIncompleteGameCanNotBeScored() {
        int[] rolls = {0, 0};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Score cannot be taken until the end of the game");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void canNotRollIfGameAlreadyHasTenFrames() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Cannot roll after game is over");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void bonusRollsForAStrikeInTheLastFrameMustBeRolledBeforeScoreCanBeCalculated() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Score cannot be taken until the end of the game");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void bothBonusRollsForAStrikeInTheLastFrameMustBeRolledBeforeScoreCanBeCalculated() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Score cannot be taken until the end of the game");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void bonusRollForASpareInTheLastFrameMustBeRolledBeforeScoreCanBeCalculated() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Score cannot be taken until the end of the game");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void canNotRollAfterBonusRollForSpare() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 2, 2};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Cannot roll after game is over");

        game.score();
    }

    @Ignore("Remove to run test")
    @Test
    public void canNotRollAfterBonusRollForStrike() {
        int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 3, 2, 2};

        playGame(rolls);

        expectedException.expect(IllegalStateException.class);
        expectedException.expectMessage("Cannot roll after game is over");

        game.score();
    }
}

src/main/java/BowlingGame.java

import java.util.ArrayList;
import java.util.List;

class BowlingGame {
    private List<Integer> rolls = new ArrayList<>();
    private List<BowlingRoll> bowlingRolls = new ArrayList<>();

    void roll(int pins) {
        rolls.add(pins);
    }

    int score() {
        rolls.forEach(this::checkPins);
        rolls.forEach(this::addPins);
        if (bowlingRolls.size() < 10) {
            throw new IllegalStateException("Score cannot be taken until the end of the game");
        }

        return bowlingRolls.parallelStream().mapToInt(BowlingRoll::getScore).sum();
    }

    private void addPins(int pins) {
        if (bowlingRolls.size() == 0) {
            addRoll(pins);
            return;
        }

        BowlingRoll currentBowlingRoll = getCurrentBowlingRoll();
        BowlingRoll previousBowlingRoll = getPreviousBowlingRoll();
        if (currentBowlingRoll.isNotFilled()) {
            currentBowlingRoll.addSecondPins(pins);
            if (previousBowlingRoll.isStrike()) {
                previousBowlingRoll.addBonus(pins);
            }
        } else {
            if (bowlingRolls.size() == 10 && !currentBowlingRoll.isBonusNotFilled()) {
                throw new IllegalStateException("Cannot roll after game is over");
            }
            if (bowlingRolls.size() < 10) {
                addRoll(pins);
            }
            if (currentBowlingRoll.isSpare()) {
                currentBowlingRoll.addBonus(pins);
            }
            if (currentBowlingRoll.isStrike() && previousBowlingRoll.isStrike() && previousBowlingRoll.isBonusNotFilled()) {
                previousBowlingRoll.addBonus(pins);
            }
        }
    }

    private void checkPins(int pins) {
        if (pins < 0) {
            throw new IllegalStateException("Negative roll is invalid");
        }
        if (pins > 10) {
            throw new IllegalStateException("Pin count exceeds pins on the lane");
        }
    }

    private void addRoll(int pins) {
        BowlingRoll br = new BowlingRoll(pins);
        bowlingRolls.add(br);
    }

    private BowlingRoll getCurrentBowlingRoll() {
        if (bowlingRolls.size() == 0) {
            return new BowlingRoll();
        }
        BowlingRoll currentBowlingRoll = bowlingRolls.get(bowlingRolls.size() - 1);
        if (currentBowlingRoll.isStrike()) {
            currentBowlingRoll.addSecondPins(0);
        }
        return currentBowlingRoll;
    }

    private BowlingRoll getPreviousBowlingRoll() {
        return bowlingRolls.size() > 1 ? bowlingRolls.get(bowlingRolls.size() - 2) : new BowlingRoll();
    }
}

src/main/java/BowlingRoll.java

class BowlingRoll {
    private int[] roll = {-1, -1};
    private int[] bonus = {-1, -1};

    BowlingRoll() {
    }

    BowlingRoll(int pins) {
        roll[0] = pins;
    }

    void addSecondPins(int pins) {
        if (roll[0] + pins > 10) {
            throw new IllegalStateException("Pin count exceeds pins on the lane");
        }
        roll[1] = pins;
    }

    void addBonus(int pins) {
        if (bonus[0] == -1) {
            bonus[0] = pins;
        } else {
            if (bonus[0] != 10 && bonus[0] + pins > 10) {
                throw new IllegalStateException("Pin count exceeds pins on the lane");
            }
            bonus[1] = pins;
        }
    }

    boolean isNotFilled() {
        return roll[0] < 0 || roll[1] < 0;
    }

    boolean isBonusNotFilled() {
        return isStrike() ? bonus[0] == -1 || bonus[1] == -1 : isSpare() && bonus[0] == -1;
    }

    boolean isSpare() {
        return roll[0] + roll[1] == 10;
    }

    boolean isStrike() {
        return roll[0] == 10;
    }

    int getScore() {
        if (isNotFilled() || isBonusNotFilled()) {
            throw new IllegalStateException("Score cannot be taken until the end of the game");
        }
        int score = roll[0] + roll[1];
        if (isSpare()) {
            score += bonus[0];
        }
        if (isStrike()) {
            score += bonus[1];
        }
        return score;
    }
}

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?