Skip to content

Instantly share code, notes, and snippets.

@BrianJoyce
Created October 10, 2012 06:04
Show Gist options
  • Save BrianJoyce/3863429 to your computer and use it in GitHub Desktop.
Save BrianJoyce/3863429 to your computer and use it in GitHub Desktop.
Bowling Game DBC
require 'pry'
class BowlingGame
binding.pry
attr_accessor :total, :game
def initialize
@game = []
@total = 0
9.times {|f| @game << [0,0]}
9.times {|f| @game[f] = roll_frame(f)}
roll_frame_10
end
def roll_frame(f)
@frame = []
@frame << rand(11)
@frame << rand(11 - @frame.reduce(:+))
@frame
end
def roll_frame_10
@frame = []
@frame << rand(11)
@frame[0] == 10 ? @frame << rand(11) : @frame << rand(11 - @frame[0]) # 3 rolls for strike frame 10
@frame[0] == 10 || @frame.reduce(:+) == 10 ? @frame << rand(11) : @frame << 0 # 3 rolls for strike frame 10
@game << @frame
end
def the_score
@game.each_index {|i| strikes_bonus(i) if strike?(i) && final_frame?(i) == false}
@game.each_index {|i| spare_bonus(i) if spare?(i) && final_frame?(i) == false}
@game.each_index {|i| @total += frame_score(i) if (strike?(i) == false) && (spare?(i) == false) && final_frame?(i) == false}
final_frame
end
def frame_score(i)
@game[i].reduce(:+)
end
def strikes_bonus(i)
case
when strike?(i) && i == 8 then return @total += 10 + @game[9][0] + @game[9][1]
when strike?(i) && strike?(i+1) && strike?(i+2) then return @total += 30
when strike?(i) && strike?(i+1) then return @total += 20 + @game[i+2][0]
else return @total += frame_score(i) + frame_score(i+1)
end
end
def strike?(i)
@game[i][0] == 10 ? true : false
end
def spare?(i)
strike?(i) == false && frame_score(i) == 10 ? true : false
end
def spare_bonus(i)
return @total += frame_score(i) + @game[i+1][0]
end
def final_frame?(i)
i + 1 == @game.size ? true : false
end
def final_frame
@total += frame_score(9)
end
end
my_game = BowlingGame.new
my_game.the_score
puts my_game.game.inspect
puts my_game.total
#
# a = []
# 1000.times { a << my_game.roll_frame_10}
# puts a.inspect
#
# puts "*** all strikes ***"
# a.each {|f| puts "SSTTRRRIIKKEE: #{f}" if f[0] == 10 }
#
# puts "*** all spares ***"
# a.each {|f| puts "spare: #{f}" if f[0] != 10 && f[0] + f[1] == 10}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment