Created
September 17, 2009 11:26
-
-
Save gcsolaroli/188452 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original formulation of the problem: http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata | |
import org.scalatest._ | |
import org.scalatest.matchers._ | |
class Game { | |
private var rolls:List[Int] = Nil | |
def roll(pins:Int) { | |
rolls += pins | |
} | |
def roll(pins:List[Any]) { | |
pins.foreach(_ match { | |
case p:Int => roll(p) | |
case (p1:Int, p2:Int) => roll(p1); roll(p2) | |
}) | |
} | |
def strikeBonus(rolls:List[Int]) = { | |
rolls.head + rolls.tail.head | |
} | |
def spareBonus(rolls:List[Int]) = { | |
rolls.head | |
} | |
def computeScore(rolls:List[Int]):Int = { | |
if (rolls != Nil) { | |
var frameScore:Int = rolls.head | |
var remainingRolls:List[Int] = rolls.tail | |
if (frameScore == 10) { | |
frameScore += strikeBonus(remainingRolls) | |
if (remainingRolls.length == 2) { | |
remainingRolls = Nil | |
} | |
} else { | |
frameScore += remainingRolls.head | |
remainingRolls = remainingRolls.tail | |
if (frameScore == 10) { | |
frameScore += spareBonus(remainingRolls) | |
if (remainingRolls.length == 1) { | |
remainingRolls = Nil | |
} | |
} | |
} | |
frameScore + computeScore(remainingRolls) | |
} else { | |
0 | |
} | |
} | |
def score:Int = { | |
this.computeScore(rolls) | |
} | |
} | |
class GameSpecs extends Spec with ShouldMatchers { | |
describe("The bowling game scoring rules") { | |
it("should be zero when no pin is dropped in any roll") { | |
val game = new Game | |
game.roll(List((0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0))) | |
game.score should equal (0) | |
} | |
it("should be the simple sum (20) if just one pin is dropped in every roll") { | |
val game = new Game | |
game.roll(List((1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1))) | |
game.score should equal (20) | |
} | |
it("should add the extra point of the next score when doing a spare") { | |
val game = new Game | |
game.roll(List((5, 5), (3, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0))) | |
game.score should equal (16) | |
} | |
it("should add the extra point of the next two scores when doing a strike") { | |
val game = new Game | |
game.roll(List((10), (3, 4), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0))) | |
game.score should equal (24) | |
} | |
it("should get 300 points for a perfect game") { | |
val game = new Game | |
game.roll(List(10, 10, 10, 10, 10, 10, 10, 10, 10, 10, /* extra rolls */ 10, 10)) | |
game.score should equal (300) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment