Skip to content

Instantly share code, notes, and snippets.

@shostakovich
Created July 9, 2012 18:04
Show Gist options
  • Save shostakovich/3077924 to your computer and use it in GitHub Desktop.
Save shostakovich/3077924 to your computer and use it in GitHub Desktop.
Bowling game 5th try
class BowlingGame
attr_reader :rolls
def initialize
@rolls = []
end
def roll(pins)
@rolls << pins
end
end
describe BowlingGame do
it "should hold a list of tries" do
game = BowlingGame.new
game.roll(1)
game.roll(3)
game.rolls.should be == [1,3]
end
end
class BowlingScore
def initialize(game)
@game = game
end
def pins(ball)
@game.rolls[ball]
end
def calculate
score = 0
@first_ball_in_frame = 0
0.upto(9) do
score += current_frame_score
@first_ball_in_frame += strike? ? 1 : 2
end
score
end
def current_frame_score
if strike?
strike_score
elsif spare?
spare_score
else
normal_score
end
end
def normal_score
pins(@first_ball_in_frame) + pins(@first_ball_in_frame + 1)
end
def strike?
pins(@first_ball_in_frame) == 10
end
def strike_score
10 + pins(@first_ball_in_frame + 1) + pins(@first_ball_in_frame + 2)
end
def spare?
pins(@first_ball_in_frame) + pins(@first_ball_in_frame + 1) == 10
end
def spare_score
10 + pins(@first_ball_in_frame + 2)
end
end
describe BowlingScore do
let(:game) { BowlingGame.new }
let(:score) do
score = BowlingScore.new(game)
score.calculate
end
let(:roll_spare) { 2.times { game.roll(5) } }
let(:roll_strike) { game.roll(10) }
it "calculates the score of a gutter game" do
20.times { game.roll(0) }
score.should be == 0
end
it "calculates the score for 2 pins + gutter balls" do
game.roll(2)
19.times { game.roll(0) }
score.should be == 2
end
it "calculates the score of a spare + 3 pins + gutter balls" do
roll_spare
game.roll(3)
17.times { game.roll(0) }
score.should be == 16
end
it "calculates the score of a strike + 2 following pins + gutter balls" do
roll_strike
game.roll(1)
game.roll(2)
16.times { game.roll(0) }
score.should be == 16
end
end
@shostakovich
Copy link
Author

I am not sure if i like this use of let.. The nice part is that it is lazy-evaluated - thats why it works..

What i like is how

score.should be == 16 

reads..

So it might be worth doing this..

The naming in the BowlingScore class is of..

Also I dont like that the concept of a frame does not really stick out in this simple algorithm.. I don't know how to solve this without an extra class - which looks like overengineering this on the other hand..

though I stop here ;) Doing this over and over and over again will sort this out I guess..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment