implement spare and strike

This commit is contained in:
DerTyp7
2023-09-08 10:44:24 +02:00
parent a096af18af
commit da8779f06d
2 changed files with 60 additions and 10 deletions

View File

@@ -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;
}
}

View File

@@ -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;
}
}