Created
October 30, 2012 17:05
-
-
Save felipernb/3981562 to your computer and use it in GitHub Desktop.
Bowling Game in Java
This file contains 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 com.feliperibeiro.bowling; | |
public class BowlingGame { | |
int[] rolls; | |
int currentRoll; | |
public BowlingGame() { | |
this.rolls = new int[21]; | |
} | |
public void roll(int p) { | |
rolls[currentRoll++] = p; | |
} | |
public int score() { | |
int score = 0; | |
int frame = 0; | |
for (int i = 0; i < 10; i++) { | |
if (isStrike(frame)) { | |
score += 10 + strikeBonus(frame); | |
frame++; | |
} else if (isSpare(frame)) { | |
score += 10 + spareBonus(frame); | |
frame += 2; | |
} else { | |
score += sumOfRolls(frame); | |
frame += 2; | |
} | |
} | |
return score; | |
} | |
private boolean isStrike(int frame) { | |
return rolls[frame] == 10; | |
} | |
private boolean isSpare(int frame) { | |
return sumOfRolls(frame) == 10; | |
} | |
private int strikeBonus(int frame) { | |
return sumOfRolls(frame+1); | |
} | |
private int spareBonus(int frame) { | |
return rolls[frame+2]; | |
} | |
private int sumOfRolls(int frame) { | |
return rolls[frame] + rolls[frame+1]; | |
} | |
} |
This file contains 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 com.feliperibeiro.bowling; | |
import static org.junit.Assert.*; | |
import org.junit.Before; | |
import org.junit.Test; | |
public class BowlingGameTest { | |
private BowlingGame g; | |
void rollMany(int n, int pins, BowlingGame g) { | |
for (int i = 0; i < n; i++) g.roll(pins); | |
} | |
@Before | |
public void setUp() { | |
this.g = new BowlingGame(); | |
} | |
@Test | |
public void testZero() { | |
rollMany(20, 0, g); | |
assertEquals(0, g.score()); | |
} | |
@Test | |
public void testAllOnes() { | |
rollMany(20, 1, g); | |
assertEquals(20, g.score()); | |
} | |
@Test | |
public void testOneSpare() { | |
g.roll(5); | |
g.roll(5); | |
g.roll(3); | |
rollMany(17, 0, g); | |
assertEquals(16, g.score()); | |
} | |
@Test | |
public void testOneStrike() { | |
g.roll(10); | |
g.roll(3); | |
g.roll(4); | |
rollMany(16, 0, g); | |
assertEquals(24, g.score()); | |
} | |
@Test | |
public void testPerfectGame() { | |
rollMany(12, 10, g); | |
assertEquals(300, g.score()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello,
i have a question please, when i compil testOneSpare it works what ever i give as values, whereas it does not!! so why??