Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. Code for the bowling game will be as below :
  2.  
  3. # Number of normal Frame in a game.
  4.  
  5. LIMIT = 10
  6.  
  7. # Total Number of pin lined up
  8. COUNT = 10
  9.  
  10. class BowlingExp < Exception ; end
  11.  
  12. class Frame_Range
  13. attr_reader :remaining_pin, :shots
  14.  
  15. def initialize(Frame_Range_num)
  16. @Frame_Range_num = Frame_Range_num
  17. @remaining_pin = COUNT
  18. @shots = []
  19. end
  20.  
  21. #Call BowlingGame#play first.Do not use this method directly;
  22.  
  23. def register_shot(pin)
  24. if !played?
  25. @remaining_pin -= pin
  26. end
  27. if !score_finalized?
  28. @shots << pin
  29. end
  30. end
  31.  
  32. def score
  33. @shots.inject(0, :+)
  34. end
  35.  
  36. def strike?
  37. shots.first == COUNT
  38. end
  39.  
  40. def spare?
  41. !strike? && remaining_pin == 0
  42. end
  43.  
  44. # If a strike or two shots have been played return true
  45. def played?
  46. remaining_pin == 0 || shots.length == 2
  47. end
  48.  
  49. # If the score has been finalized return true: no more bonus shots
  50.  
  51. def score_finalized?
  52. if @Frame_Range_num > LIMIT
  53. played? # No bonuses
  54. else
  55. shots.length == ((strike? || spare?) ? 3 : 2 : 1)
  56. end
  57. end
  58.  
  59. def to_s
  60. strike? ? 'X' :
  61. spare? ? "#{shots[0]}/" :
  62. shots[0...2].join()
  63. end
  64. end
  65.  
  66. attr_reader :Frame_Ranges
  67.  
  68. def initialize
  69. @Frame_Ranges = []
  70. new_Frame_Range()
  71. end
  72.  
  73. def play(&block)
  74. throw BowlingExp.new("Game over") if completed?
  75. pin = yield Frame_Ranges.last.remaining_pin, Frame_Ranges.last.shots.length
  76. throw BowlingExp.new("Shot Impossible") if pin > Frame_Ranges.last.remaining_pin
  77. Frame_Ranges.each { |f| f.register_shot(pin) }
  78. new_Frame_Range() if Frame_Ranges.last.played? && !completed?
  79. end
  80.  
  81. def completed?
  82. Frame_Ranges.length >= LIMIT && Frame_Ranges[LIMIT - 1].score_finalized?
  83. end
  84.  
  85. def score
  86. Frame_Ranges[0...LIMIT].collect { |f| f.score }.inject(0, :+)
  87. end
  88.  
  89. def to_s
  90. Frame_Ranges.collect { |f| f.to_s }.join('-')
  91. end
  92.  
  93. private
  94. def new_Frame_Range
  95. @Frame_Ranges << Frame_Range.new(@Frame_Ranges.length + 1)
  96. end
  97. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement