diff --git a/.rspec b/.rspec new file mode 100644 index 00000000..c99d2e73 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/README.md b/README.md index 15dc4762..d46a31c0 100644 --- a/README.md +++ b/README.md @@ -1,65 +1,15 @@ Bowling Challenge in Ruby ================= - -* Feel free to use google, your notes, books, etc. but work on your own -* If you refer to the solution of another coach or student, please put a link to that in your README -* If you have a partial solution, **still check in a partial solution** -* You must submit a pull request to this repo with your code by 9am Monday week - -## The Task - -**THIS IS NOT A BOWLING GAME, IT IS A BOWLING SCORECARD PROGRAM. DO NOT GENERATE RANDOM ROLLS. THE USER INPUTS THE ROLLS.** - -Count and sum the scores of a bowling game for one player. For this challenge, you do _not_ need to build a web app with a UI, instead, just focus on the logic for bowling (you also don't need a database). Next end-of-unit challenge, you will have the chance to translate the logic to Javascript and build a user interface. - -A bowling game consists of 10 frames in which the player tries to knock down the 10 pins. In every frame the player can roll one or two times. The actual number depends on strikes and spares. The score of a frame is the number of knocked down pins plus bonuses for strikes and spares. After every frame the 10 pins are reset. - -As usual please start by - -* Forking this repo - -* Finally submit a pull request before Monday week at 9am with your solution or partial solution. However much or little amount of code you wrote please please please submit a pull request before Monday week at 9am. - -___STRONG HINT, IGNORE AT YOUR PERIL:___ Bowling is a deceptively complex game. Careful thought and thorough diagramming — both before and throughout — will save you literal hours of your life. - -## Focus for this challenge -The focus for this challenge is to write high-quality code. - -In order to do this, you may pay particular attention to the following: -* Using diagramming to plan your approach to the challenge -* TDD your code -* Focus on testing behaviour rather than state -* Commit often, with good commit messages -* Single Responsibility Principle and encapsulation -* Clear and readable code - -## Bowling — how does it work? - -### Strikes - -The player has a strike if he knocks down all 10 pins with the first roll in a frame. The frame ends immediately (since there are no pins left for a second roll). The bonus for that frame is the number of pins knocked down by the next two rolls. That would be the next frame, unless the player rolls another strike. - -### Spares - -The player has a spare if the knocks down all 10 pins with the two rolls of a frame. The bonus for that frame is the number of pins knocked down by the next roll (first roll of next frame). - -### 10th frame - -If the player rolls a strike or spare in the 10th frame they can roll the additional balls for the bonus. But they can never roll more than 3 balls in the 10th frame. The additional rolls only count for the bonus not for the regular frame count. - - 10, 10, 10 in the 10th frame gives 30 points (10 points for the regular first strike and 20 points for the bonus). - 1, 9, 10 in the 10th frame gives 20 points (10 points for the regular spare and 10 points for the bonus). - -### Gutter Game - -A Gutter Game is when the player never hits a pin (20 zero scores). - -### Perfect Game - -A Perfect Game is when the player rolls 12 strikes (10 regular strikes and 2 strikes for the bonus in the 10th frame). The Perfect Game scores 300 points. - -In the image below you can find some score examples. - -More about ten pin bowling here: http://en.wikipedia.org/wiki/Ten-pin_bowling - -![Ten Pin Score Example](images/example_ten_pin_scoring.png) +The program is designed in a single class for simplicity and does not include UI handling as per the specs. +BowlingScorer class holds the frame records, which is then iterated over when scores need to be counted. + +Frames +---- +First 10 frames are added to the @frames array. The amount of bonus shots player can take depend on their score on the 10th frame (effectively giving 3 different options) and its scoring is different than the regular game, so bonus shots are handled with an array of many args. The bonus array is also added to the @frames. + +Counting Scores +---- +This method iterates over the entire @frames array (starting from index 1 and not 0). +It relies on another method to check if the previous frame was a spare or not (that is why it starts from index 1). +It adds the bonus points to the current frame if the player has scored a spare or strike, not the previous one. +It stops the count after frame 10, and checks the length of the @frames whether the player has produced and bonus shots. diff --git a/lib/bowl.rb b/lib/bowl.rb new file mode 100644 index 00000000..69b60885 --- /dev/null +++ b/lib/bowl.rb @@ -0,0 +1,71 @@ +class BowlingScorer + def initialize + @player_score = 0 + @frames = [] + end + + def add_frame(shot1, shot2) + fail "Looks like you hit the next lane or something, cant knock more than 10" if shot1 + shot2 > 10 + fail "Smells like invalid input" if shot1 < 0 || shot2 < 0 + ## Line below is irrelevant for the current specs, but this is done assuming when UI is developed + ## the user will input their shots sequentially as opposed to passing them in together + shot1 == 10 ? current_frame = [10,0] : current_frame = [shot1, shot2] + @frames << current_frame + return current_frame + end + + def check_for_specials(frame) + message = "" + if frame[0] == 10 + message = "strike" + elsif frame.sum == 10 + message = "spare" + end + return message + end + + def add_bonus_frame(*args) + @frames << [*args] + return [*args] + end + + def count_player_bonus_scores + fail "Player has not scored any bonuses!" if @frames.length <= 10 + @player_score += @frames[-1].flatten.sum + end + + def count_frame_score(index) + current_frame = @frames[index] + previous_frame = @frames[index-1] + frame_score = current_frame.flatten.sum + if check_for_specials(previous_frame) == "spare" + frame_score += current_frame[0] + elsif check_for_specials(previous_frame) == "strike" + frame_score += current_frame.sum + end + return frame_score + end + + def count_player_score + i = 1 + @player_score += @frames[0].sum + ### The line below is added to be able to test small chunks of frames + frame_count = [@frames.length, 10].min + while i < frame_count + @player_score += count_frame_score(i) + i += 1 + end + count_player_bonus_scores if @frames.length > 10 + return @player_score + end + + ## Helper methods - Used in testing and not relevant to gameplay ## + def frames + @frames + end + + def reset_scores_and_frames + @player_score = 0 + @frames = [] + end +end \ No newline at end of file diff --git a/spec/bowl_spec.rb b/spec/bowl_spec.rb new file mode 100644 index 00000000..91deafd9 --- /dev/null +++ b/spec/bowl_spec.rb @@ -0,0 +1,255 @@ +require 'bowl' + +describe BowlingScorer do + let(:bowl) {BowlingScorer.new} + + before(:each) do + bowl.reset_scores_and_frames + end + + def simulate_a_game_until_last_shot + bowl.add_frame(5,5) + bowl.add_frame(3,5) + bowl.add_frame(7,0) + bowl.add_frame(2,5) + bowl.add_frame(10,0) + bowl.add_frame(3,5) + bowl.add_frame(7,0) + bowl.add_frame(2,5) + bowl.add_frame(7,2) + ## By the end of round 9, player has 84 points scored. + ## All subsequent endgame tests are based on this one + end + + context "add_frame method" do + it "fails if user tries to knock more than 10 in one frame" do + expect{bowl.add_frame(6,5)}.to raise_error "Looks like you hit the next lane or something, cant knock more than 10" + end + + it "fails if user inputs negative numbers" do + expect{bowl.add_frame(-1,5)}.to raise_error "Smells like invalid input" + end + + it "fails if user inputs negative numbers" do + expect{bowl.add_frame(4,-5)}.to raise_error "Smells like invalid input" + end + + it "returns the current frame in an array of numbers" do + expect(bowl.add_frame(4,3)).to eq [4,3] + end + + it "returns [10,0] if the user strikes on the first shot" do + expect(bowl.add_frame(10,0)).to eq [10,0] + end + end + + context "check_for_spares method" do + it "returns strike if the first shot is 10" do + expect(bowl.check_for_specials([10,0])).to eq "strike" + end + + it "returns spare if the total input is 10" do + expect(bowl.check_for_specials([3,7])).to eq "spare" + end + + it "returns spare if the total input is 10" do + expect(bowl.check_for_specials([0,10])).to eq "spare" + end + end + + context "frames method" do + it "shows all the shots user took as an array of arrays" do + bowl.add_frame(1,2) + bowl.add_frame(4,5) + bowl.add_frame(5,3) + expect(bowl.frames).to eq [[1,2],[4,5],[5,3]] + end + end + + context "count frame score method" do + it "counts the score of the given frame as is if no special events happened" do + bowl.add_frame(1,2) + bowl.add_frame(4,5) + expect(bowl.count_frame_score(1)).to eq 9 + end + + it "includes the bonus points awarded by a spare" do + bowl.add_frame(4,6) + bowl.add_frame(4,5) + expect(bowl.count_frame_score(1)).to eq 13 + end + + it "includes the bonus points awarded by a strike" do + bowl.add_frame(10,0) + bowl.add_frame(4,5) + expect(bowl.count_frame_score(1)).to eq 18 + end + end + + context "count player score method" do + it "returns the total score if there are no additionals strikes or spares" do + bowl.add_frame(4,5) + bowl.add_frame(4,5) + bowl.add_frame(4,5) + bowl.add_frame(4,5) + expect(bowl.count_player_score).to eq 36 + end + + it "returns the total score including spare points" do + bowl.add_frame(5,5) + bowl.add_frame(3,5) + bowl.add_frame(7,0) + bowl.add_frame(2,5) + expect(bowl.count_player_score).to eq 35 + end + + it "returns the total score including consecutive spare points" do + bowl.add_frame(3,1) + bowl.add_frame(3,7) + bowl.add_frame(7,3) + bowl.add_frame(2,5) + expect(bowl.count_player_score).to eq 40 + end + + it "returns the total score including zigzagged spare points" do + bowl.add_frame(3,7) + bowl.add_frame(2,5) + bowl.add_frame(7,3) + bowl.add_frame(2,5) + expect(bowl.count_player_score).to eq 38 + end + + it "returns the total score including strike points" do + bowl.add_frame(10,0) + bowl.add_frame(3,5) + bowl.add_frame(7,0) + bowl.add_frame(2,5) + expect(bowl.count_player_score).to eq 40 + end + + it "returns the total score including consecutive strike points" do + bowl.add_frame(10,0) + bowl.add_frame(10,0) + bowl.add_frame(7,0) + bowl.add_frame(2,5) + expect(bowl.count_player_score).to eq 51 + end + + it "returns the total score including zigzagged strike points" do + bowl.add_frame(10,0) + bowl.add_frame(5,4) + bowl.add_frame(10,0) + bowl.add_frame(2,5) + expect(bowl.count_player_score).to eq 52 + end + end + + ## There is no UI, so we assume validations to check if player is allowed + ## to take additional shots will be handled by the UI and not these methods. + context "add bonus frame method" do + it "adds an array of one element if player gets one bonus shot" do + bowl.add_bonus_frame(5) + expect(bowl.frames[-1]).to eq [5] + end + + it "adds an array of two elements if player gets two bonus shots" do + bowl.add_bonus_frame(10,7) + expect(bowl.frames[-1]).to eq [10,7] + end + + it "adds an array of three elements if player gets three bonus shots" do + bowl.add_bonus_frame(10,5,5) + expect(bowl.frames[-1]).to eq [10,5,5] + end + + it "adds an array of three elements if player gets three bonus shots" do + bowl.add_bonus_frame(10,10,10) + expect(bowl.frames[-1]).to eq [10,10,10] + end + end + + context "count_player_bonus_scores method" do + it "fails if player does not have any bonus points" do + simulate_a_game_until_last_shot + bowl.add_frame(6,3) + expect{bowl.count_player_bonus_scores}.to raise_error "Player has not scored any bonuses!" + end + + it "counts the total number of points player collected after 10th frame" do + simulate_a_game_until_last_shot + bowl.add_frame(6,4) + bowl.add_bonus_frame(10,5,4) + expect(bowl.count_player_bonus_scores).to eq 19 + end + end + + context "frames method" do + it "lists the shots user has made in an array of integer pairs" do + simulate_a_game_until_last_shot + bowl.add_frame(6,3) + expect(bowl.frames).to eq [[5, 5], [3, 5], [7, 0], [2, 5], [10, 0], [3, 5], [7, 0], [2, 5], [7, 2], [6, 3]] + end + + it "lists the shots user has made in an array of integer pairs, also includes tenth special frame if it exists" do + simulate_a_game_until_last_shot + bowl.add_frame(6,4) + bowl.add_bonus_frame(10,5,4) + expect(bowl.frames).to eq [[5, 5], [3, 5], [7, 0], [2, 5], [10, 0], [3, 5], [7, 0], [2, 5], [7, 2], [6, 4], [10, 5, 4]] + end + end + + describe "when evaluating the 10th frame" do + context "count_player_score method" do + it "counts the game regularly if the player fails to score any spare or strikes" do + simulate_a_game_until_last_shot + bowl.add_frame(4,3) + expect(bowl.count_player_score).to eq 91 + end + + it "if player ends with spare / fails to score strike" do + simulate_a_game_until_last_shot + bowl.add_frame(7,3) + expect(bowl.add_bonus_frame(6)) + expect(bowl.count_player_score).to eq 100 + end + + it "if player ends with spare / scores a strike and two randoms" do + simulate_a_game_until_last_shot + bowl.add_frame(7,3) + expect(bowl.add_bonus_frame(10,4,5)) + expect(bowl.count_player_score).to eq 113 + end + + it "if player ends with spare / scores a strike and two randoms" do + simulate_a_game_until_last_shot + bowl.add_frame(7,3) + expect(bowl.add_bonus_frame(10,4,5)) + expect(bowl.count_player_score).to eq 113 + end + + it "if player ends with a strike / scores three consecutive strikes" do + simulate_a_game_until_last_shot + bowl.add_frame(10,0) + expect(bowl.add_bonus_frame(10,10,10)) + expect(bowl.count_player_score).to eq 124 + end + end + end + + context "cross checking with readme gameplay for validating scores" do + it "returns 133" do + bowl.add_frame(1,4) + bowl.add_frame(4,5) + bowl.add_frame(6,4) + bowl.add_frame(5,5) + bowl.add_frame(10,0) + bowl.add_frame(0,1) + bowl.add_frame(7,3) + bowl.add_frame(6,4) + bowl.add_frame(10,0) + bowl.add_frame(2,8) + bowl.add_bonus_frame(6) + expect(bowl.count_player_score).to eq 133 + end + end +end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 00000000..5ae5b696 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,98 @@ +# This file was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # https://relishapp.com/rspec/rspec-core/docs/configuration/zero-monkey-patching-mode + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = "doc" + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end