Created
February 17, 2014 23:50
-
-
Save DavidCulpepper/9061695 to your computer and use it in GitHub Desktop.
Bowling Game
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
package net.davidculpepper; | |
import org.junit.Test; | |
import static org.hamcrest.CoreMatchers.is; | |
import static org.hamcrest.MatcherAssert.assertThat; | |
public class BowlingGameTest { | |
Game sut = new Game(); | |
@Test | |
public void gutter_test() { | |
rollMany(20, 0); | |
assertThat(sut.finalScore(), is(0)); | |
} | |
@Test | |
public void single_pin_test() { | |
sut.roll(1); | |
rollMany(19, 0); | |
assertThat(sut.finalScore(), is(1)); | |
} | |
@Test | |
public void spare_test() { | |
rollSpare(); | |
sut.roll(1); | |
rollMany(17, 0); | |
assertThat(sut.finalScore(), is(12)); | |
} | |
@Test | |
public void strike_test() { | |
rollStrike(); | |
sut.roll(4); | |
sut.roll(3); | |
rollMany(16, 0); | |
assertThat(sut.finalScore(), is(24)); | |
} | |
@Test | |
public void perfect_game_test() { | |
rollMany(12, 10); | |
assertThat(sut.finalScore(), is(300)); | |
} | |
private void rollMany(int numRolls, int pins) { | |
for (int i = 0; i < numRolls; i++) { | |
sut.roll(pins); | |
} | |
} | |
private void rollStrike() { | |
sut.roll(10); | |
} | |
private void rollSpare() { | |
sut.roll(6); | |
sut.roll(4); | |
} | |
} |
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
package net.davidculpepper; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Game { | |
private List<Integer> rolls = new ArrayList<Integer>(); | |
public void roll(int numberOfPins) { | |
rolls.add(numberOfPins); | |
} | |
public int finalScore() { | |
int score = 0; | |
int ball = 0; | |
for (int frame = 0; frame < 10; frame++) { | |
score += rolls.get(ball); | |
score += rolls.get(ball + 1); | |
if (isStrike(ball)) { | |
score += rolls.get(ball + 2); | |
ball++; | |
} else if (isSpare(ball)) { | |
score += rolls.get(ball + 2); | |
ball += 2; | |
} else { | |
ball += 2; | |
} | |
} | |
return score; | |
} | |
private boolean isStrike(int ball) { | |
return rolls.get(ball) == 10; | |
} | |
private boolean isSpare(int ball) { | |
return rolls.get(ball) + rolls.get(ball + 1) == 10; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment