I came across this method when doing a google search for how to sum in an array. I'm using it now to try and build my blackjack game. It seems to be working fine for what I want it to do for now. I'm not too sure yet on what all this method can do or problems that can arise. I took the info from a stack overflow post,
http://stackoverflow.com/questions/1538789/how-to-sum-array-members-in-ruby.
My blackjack game is a work in progress. I tried building this mostly on my own before looking at the tealeaf videos that show building the program up. I don't know if i'll get a chance to totally finish my own version of it. Here is where i'm at to show how i'm using inject. Note that this will run for most instances, but i haven't fixed a couple issues yet. Note inject returns a fixnum.
deck = [1,2,3,4,5,6,7,8,9,10,10,10,10,'Ace']
deck.shuffle!
ph = []
dh =[]
2.times do
ph << deck.pop
dh << deck.pop
end
puts 'Hand'
puts ph
puts
if ph.include? 'Ace'
puts 'Ace in hand'
end
puts
if ph.include? 'Ace'
puts 'Choose ace high or low' i'm expecting a 1 or 11 response here
ace = gets.chomp
ace = ace.to_i
ph.map! {|x| x == 'Ace' ? ace : x}
puts
puts ph
end
puts 'Hand total'
sum = ph.inject(:+) here i use inject to get the total for the players hand
puts sum
puts 'Would you like a hit or stay?'
reply = gets.chomp
puts
if reply == 'hit'
ph << deck.pop
puts ph
puts
puts 'Hand total'
sum = ph.inject(:+) new total for player after hit
puts sum
end
if reply == 'stay' and dh.inject(:+)<17
dh << deck.pop
puts 'Dealer hand'
puts dh
puts
puts 'Dealer total'
sum = dh.inject(:+) dealer total. need to fix for aces
puts sum
end
puts
if ph.inject(:+) > dh.inject(:+) comparing hands
puts 'You win!'
elsif dh.inject(:+) >=22
puts 'You win'
else
puts 'Dealer wins :('
end
No comments:
Post a Comment