Created
July 30, 2011 23:31
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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