Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class GameNotStarted(Exception):
- pass
- class GameNotFinished(Exception):
- pass
- class GameOver(Exception):
- pass
- class BowlingGameSetting(object):
- MAX_ROLLS = 21
- ROLL_PER_FRAME = 2
- STRIKE_POINTS = 10
- STRIKE_BOUNS_ROLLS = 2
- SPARE_POINTS = 10
- SPARE_BONUS_ROLLS = 1
- class BowlingGame(object):
- """ Bowling game """
- def __init__(self):
- """ Constructor """
- self.__rolls = []
- def play(self,pinsDown):
- """ update the scores based on the pins down during the roll """
- if len(self.__rolls) >= BowlingGameSetting.MAX_ROLLS:
- raise GameOver
- self.__rolls.append(pinsDown)
- def __canScore(self):
- """ checks to see if we can score """
- if len(self.__rolls) == 0:
- raise GameNotStarted
- if len(self.__rolls) < BowlingGameSetting.MAX_ROLLS - 1:
- raise GameNotFinished
- def __getBonusRollScores(self,startingAt,nItems):
- """ total the scores of bonus rolls """
- itemCount = 0
- bonus = 0
- for item in self.__rolls[startingAt + 1:]:
- if itemCount >= nItems:
- break
- bonus += item
- itemCount += 1
- return bonus
- def __getBonus(self,frameIndex,frame):
- """ calculates the bonus for the provided frame """
- #bonus for spare frame
- if sum(frame) == BowlingGameSetting.SPARE_POINTS:
- return self.__getBonusRollScores((frameIndex * BowlingGameSetting.ROLL_PER_FRAME) + 1,BowlingGameSetting.SPARE_BONUS_ROLLS)
- #bonus for every strike in the frame
- bonus = 0
- for index,roll in enumerate(frame):
- if roll == BowlingGameSetting.STRIKE_POINTS:
- bonus += self.__getBonusRollScores((frameIndex * BowlingGameSetting.ROLL_PER_FRAME) + index,BowlingGameSetting.STRIKE_BOUNS_ROLLS)
- return bonus
- def score(self):
- """ calculates the score """
- self.__canScore()
- #calculate the score
- score = 0
- for frameIndex,frame in enumerate(zip(*[iter(self.__rolls)]* BowlingGameSetting.ROLL_PER_FRAME)): #split the rolls into frame.
- score += sum(frame) + self.__getBonus(frameIndex,frame)
- return score
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement