Jim's
Tutorials

Fall 2018
course
site

Rails week 10

finished blackjack

below is part of lib file, which I finished by adding a computer as a player. I'll explain it after the code:

require_relative 'deck'
require_relative 'hand'
require_relative 'card'

puts "would you like to play blackjack? (y/n)"
start = gets.chomp
if start == 'y'
    new_deck = Deck.new
    new_deck.deal
    player_hand = Hand.new(new_deck.deal, new_deck.deal)
    computer_hand = Hand.new(new_deck.deal, new_deck.deal)
    puts "you have an #{player_hand.card_1.rank} of #{player_hand.card_1.suite} and a #{player_hand.card_2.rank} of #{player_hand.card_2.suite} in your hand"
    player_score = player_hand.display_score
    puts "#{player_score}"


while player_hand.display_score <= 21

    puts 'hit or stand?'
    answer = gets.chomp
    if answer == 'stand'
            puts "Ive delt the computer #{computer_hand.card_1.rank} of #{computer_hand.card_1.suite} and a #{computer_hand.card_2.rank} of #{computer_hand.card_2.suite}"
            computer_score = computer_hand.display_score
            puts "#{computer_score}"
            while computer_hand.display_score < 16
                new_compcard = new_deck.deal
                computer_hand.add_card(new_compcard)
                puts "computer was delt a #{new_compcard.rank} of #{new_compcard.suite}"
                new_compscore = computer_hand.display_score
                puts "#{new_compscore}"
                if new_compscore > 21
                    puts 'oh crap the comp busted'
end
end
break
end
    if answer == 'hit'
        new_card = new_deck.deal
        player_hand.add_card(new_card)
        puts "you were delt a #{new_card.rank} of #{new_card.suite} "
        new_score = player_hand.display_score
        puts "#{new_score}"
        if new_score > 21
            puts "oh crap you busted"
        end
end
end
if computer_hand.display_score > player_hand.display_score && computer_hand.display_score < 21
    puts "comp wins"
elsif
     computer_hand.display_score < player_hand.display_score && player_hand.display_score < 21
    puts "player wins"
end
end


...and the output:

ruby lib.rb
would you like to play blackjack? (y/n)
y
you have an 4 of diamonds and a 7 of spades in your hand
11
hit or stand?
stand
Ive delt the computer 8 of spades and a a of diamonds
19
comp wins

Discussion

Making the computer part was much easier than making the player parts from scratch. Could mostly copy the way I'd made the player. I'd say the most difficult thing to do was knowing that 'new_score' once set, wouldn't change so I had to actually refer to the original variables I'd named it to, computer_score.display_score, in order to get the updated score of the computer. Setting the bounds of the computer rules was also a little tricky, mostly syntactically- the whole '&&' thing I wasn't sure about but seems to work fine.