Skip to content

Instantly share code, notes, and snippets.

@JDLeigh10
Created June 30, 2012 18:18
Show Gist options
  • Save JDLeigh10/3024927 to your computer and use it in GitHub Desktop.
Save JDLeigh10/3024927 to your computer and use it in GitHub Desktop.
Ruby Blackjack
# Initialize Variables
deck = []
suits = ["C", "H", "S", "D"]
card_nos = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"]
user_hand = []
@@dealer_hand = []
user_hand_total = 0
valid_input = ['hit', 'stand', 'double', 'split']
# Create a Deck
card_nos.each do |x|
suits.each_index do |y|
z = x.to_s + suits[y]
deck << z
end
end
# Shuffle the Deck
deck.shuffle!
# Burn the first card, deal the user cards 2 and 4, the dealer 3 and 5
deck.delete_at(0)
user_hand << deck[0]
@@dealer_hand << deck[1]
user_hand << deck[2]
@@dealer_hand << deck[3]
# Calculate the users hand total
# This is overly complicated and clearly needs to be refactored but I don't know a better way to do it
if user_hand[0].chars.first == "J" || user_hand[0].chars.first == "Q" || user_hand[0].chars.first == "K" || user_hand[0] == "10C" || user_hand[0] == "10H" || user_hand[0] == "10S" || user_hand[0] == "10D"
a = 10
elsif user_hand[0].chars.first == "A"
a = 11
ace = 1
else
a = user_hand[0].chars.first.to_i
end
if user_hand[1].chars.first == "J" || user_hand[1].chars.first == "Q" || user_hand[1].chars.first == "K" || user_hand[1] == "10C" || user_hand[1] == "10H" || user_hand[1] == "10S" || user_hand[1] == "10D"
b = 10
elsif user_hand[1].chars.first == "A"
b = 11
bace = 1
else
b = user_hand[1].chars.first.to_i
end
user_hand_total = a + b
if ace && bace
user_hand_total = 12
user_hand_total_ace = 2
elsif ace
user_hand_total_ace = ace + b
elsif bace
user_hand_total_ace = a + bace
end
# Figure out the output
if user_hand_total == 21
output = "BLACKJACK!!"
elsif user_hand[0].chars.first == "A" || user_hand[1].chars.first == "A"
output = "Total: #{user_hand_total}/#{user_hand_total_ace}"
else
output = "Total: #{user_hand_total}"
end
# Display the cards
puts "Dealer Shows : #{@@dealer_hand[1]}"
puts "Player Hand : #{user_hand[0]}, #{user_hand[1]} | #{output}"
# Prompt the user
print "Decision: "
user_response = gets.chomp.downcase.strip
until valid_input.include?(user_response) == true
puts "Valid moves: hit, stand, double, split"
print "Decision: "
user_response = gets.chomp.downcase.strip
end
# Define the action method for decision
#
# I'm giving up here, because I don't have a good understanding of classes and methods yet.
#
def action(decision)
if decision == 'stand'
# Display dealer card
puts "Dealer Turns over: #{@@dealer_hand[0]}"
puts "Dealer Hand: #{@@dealer_hand[1]}, #{@@dealer_hand[0]}"
# See who won
# Display result
end
end
# Act on the decision
action(user_response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment