Created
December 21, 2012 16:41
-
-
Save sczizzo/4353914 to your computer and use it in GitHub Desktop.
Bowling Game Kata
This file contains hidden or 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 Bowling; | |
public class Game { | |
int nrolls = 0; | |
int[] rolls = new int[21]; | |
public void roll(int pins) { | |
rolls[nrolls++] = pins; | |
} | |
private boolean isStrike(int frameIdx) { | |
return 10 == rolls[frameIdx]; | |
} | |
private boolean isSpare(int frameIdx) { | |
return 10 == rolls[frameIdx] + rolls[frameIdx + 1]; | |
} | |
public int score() { | |
int score = 0; | |
int frameIdx = 0; | |
for (int frameNum = 0; frameNum < 10; ++frameNum) { | |
if (isStrike(frameIdx)) { | |
score += 10 + rolls[frameIdx + 1] + rolls[frameIdx + 2]; | |
frameIdx += 1; | |
} else if (isSpare(frameIdx)) { | |
score += 10 + rolls[frameIdx + 2]; | |
frameIdx += 2; | |
} else { | |
score += rolls[frameIdx] + rolls[frameIdx + 1]; | |
frameIdx += 2; | |
} | |
} return score; | |
} | |
} |
This file contains hidden or 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
import Bowling.Game; | |
import junit.framework.TestCase; | |
public class GameTest extends TestCase { | |
Game g; | |
protected void setUp() { | |
g = new Game(); | |
} | |
protected void tearDown() { | |
g = null; | |
} | |
private void rollMany(int n, int pins) { | |
for (int roll = 0; roll < n; ++roll) | |
g.roll(pins); | |
} | |
private void rollSpare() { | |
rollMany(2, 5); | |
} | |
private void rollStrike() { | |
g.roll(10); | |
} | |
public void testGutterGame() { | |
rollMany(20, 0); | |
assertEquals(0, g.score()); | |
} | |
public void testAllOnes() { | |
rollMany(20, 1); | |
assertEquals(20, g.score()); | |
} | |
public void testOneSpare() { | |
rollSpare(); | |
g.roll(3); | |
rollMany(17, 0); | |
assertEquals(16, g.score()); | |
} | |
public void testOneStrike() { | |
rollStrike(); | |
g.roll(5); | |
g.roll(4); | |
rollMany(16, 0); | |
assertEquals(28, g.score()); | |
} | |
public void testPerfectGame() { | |
rollMany(12, 10); | |
assertEquals(300, g.score()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment