public
Created

Bowling Kata

  • Download Gist
Game.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
 
public class Game {
private static final int MAX_ROLLS_IN_GAME = 21;
private static final int FRAMES_IN_GAME = 10;
private int rolls[] = new int [MAX_ROLLS_IN_GAME];
private int currRoll;
public void roll(int pins) {
rolls[currRoll] = pins;
currRoll++;
}
 
public int score() {
int score = 0;
int frameIndex = 0;
for (int i = 0; i < FRAMES_IN_GAME; i++) {
if (isStrike(frameIndex)) {
score += strikeFrameScore(frameIndex) + strikeBonus(frameIndex);
frameIndex++;
} else if (isSpare(frameIndex)) {
score += fullFrameScore(frameIndex) + spareBonus(frameIndex);
frameIndex += 2;
} else {
score += fullFrameScore(frameIndex);
frameIndex += 2;
}
}
return score;
}
 
private int strikeBonus(int frameIndex) {
return rolls[frameIndex + 1] + rolls[frameIndex + 2];
}
 
private int strikeFrameScore(int frameIndex) {
return rolls[frameIndex];
}
 
private boolean isStrike(int frameIndex) {
return rolls[frameIndex] == 10;
}
 
private int spareBonus(int frameIndex) {
return rolls[frameIndex + 2];
}
 
private int fullFrameScore(int frameIndex) {
return rolls[frameIndex] + rolls[frameIndex + 1];
}
 
private boolean isSpare(int frameIndex) {
return fullFrameScore(frameIndex) == 10;
}
}
GameTest.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
import static org.junit.Assert.*;
 
import org.junit.Before;
import org.junit.Test;
 
 
 
public class GameTest {
private Game g;
 
@Before
public void setUp() {
g = new Game();
}
@Test
public void gutterGameScoreIsZero() throws Exception {
rollMany(0, 20);
assertEquals(0, g.score());
}
@Test
public void gameWithOnlyOnesScoreIs20() throws Exception {
rollMany(1, 20);
assertEquals(20, g.score());
}
 
private void rollMany(int pins, int n) {
for (int i = 0; i < n; i++) {
g.roll(pins);
}
}
@Test
public void oneSpareShouldGetBonusForThatSpare() throws Exception {
rollSpare();
g.roll(3);
rollMany(0, 17);
assertEquals(10 + 3 + 3, g.score());
}
 
private void rollSpare() {
g.roll(5);
g.roll(5);
}
@Test
public void oneStrikeShouldGetBonusForThatStrike() throws Exception {
rollStrike();
g.roll(3);
g.roll(4);
rollMany(0, 16);
assertEquals(10 + 3 + 4 + 3 + 4, g.score());
}
 
private void rollStrike() {
g.roll(10);
}
@Test
public void perfectGame() throws Exception {
rollMany(10, 12);
assertEquals(300, g.score());
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.