Simulating Blackjack

The code we went over in class to simulate the game of Blackjack can be found at http://github.com/michaelee/cs105/tree/master/examples/lect20_blackjack.rb. Instead of removing the programming shortcuts (a.k.a. “syntactic sugar”) I use in the uploaded code, I’m attaching a small section of the code in this post with comments to help you understand and perhaps use them in your own programs:

CARDS = %w(A 2 3 4 5 6 7 8 9 10 J Q K)
# The %w(...) syntax creates an array of strings, delineated by spaces.
# Compare to ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
 
def hand_value(hand)
  value = 0
  hand.each do |card|
    if card == 'J' || card == 'Q' || card == 'K'
      value += 10  # We do this sort of thing quite frequently:
                   # the += operator is a shortcut that says "add the given value
                   # to and assign it to the variable on the left hand side".
                   # value += 10 is the same as value = value + 10
    elsif card != 'A'
      value += card.to_i   # The same as value = value + card.to_i
    end
  end
  hand.each do |card|
    if card == 'A'
      if value > 10
        value += 1   # The same as value = value + 1
      else
        value += 11  # The same as value = value + 11
      end
    end
  end
  value
end

Leave a comment

You must be logged in to post a comment.