Avatar of emengd

emengd's solution

to Bowling in the OCaml Track

Published at Apr 13 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.

Getting Started

For installation and learning resources, refer to the exercism help page.

Installation

To work on the exercises, you will need Opam and Base. Consult opam website for instructions on how to install opam for your OS. Once opam is installed open a terminal window and run the following command to install base:

opam install base

To run the tests you will need OUnit. Install it using opam:

opam install ounit

Running Tests

A Makefile is provided with a default target to compile your solution and run the tests. At the command line, type:

make

Interactive Shell

utop is a command line program which allows you to run Ocaml code interactively. The easiest way to install it is via opam:

opam install utop

Consult utop for more detail.

Feedback, Issues, Pull Requests

The exercism/ocaml repository on GitHub is the home for all of the Ocaml exercises.

If you have feedback about an exercise, or want to help implementing a new one, head over there and create an issue. We'll do our best to help you!

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.

test.ml

open Base
open OUnit2
open Bowling

type game = Bowling.t

let to_ok = function
| Ok x -> x
| Error e -> failwith @@ "should be OK but got Error " ^ e

let set_previous_frames (frames : int list): game =
  List.fold frames ~init:new_game ~f:(fun g f -> roll f g |> to_ok)

let score_printer = function
| Ok n -> Int.to_string n
| Error e -> e
let assert_score exp game = assert_equal ~printer:score_printer exp (score game)

let roll_printer = function
| Ok _ -> "Ok <some game>"
| Error e -> e
let assert_roll exp frame game = assert_equal ~printer:roll_printer exp (roll frame game)

let tests = [
   "should be able to score a game with all zeros" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
      assert_score (Ok 0) g
   );
   "should be able to score a game with no strikes or spares" >:: (fun _ ->
      let g = set_previous_frames [3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6; 3; 6] in
      assert_score (Ok 90) g
   );
   "a spare followed by zeros is worth ten points" >:: (fun _ ->
      let g = set_previous_frames [6; 4; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
      assert_score (Ok 10) g
   );
   "points scored in the roll after a spare are counted twice" >:: (fun _ ->
      let g = set_previous_frames [6; 4; 3; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
      assert_score (Ok 16) g
   );
   "consecutive spares each get a one roll bonus" >:: (fun _ ->
      let g = set_previous_frames [5; 5; 3; 7; 4; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
      assert_score (Ok 31) g
   );
   "a spare in the last frame gets a one roll bonus that is counted once" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 7; 3; 7] in
      assert_score (Ok 17) g
   );
   "a strike earns ten points in a frame with a single roll" >:: (fun _ ->
      let g = set_previous_frames [10; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
      assert_score (Ok 10) g
   );
   "points scored in the two rolls after a strike are counted twice as a bonus" >:: (fun _ ->
      let g = set_previous_frames [10; 5; 3; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
      assert_score (Ok 26) g
   );
   "consecutive strikes each get the two roll bonus" >:: (fun _ ->
      let g = set_previous_frames [10; 10; 10; 5; 3; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
      assert_score (Ok 81) g
   );
   "a strike in the last frame gets a two roll bonus that is counted once" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 7; 1] in
      assert_score (Ok 18) g
   );
   "rolling a spare with the two roll bonus does not get a bonus roll" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 7; 3] in
      assert_score (Ok 20) g
   );
   "strikes with the two roll bonus do not get bonus rolls" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 10; 10] in
      assert_score (Ok 30) g
   );
   "a strike with the one roll bonus after a spare in the last frame does not get a bonus" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 7; 3; 10] in
      assert_score (Ok 20) g
   );
   "all strikes is a perfect game" >:: (fun _ ->
      let g = set_previous_frames [10; 10; 10; 10; 10; 10; 10; 10; 10; 10; 10; 10] in
      assert_score (Ok 300) g
   );
   "rolls cannot score negative points" >:: (fun _ ->
      let g = set_previous_frames [] in
      assert_roll (Error "Negative roll is invalid") (-1) g
   );
   "a roll cannot score more than 10 points" >:: (fun _ ->
      let g = set_previous_frames [] in
      assert_roll (Error "Pin count exceeds pins on the lane") 11 g
   );
   "two rolls in a frame cannot score more than 10 points" >:: (fun _ ->
      let g = set_previous_frames [5] in
      assert_roll (Error "Pin count exceeds pins on the lane") 6 g
   );
   "bonus roll after a strike in the last frame cannot score more than 10 points" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10] in
      assert_roll (Error "Pin count exceeds pins on the lane") 11 g
   );
   "two bonus rolls after a strike in the last frame cannot score more than 10 points" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 5] in
      assert_roll (Error "Pin count exceeds pins on the lane") 6 g
   );
   "two bonus rolls after a strike in the last frame can score more than 10 points if one is a strike" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 10; 6] in
      assert_score (Ok 26) g
   );
   "the second bonus rolls after a strike in the last frame cannot be a strike if the first one is not a strike" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 6] in
      assert_roll (Error "Pin count exceeds pins on the lane") 10 g
   );
   "second bonus roll after a strike in the last frame cannot score more than 10 points" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 10] in
      assert_roll (Error "Pin count exceeds pins on the lane") 11 g
   );
   "an unstarted game cannot be scored" >:: (fun _ ->
      let g = set_previous_frames [] in
      assert_score (Error "Score cannot be taken until the end of the game") g
   );
   "an incomplete game cannot be scored" >:: (fun _ ->
      let g = set_previous_frames [0; 0] in
      assert_score (Error "Score cannot be taken until the end of the game") g
   );
   "cannot roll if game already has ten frames" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] in
      assert_roll (Error "Cannot roll after game is over") 0 g
   );
   "bonus rolls for a strike in the last frame must be rolled before score can be calculated" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10] in
      assert_score (Error "Score cannot be taken until the end of the game") g
   );
   "both bonus rolls for a strike in the last frame must be rolled before score can be calculated" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 10; 10] in
      assert_score (Error "Score cannot be taken until the end of the game") g
   );
   "bonus roll for a spare in the last frame must be rolled before score can be calculated" >:: (fun _ ->
      let g = set_previous_frames [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 7; 3] in
      assert_score (Error "Score cannot be taken until the end of the game") g
   );
]

