🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of angelikatyborska

angelikatyborska's solution

to Bowling in the Elixir Track

Published at Apr 29 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

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 tests

Execute the tests with:

$ elixir bowling_test.exs

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

If you're stuck on something, it may help to look at some of the available resources out there where answers might be found.

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.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("bowling.exs", __DIR__)
end

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

defmodule BowlingTest do
  use ExUnit.Case

  defp roll_reduce(game, rolls) do
    Enum.reduce(rolls, game, fn roll, game -> Bowling.roll(game, roll) end)
  end

  test "should be able to score a game with all zeros" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 0
  end

  @tag :pending
  test "should be able to score a game with no strikes or spares" do
    game = Bowling.start()
    rolls = [3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 90
  end

  @tag :pending
  test "a spare followed by zeros is worth ten points" do
    game = Bowling.start()
    rolls = [6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 10
  end

  @tag :pending
  test "points scored in the roll after a spare are counted twice" do
    game = Bowling.start()
    rolls = [6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 16
  end

  @tag :pending
  test "consecutive spares each get a one roll bonus" do
    game = Bowling.start()
    rolls = [5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 31
  end

  @tag :pending
  test "a spare in the last frame gets a one roll bonus that is counted once" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 17
  end

  @tag :pending
  test "a strike earns ten points in a frame with a single roll" do
    game = Bowling.start()
    rolls = [10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 10
  end

  @tag :pending
  test "points scored in the two rolls after a strike are counted twice as a bonus" do
    game = Bowling.start()
    rolls = [10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 26
  end

  @tag :pending
  test "consecutive strikes each get the two roll bonus" do
    game = Bowling.start()
    rolls = [10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 81
  end

  @tag :pending
  test "a strike in the last frame gets a two roll bonus that is counted once" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 18
  end

  @tag :pending
  test "rolling a spare with the two roll bonus does not get a bonus roll" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 20
  end

  @tag :pending
  test "strikes with the two roll bonus do not get bonus rolls" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 30
  end

  @tag :pending
  test "a strike with the one roll bonus after a spare in the last frame does not get a bonus" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 20
  end

  @tag :pending
  test "all strikes is a perfect game" do
    game = Bowling.start()
    rolls = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 300
  end

  @tag :pending
  test "rolls cannot score negative points" do
    game = Bowling.start()
    assert Bowling.roll(game, -1) == {:error, "Negative roll is invalid"}
  end

  @tag :pending
  test "a roll cannot score more than 10 points" do
    game = Bowling.start()
    assert Bowling.roll(game, 11) == {:error, "Pin count exceeds pins on the lane"}
  end

  @tag :pending
  test "two rolls in a frame cannot score more than 10 points" do
    game = Bowling.start()
    game = Bowling.roll(game, 5)
    assert Bowling.roll(game, 6) == {:error, "Pin count exceeds pins on the lane"}
  end

  @tag :pending
  test "bonus roll after a strike in the last frame cannot score more than 10 points" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10]
    game = roll_reduce(game, rolls)
    assert Bowling.roll(game, 11) == {:error, "Pin count exceeds pins on the lane"}
  end

  @tag :pending
  test "two bonus rolls after a strike in the last frame cannot score more than 10 points" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5]
    game = roll_reduce(game, rolls)
    assert Bowling.roll(game, 6) == {:error, "Pin count exceeds pins on the lane"}
  end

  @tag :pending
  test "two bonus rolls after a strike in the last frame can score more than 10 points if one is a strike" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == 26
  end

  @tag :pending
  test "the second bonus rolls after a strike in the last frame cannot be a strike if the first one is not a strike" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6]
    game = roll_reduce(game, rolls)
    assert Bowling.roll(game, 10) == {:error, "Pin count exceeds pins on the lane"}
  end

  @tag :pending
  test "second bonus roll after a strike in the last frame cannot score more than 10 points" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10]
    game = roll_reduce(game, rolls)
    assert Bowling.roll(game, 11) == {:error, "Pin count exceeds pins on the lane"}
  end

  @tag :pending
  test "an unstarted game cannot be scored" do
    game = Bowling.start()
    assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"}
  end

  @tag :pending
  test "an incomplete game cannot be scored" do
    game = Bowling.start()
    rolls = [0, 0]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"}
  end

  @tag :pending
  test "cannot roll if game already has ten frames" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    game = roll_reduce(game, rolls)
    assert Bowling.roll(game, 0) == {:error, "Cannot roll after game is over"}
  end

  @tag :pending
  test "bonus rolls for a strike in the last frame must be rolled before score can be calculated" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"}
  end

  @tag :pending
  test "both bonus rolls for a strike in the last frame must be rolled before score can be calculated" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"}
  end

  @tag :pending
  test "bonus roll for a spare in the last frame must be rolled before score can be calculated" do
    game = Bowling.start()
    rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3]
    game = roll_reduce(game, rolls)
    assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"}
  end
end
defmodule Bowling do
  alias __MODULE__, as: Game

  @type throw :: nil | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10

  defmodule Frame do
    defstruct throw1: nil, throw2: nil

    @type t :: %__MODULE__{throw1: Bowling.throw(), throw2: Bowling.throw()}
  end

  defstruct frames: [], fill_balls: []

  @type t :: %__MODULE__{frames: list(Frame.t()), fill_balls: list(throw())}

  @max_pins 10
  @frames_in_game 10
  @game_not_over_error {:error, "Score cannot be taken until the end of the game"}
  @game_over_error {:error, "Cannot roll after game is over"}
  @negative_error {:error, "Negative roll is invalid"}
  @too_much_error {:error, "Pin count exceeds pins on the lane"}

  @doc """
    Creates a new game of bowling that can be used to store the results of
    the game
  """

  @spec start() :: any
  def start do
    %Game{}
  end

  @doc """
    Records the number of pins knocked down on a single roll. Returns `any`
    unless there is something wrong with the given number of pins, in which
    case it returns a helpful message.
  """

  @spec roll(any, integer) :: any | String.t()
  def roll(game, roll) do
    with {:can_roll, true} <- {:can_roll, can_roll?(game)},
         {:validate_roll, :ok} <- {:validate_roll, validate_roll(game, roll)} do
      cond do
        game.frames == [] ->
          add_frame(game, roll)

        should_do_second_throw?(hd(game.frames)) ->
          add_second_throw(game, roll)

        should_do_fill_ball?(game) ->
          add_fill_ball(game, roll)

        true ->
          add_frame(game, roll)
      end
    else
      {:can_roll, false} -> @game_over_error
      {:validate_roll, error} -> error
    end
  end

  @doc """
    Returns the score of a given game of bowling if the game is complete.
    If the game isn't complete, it returns a helpful message.
  """

  @spec score(any) :: integer | String.t()
  def score(game) do
    if can_roll?(game) do
      @game_not_over_error
    else
      do_score(Enum.reverse(game.frames), 0, game.fill_balls)
    end
  end

  defp do_score([], score, _), do: score

  defp do_score([frame | next_frames], score, fill_balls) do
    add =
      cond do
        strike?(frame) -> @max_pins + sum_two_next_throws(next_frames, fill_balls)
        spare?(frame) -> @max_pins + sum_next_throw(next_frames, fill_balls)
        true -> frame.throw1 + frame.throw2
      end

    do_score(next_frames, score + add, fill_balls)
  end

  defp can_roll?(%Game{frames: frames}) when length(frames) < @frames_in_game, do: true

  defp can_roll?(%Game{frames: frames} = game) when length(frames) == @frames_in_game do
    should_do_second_throw?(hd(frames)) || should_do_fill_ball?(game)
  end

  defp strike?(%Frame{throw1: @max_pins}), do: true
  defp strike?(%Frame{}), do: false

  defp spare?(%Frame{throw1: @max_pins}), do: false
  defp spare?(%Frame{throw1: nil}), do: false
  defp spare?(%Frame{throw2: nil}), do: false
  defp spare?(%Frame{throw1: t1, throw2: t2}), do: t1 + t2 == @max_pins

  defp should_do_second_throw?(%Frame{throw1: @max_pins}), do: false
  defp should_do_second_throw?(%Frame{throw1: t, throw2: nil}), do: !is_nil(t)
  defp should_do_second_throw?(%Frame{}), do: false

  defp should_do_fill_ball?(%Game{frames: frames, fill_balls: fill_balls}) do
    if length(frames) == @frames_in_game do
      [h | _] = frames

      (strike?(h) && length(fill_balls) < 2) ||
        (spare?(h) && length(fill_balls) < 1)
    else
      false
    end
  end

  defp sum_next_throw([next_frame | _], _fill_balls) do
    next_frame.throw1
  end

  defp sum_next_throw([], [fill_ball | _]) do
    fill_ball
  end

  defp sum_two_next_throws([next_frame | t], fill_balls) do
    if strike?(next_frame) do
      @max_pins + if t == [], do: hd(fill_balls), else: hd(t).throw1
    else
      next_frame.throw1 + next_frame.throw2
    end
  end

  defp sum_two_next_throws([], [fill_ball1, fill_ball2]) do
    fill_ball1 + fill_ball2
  end

  defp add_frame(game, roll) do
    %{game | frames: [%Frame{throw1: roll} | game.frames]}
  end

  defp add_second_throw(game, roll) do
    [frame | t] = game.frames
    %{game | frames: [%Frame{frame | throw2: roll} | t]}
  end

  defp add_fill_ball(game, roll) do
    %{game | fill_balls: [roll | game.fill_balls]}
  end

  defp validate_roll(_game, roll) when roll < 0, do: @negative_error
  defp validate_roll(_game, roll) when roll > @max_pins, do: @too_much_error

  defp validate_roll(game, roll) do
    with [frame | _] <- game.frames do
      cond do
        should_do_second_throw?(frame) && frame.throw1 + roll > @max_pins ->
          @too_much_error

        should_do_fill_ball?(game) && game.fill_balls != [@max_pins] &&
            Enum.sum([roll | game.fill_balls]) > @max_pins ->
          @too_much_error

        true ->
          :ok
      end
    else
      _ -> :ok
    end
  end
end

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?