Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Created December 5, 2011 03:46
Show Gist options
  • Save steveklabnik/1432218 to your computer and use it in GitHub Desktop.
Save steveklabnik/1432218 to your computer and use it in GitHub Desktop.
Bowling kata
class Game
attr_reader :rolls
def initialize(rolls)
@rolls = rolls
end
def score
frames.inject(0) do |score, frame|
score += FrameScorer.new(frame).score
end
end
def frames
Enumerator.new do |yielder|
position = 0
10.times do
yielder << rolls[position,3].map(&:to_i)
if rolls[position] == 10
position += 1
else
position += 2
end
end
end
end
end
class FrameScorer
attr_reader :rolls
def initialize(rolls)
@rolls = rolls
end
def score
if spare? or strike?
sum_all_rolls
else
sum_first_two_rolls
end
end
def strike?
rolls[0] == 10
end
def spare?
sum_first_two_rolls == 10
end
def sum_first_two_rolls
rolls[0,2].inject(&:+)
end
def sum_all_rolls
rolls.inject(&:+)
end
end
require_relative "../bowling"
describe Game do
subject { Game.new(@rolls) }
it "scores a frame" do
@rolls = [4,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
subject.score.should eq(9)
end
it "scores two frames" do
@rolls = [4,5,4,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
subject.score.should eq(18)
end
it "scores two frames with spares" do
@rolls = [5,5,5,5,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
subject.score.should eq(35)
end
it "scores two frames with strikes" do
@rolls = [10,10,5,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
subject.score.should eq(53)
end
it "scores a perfect game" do
@rolls = [10,10,10,10,10,10,10,10,10,10,10,10]
subject.score.should eq(300)
end
end
describe FrameScorer do
subject { FrameScorer.new(@rolls) }
it "can score two zeros" do
@rolls = [0,0]
subject.score.should eq(0)
end
it "can score < 10" do
@rolls = [4,5]
subject.score.should eq(9)
end
it "can score a spare" do
@rolls = [4,6,5]
subject.score.should eq(15)
end
it "does not overscore" do
@rolls = [4,5,8]
subject.score.should eq(9)
end
it "can score a strike" do
@rolls = [10,5,4]
subject.score.should eq(19)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment