REFACTOR: break down the logic into dedicated methods, tests cleaned up
This commit is contained in:
parent
8474b20e85
commit
a93a6abb28
2 changed files with 88 additions and 33 deletions
|
|
@ -1,35 +1,58 @@
|
|||
class BowlingGame {
|
||||
static const _totalFrames = 10;
|
||||
static const _allPins = 10;
|
||||
static const _rollsInNormalFrame = 2;
|
||||
static const _rollsInStrike = 1;
|
||||
|
||||
final List<int> _rolls = [];
|
||||
|
||||
void roll(int pins) {
|
||||
_rolls.add(pins);
|
||||
}
|
||||
void roll(int pins) => _rolls.add(pins);
|
||||
|
||||
int score() {
|
||||
int totalScore = 0;
|
||||
int total = 0;
|
||||
int rollIndex = 0;
|
||||
|
||||
for (int frame = 0; frame < 10; frame++) {
|
||||
for (int frame = 0; frame < _totalFrames; frame++) {
|
||||
if (_isStrike(rollIndex)) {
|
||||
totalScore += 10 + _rolls[rollIndex + 1] + _rolls[rollIndex + 2];
|
||||
rollIndex += 1;
|
||||
total += _strikeScore(rollIndex);
|
||||
rollIndex += _rollsInStrike;
|
||||
} else if (_isSpare(rollIndex)) {
|
||||
totalScore += 10 + _rolls[rollIndex + 2];
|
||||
rollIndex += 2;
|
||||
total += _spareScore(rollIndex);
|
||||
rollIndex += _rollsInNormalFrame;
|
||||
} else {
|
||||
totalScore += _rolls[rollIndex] + _rolls[rollIndex + 1];
|
||||
rollIndex += 2;
|
||||
total += _normalScore(rollIndex);
|
||||
rollIndex += _rollsInNormalFrame;
|
||||
}
|
||||
}
|
||||
|
||||
return totalScore;
|
||||
return total;
|
||||
}
|
||||
|
||||
int _strikeScore(int rollIndex) {
|
||||
return _allPins + _nextTwoRollsBonus(rollIndex);
|
||||
}
|
||||
|
||||
int _spareScore(int rollIndex) {
|
||||
return _allPins + _nextRollBonus(rollIndex);
|
||||
}
|
||||
|
||||
int _normalScore(int rollIndex) {
|
||||
return _rolls[rollIndex] + _rolls[rollIndex + 1];
|
||||
}
|
||||
|
||||
int _nextTwoRollsBonus(int rollIndex) {
|
||||
return _rolls[rollIndex + 1] + _rolls[rollIndex + 2];
|
||||
}
|
||||
|
||||
int _nextRollBonus(int rollIndex) {
|
||||
return _rolls[rollIndex + 2];
|
||||
}
|
||||
|
||||
bool _isSpare(int rollIndex) {
|
||||
return _rolls[rollIndex] + _rolls[rollIndex + 1] == 10;
|
||||
return _rolls[rollIndex] + _rolls[rollIndex + 1] == _allPins;
|
||||
}
|
||||
|
||||
bool _isStrike(int rollIndex) {
|
||||
return _rolls[rollIndex] == 10;
|
||||
return _rolls[rollIndex] == _allPins;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue