Skip to content

Instantly share code, notes, and snippets.

@jastice
Created January 16, 2015 19:54
Show Gist options
  • Save jastice/8c693526bd40e65256d1 to your computer and use it in GitHub Desktop.
Save jastice/8c693526bd40e65256d1 to your computer and use it in GitHub Desktop.
Bowling DDDified
package de.munich.softwerkskammer;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class Game {
private Deque<Frame> frames = new LinkedList<Frame>();
private List<Roll> rolls = new ArrayList<Roll>();
public Game() {
frames.push(new Frame(0));
}
public void roll(int pins) {
Roll roll = new Roll(pins);
if (rolls.size() >= 21) throw new RuntimeException("game is over, stop rolling");
rolls.add(roll);
if (frames.peek().isComplete() && frames.size() < 10) {
frames.push(new Frame(rolls.size()-1));
}
frames.peek().addRoll(roll);
}
public int score() {
int score = 0;
for (Frame f : frames) {
if (f.isStrike()) score += 10 + strikeBonus(f);
else if (f.isSpare()) score += 10 + spareBonus(f);
else score += f.sumOfBallsInFrame();
}
return score;
}
private int strikeBonus(Frame frame) {
return scoreOf(frame.rollIndex+1) + scoreOf(frame.rollIndex+1);
}
private int scoreOf(int roll) {
if (rolls.size() <= roll) return 0;
else return rolls.get(roll).pins;
}
private int spareBonus(Frame frame) {
return scoreOf(frame.rollIndex + 2);
}
private int sumOfBallsInFrame(Frame frame) {
return scoreOf(frame.rollIndex) + scoreOf(frame.rollIndex + 1);
}
static class Frame {
private List<Roll> rolls = new ArrayList<Roll>();
public final int rollIndex;
Frame(int rollIndex) {
this.rollIndex = rollIndex;
}
void addRoll(Roll roll) {
rolls.add(roll);
}
boolean isComplete() {
return rolls.size() == 2 || isStrike();
}
public boolean isStrike() { return rolls.size() == 1 && rolls.get(0).isStrike(); }
public boolean isSpare() { return rolls.size() == 2 && sumOfBallsInFrame() == 10; }
public int sumOfBallsInFrame() {
int sum = 0;
for (Roll r : rolls)
sum += r.pins;
return sum;
}
}
static class Roll {
public final int pins;
Roll(int pins) {
this.pins = pins;
}
public boolean isStrike() {
return pins == 10;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment