Repository navigation
Expand file tree
/
Copy pathBowlingGame.java
More file actions
executable file
·84 lines (67 loc) · 2.77 KB
/
Copy pathBowlingGame.java
File metadata and controls
executable file
·84 lines (67 loc) · 2.77 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.ArrayList;
import java.util.List;
public class BowlingGame {
private static final int NUMBER_OF_FRAMES = 10;
private static final int MAXIMUM_FRAME_SCORE = 10;
private List<Integer> rolls = new ArrayList<Integer>();
public void roll(int pins) {
rolls.add(pins);
}
public int score() {
int score = 0;
int frameIndex = 0;
for (int i = 1; i <= NUMBER_OF_FRAMES; i++) {
if (rolls.size() <= frameIndex) {
throw new IllegalStateException("Score cannot be taken until the end of the game");
}
if (isStrike(frameIndex)) {
if (rolls.size() <= frameIndex + 2) {
throw new IllegalStateException("Score cannot be taken until the end of the game");
}
int strikeBonus = strikeBonus(frameIndex);
if (strikeBonus > MAXIMUM_FRAME_SCORE && !isStrike(frameIndex + 1)) {
throw new IllegalStateException("Pin count exceeds pins on the lane");
}
score += 10 + strikeBonus;
frameIndex += i == NUMBER_OF_FRAMES ? 3 : 1;
} else if (isSpare(frameIndex)) {
if (rolls.size() <= frameIndex + 2) {
throw new IllegalStateException("Score cannot be taken until the end of the game");
}
score += 10 + spareBonus(frameIndex);
frameIndex += i == NUMBER_OF_FRAMES ? 3 : 2;
} else {
int frameScore = frameScore(frameIndex);
if (frameScore < 0) {
throw new IllegalStateException("Negative roll is invalid");
} else if (frameScore > 10) {
throw new IllegalStateException("Pin count exceeds pins on the lane");
}
score += frameScore;
frameIndex += 2;
}
}
if (!correctNumberOfRolls(frameIndex)) {
throw new IllegalStateException("Cannot roll after game is over");
}
return score;
}
private boolean correctNumberOfRolls(int frameIndex) {
return frameIndex == rolls.size();
}
private boolean isStrike(int frameIndex) {
return rolls.get(frameIndex) == MAXIMUM_FRAME_SCORE;
}
private boolean isSpare(int frameIndex) {
return rolls.get(frameIndex) + rolls.get(frameIndex + 1) == MAXIMUM_FRAME_SCORE;
}
private int strikeBonus(int frameIndex) {
return rolls.get(frameIndex + 1) + rolls.get(frameIndex + 2);
}
private int spareBonus(int frameIndex) {
return rolls.get(frameIndex + 2);
}
private int frameScore(int frameIndex) {
return rolls.get(frameIndex) + rolls.get(frameIndex + 1);
}
}