Skip to content

Instantly share code, notes, and snippets.

@sprengerjo
Last active December 18, 2015 22:18
Show Gist options
  • Save sprengerjo/5853355 to your computer and use it in GitHub Desktop.
Save sprengerjo/5853355 to your computer and use it in GitHub Desktop.
bowling game test and implementation
package de.sprengerjo.game.xtend
import static org.junit.Assert.*
import org.junit.Test
import org.junit.Before
class GameTest {
var game = new Game()
@Before
def void setUp() {
game = new Game()
}
@Test
def void gutterGamesOnly() {
(1 .. 20).forEach[game.roll(0)]
assertEquals(20 * 0, game.score())
}
@Test
def void oneGamesOnly() {
(1 .. 20).forEach[game.roll(1)]
assertEquals(20 * 1, game.score())
}
@Test
def void oneSpareAnd18OneGames() {
rollSpare()
(3 .. 20).forEach[game.roll(1)]
assertEquals(5 + 5 + 1 + 18 * 1, game.score())
}
def rollSpare() {
game.roll(5)
game.roll(5)
}
@Test
def void oneStrikeAnd18OneGames() {
game.roll(10)
(3 .. 20).forEach[game.roll(1)]
assertEquals(10 + 1 + 1 + 18 * 1, game.score())
}
@Test
def void perfectGameScoreIs300() {
(1 .. 12).forEach[game.roll(10)]
assertEquals(300, game.score())
}
}
// game impl...
package de.sprengerjo.game.xtend
class Game {
@Property // sugar for producing getter and setter in Java file
var scores = newArrayList(0)
def roll(int i) {
scores.add(i)
}
def score() {
var score = 0
var roll = 1
for (i : 0 ..< 10) {
if (isStrike(roll)) {
score = score + strikeBonus(roll)
roll = roll + 1
} else if (isSpare(roll)) {
score = score + 10 + scores.get(roll + 2)
roll = roll + 2
} else {
score = score + scores.get(roll) + scores.get(roll + 1)
roll = roll + 2
}
}
score
}
def isSpare(int roll) {
10 == scores.get(roll) + scores.get(roll + 1)
}
def isStrike(int roll) {
10 == scores.get(roll)
}
def strikeBonus(int roll) {
10 + scores.get(roll + 1) + scores.get(roll + 2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment