Skip to content

Instantly share code, notes, and snippets.

@philipschwarz
Created July 30, 2011 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipschwarz/1116154 to your computer and use it in GitHub Desktop.
Save philipschwarz/1116154 to your computer and use it in GitHub Desktop.
Modified Frame and FrameSequence so that "future" rolls are referenced without linking through "future" frames
package bowling
class Frame
{
public add(roll) { rolls << roll }
public addBonus(roll) { rolls << roll }
public score(){ rolls.sum() }
private rolls = []
public isStrike(){ roll(1) == 10 }
public isSpare(){ (roll(1) + roll(2)) == 10 }
private roll(n){ rolls[n-1] }
}
package bowling
import java.util.Iterator;
class FrameSequence
{
public FrameSequence(n)
{
n.times{ frames.add( new Frame() ) }
}
public populateWith(rolls){ populateWith(rolls.listIterator()) }
public score() { frames.sum{ it.score() } }
private populateWith(Iterator rolls)
{
frames.each { populate(it, with(rolls)) }
}
private populate(frame, rolls)
{
frame.add(rolls.next())
if(frame.isStrike())
{
def (roll1, roll2) = nextTwo(rolls)
frame.addBonus(roll1)
frame.addBonus(roll2)
}
else
{
frame.add(rolls.next())
if (frame.isSpare())
{
frame.addBonus(first(rolls))
}
}
}
public first(Iterator rolls) {
def roll = rolls.next();
rolls.previous();
return roll;
}
public nextTwo(ListIterator rolls) {
def roll1 = rolls.next();
def roll2 = rolls.next();
rolls.previous();
rolls.previous();
return [roll1, roll2];
}
private List frames = [];
private with(rolls){rolls}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment