How can I fix the scoring on my blackjack game?

63 Views Asked by At

I'm currently having an issue where I play a round of blackjack on the code I created, but keep losing. My score will be <21 but still more than the dealer and I will lose. I am pretty new to coding so any help is appreciated, thanks.

def FinalScore():
    global bank, bet

    # different win conditions
    # pays the player their original bet * 2

    if player_score == dealer_score and player_score <= 21:
        print("It's a tie!")
        bank = bank + bet
        print("You currently have $",bank,"left.")
        Restart()
    elif player_score > 21:
        print("You lost!")
        print("You currently have $",bank,"left.")
        Restart()
    elif player_score < 21 and dealer_score > player_score:
        print("You lost!")
        print("You currently have $",bank,"left.")
        Restart()
    elif player_score > dealer_score and player_score <= 21:
        print("You win!")
        bank = bet + bet + bank
        print("You currently have $",bank,"left.")
        Restart()
    elif dealer_score > 21 and player_score <= 21:
        print("You win!")
        bank = bet + bet + bank
        print("You currently have $",bank,"left.")
        Restart()

I tried rearranging the order of the win conditions and it did change some outcomes, but ultimately it was still finnicky. I think there is a better way to do this that I am not aware of.

2

There are 2 best solutions below

0
lexer31 On

You have a lot of conditions; In BJ, you lose if you burn (>21); but after that you win if dealer burn; after your score in compared with dealer;

def FinalScore():
    global bank, bet

    # different win conditions
    # pays the player their original bet * 2

    if player_score > 21:
        print("You lost!")
    else:
        if dealer_score > 21:
            print("You win!")
            bank = bank + 2*bet
        elif player_score == dealer_score:
            print("It's a tie !")
            bank = bank + bet
        elif player_score < dealer_score:
            print("You lost!")
        else:
            print("You win!")
            bank = bank + 2*bet
    print("You currently have $",bank,"left.")
    Restart()
0
tac toc On

The thing is that you use if conditions as 'case', that is what is happening with elif condition here is that it will fall on the first true statement, here elif player_score < 21 and dealer_score > player_score: , at this stage there is no check of the value of the dealer_score who could be greater than 21. To be more readable, try to define first what happen when a player is higher than 21, something like that :

if dealer_score > 21:
    print('win')
    return Restart()

if player_score > 21 :
    print('loose')
    return Restart()

else :
    if player_score > dealer_score :
        print('win')
    elif player_score == dealer_score:
        print('tie')
    else:
        print('loose')
    return Restart()