Skip to content

Instantly share code, notes, and snippets.

@iyuuya
Last active December 14, 2015 10:28
Show Gist options
  • Save iyuuya/5071945 to your computer and use it in GitHub Desktop.
Save iyuuya/5071945 to your computer and use it in GitHub Desktop.
# coding: utf-8
class Game
def initialize
@rolls = []
end
def roll(pins)
@rolls << pins
end
def score
roll_idx = 0
score = 0
10.times do |frame|
if strike?(roll_idx)
score += strike_bonus(roll_idx)
roll_idx += 1
elsif spare?(roll_idx)
score += spare_bonus(roll_idx)
roll_idx += 2
else
score += score_of_rame(roll_idx)
roll_idx += 2
end
end
score
end
private
def strike?(roll_idx)
@rolls[roll_idx] == 10
end
def spare?(roll_idx)
@rolls[roll_idx] + @rolls[roll_idx+1] == 10
end
def score_of_rame(roll_idx)
@rolls[roll_idx] + @rolls[roll_idx + 1]
end
def strike_bonus(roll_idx)
10 + @rolls[roll_idx + 1] + @rolls[roll_idx + 2]
end
def spare_bonus(roll_idx)
10 + @rolls[roll_idx + 2]
end
end
describe Game do
before :each do
@game = Game.new
end
specify "すべてガターの場合スコアは0点" do
20.times { @game.roll 0 }
@game.score.should == 0
end
end
private
def roll_gutter
game.roll 0
end
def roll_strike
game.roll 10
end
def roll_spare
game.roll 5; game.roll 5
end
public
describe Game do
let(:game) { Game.new }
context "すべて1ピンの場合" do
before do
20.times { game.roll 1 }
end
it "スコアは20点" do
game.score.should == 20
end
end
subject { game.score }
context "ストライクの場合" do
before do
roll_strike
game.roll 3
game.roll 4 # 24
18.times { roll_gutter }
end
it "スコアは24点" do
should == 24
end
end
context "パーフェクトゲームの場合" do
before do 12.times { roll_strike } end
it { should == 300 }
end
context "スペアの場合" do
before do
roll_spare
game.roll 4
game.roll 3 # 21
16.times { roll_gutter }
end
it { should == 21 }
end
context "Uncle Bobの受け入れゲームの場合" do
# [1,4,4,5,6,4,5,5,10,0,1,7,3,6,4,10,2,8,6] => 133
before do
[1,4,4,5,6,4,5,5,10,0,1,7,3,6,4,10,2,8,6].each { |pins| game.roll pins }
end
it { should == 133 }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment