01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package eg.bowling;
04:
05: public class BowlingScorer {
06: private int[] rolls = new int[21];
07: protected int rollNumber = 0;
08:
09: public void roll(int pins) {
10: rolls[rollNumber++] = pins;
11: }
12:
13: public int score(int frame) {
14: int score = 0;
15: int roll = 0;
16: for (int f = 0; f < frame; f++) {
17: if (strike(roll)) {
18: score += 10 + nextTwoBallsForStrike(roll);
19: roll++;
20: } else if (spare(roll)) {
21: score += 10 + nextBallForSpare(roll);
22: roll += 2;
23: } else {
24: score += ballsInFrame(roll);
25: roll += 2;
26: }
27: }
28: return score;
29: }
30:
31: private int ballsInFrame(int roll) {
32: return rolls[roll] + rolls[roll + 1];
33: }
34:
35: private int nextBallForSpare(int roll) {
36: return rolls[roll + 2];
37: }
38:
39: private int nextTwoBallsForStrike(int roll) {
40: return (rolls[roll + 1] + rolls[roll + 2]);
41: }
42:
43: private boolean spare(int roll) {
44: return rolls[roll] + rolls[roll + 1] == 10;
45: }
46:
47: private boolean strike(int roll) {
48: return rolls[roll] == 10;
49: }
50:
51: protected boolean lastRollWasStrike() {
52: return rolls[rollNumber - 1] == 10;
53: }
54:
55: protected boolean lastRollWasSpare() {
56: return rolls[rollNumber - 2] + rolls[rollNumber - 1] == 10;
57: }
58: }
|