let () =
  run_test_tt_main ("bowling tests" >::: tests)
open Base

type throw =
  | First
  | Second
  | Fill_ball

type frame_state = {
  frame: int;
  throw: throw;
  bonus: int list;
  pins: int;
  score: int;
}

type t =
  | Finished of int (* score *)
  | Frame of frame_state

let new_game =
  Frame {
    frame = 1;
    throw = First;
    bonus = [];
    pins = 10;
    score = 0;
  }

let evaluate_throw pins state =
  let base_multiplier =
    match state.throw with
    | Fill_ball -> 0
    | First | Second -> 1
  in
  let multiplier, bonus =
    match state.bonus with
    | [] -> (base_multiplier, [])
    | bonus :: rest -> (bonus + base_multiplier, rest)
  in
  { state with
    score = state.score + pins * multiplier;
    bonus;
    pins = state.pins - pins;
  }

let add_bonus state =
  if state.pins > 0 then
    state
  else
    let bonus =
      match state.throw, state.bonus with
      | First, [] -> [1; 1]
      | First, [b] -> [b + 1; 1]
      | Second, [] -> [1]
      | Fill_ball, l -> l (* do not add bonuses in fill balls *)
      | _ -> assert false
    in
    { state with bonus }

let advance state =
  let next_frame state =
    if state.frame = 10 then
      if List.is_empty state.bonus then
        Finished state.score
      else
        Frame { state with
                throw = Fill_ball;
                pins = if state.pins = 0 then 10 else state.pins;
              }
    else
      Frame { state with
              frame = state.frame + 1;
              throw = First;
              pins = 10;
            }
  in
  match state.throw with
  | Second | Fill_ball -> next_frame state
  | First ->
    if state.pins = 0 then
      next_frame state
    else
      Frame { state with throw = Second }

let roll pins game =
  if pins < 0 then
    Error "Negative roll is invalid"
  else
    match game with
    | Finished _ ->
      Error "Cannot roll after game is over"
    | Frame state ->
      if pins > state.pins then
        Error "Pin count exceeds pins on the lane"
      else
        state
        |> evaluate_throw pins
        |> add_bonus
        |> advance
        |> Result.return


let score game =
  match game with
  | Finished score ->
    Ok score
  | Frame _ ->
    Error "Score cannot be taken until the end of the game"

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?