Skip to content

Instantly share code, notes, and snippets.

@techbelly
Created January 10, 2011 00:26
Show Gist options
  • Save techbelly/772179 to your computer and use it in GitHub Desktop.
Save techbelly/772179 to your computer and use it in GitHub Desktop.
import unittest
class Game:
rolls = [0] * 21
current_roll = 0
def roll(self,pins):
self.rolls[self.current_roll] = pins
self.current_roll += 1
def score(self):
sc = 0
frameindex = 0
for frame in xrange(0,10):
if self.is_strike(frameindex):
sc += 10 + self.strike_bonus(frameindex)
frameindex +=1
elif self.is_spare(frameindex):
sc += 10 + self.spare_bonus(frameindex)
frameindex += 2
else:
sc += self.sum_of_balls(frameindex)
frameindex += 2
return sc
def is_strike(self,frameindex):
return self.rolls[frameindex] == 10
def strike_bonus(self,frameindex):
return self.rolls[frameindex+1] + self.rolls[frameindex+2]+ self.rolls[frameindex+2]
def spare_bonus(self,frameindex):
return self.rolls[frameindex+2]
def sum_of_balls(self,frameindex):
return self.rolls[frameindex] + self.rolls[frameindex+1]
def is_spare(self,frameindex):
return self.sum_of_balls(frameindex) == 10
class TestBowling(unittest.TestCase):
def setUp(self):
self.g = Game()
def rollMany(self,n,pins):
for i in xrange(0,n):
self.g.roll(pins)
def rollSpare(self):
self.g.roll(5)
self.g.roll(5)
def rollStrike(self):
self.g.roll(10)
def test_perfect_game(self):
self.rollMany(12,10)
self.assertEquals(300, self.g.score())
def test_gutter_game(self):
self.rollMany(20,0)
self.assertEquals(0, self.g.score())
def test_all_ones(self):
self.rollMany(20,1)
self.assertEquals(20, self.g.score())
def test_one_spare(self):
self.rollSpare()
self.g.roll(3)
self.rollMany(17,0)
self.assertEquals(16,self.g.score())
def test_one_strike(self):
self.rollStrike()
self.g.roll(3)
self.g.roll(4)
self.rollMany(16,0)
self.assertEquals(24,self.g.score())
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment