mirror of
https://github.com/DerTyp7/bowling-kata-java.git
synced 2025-10-29 12:52:12 +01:00
implement spare and strike
This commit is contained in:
@@ -1,15 +1,53 @@
|
||||
package de.tealfire;
|
||||
|
||||
public class Bowling {
|
||||
int score = 0;
|
||||
int roll = 0;
|
||||
int[] rolls = new int[21];
|
||||
|
||||
int currentRoll = 0;
|
||||
|
||||
public void roll(int i) {
|
||||
score += i;
|
||||
roll++;
|
||||
rolls[currentRoll] = i;
|
||||
currentRoll++;
|
||||
}
|
||||
|
||||
public int score() {
|
||||
int score = 0;
|
||||
int frameIndex = 0;
|
||||
for (int frame = 0; frame < 10; frame++) {
|
||||
if (isStrike(frameIndex)) {
|
||||
score += 10 + strikeBonus(frameIndex);
|
||||
frameIndex++;
|
||||
} else if (isSpare(frameIndex)) {
|
||||
score += 10 + spareBonus(frameIndex);
|
||||
frameIndex += 2;
|
||||
} else {
|
||||
score += sumOfBallsInFrame(frameIndex);
|
||||
frameIndex += 2;
|
||||
}
|
||||
}
|
||||
return score;
|
||||
}
|
||||
|
||||
private boolean isStrike(int frameIndex) {
|
||||
return rolls[frameIndex] == 10;
|
||||
}
|
||||
|
||||
private int strikeBonus(int frameIndex) {
|
||||
return rolls[frameIndex + 1] + rolls[frameIndex + 2];
|
||||
}
|
||||
|
||||
private boolean isSpare(int frameIndex) {
|
||||
return rolls[frameIndex] + rolls[frameIndex + 1] == 10;
|
||||
}
|
||||
|
||||
private int spareBonus(int frameIndex) {
|
||||
return rolls[frameIndex + 2];
|
||||
}
|
||||
|
||||
private int sumOfBallsInFrame(int frameIndex) {
|
||||
return rolls[frameIndex] + rolls[frameIndex + 1];
|
||||
}
|
||||
public void reset() {
|
||||
currentRoll = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,17 +12,29 @@ public class BowlingTest {
|
||||
|
||||
@Test
|
||||
public void testScoreGutterGame() {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
bowling.roll(0);
|
||||
}
|
||||
roll(20, 0);
|
||||
assert bowling.score() == 0;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testScoreGameOfOnes() {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
bowling.roll(1);
|
||||
}
|
||||
roll(20, 1);
|
||||
assert bowling.score() == 20;
|
||||
}
|
||||
|
||||
private void roll(int n, int pins) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
bowling.roll(pins);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testScoreSpare() {
|
||||
bowling.roll(5);
|
||||
bowling.roll(5);
|
||||
bowling.roll(3);
|
||||
roll(17, 0);
|
||||
assert bowling.score() == 16;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user