Skip to content

Instantly share code, notes, and snippets.

@chadrien
Created December 3, 2013 20:05
Show Gist options
  • Save chadrien/7776576 to your computer and use it in GitHub Desktop.
Save chadrien/7776576 to your computer and use it in GitHub Desktop.
# encoding: UTF-8
class Score
attr_accessor :rolls
def initialize(rolls)
@rolls = rolls.each_char
end
def total
@special_trick_bonus = 1
rolls.inject 0 do | total, current |
roll_score = score_as_points current
roll_score = roll_score * @special_trick_bonus if in_special_trick?
@previous_score = roll_score
update_special_trick_bonus! current
total + roll_score
end
end
private
def score_as_points score
return 10 if strike? score
return 10 - @previous_score if spare? score
score.to_i
end
def strike?(score) score == "X" end
def spare?(score) score == "/" end
def in_special_trick?() @special_trick_bonus > 1 end
def update_special_trick_bonus! score
if(strike?(score) || spare?(score))
@special_trick_bonus += 1
else
@special_trick_bonus = 1
end
end
end
# encoding: UTF-8
require_relative "../lib/score"
require "test/unit"
class ScoreTest < Test::Unit::TestCase
def test_score_can_have_rolls_given
rolls = "--------------------"
score = Score.new(rolls)
assert_not_nil score.rolls
end
def test_all_zero_rolls_should_return_zero
rolls = "--------------------"
score = Score.new(rolls)
expected = 0
assert_equal expected, score.total
end
def test_one_5_score_and_nine_zeros_should_return_5
rolls = "5-------------------"
score = Score.new(rolls)
assert_equal 5, score.total
end
def test_one_strike_followed_by_a_5_and_8_zeros_should_return_20
rolls = "X5-----------------"
score = Score.new(rolls)
assert_equal 20, score.total
end
def test_one_spare_followed_by_a_5_and_8_zeros_should_return_20
rolls = "9/5----------------"
score = Score.new(rolls)
assert_equal 20, score.total
end
def test_one_spare_of_8_followed_by_a_5_and_8_zeros_should_return_20
rolls = "8/5----------------"
score = Score.new(rolls)
assert_equal 20, score.total
end
def test_two_strikes_followed_by_8_zeros_should_return_30
rolls = "XX-----------------"
score = Score.new(rolls)
assert_equal 30, score.total
end
def test_two_strikes_followed_by_3_and_7_zeros_should_return_39
rolls = "XX3----------------"
score = Score.new(rolls)
assert_equal 39, score.total
end
def test_7_zeros_should_return_39
rolls = "---------------/XX3"
score = Score.new(rolls)
assert_equal 59, score.total
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment