Search code examples
pythonwhile-loopinfinite-loop

Python Blackjack Functions and Inputs Arrangement


This code should to generate a blackjack hand, keep score, and tally the number of soft aces. It should stop or proceed depending on the type of game. The code isn't arranged properly and keeps the "total" value and/or "hand" empty giving an infinite while loop. How do I arrange the code so it returns the desired outcome?

import random

def get_card():
    #hand = []
    card = random.randint(1, 13)
    if card == 10 or card == 11 or card == 12 or card == 13:
        card = 10
    #hand.append(card)
    #return hand
    return card

def score():
    """
    keeps score of the hand and counts saft aces.
    """
    hand = []
    card = get_card()
    #hand = [get_card()]
    game_type = input("Enter 'soft'for S17 ot 'hard for H17'.")
    total = 0
    soft_ace_count = 0
    for ele in range(0, len(hand)):
        total = total + hand[ele]

    while len(hand) <= 5:
        while total <= 17 and game_type == 'soft':
            if card == 1:
                card = 11
                hand.append(card)

        while total <= 17 and game_type == 'hard':
            if card == 1:
                hand.append(card)

        if ele in hand == 11:
                soft_ace_count += 1

    return(total, soft_ace_count)

I also want to modularize the program and compute the probability of busting based on a number of user-defined simulations. I don't know how to set up the simulations for-loop to temporarily save the simulations results for calculation the probability. Should I place them in a temporary file?


def main():
    try:
        num_simulations = int(input("Please enter the desired number of simulations: "))
    except ValueError:
        print("Please enter an integer value for the nummer of simulations.")

    try:
        stand_on_value = int(input("Please enter a score value to stand on. "))
    except ValueError:
        print("Please enter an integer value for the stand-on score.")

    try:
        game_type = input("Enter 'soft' for S17 or 'hard' for H17.")
    except ValueError:
        if game_type != 'soft' or game_type != 'hard':
            print("Please enter 'soft' or 'hard'.")

    for i in range(0, num_simulations):
        get_card()
        score()

    "for-loop to calculate probability of busting as the percentage of busted hands in the simulations."```



Solution

  • The first while loop will continue for ever since you never adapt total, but there are several other issues:

    • when the if condition within the while is false then also the hand is not extended and nothing else happens.

    • Whenever the loop iterates, you should select a new card

    • The for ele in range(0, len(hand)) is useless where it is currently placed, as there is no card in the hand

    • if ele in hand == 11 is not doing what you want. It should be if 11 in hand. Even better is to just do this job when you actually set the card to 11. Then no more additional if is needed.

    • As only one while loop condition of the two loops can ever be true, use only one while loop and make the distinction within it.

    Change to this:

    def score():
        game_type = input("Enter 'soft' for S17 or 'hard' for H17.")
        hand = []
        total = 0
        soft_ace_count = 0
        while total <= 17:
            card = get_card()
            total += card # you must bring total up to date here
            if game_type == 'soft' and card == 1 and total <= 11:
                card = 11
                total += 10  # adapt to the new value of the card
                soft_ace_count += 1  # move this here...
            # so you can see what is happening 
            print("Got card {}. Total is {}".format(card, total))  
            hand.append(card) # always append...
        # Do you plan to do something with hand? Do you really need it?
        # ...
        return total, soft_ace_count  # parentheses are not needed           
    

    I did not verify the rest of your code, but this at least solves the matter of your question.