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/Gemfile b/Gemfile new file mode 100644 index 00000000..41df210d --- /dev/null +++ b/Gemfile @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +# gem "rails" + +gem "rspec", "~> 3.12" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 00000000..aac3c6c8 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,26 @@ +GEM + remote: https://rubygems.org/ + specs: + diff-lcs (1.5.0) + rspec (3.12.0) + rspec-core (~> 3.12.0) + rspec-expectations (~> 3.12.0) + rspec-mocks (~> 3.12.0) + rspec-core (3.12.1) + rspec-support (~> 3.12.0) + rspec-expectations (3.12.2) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-mocks (3.12.4) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-support (3.12.0) + +PLATFORMS + x86_64-darwin-21 + +DEPENDENCIES + rspec (~> 3.12) + +BUNDLED WITH + 2.4.8 diff --git a/README.md b/README.md index 15dc4762..deb44091 100644 --- a/README.md +++ b/README.md @@ -1,65 +1,18 @@ -Bowling Challenge in Ruby -================= +Game Scorecount +=============== -* 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 +![Diagram for Scorecount](https://github.com/francescoGuglielmi/bowling-challenge-ruby/blob/454472c0f2d718b5b780cda132a3b4f0a9f869aa/documents/images/Diagram%20Scorecount.png) -## The Task +# Content -**THIS IS NOT A BOWLING GAME, IT IS A BOWLING SCORECARD PROGRAM. DO NOT GENERATE RANDOM ROLLS. THE USER INPUTS THE ROLLS.** +- **class Frame** -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. +It generates the score for the one of the frames based on user input for each roll. -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. +- **class Scorecount** -As usual please start by +It runs each frame of a game and returns the sum of their scores. -* 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) diff --git a/documents/images/Diagram Scorecount.png b/documents/images/Diagram Scorecount.png new file mode 100644 index 00000000..6ecfebc5 Binary files /dev/null and b/documents/images/Diagram Scorecount.png differ diff --git a/images/example_ten_pin_scoring.png b/documents/images/example_ten_pin_scoring.png similarity index 100% rename from images/example_ten_pin_scoring.png rename to documents/images/example_ten_pin_scoring.png diff --git a/documents/instructions.md b/documents/instructions.md new file mode 100644 index 00000000..15dc4762 --- /dev/null +++ b/documents/instructions.md @@ -0,0 +1,65 @@ +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) diff --git a/lib/frame.rb b/lib/frame.rb new file mode 100644 index 00000000..2e119173 --- /dev/null +++ b/lib/frame.rb @@ -0,0 +1,51 @@ +class Frame + def initialize(io) + @io = io + @frame = [] + @pins = 0 + end + + def check_invalid + raise 'Invalid entry.' if (@pins < 0 || @pins > 10) + raise 'Invalid entry.' if @frame.size == 1 && (@pins < 0 || @pins > (10 - @frame[0])) + end + + def roll + @pins = @io.gets.to_i + check_invalid + @frame << @pins + end + + def strike? + true if @frame[0] == 10 && @frame.size == 1 + end + + def spare? + true if @frame.size == 2 && @frame.sum == 10 + end + + def run + roll + return @frame = ['X'] if strike? + roll + @frame[1] = '/' if spare? + return @frame + end + + def tenth + @pins = @io.gets.to_i + @pins = 'X' if @pins == 10 + @frame << @pins + @pins = @io.gets.to_i + @frame << @pins + if (!@frame.include? 'X') && @frame.sum == 10 + @frame[1] = '/' + end + if (@frame.include? '/') || (@frame.include? 'X') + @pins = @io.gets.to_i + @frame << @pins + end + return @frame + end + +end \ No newline at end of file diff --git a/lib/scorecount.rb b/lib/scorecount.rb new file mode 100644 index 00000000..9c3e22d1 --- /dev/null +++ b/lib/scorecount.rb @@ -0,0 +1,63 @@ +require_relative './frame' + +class Scorecount + def initialize(io) + @io = io + @points = 0 + @frames = [] + @bonus = [] + end + + def count_points + @frames.flatten!.each_with_index do |score, index| + if score == 'X' + if (index == @frames.length - 1) || (index == @frames.length - 2) + @points += 10 + else + @points += 10 + @bonus << @frames[index + 1] + @bonus << @frames[index + 2] + end + elsif score == '/' + @points += 10 + @points -= @frames[index - 1] + puts index - 1 + puts @frames[index - 1] + @bonus << @frames[index + 1] + else + @points += score + end + end + end + + def calculate_bonus + #@bonus.each do |frame| + @bonus.each do |score| + if score == 'X' + score = 10 + end + @points += score + end + #end + + end + + def run + n = 1 + 9.times do + puts "Frame #{n}" + frame = Frame.new(@io).run + @frames << frame + n += 1 + end + @frames << Frame.new(@io).tenth + print @frames + count_points + calculate_bonus + p @points + return @points + end + +end + +Scorecount.new(Kernel).run \ No newline at end of file diff --git a/spec/frame_spec.rb b/spec/frame_spec.rb new file mode 100644 index 00000000..79a392fa --- /dev/null +++ b/spec/frame_spec.rb @@ -0,0 +1,75 @@ +require 'frame' + +describe Frame do + + context '#roll' do + it 'throws an error if the amount of pins hit is an invalid entry' do + io = double :io + frame = Frame.new(io) + + expect(io).to receive(:gets).and_return('12') + expect{ frame.roll }.to raise_error 'Invalid entry.' + end + + it 'plays a roll' do + io = double :io + frame = Frame.new(io) + + expect(io).to receive(:gets).and_return('5') + expect(frame.roll[0]).to eq 5 + end + end + + context '#strike' do + it 'returns true if a strike has been achieved' do + io = double :io + frame = Frame.new(io) + + expect(io).to receive(:gets).and_return('10') + expect(frame.roll).to eq [10] + expect(frame.strike?).to eq true + end + end + + context '#spare' do + it 'returns true if a spare has been achieved' do + io = double :io + frame = Frame.new(io) + + expect(io).to receive(:gets).and_return('6') + expect(io).to receive(:gets).and_return('4') + frame.roll + + expect(frame.roll.sum).to eq 10 + expect(frame.spare?).to eq true + end + end + + context '#run' do + it 'plays the whole frame and returns the score for that frame' do + io = double :io + frame = Frame.new(io) + + expect(io).to receive(:gets).and_return('3') + expect(io).to receive(:gets).and_return('5') + expect(frame.run).to eq [3, 5] + end + + it 'plays the whole frame and returns a strike' do + io = double :io + frame = Frame.new(io) + + expect(io).to receive(:gets).and_return('10') + expect(frame.run).to eq ['X'] + end + + it 'plays the whole frame and returns a spare' do + io = double :io + frame = Frame.new(io) + + expect(io).to receive(:gets).and_return('9') + expect(io).to receive(:gets).and_return('1') + expect(frame.run).to eq [9, '/'] + end + end +end \ No newline at end of file diff --git a/spec/scorecount_spec.rb b/spec/scorecount_spec.rb new file mode 100644 index 00000000..90b52f56 --- /dev/null +++ b/spec/scorecount_spec.rb @@ -0,0 +1,24 @@ +require 'scorecount' + +describe Scorecount do + + context '#count_points' do + it 'counts and returns 0' do + scorecount = Scorecount.new + + expect(scorecount.count_points).to eq 0 + end + end + + context '#bonus_strike' do + it 'adds the bonus for achieving a strike' do + io = double :io + frame = Frame.new + scorecount = Scorecount.new + + expect(io).to receive(:gets).and_return('10') + expect + 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