-
-
Save qingwang/7e561648c721c0be9cbc to your computer and use it in GitHub Desktop.
hmm... Blackjack. Ugly code in a hurry :p This code does not handle "A" being either 11 or 1. However it shouldn't be hard to add.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Deck | |
attr_reader :deck | |
def initialize | |
@deck = self.class.shuf | |
end | |
private | |
def self.shuf | |
deck = [] | |
ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] | |
suits = ["♦", "♣", "♥", "♠"] | |
ranks.each do |rank| | |
suits.each do |suit| | |
deck << [rank, suit] | |
end | |
end | |
deck.shuffle | |
end | |
end | |
def yes_or_no(question) | |
puts question | |
answer = gets.chomp | |
if answer =~ /y|Y/ | |
return true | |
elsif answer =~ /n|N/ | |
return false | |
else | |
yes_or_no(question) | |
end | |
end | |
def value(rank) | |
case rank | |
when "A" | |
return 1 | |
when "2".."10" | |
return rank.to_i | |
else | |
return 10 | |
end | |
end | |
def total(hand) | |
hand.inject(0){ |sum, card| sum + value(card[0]) } | |
end | |
def print_cards(hand) | |
hand.each { |card| print "#{card[0]}#{card[1]} " } | |
end | |
puts "Welcome to the Blackjack Casino!" | |
deck = Deck.new.deck | |
hand = [] | |
dealers_hand = [] | |
while (yes_or_no "\nHit?") | |
hand << deck.pop | |
print "You now have " | |
print_cards(hand) | |
if total(hand) > 21 | |
puts "\nBusted~~" | |
sleep 1 | |
puts "You lost. Good luck next time." | |
abort | |
end | |
end | |
loop do | |
dealers_hand << deck.pop | |
sleep 1 | |
print_cards(dealers_hand) | |
case | |
when total(dealers_hand) > 21 | |
puts "\nOops~ I busted~~" | |
sleep 1 | |
puts "\nYou win. Congratulations!" | |
abort | |
when total(dealers_hand) > 16 | |
sleep 1 | |
puts "\nOK, let's see who gets this round" | |
break | |
else | |
puts "\nHit me!" | |
end | |
end | |
sleep 1 | |
puts "You get a #{total(hand)}." | |
sleep 1 | |
puts "The dealer gets a #{total(dealers_hand)}." | |
sleep 1 | |
if total(hand) > total(dealers_hand) | |
puts "You win. Congratulations!" | |
elsif total(hand) < total(dealers_hand) | |
puts "You lost. Good luck next time." | |
else | |
puts "It's a draw. Let's go grab a beer." | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment