Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Code for the bowling game will be as below :
- # Number of normal Frame in a game.
- LIMIT = 10
- # Total Number of pin lined up
- COUNT = 10
- class BowlingExp < Exception ; end
- class Frame_Range
- attr_reader :remaining_pin, :shots
- def initialize(Frame_Range_num)
- @Frame_Range_num = Frame_Range_num
- @remaining_pin = COUNT
- @shots = []
- end
- #Call BowlingGame#play first.Do not use this method directly;
- def register_shot(pin)
- if !played?
- @remaining_pin -= pin
- end
- if !score_finalized?
- @shots << pin
- end
- end
- def score
- @shots.inject(0, :+)
- end
- def strike?
- shots.first == COUNT
- end
- def spare?
- !strike? && remaining_pin == 0
- end
- # If a strike or two shots have been played return true
- def played?
- remaining_pin == 0 || shots.length == 2
- end
- # If the score has been finalized return true: no more bonus shots
- def score_finalized?
- if @Frame_Range_num > LIMIT
- played? # No bonuses
- else
- shots.length == ((strike? || spare?) ? 3 : 2 : 1)
- end
- end
- def to_s
- strike? ? 'X' :
- spare? ? "#{shots[0]}/" :
- shots[0...2].join()
- end
- end
- attr_reader :Frame_Ranges
- def initialize
- @Frame_Ranges = []
- new_Frame_Range()
- end
- def play(&block)
- throw BowlingExp.new("Game over") if completed?
- pin = yield Frame_Ranges.last.remaining_pin, Frame_Ranges.last.shots.length
- throw BowlingExp.new("Shot Impossible") if pin > Frame_Ranges.last.remaining_pin
- Frame_Ranges.each { |f| f.register_shot(pin) }
- new_Frame_Range() if Frame_Ranges.last.played? && !completed?
- end
- def completed?
- Frame_Ranges.length >= LIMIT && Frame_Ranges[LIMIT - 1].score_finalized?
- end
- def score
- Frame_Ranges[0...LIMIT].collect { |f| f.score }.inject(0, :+)
- end
- def to_s
- Frame_Ranges.collect { |f| f.to_s }.join('-')
- end
- private
- def new_Frame_Range
- @Frame_Ranges << Frame_Range.new(@Frame_Ranges.length + 1)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement