Python Script: Blackjack

by Vince
in Blog
Hits: 1653

I was working on a project and while looking at the randint function, I suddenly thought about blackjack.  It makes sense -- you have a function, randint, that generates a random number.  So I open a terminal and after a little side deviation, I'm generating a couple of cards.  I realize a few things I'm missing and I build it out a bit further.  Then even further.  Each time realizing that there's more to this little game project than I had anticipated.  I finally decide to stop at this version you see below.

There are a couple of things to note here -- first, my dealer cheats.  That's intentional.  The second thing to note is that I didn't take into account that an Ace can be worth one or 11.  I could go back in an assign values to variables but then this would grow further and that wasn't really my point.  

As always, my Python is pretty weak so don't critique me.  I don't use it for much other than single functions hence the very small hacky scripts you see here.  One day I'll build something... one day...

#!/usr/bin/python3
import os
import sys
from random import randint
os.system('clear')
card1=randint(1,11)
card2=randint(1,11)
dealercard1=randint(1,11)
dealercard2=randint(1,11)
cards=card1+card2
dealercards=dealercard1+dealercard2
while(dealercards <=17):
    newdealercard=randint(1,4)
    dealercards=dealercards+newdealercard
else:
pass
print("You have:",card1,card2)
print("Total: ",cards, "\n")
while (cards <=20):
    if (cards==21):
        print("Blackjack!")
    if (cards <=20):
        x = input("Would you like another card? Y/N ").lower()
        if x == 'y':
            newcard=randint(1,11)
            cards=cards+newcard
            print(newcard)
            print("")
            print("Total: ",cards, "\n")
            if (cards == 21):
                print("Blackjack!")
            else:
                pass
        else:
            print("You're holding at: ",cards, "\n")
            print("Dealer has:",dealercards)
            if (dealercards >= cards):
                print("Dealer Wins!","\n")
            else:
                print("You Win!", "\n")
            break
    else:
        pass
    if cards > 21:
        print("Bust!", "\n")
y = input("Would you like to play again? Y/N ").lower()
if y == "y":
    os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
else:
    sys.exit(0)