Search code examples
pythonrandomwhile-loopblackjack

Blackjack While Loop Trouble


So I'm pretty much making a blackjack simulator to find the probability of certain hands winning or not. I have a while loop to cycle through one full deck of 52 cards until there is 4 cards left. Within that I have a while loop having the dealer draw until his count is 17+ just like real blackjack. When I run the code, it will run through one deck successfully, but only prints the same hand every time. Here's the code:

# <--- PROGRAM SETUP --->
import random

# Drawing Card Function
def draw_card():
    # Card Values in 1 Deck
    vals = [2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,
            8,8,8,8,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,
            10,10,10,10,10,10,10,10,10,11,11,11,11]
    # </--->

    dealer = 0
    player = 0
    bust = 21


    deck_count = 0
    hand_count = 0

    dealer_cards = []

    # <--- // --->

    cards = 52
    # Loop Hands Through Deck
    while(cards > 4):

        # Draw Card Loop
        while(dealer <= 16):
            card = random.choice(vals)
            vals.remove(card)
            dealer_cards.append(card)

            dealer = dealer + card

        hand_count = hand_count + 1
        cards = cards - len(dealer_cards)


        # <--- Results --->
        if 17 <= dealer <= 21:
            print "Hand: {}, Dealer Stands @ {}".format(hand_count, dealer)
            for i in dealer_cards:
                print "Card: {}".format(i)

        else:
            print "Hand: {}, Dealer Busts @ {}".format(hand_count, dealer)
            for i in dealer_cards:
                print "Card: {}".format(i)

    else:
        deck_count = deck_count + 1
        print "Deck {} is finished!".format(deck_count)

# <--- // --->

draw_card()

When running this I get:

    Hand: 1, Dealer Stands @ 19
Card: 10
Card: 9
Hand: 2, Dealer Stands @ 19
Card: 10
Card: 9
Hand: 3, Dealer Stands @ 19
Card: 10
Card: 9
Hand: 4, Dealer Stands @ 19
Card: 10
Card: 9
Hand: 5, Dealer Stands @ 19
Card: 10
Card: 9
Hand: 6, Dealer Stands @ 19
Card: 10
Card: 9
Hand: 7, Dealer Stands @ 19
Card: 10
Card: 9
Hand: 8, Dealer Stands @ 19
Card: 10
Card: 9
Hand: 9, Dealer Stands @ 19
Card: 10
Card: 9
Hand: 10, Dealer Stands @ 19
...All the way till the deck has less than 4 cards left.

What can I fix to make each hand be a unique draw instead of printing the first hand multiple times? Thanks


Solution

  • You forgot to reset dealer and dealer_cards before each iteration, so your while(dealer <= 16): block will never run after the first time; it will just keep using the same score, but continue to decrement cards.

    Move your initializations into the main while loop:

    while(cards > 4):
        dealer_cards = []
        dealer = 0
    
        # Draw Card Loop
        while(dealer <= 16):
            card = random.choice(vals)
            vals.remove(card)
            dealer_cards.append(card)
    
            dealer = dealer + card
    
    ...