Skip to content

Instantly share code, notes, and snippets.

@mjhea0
Last active May 1, 2024 17:03
Show Gist options
  • Star 53 You must be signed in to star a gist
  • Fork 33 You must be signed in to fork a gist
  • Save mjhea0/5680216 to your computer and use it in GitHub Desktop.
Save mjhea0/5680216 to your computer and use it in GitHub Desktop.
python blackjack
import os
import random
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*4
def deal(deck):
hand = []
for i in range(2):
random.shuffle(deck)
card = deck.pop()
if card == 11:card = "J"
if card == 12:card = "Q"
if card == 13:card = "K"
if card == 14:card = "A"
hand.append(card)
return hand
def play_again():
again = raw_input("Do you want to play again? (Y/N) : ").lower()
if again == "y":
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*4
game()
else:
print "Bye!"
exit()
def total(hand):
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total+= 10
elif card == "A":
if total >= 11: total+= 1
else: total+= 11
else:
total += card
return total
def hit(hand):
card = deck.pop()
if card == 11:card = "J"
if card == 12:card = "Q"
if card == 13:card = "K"
if card == 14:card = "A"
hand.append(card)
return hand
def clear():
if os.name == 'nt':
os.system('CLS')
if os.name == 'posix':
os.system('clear')
def print_results(dealer_hand, player_hand):
clear()
print "The dealer has a " + str(dealer_hand) + " for a total of " + str(total(dealer_hand))
print "You have a " + str(player_hand) + " for a total of " + str(total(player_hand))
def blackjack(dealer_hand, player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand)
print "Congratulations! You got a Blackjack!\n"
play_again()
elif total(dealer_hand) == 21:
print_results(dealer_hand, player_hand)
print "Sorry, you lose. The dealer got a blackjack.\n"
play_again()
def score(dealer_hand, player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand)
print "Congratulations! You got a Blackjack!\n"
elif total(dealer_hand) == 21:
print_results(dealer_hand, player_hand)
print "Sorry, you lose. The dealer got a blackjack.\n"
elif total(player_hand) > 21:
print_results(dealer_hand, player_hand)
print "Sorry. You busted. You lose.\n"
elif total(dealer_hand) > 21:
print_results(dealer_hand, player_hand)
print "Dealer busts. You win!\n"
elif total(player_hand) < total(dealer_hand):
print_results(dealer_hand, player_hand)
print "Sorry. Your score isn't higher than the dealer. You lose.\n"
elif total(player_hand) > total(dealer_hand):
print_results(dealer_hand, player_hand)
print "Congratulations. Your score is higher than the dealer. You win\n"
def game():
choice = 0
clear()
print "WELCOME TO BLACKJACK!\n"
dealer_hand = deal(deck)
player_hand = deal(deck)
while choice != "q":
print "The dealer is showing a " + str(dealer_hand[0])
print "You have a " + str(player_hand) + " for a total of " + str(total(player_hand))
blackjack(dealer_hand, player_hand)
choice = raw_input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower()
clear()
if choice == "h":
hit(player_hand)
while total(dealer_hand) < 17:
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "s":
while total(dealer_hand) < 17:
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "q":
print "Bye!"
exit()
if __name__ == "__main__":
game()
@YoshiBoiy
Copy link

for line 85 if I uncomment in it gives me an indentation error, and I tried putting it in other indentations and it didnt work. Sorry I am a beginner at python.

@igor-tanv
Copy link

cool program but it only lets you hit the dealer once. it should let you hit the dealer multiple times until you choose to stand or you bust. revised code below

def game():
    choice = 0
    clear()
    print ("WELCOME TO BLACKJACK!\n")
    dealer_hand = deal(deck)
    player_hand = deal(deck)
    print ("The dealer is showing a " + str(dealer_hand[0]))
    print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand)))
    blackjack(dealer_hand, player_hand)
    quit=False
    while not quit:
        choice = input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower()
        if choice == 'h':
            hit(player_hand)
            print(player_hand)
            if total(player_hand)>21:
                print('You busted')
                play_again()
        elif choice=='s':
            while total(dealer_hand)<17:
                hit(dealer_hand)
                print(dealer_hand)
                if total(dealer_hand)>21:
                    print('Dealer busts, you win!')
                    play_again()
            score(dealer_hand,player_hand)
            play_again()
        elif choice == "q":
            print("Bye!")
            quit=True
            exit()


if __name__ == "__main__":
   game()

@patrick-ziemke
Copy link

I have updated a few aspects of this program. Mainly, I added a global and colorful wins/losses display that is updated after each round. I added the small feature of displaying your updated hand total after hitting. I also added the ability to choose number of decks of cards to use, because after 4 or 5 games it would run out of cards and the program would crash, so now you can choose number of cards.
Revised code below!

import os
import random

decks = input("Enter number of decks to use: ")

# user chooses number of decks of cards to use
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*(int(decks)*4)

# initialize scores
wins = 0
losses = 0

def deal(deck):
    hand = []
    for i in range(2):
        random.shuffle(deck)
        card = deck.pop()
        if card == 11:card = "J"
        if card == 12:card = "Q"
        if card == 13:card = "K"
        if card == 14:card = "A"
        hand.append(card)
    return hand

def play_again():
    again = input("Do you want to play again? (Y/N) : ").lower()
    if again == "y":
        dealer_hand = []
        player_hand = []
        deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*4
        game()
    else:
        print("Bye!")
        exit()

def total(hand):
    total = 0
    for card in hand:
        if card == "J" or card == "Q" or card == "K":
            total+= 10
        elif card == "A":
            if total >= 11: total+= 1
            else: total+= 11
        else: total += card
    return total

def hit(hand):
    card = deck.pop()
    if card == 11:card = "J"
    if card == 12:card = "Q"
    if card == 13:card = "K"
    if card == 14:card = "A"
    hand.append(card)
    return hand

def clear():
    if os.name == 'nt':
        os.system('CLS')
    if os.name == 'posix':
        os.system('clear')

def print_results(dealer_hand, player_hand):
    clear()

    print("\n    WELCOME TO BLACKJACK!\n")
    print("-"*30+"\n")
    print("    \033[1;32;40mWINS:  \033[1;37;40m%s   \033[1;31;40mLOSSES:  \033[1;37;40m%s\n" % (wins, losses))
    print("-"*30+"\n")
    print ("The dealer has a " + str(dealer_hand) + " for a total of " + str(total(dealer_hand)))
    print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand)))

def blackjack(dealer_hand, player_hand):
    global wins
    global losses
    if total(player_hand) == 21:
        print_results(dealer_hand, player_hand)
        print ("Congratulations! You got a Blackjack!\n")
        wins += 1
        play_again()
    elif total(dealer_hand) == 21:
        print_results(dealer_hand, player_hand)
        print ("Sorry, you lose. The dealer got a blackjack.\n")
        losses += 1
        play_again()

def score(dealer_hand, player_hand):
        # score function now updates to global win/loss variables
        global wins
        global losses
        if total(player_hand) == 21:
            print_results(dealer_hand, player_hand)
            print ("Congratulations! You got a Blackjack!\n")
            wins += 1
        elif total(dealer_hand) == 21:
            print_results(dealer_hand, player_hand)
            print ("Sorry, you lose. The dealer got a blackjack.\n")
            losses += 1
        elif total(player_hand) > 21:
            print_results(dealer_hand, player_hand)
            print ("Sorry. You busted. You lose.\n")
            losses += 1
        elif total(dealer_hand) > 21:
            print_results(dealer_hand, player_hand)
            print ("Dealer busts. You win!\n")
            wins += 1
        elif total(player_hand) < total(dealer_hand):
            print_results(dealer_hand, player_hand)
            print ("Sorry. Your score isn't higher than the dealer. You lose.\n")
            losses += 1
        elif total(player_hand) > total(dealer_hand):
            print_results(dealer_hand, player_hand)
            print ("Congratulations. Your score is higher than the dealer. You win\n")
            wins += 1

def game():
    global wins
    global losses
    choice = 0
    clear()
    print("\n    WELCOME TO BLACKJACK!\n")
    print("-"*30+"\n")
    print("    \033[1;32;40mWINS:  \033[1;37;40m%s   \033[1;31;40mLOSSES:  \033[1;37;40m%s\n" % (wins, losses))
    print("-"*30+"\n")
    dealer_hand = deal(deck)
    player_hand = deal(deck)
    print ("The dealer is showing a " + str(dealer_hand[0]))
    print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand)))
    blackjack(dealer_hand, player_hand)
    quit=False
    while not quit:
        choice = input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower()
        if choice == 'h':
            hit(player_hand)
            print(player_hand)
            print("Hand total: " + str(total(player_hand)))
            if total(player_hand)>21:
                print('You busted')
                losses += 1
                play_again()
        elif choice=='s':
            while total(dealer_hand)<17:
                hit(dealer_hand)
                print(dealer_hand)
                if total(dealer_hand)>21:
                    print('Dealer busts, you win!')
                    wins += 1
                    play_again()
            score(dealer_hand,player_hand)
            play_again()
        elif choice == "q":
            print("Bye!")
            quit=True
            exit()


if __name__ == "__main__":
   game()

@frzn4ever
Copy link

the win lose counter outputs:
�[1;32;40mWINS: �[1;37;40m1 �[1;31;40mLOSSES: �[1;37;40m0

@frzn4ever
Copy link

Also "welcome to blackjack" is duplicated in Print_results

@frzn4ever
Copy link

If you get a blackjack, the game just continues. duplicate code in score() and game()

@frzn4ever
Copy link

Play_again() resets the deck to a single deck.
deal() shuffles the deck every time it's called
there's no code for a "push" or a tie

@frzn4ever
Copy link

Here's what I got so far. I'm not sure about score(), is it necessary or well implemented enough?

wait how do I put my code here?

@FrancisFan98
Copy link

A bug found on total(hand)

if the hand is [9, "A", 9], the result should be 19 instead of 29.

Though I would not hit when I get a [9, "A"], but there is still a logical error in this situation

@Himan10
Copy link

Himan10 commented Nov 21, 2019

@FrancisFan98 hey man, wanna check mine version of blackjack using OOP in python...
I added both player and dealer hits (multiple times) with several conditions for both player and dealer about win and loss. I haven't added those functions -> split, double down and insurance but still implementation was good.
you can check it from here -> https://github.com/Himan10/Black-Jack

@datastare
Copy link

@FrancisFan98 hey man, wanna check mine version of blackjack using OOP in python...
I added both player and dealer hits (multiple times) with several conditions for both player and dealer about win and loss. I haven't added those functions -> split, double down and insurance but still implementation was good.
you can check it from here -> https://github.com/Himan10/Black-Jack

Tried it, but it's not working.. tried both python2 & 3

@arch-52factorial
Copy link

arch-52factorial commented Nov 24, 2019

I've come up with a version based on this. As my first python project, I don't think its half bad. Let's see what the 'net thinks lol

blackjack.py

from deck import Deck
import os
# from cards import Card
deck = Deck()
deck.shuffle()
player_hand = []
dealer_hand = []
won = 0
lost = 0
def clear():
    if os.name == 'nt':
        os.system('CLS')
    if os.name == 'posix':
        os.system('clear')
def deal():
    hand1 = []
    hand2 = []
    for i in range(2):
        deck.shuffle()
        hand1.append(deck.deal())
        hand2.append(deck.deal())
    hands = [hand1 , hand2]
    return hands
def hit():
    return deck.deal()
def play_again():
    global player_hand
    global dealer_hand
    again = input("Do you want to try another hand? (Y/n) :").lower()
    if again != "n":    #if our answer is not 'n' then we default to 'y'
        for i in dealer_hand:
            deck.return_card(i)
        for a in player_hand:
            deck.return_card(a)
        player_hand = []
        dealer_hand = []
        if deck.deck_count() != 52:
            print("Error in Function 'play_again()'. Deck count invalid.")
            exit()
        game();
    else:
        print("Goodbye...")
        exit()
def total(hand):
    total = 0
    for i in hand:
        if i.number == "Jack" or i.number == "Queen" or i.number == "King" :
            total += 10
        elif i.number == "Ace":
            if total >= 11: total +=1
            else: total += 11
        else:
            total += int(i.number)
    return total
def print_results(dealer_hand,  player_hand):
    clear()
    dstr = ""
    pstr = ""
    for i in dealer_hand:
        dstr += i.__repr__()
        dstr += " "
    for a in player_hand:
        pstr += a.__repr__()
        pstr += " "
    print("The Dealer's hand is " + dstr + ". With a total of: " + str(total(dealer_hand)))
    print("Your hand is " + pstr + ". With a total of: " + str(total(player_hand)))
def blackjack(dealer_hand,  player_hand):
    global won
    global lost
    if total(player_hand) == 21:
        print_results(dealer_hand,  player_hand)
        print("Blackjack... Congratulations")
        won += 1
        play_again()
    elif total(dealer_hand) == 21:
        print_results(dealer_hand,  player_hand)
        print("Bad luck... The Dealer has Blackjack!")
        lost += 1
        play_again()
def score(td,  tp):
    global won
    global lost
    if tp <= 21:
        if td <= 21:
            if td < tp:
                won += 1
                print_results(dealer_hand,  player_hand)
                x = 0
                for i in player_hand:
                    x += 1
                if x == 5 and tp == 21:
                    print("5 Card Trick!")
                print("Congratulations... You Win.")
                play_again()
            elif td > tp:
                lost += 1
                print_results(dealer_hand,  player_hand)
                print("Bad luck... The Dealer won.")
                play_again()
            else:
                print_results(dealer_hand,  player_hand)
                print("A Draw...")
                play_again()
        else:
            won += 1
            print_results(dealer_hand, player_hand)
            print("The Dealer is Bust... You Win.")
            play_again()
    else:
        lost += 1
        print("You are Bust...")
        play_again()
def game():
    global won
    global lost
    global dealer_hand
    global player_hand
    choice = 0
    clear()
    print("Welcome to Blackjack")
    print(" Games Won: %s  Games Lost: %s" % (won,  lost))
    hands = deal()
    dealer_hand = hands.pop()
    player_hand = hands.pop()
    print("The Dealer is showing the " + dealer_hand[1].__repr__())
    hstr = ""
    for i in player_hand:
        hstr += i.__repr__()
        hstr += " "
    print ("")
    print("Your hand is: " + hstr + " for a total of " + str(total(player_hand)))
    blackjack(dealer_hand,  player_hand)
    while choice != "q":
        choice = input("Do you want to [H]it, [S]tick, or [Q]uit: ").lower()
        if choice == "q":
            print("Goodbye... See you soon...")
            exit()
        elif choice == "h":
            card = hit()
            player_hand.append(card)
            tp = total(player_hand)
            print(card.__repr__() + "  new total is " + str(tp))
            if tp > 21:
                score(total(dealer_hand),  tp)
        else: #make [S]tick the default option
            while total(dealer_hand) < 17:
                dealer_hand.append(hit())
            score(total(dealer_hand),  total(player_hand))
if __name__ == "__main__":
    game()

deck.py

from cards import Card
import random
class Deck:
    def __init__(self):
        self._cards = []
        self.populate()
        #print(self._cards)
    def populate(self):
        suits = ["hearts", "clubs", "diamonds", "spades"]
        numbers = [str(n) for n in range(2,11)] + ["Jack","Queen","King","Ace"]
        self._cards = [Card(s, n) for s in suits for n in numbers]
    def shuffle(self):
        random.shuffle(self._cards)
    def deal(self):
        return self._cards.pop()
    def return_card(self, card):
        if card in self._cards:
            print("Error card already in deck.")
        self._cards.append(card)
    def deck_count(self):
        c = 0
        for i in self._cards:
            c += 1
        return c
# Test Code Area
#d = Deck()
#print(str(d.deck_count()))

cards.py

#UTF-8 Encoding
class Card:
    def __init__(self, suit, number):
        self._suit = suit
        self._number = number
    def __repr__(self):
        return self.number + " of " + self.suit
    @property
    def suit(self):
        return self._suit
    @property
    def number(self):
        return self._number
    @suit.setter
    def suit(self, suit):
        if suit in ["hearts", "clubs", "diamonds", "spades"]:
            self._suit = suit
        else:
            print("Invalid Suit")
    @number.setter
    def number(self, number):
        if number in ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]:
            self._number = number
        else:
            print("Invalid Face Value")
# Test Code Area    
#my_card = Card("Spades", "Ace")
#my_card.suit = "dinosaur"
#my_card.number = 3.14159
#print(my_card)

@Himan10
Copy link

Himan10 commented Nov 24, 2019

@datastare no man, it's working fine... some of my friends tried it several times.
okay tell me this, have you tried to run this file on the command line? using python interpreter, I mean just like this
python -i blackjack.py
let me call main() at the end of my code .. and either you need to download the repo. or copy the code from my repo. coz i added some new functions to it. Here we go again -> https://github.com/Himan10/BlackJack
Thankyou

@datastare
Copy link

@datastare no man, it's working fine... some of my friends tried it several times.
okay tell me this, have you tried to run this file on the command line? using python interpreter, I mean just like this
python -i blackjack.py
let me call main() at the end of my code .. and either you need to download the repo. or copy the code from my repo. coz i added some new functions to it. Here we go again -> https://github.com/Himan10/BlackJack
Thankyou

@Himan10
I had run from command line...
Just pulled the code down again and ran it.. Works great.
Nicely done!!
Thank You.

@datastare
Copy link

@Himan10

Here is something you can add.

When the Player is dealt "21" and the dealer "first" card is showing anything other than a 10 or an Ace, it's going to be an automatic BJ for the player. No need for the Player to "HIT or STAND or DOUBLE"

In the example below, there is ZERO chance the dealer will also have a BJ, so game function should go directly to "PLAYER_WINS"
However, if the Dealer is showing a 10 or 11 as first card, then game should automatically proceed to see if the 2nd card makes a BJ for the dealer, in which case it would be a PUSH.. Player does not lose bet amount.

Also, Casinos pay 3 to 2 when player hits "BlackJack"
Since the "Amount to Bet" = $20
The the payout should be = $30 (not $20)
the formula is bet_amount * 1.5

-----------GAME PLAY---------------
Player Balance:$ 1000
Amount to Bet: $ 20

----->
PLAYER CARDS [21] : [('Hearts', 'Ace'), ('Spades', 'Ten')]
DEALER CARDS [2] : [('Diamonds', 'Two')]
----->

[ HIT | STAND | SURRENDER | DOUBLE ] : stand

----->
PLAYER_CARDS [21] : [('Hearts', 'Ace'), ('Spades', 'Ten')]
DEALER_CARDS [17] : [('Diamonds', 'Four'), ('Diamonds', 'Two'), ('Diamonds', 'Ace'), ('Clubs', 'Ten')]
----->

---- PLAYER_WINS -----

Player Balance: $1020

Player Balance should be $1030

Again, great work !!

@Himan10
Copy link

Himan10 commented Nov 25, 2019

@datastare Thank you so much sir that you actually liked it... yeah that's right, the user will be rewarded in a ratio 3:2 for a BlackJack condition (if dealer cards are below than value 10 or 11) and yeah '$' sign, that looks pretty good, am going to add this in code.. but one thing I want to ask i.e., is the code looks so much complicated/odd/ugly (in terms of readability or say dealing with robust input) ?

@goodpvp90
Copy link

Hey,
i announced problem in total calculation
if "A" is coming on hand first or second and you keep hitting ( which not working well also ), it keeps the "A" to be 11 then being 1 and total going up then 21.
i've edited this way, i hope its correct :
def total(hand):
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total += 10
elif card == "A":
total += 11
else:
total += int(card)
if 'A' in hand and total > 21:
total -= 10
return total

@Himan10
Copy link

Himan10 commented Jan 11, 2020

@goodpvp90 if you mentioned the problem in my code then I had already changed the adjust_for_ace() function. Means now our value can grow/shrink based on Ace current value (either 11 or 1)

@jukujala
Copy link

I reused this code to create an environment simulator for Reinforcement Learning agents: https://gist.github.com/jukujala/eb86e6fcd1570340d1b4171b440e3ca5

@meneerferment
Copy link

my blackjack project

python 3.6.5

in Dutch

extra features as:

multiple players

insurance

splitting

scamming

enjoy

exec(open("fin1.py").read())

import numpy as np

class BlackJack:
print('| | ----------------------------------------------------------------------------------------------------------------------------')
print('| | Welkom in het speelhuis, heeft U uw creditcard bij U?, uw startbedrag bedraagt $100, daarvan kunt U vrijelijk gebruik maken.')
print('| |-----------------------------------------------------------------------------------------------------------------------------')
# kaarten
suit = ('Harten', 'Ruiten', 'Klaveren', 'Schoppen')
value = ('aas','2','3','4','5','6','7','8','9','10','boer','vrouw','heer')

index = [None] * 52
for i in range(4):
	for j in range(13):
		index[i*13+j] = [i, j]

def __init__(self):
	# self.parameters
	
	# aantal spelers, default:3 (zonder vraag een speler)
	testversie = False

	vraag1 = False
	vraagnaam = False
	self.vraagInzet = False

	if testversie == False:
		vraag1 = True
		vraagnaam = True
		self.vraagInzet = True
	else:
		print('| |')
		print('TESTVERSIE')

	self.aantalSpelers = 6

	
	if vraag1:
		self.vraagAantalSpelers()  
	
	self.aantalSpelersOrig = self.aantalSpelers
	self.saldo =     [100] * (self.aantalSpelers +1)

	self.saldoOud =   [0] * (self.aantalSpelers +1)
	self.saldoNieuw = [0] * (self.aantalSpelers +1)


	self.namen = [''] * self.aantalSpelers
	self.namen.append('De dealer')
	self.namenFil = [''] *(self.aantalSpelers + 1)

	for i in range(0, self.aantalSpelers):
		self.namen[i] = 'Henkie ' + str(i)

	self.bankrekeningnummer = [''] * self.aantalSpelers
	self.pincode = [0] * self.aantalSpelers

	if vraagnaam:
		self.vraagNamen()

	self.namenOrig = [''] * (self.aantalSpelers +1)

	for i in range(0, self.aantalSpelers+1):
		self.namenFil[i] =self.namen[i]
		self.namenOrig[i] = self.namen[i]

	self.game()

	if testversie == False:
		self.scam()


	
def game(self):
	# nieuw spel
	self.insurantie = False
	self.beurt = 0

	self.puntLijst = [0] * (self.aantalSpelers + 1 )
	self.bestscore = [0] * (self.aantalSpelers + 1)
	self.kaartAantal = [0] * (self.aantalSpelers + 1 )   
	self.aasAantal = [0] * (self.aantalSpelers + 1 )
	self.blackjack = [False] * (self.aantalSpelers + 1) 
	self.levend = [True] * (self.aantalSpelers + 1)
	self.gewonnen = [False] * (self.aantalSpelers + 1)
	self.gesplitst = [False] * (self.aantalSpelers + 1)

	self.lotLijst = []
	self.wiens = []
	self.aasLijst = []
	self.waardeLijst = []


	self.verzekeringAntwoord = [True] * (self.aantalSpelers + 1)
	self.gepast = [False] * (self.aantalSpelers + 1)

	self.inzet = [5] * (self.aantalSpelers + 1)
	self.winst = [0] * (self.aantalSpelers + 1)

	self.status = [''] * (self.aantalSpelers +1)
	self.saldoOP = ['']* (self.aantalSpelers +1)
	self.saldoNP = ['']* (self.aantalSpelers +1)
	self.inzetP = [''] * (self.aantalSpelers +1)
	self.winstP = [''] * (self.aantalSpelers +1)

	self.inzet[self.aantalSpelers]      = 'n/a'
	self.winst[self.aantalSpelers]      = 'n/a'
	self.saldo[self.aantalSpelers]      = 'n/a'
	self.saldoOud[self.aantalSpelers]   = 'n/a'
	self.saldoNieuw[self.aantalSpelers] = 'n/a'





	if self.vraagInzet:
		self.hoeveelInzet()
	
	for i in range(0, len(self.saldo)):
		if i == self.aantalSpelers:
			pass
		else:
			self.saldoOud[i] = self.saldo[i]
			self.saldo[i] += - self.inzet[i]

	print("| |")
	print('| | De kaarten worden geschud.')
	print("| |")
	self.eersteKaarten()
	self.emiel()
	self.controleerblackjack()
	self.verzekering()
	self.standoff()

	self.split()


	if self.blackjack[-1] == True:
		pass 
	else:
		self.uitkeer()
		print('| |')
		self.keuze()
		print('| |')
		self.huis()
		self.winnaar()
		print('| |')
		
	self.clear()
	self.nogmaals()

def scam(self, iteration = 0):
	if iteration == 0:
		print('| |')
		print('| | Uw saldi worden overgemaakt naar uw rekeningen.')
		print('| |')
	for i in range(iteration, self.aantalSpelers):
		antwoord1 = input('| | Beste ' + self.namen[i] + '. Wat is uw bankrekeningnummer? \n| | ')
		antwoord2 = input('| | pincode? \n| | ')

		self.bankrekeningnummer[i] = antwoord1
		try:
			self.pincode[i] = int(antwoord2)
		except:
			print('| | Beste ' + self.namen[i] + '. Uw bankgegevens zijn niet gevonden in onze database. Wilt U zo vriendelijk zijn ze opnieuw in te toetsen?')
			self.scam(i)
			break

def nogmaals(self, iteration = 0):
	antwoord = input('| | Nogmaals een gokje wagen? \n| | ')
	if antwoord == 'y':
		self.game()

	elif antwoord =='n':
		print('| |Wij zien u graag binnenkort terug in Emiel\'s Speelhuis')
	else:
		print("| | antwoord: y/n")
		self.nogmaals()

def uitkeer(self):
	for i in range(0, self.aantalSpelers):
		if self.blackjack[i] == True:
			self.saldo[i] += (3 * self.inzet[i])
			self.winst[i] =  (2 * self.inzet[i])
			print('| | Wow, geeerde ' + str(self.namen[i]) +', uw heeft BLACKJACK, uw ontvangt drievoudig uw inzet, dat is $' + str(self.inzet[i]*3) + 'en uw saldo bedraagt nu:$' +str(self.saldo[i]))

def standoff(self):
	if self.insurantie == True:
		print('| |')
		print('| |De gesloten kaart van de dealer blijkt een : ' + self.lotLijst2String(2 * self.aantalSpelersOrig + 1))
		print('| |')
		self.printHand(self.aantalSpelers)
		if self.blackjack[-1] == True:
			for i in range(0, self.aantalSpelers):
				if self.blackjack[i] == True:
					self.winst[i] = 0
					self.saldo[i] += self.inzet[i]
					print('| | Er is een standoff met speler ' + str(i+1) + ', u behoud uw inzet, uw saldo bedraagt nu:$' +str(self.saldo[i]))
				else:
					print('| | Geeerde ' + str(self.namen[i]) + ', u verliest, uw saldo bedraagt nu:$' +str(self.saldo[i]))
					self.winst[i] = - self.inzet[i]

def verzekering(self, iteration = 0):
	openKaartDealer = len(self.lotLijst) - 2

	if self.waardeLijst[openKaartDealer] == 1 or self.waardeLijst[openKaartDealer] == 10:
		print('| | Verzekering')
		print('| | ------------')
		print('| | Het huis heeft kans op blackjack, wenst u door te spelen? U zult uw inzet terugkrijgen wanneer U nu stopt')
		
		self.insurantie = True
		for i in range(iteration, self.aantalSpelers):
			if self.blackjack[i] == True:
				pass
			else:
				antwoord = input('| | Zeer gewaardeerde ' + str(self.namen[i]) + ', wenst u door te speler?\n| | ')
				if antwoord == 'y':
					 self.verzekeringAntwoord[i] = True 
				elif antwoord =='n':
					self.inzet[i] = 0
					self.winst[i] = 0
					self.saldo[i] = self.saldoOud[i]
					self.verzekeringAntwoord[i] = False
				else:
					print("| | Antwoord: y/n")
					self.verzekering(i)
					break

def printEersteKaarten(self, message = 0):
	kaartenlijst = [''] * len(self.lotLijst)
	
	kaart1 = [''] * (self.aantalSpelers + 1)
	kaart2 = [''] * (self.aantalSpelers + 1)
	

	filler = 16
	s = ['-' * filler] * (self.aantalSpelers + 1)

	for i in range(0, len(self.lotLijst)):
		kaartenlijst[i] = self.lotLijst2String(i)

	for i in range(0, self.aantalSpelers + 1):
		kaart1[i] = kaartenlijst[2 * i]
	
	for i in range(self.aantalSpelers):
		kaart2[i] = kaartenlijst[2 * i + 1]
	
	kaart2[-1] = 'Gesloten'

	for i in range(0, self.aantalSpelers + 1):  
		fill = filler-len(kaart1[i])
		kaart1[i] += ' '* fill

		fill = filler-len(kaart2[i])
		kaart2[i] += ' '* fill

		fill = filler-len(self.namenFil[i])
		self.namenFil[i] += ' '* fill

	print('|', * self.namenFil, sep = " | ") 
	print('|', * s, sep = ' | ')
	print('|', * kaart1, sep = " | ") 
	print('|', * kaart2, sep = " | ") 
	print('| |')

def clear(self):
	for i in range(0, self.aantalSpelersOrig):
		if self.gesplitst[i]:
			self.puntLijst.pop(i)
			self.bestscore.pop(i)
			self.kaartAantal.pop(i)
			self.aasAantal.pop(i)
			self.blackjack.pop(i)
			self.levend.pop(i)
			self.gewonnen.pop(i)
			self.verzekeringAntwoord.pop(i)
			self.gepast.pop(i)
			self.inzet.pop(i)
			self.saldo.pop(i)
			self.saldoOud.pop(i)
			self.saldoNieuw.pop(i)
			self.status.pop(i)
			self.winst.pop(i)
			self.saldoOP.pop(i)
			self.saldoNP.pop(i)
			self.inzetP.pop(i)
			self.winstP.pop(i)

			self.namen.pop(i)
			self.namenFil.pop(i)

	self.aantalSpelers = self.aantalSpelersOrig

	for i in range(0, self.aantalSpelers):
		self.namenFil[i] = self.namenOrig[i]
		self.namen[i] = self.namenOrig[i]

	self.namenFil[self.aantalSpelers] = self.namen[self.aantalSpelers]


	
	

def splitsen(self, i, kaart):
	waarde = 0

	self.gesplitst[i] = True

	if kaart == 0 :
		waarde = 1
	elif kaart >= 9:
		waarde = 10
	else:
		waarde = kaart + 1 

	self.aantalSpelers += 1


	for k in range(0, len(self.lotLijst)):
		if k > 2 * i:
			self.wiens[k] += 1

	self.puntLijst.insert(i, waarde)
	self.puntLijst[i+1] = waarde

	if waarde == 1:
		waarde = 11
	self.bestscore.insert(i, waarde)
	self.bestscore[i+1] = waarde

	self.kaartAantal.insert(i, 1)
	self.kaartAantal[i+1] = 1

	if kaart == 0:
		self.aasAantal.insert(i, 1)
		self.aasAantal[i+1] = 1
	else:
		self.aasAantal.insert(i, 0)
	
	self.blackjack.insert(i, False)
	self.levend.insert(i, True)
	self.gewonnen.insert(i, False)
	self.verzekeringAntwoord.insert(i, True)
	self.gepast.insert(i, False)

	self.inzet.insert(i, 25)

	self.saldo.insert(i, 'n/a')
	self.saldoOud.insert(i, 'n/a')
	self.saldoNieuw.insert(i, 'n/a') 

	self.winst.insert(i, 0)

	self.status.insert(i, [''])
	self.saldoOP.insert(i, [''])
	self.saldoNP.insert(i, [''])
	self.inzetP.insert(i, [''])
	self.winstP.insert(i, [''])

	self.namen.insert(i, self.namen[i] + ' Splt1')
	self.namen[i+1] += ' Splt2'
	
	self.namenFil.insert(i, '')



	self.saldoOud[i] = 'n/a'
	self.saldoNieuw[i] = 'n/a'

def vraagSplits(self, i, kaart):
	antwoord = input('| | Heer ' + str(self.namen[i]) + ', splitsen?\n| | ')
	if antwoord == 'y':
		self.splitsen(i, kaart)
	elif antwoord =='n':
		print('| |u kiest niet te splitsen')
	else:
		print('| | Antwoord: y/n')
		self.vraagSplits(i, kaart)
			



def split(self, iteration = 0):
	for i in range(0, self.aantalSpelers):
		kaart = self.lotLijst[2*i]%13
		if (self.lotLijst[2*i]%13) == (self.lotLijst[2*i+1]%13):
			if kaart == 0:
				self.splitsen(i, kaart)
				print('| | Dubbele azen, gedwongen splits')
				# print('| | gedwongen splits')
			else:
				print('| |keuze op te splitsen')
				self.vraagSplits(i, kaart)
				# # self.splitsen(i, kaart)
				# try:
				# 	if self.saldo[i] < (self.saldo[i] - self.inzet[i]):
				# 		print(self.namen[i] + 'U heeft niet genoeg saldo om te splitsen')
				# 	else:
				# 		print('| | U kunt splitsen, u saldo is toereikend genoeg, kies de inzet per splits')
				# except:
					# print(self.saldo[i])

def eersteKaarten(self):
	for i in range(0, self.aantalSpelers):
		self.geef(2, False)
	self.geef(1, False)
	self.geef(1, False)
	self.printEersteKaarten()

def lotLijst2String(self, nummer):
	a = self.lotLijst[nummer]
	A = self.index[a]
	S = self.suit[A[0]]
	V = self.value[A[1]]
	kaartstring = S + ' ' + V
	return kaartstring

def test5(self):
	print('| |')
	for i in range(0, self.aantalSpelers):
		print('| | Speler no' + str(i +1) + ', gepast ' + str(self.gepast[i]) + ', saldo ' + str(self.saldo[i]) + ', inzet ' + str(self.inzet[i]) + ', levend ' + str(self.levend[i]) + ', azen:' + str(self.aasAantal[i]) + ', blackjack:' + str(self.blackjack[i]) + ', verzekering: ' + str(self.verzekeringAntwoord[i]) + ', punten: ' + str(self.puntLijst[i]))
	
	print('| | Uw huis, levend ' + str(self.levend[-1]) + ', azen:' + str(self.aasAantal[-1]) + ', blackjack ' + str(self.blackjack[-1]) + ', punten: ' + str(self.puntLijst[-1]) )   

def test3(self):
	print('| |')
	print('| | beurt, voor wie, kaart')
	for i in range(0, len(self.lotLijst)):
		print(i, self.wiens[i], self.lotLijst2String(i))

def test(self):
	print('lotLijst, waardeLijst, puntLijst, wiens, aasLijst, inzet, aasAantal, puntLijst')
	print(self.lotLijst)
	print(self.waardeLijst)
	print(self.puntLijst)
	print(self.wiens)
	print(self.aasLijst)
	print(self.inzet)
	print(self.aasAantal)
	print(self.puntLijst)
   
def vraagAantalSpelers(self):
	antwoord = input('| | Uw gezelschap bestaat uit hoeveel spelers?\n| | ')
	try:
		self.aantalSpelers  = int(antwoord)
	except:
		print("| | Ai mattie, moet gewoon een getal intikken noh")
		self.vraagAantalSpelers()
		
	if self.aantalSpelers > 18:
		print('| | Uw speelt met een te groot gezelschap, verdeel U in tweetallen')
		self.vraagAantalSpelers()

def vraagNamen(self):
		for i in range(0, self.aantalSpelers):
			if i == 0:
				self.namen[i]  = input('| | Mijn ' + str(i + 1) + 'ste' + ' heer, hoe luidt uw naam?\n| | ')
			else:
				self.namen[i]  = input('| | Mijn ' + str(i + 1) + 'de' + ' heer, hoe wenst u aangesproken te worden?\n| | ')
	
def hoeveelInzet(self, iteration = 0):
		for i in range(iteration, self.aantalSpelers):    
			if i == 0:
				antwoord = input('| | Geeerde heer ' + str(self.namen[i]) + '. Hoeveel florino\'s wilt u te spel brengen?\n| | ')
			else:
				antwoord = input('| | Mijn heer ' + str(self.namen[i]) + '. Hoeveel florino\'s wilt u te spel brengen?\n| | ')
			try:
				self.inzet[i] = int(antwoord)
			except:
				print("| | Wilt uw zo vriendelijk zijn uw bedrag zonder dollarteken in te toetsen")
				self.hoeveelInzet(i)
				break
	   
def geef(self, X = 1, latenzien = True):
	for i in range (0, X):
		self.trek(latenzien)
		self.lotLijst8()
		self.wiens8()
		self.combi8()
		self.controleerlevend()

def trek(self, latenzien = True):
	self.nummer = np.random.randint(0,52)     
	self.alGetrokken()
	self.lotLijst.append(self.nummer)
	if latenzien == True:
		print('| | De gekochte kaart is een ' + self.lotLijst2String(len(self.lotLijst) -1))
	
def alGetrokken(self):
	if self.nummer in self.lotLijst:
			self.nummer = np.random.randint(0,52)
			self.alGetrokken()

def hit(self, iteration): 
	self.beurt = iteration
	self.geef()
	# self.keuze(iteration)

def lotLijst8(self):
	laatste = self.lotLijst[-1]
	waarde = laatste % 13

	if waarde == 0:
		self.aasLijst.append(True)
	else:
		self.aasLijst.append(False)

	if waarde >= 9:
		waarde = 10
	elif waarde == 0:
		waarde = 1
	else:
		waarde += 1 
	self.waardeLijst.append(waarde)
	
def wiens8(self):
	kaart = len(self.lotLijst)
	if kaart <= (2 * self.aantalSpelersOrig + 2):
		self.wiens.append(((kaart+1)//2)-1)
	else:
		self.wiens.append(self.beurt)

	self.kaartAantal[self.wiens[-1]] += 1

def combi8(self):
	waarde = self.waardeLijst[-1]
	wie = self.wiens[-1]

	self.puntLijst[wie] += waarde

	if self.aasLijst[-1] == True:
		self.aasAantal[wie] += 1
	else:
		pass

	for i in range(0, (self.aantalSpelers + 1)):
		self.bestscore[i] = self.puntLijst[i]   
		if self.aasAantal[i] == 0:
			pass
		elif self.puntLijst[i] < 12:
			self.bestscore[i] += 10


def printHand(self, iteration):
	print('| |')
	hand = []  
	for i in range(0, len(self.lotLijst)):
		if self.wiens[i] == iteration:
			# print(self.lotLijst2String(i))
			hand.append(self.lotLijst2String(i))

	print('| |', self.namen[iteration] )
	print('| | ---------', *hand, sep = ' \n| | ')
	print('| | ---------')

	if self.blackjack[iteration]:
		print('| | BLACKJACK')
	elif self.verzekeringAntwoord[iteration] == False:
		print('| | Gevlucht; ' + str(self.bestscore[iteration]))
	elif self.gepast[iteration]:
		print('| | Gepast: '  + str(self.bestscore[iteration]))
	elif self.levend[iteration] == False:
		print('| | Dood: '  + str(self.bestscore[iteration]))          
	else:
		print('| | Punten: ' +str(self.bestscore[iteration]))
	print('| |')

def printScore(self):
	
	for i in range(0, self.aantalSpelers + 1):
	
		self.saldoOP[i] = 'Oud saldo: $' + str(self.saldoOud[i])
		self.saldoNP[i] = 'New saldo: $' + str(self.saldo[i])
		self.inzetP[i] = 'Inzet: $' + str(self.inzet[i])
		self.winstP[i] = 'Winst: $' + str(self.winst[i])

		if self.blackjack[i]:
			self.status[i]  = 'Blackjack'
		elif self.verzekeringAntwoord[i] == False:
			self.status[i]  ='Gevlucht: ' + str(self.bestscore[i])
		elif self.gewonnen[i]:
			self.status[i] = 'Gewonnen: ' + str( self.bestscore[i])
		elif self.levend[i] == False:
			self.status[i]  ='Dood: '  + str(self.bestscore[i])
		else:
			self.status[i] = 'Verloren: ' +str(self.bestscore[i])
			self.winstP[i] = 'Verlies: $' + str((-1*self.winst[i]))

	self.status[self.aantalSpelers] = 'Punten: ' +str(self.bestscore[i])
	
	
	filler = 16


	s = ['-' * filler] * (self.aantalSpelers + 1)

	for i in range(0, self.aantalSpelers + 1):

		self.namenFil[i] = self.namen[i]
		
		fill = filler-len(self.status[i])
		self.status[i] += ' '* fill

		fill = filler-len(self.saldoOP[i])
		self.saldoOP[i] += ' '* fill

		fill = filler-len(self.inzetP[i])
		self.inzetP[i] += ' '* fill

		fill = filler-len(self.winstP[i])
		self.winstP[i] += ' '* fill

		fill = filler-len(self.saldoNP[i])
		self.saldoNP[i] += ' '* fill

		fill = filler - len(self.namen[i])
		self.namenFil[i] += ' ' * fill

		# fill = filler-len(self.namenFil[i])
		# self.namenFil[i] += ' ' * fill

	self.saldoOP[self.aantalSpelers] = 'n/a'
	self.saldoNP[self.aantalSpelers] = 'n/a'
	self.inzetP[self.aantalSpelers] = 'n/a'
	self.winstP[self.aantalSpelers] = 'n/a'


	print('|', *self.namenFil, sep = ' | ' )
	print('|', *s, sep = ' | ')
	print('|', *self.status, sep = ' | ')
	print('|', *self.saldoOP, sep = ' | ')
	print('|', *self.inzetP, sep = ' | ')
	print('|', *self.winstP, sep = ' | ')
	print('|', *self.saldoNP, sep = ' | ')
	print('| |')
	

 
def keuze(self, iteration = 0):
	for i in range(iteration, self.aantalSpelers):
		print('| |')        
		if self.levend[i] == False:   
			self.printHand(i)
		elif self.gepast[i] == True:
			print('| | ' + self.namen[i] + ' uw bent gepast met ' + str(self.bestscore[i]) + ' punten, jammer he.')    
			self.printHand(i)
		elif self.verzekeringAntwoord[i] == False:
			print('| | ' + self.namen[i] + ' u bent weg met ' + str(self.bestscore[i]) + ' punten, jammer he.')    
			self.printHand(i)
		elif self.blackjack[i] == True:
			self.printHand(i)
		else:
			self.printHand(i)
			antwoord = input('| | Heer ' + str(self.namen[i]) + ', hit me?\n| | ')
			if antwoord == 'y':
				self.hit(i)
				self.keuze(i)
				break
			elif antwoord =='n':   
				self.gepast[i] = True
				self.printHand(i) 
			else:
				print('| | Antwoord: y/n')
				self.keuze(i)
				break
				
def controleerlevend(self):
	for k in range(0, self.aantalSpelers + 1):
		if self.puntLijst[k] > 21 :
			self.levend[k] = False            

def controleerblackjack(self):
	for i in range(0, self.aantalSpelers + 1):
		if self.puntLijst[i] == 11 and self.aasAantal[i] == 1:
			self.blackjack[i] = True             

def winnaar(self):
	huisscore = self.bestscore[self.aantalSpelers]
	
	
	
	print('| |')  

	for i in range(0, self.aantalSpelers):
		if self.blackjack[i] == True:
			# print('| | Mijnheer ' + str(i+1) + ', wederom gefeliciteerd met uw blackjack. Mogen wij U een aangenaam verstrooiing toewensen')
			pass
		elif self.verzekeringAntwoord[i] == False:
			pass
			# print('| | Speler no' +str(i+1) + ', uw score is ' + str(self.bestscore[i])+ ', u bent gevlucht, uw saldo bedrag nogsteedsS:$' +str(self.saldo[i])) 
		
		elif huisscore > 21:
			if self.bestscore[i] > 21:
				self.winst[i] = 0
				self.saldo[i] = self.saldoOud[i]
				# print('| | Speler no' + str(i+1) + ', uw score is ' + str(self.bestscore[i]) + ', uw bent dood, heeft uw inzet terug, uw saldo bedrag nu:$' +str(self.saldo[i]))
			else:
				if self.gesplitst[i] == False:
					self.saldo[i] += (2*self.inzet[i])
				self.gewonnen[i] = True
				self.winst[i] = self.inzet[i]
				# print('| | Speler no' + str(i+1) + ', uw score is ' + str(self.bestscore[i])+ ', uw leeft en wint, uw saldo bedrag nu:$' +str(self.saldo[i]))
		
		elif self.bestscore[i] > huisscore:
			if self.bestscore[i] > 21:
				self.winst[i] =  -self.inzet[i]
				# print('| | Speler no' + str(i+1) + ', uw score is ' + str(self.bestscore[i]) + ', uw bent dood, uw saldo bedrag nu:$' +str(self.saldo[i]))                
			else:
				if self.gesplitst[i] == False:
					self.saldo[i] += (2*self.inzet[i])
				self.winst[i] = self.inzet[i]
				self.gewonnen[i] = True
				# print('| | Speler no' + str(i+1) + ', uw score is ' + str(self.bestscore[i]) +  ', uw heeft gewonnen, uw saldo bedrag nu:$' +str(self.saldo[i]))
		else:
			self.winst[i] = -self.inzet[i]
			# print('| | Speler no' + str(i+1) + ', uw eindscore is ' + str(self.bestscore[i]) + ', uw heeft verloren, uw saldo bedrag nu:$' +str(self.saldo[i]))
		
		if self.gesplitst[i]:
			self.saldo[i+1] += self.winst[i]

	for i in range(0, self.aantalSpelers):
		self.saldoNieuw[i] = self.saldo[i]

	print('| |')
	self.printScore()
				
def huis(self):

	if self.kaartAantal[-1] == 2 and self.insurantie == False:
		self.printHand(self.aantalSpelers)
	
	print('| |')
	if self.blackjack[-1] == True:
		print('| | standoff-error')
		print('| | 2de: ' + self.lotLijst2String(2* self.aantalSpelers +1))
		print('| | 1ste: ' + self.lotLijst2String(2* self.aantalSpelers))
	elif self.bestscore[-1] < 17:
		print('| | Ach so, hehe, das Haus kauft, jawohl.:')
		self.hit(self.aantalSpelers)
		self.printHand(self.aantalSpelers)
		self.huis()
	else:
		pass

def emiel(self):
	for i in range(0, self.aantalSpelers):
		if self.namen[i] == 'emiel' or self.namen[i] =='Emiel':
			self.saldo[i] += 50

if name == "main":
c = BlackJack()

@Himan10
Copy link

Himan10 commented Apr 16, 2020

@meneerferment hey, I'm interested in playing the blackjack version which you've created but it seems like it have some errors related to proper formatting the code.. so, would you like to give us proper code or a Github repo. link where you uploaded it.
Thank you.

@meneerferment
Copy link

meneerferment commented Apr 16, 2020 via email

@getmehire
Copy link

Here is my take. Compatible with Python 3.8
BlackJack Game in Python 3.8 By Ahmed Q.

@PrometheusAndBob
Copy link

How would we do this with a dictionary instead of a list?

@bettybel
Copy link

cool cool

thanks for that piece of code)

@TheodoreR-cpu
Copy link

TheodoreR-cpu commented Aug 18, 2021

I like it. Looks good

@smizers
Copy link

smizers commented Nov 23, 2021

Guys, thanks for that. It was interesting to me and I found it! I have been programming for online casinos for a long time and I cooperate with the review service https://casinotop.pt/deposito-minimo-1-euros/ because working with a minimum deposit of 1 euro is quite profitable. I love programming and entertainment so the combination of these two elements is great.

@marcelo321
Copy link

It is missing the ability to split and double

@ARETARD1945
Copy link

if I bet 99 and win i get 199 instead of 200 so it doesnt render the 1 money

@Kentcas
Copy link

Kentcas commented Nov 25, 2022

Can someone check this? I can't figure out what's wrong. I can't get past the dealing cards phase. It just keeps running but doesn't move forward to the next step to ask me to hit or stand.

import random
import os

The Card class definition

class Card:
def init(self, suit, value, card_value):

    # Suit of the Card like Spades and Clubs
    self.suit = suit

    # Representing Value of the Card like A for Ace, K for King
    self.value = value

    # Score Value for the Card like 10 for King
    self.card_value = card_value

Clear the terminal

def clear():
os.system("clear")

Print player stats

def print_stats(player_name, funds, wins, losses, ties, blackjacks, busts):
print('Player: ', player_name)
print('Funds: $', funds)
print(f'Wins: {wins} Losses: {losses} Ties: {ties} Blackjacks: {blackjacks} Busts: {busts}')

Function to print the cards

def print_cards(cards, hidden):

s = ""
for card in cards:
    s = s + "\t ________________"
if hidden:
    s += "\t ________________"
print(s)


s = ""
for card in cards:
    s = s + "\t|                |"
if hidden:
    s += "\t|                |"    
print(s)

s = ""
for card in cards:
    if card.value == '10':
        s = s + "\t|  {}            |".format(card.value)
    else:
        s = s + "\t|  {}             |".format(card.value)  
if hidden:
    s += "\t|                |"    
print(s)

s = ""
for card in cards:
    s = s + "\t|                |"
if hidden:
    s += "\t|      * *       |"
print(s)    

s = ""
for card in cards:
    s = s + "\t|                |"
if hidden:
    s += "\t|    *     *     |"
print(s)    

s = ""
for card in cards:
    s = s + "\t|                |"
if hidden:
    s += "\t|   *       *    |"
print(s)    

s = ""
for card in cards:
    s = s + "\t|                |"
if hidden:
    s += "\t|   *       *    |"
print(s)    

s = ""
for card in cards:
    s = s + "\t|       {}        |".format(card.suit)
if hidden:
    s += "\t|          *     |"
print(s)    

s = ""
for card in cards:
    s = s + "\t|                |"
if hidden:
    s += "\t|         *      |"
print(s)    

s = ""
for card in cards:
    s = s + "\t|                |"
if hidden:
    s += "\t|        *       |"
print(s)

s = ""
for card in cards:
    s = s + "\t|                |"
if hidden:
    s += "\t|                |"
print(s)

s = ""
for card in cards:
    s = s + "\t|                |"
if hidden:
    s += "\t|                |"
print(s)    

s = ""
for card in cards:
    if card.value == '10':
        s = s + "\t|            {}  |".format(card.value)
    else:
        s = s + "\t|            {}   |".format(card.value)
if hidden:
    s += "\t|        *       |"        
print(s)    
     
s = ""
for card in cards:
    s = s + "\t|________________|"
if hidden:
    s += "\t|________________|"
print(s)        

print()

Function for a game of blackjack

def blackjack_game(deck):
end_game = False
play_again = 'Y'

# Player name
player_name = str(input('Enter player name: '))

# Intro
print('Lets have a fun game of Blackjack, ', player_name)

# Cards for both dealer and player
player_cards = []
dealer_cards = []

# Scores for both dealer and player
player_score = 0
dealer_score = 0

# Player stats
funds = 100
wins = 0
losses = 0
ties = 0
blackjacks = 0
busts = 0

bet = 0

clear()

# Current Stats Display
print_stats(player_name, funds, wins, losses, ties, blackjacks, busts)

# Bets
while play_again == 'Y':
 while end_game == False:
  while funds > 0:
   while bet == 0:
    bet = int(input('Enter bet amount: '))

    if bet > funds:
     print('Insufficient funds')
     bet = 0

   # Initial dealing for player and dealer
   while len(player_cards) < 2:

    # Randomly dealing a card
    player_card = random.choice(deck)
    player_cards.append(player_card)
    deck.remove(player_card)

    # Updating the player score
    player_score += player_card.card_value

    # In case both the cards are Ace, make the first ace value as 1 
    if len(player_cards) == 2:
        if player_cards[0].card_value == 11 and player_cards[1].card_value == 11:
            player_cards[0].card_value = 1
            player_score -= 10

    # Print player cards and score      
    print("PLAYER CARDS: ")
    print_cards(player_cards, False)
    print("PLAYER SCORE = ", player_score)

    input()

    # Randomly dealing a card
    dealer_card = random.choice(deck)
    dealer_cards.append(dealer_card)
    deck.remove(dealer_card)

    # Updating the dealer score
    dealer_score += dealer_card.card_value

    # Print dealer cards and score, keeping in mind to hide the second card and score
    print("DEALER CARDS: ")
    if len(dealer_cards) == 1:
        print_cards(dealer_cards, False)
        print("DEALER SCORE = ", dealer_score)
    else:
        print_cards(dealer_cards[:-1], True)    
        print("DEALER SCORE = ", dealer_score - dealer_cards[-1].card_value)


    # In case both the cards are Ace, make the second ace value as 1 
    if len(dealer_cards) == 2:
        if dealer_cards[0].card_value == 11 and dealer_cards[1].card_value == 11:
            dealer_cards[1].card_value = 1
            dealer_score -= 10

    input()

  # Player gets a blackjack   
  if player_score == 21:
    print("PLAYER HAS A BLACKJACK!!!!")
    print("PLAYER WINS!!!!")
    blackjacks += 1
    wins += 1
    funds += bet
    bet = 0
    print_stats(player_name, funds, wins, losses, ties, blackjacks, busts)
    end_choice = input('Play again(Y/N)?: ')
    play_again = end_choice.upper()
    end_game = True


  clear()

  # Print dealer and player cards
  print("DEALER CARDS: ")
  print_cards(dealer_cards[:-1], True)
  print("DEALER SCORE = ", dealer_score - dealer_cards[-1].card_value)

  print() 

  print("PLAYER CARDS: ")
  print_cards(player_cards, False)
  print("PLAYER SCORE = ", player_score)
  

  # Managing the player moves
  while player_score < 21:
    choice = input("Enter H to Hit or S to Stand : ")

    # Sanity checks for player's choice
    if len(choice) != 1 or (choice.upper() != 'H' and choice.upper() != 'S'):
        clear()
        print("Wrong choice!! Try Again")

    # If player decides to HIT
    if choice.upper() == 'H':

        # Dealing a new card
        player_card = random.choice(deck)
        player_cards.append(player_card)
        deck.remove(player_card)

        # Updating player score
        player_score += player_card.card_value

        # Updating player score in case player's card have ace in them
        c = 0
        while player_score > 21 and c < len(player_cards):
            if player_cards[c].card_value == 11:
                player_cards[c].card_value = 1
                player_score -= 10
                c += 1
            else:
                c += 1 

        clear()     

        # Print player and dealer cards
        print("DEALER CARDS: ")
        print_cards(dealer_cards[:-1], True)
        print("DEALER SCORE = ", dealer_score - dealer_cards[-1].card_value)

        print()

        print("PLAYER CARDS: ")
        print_cards(player_cards, False)
        print("PLAYER SCORE = ", player_score)
         
    # If player decides to Stand
    if choice.upper() == 'S':
        break


  clear() 

  # Print player and dealer cards
  print("PLAYER CARDS: ")
  print_cards(player_cards, False)
  print("PLAYER SCORE = ", player_score)

  print()
  print("DEALER IS REVEALING THE CARDS....")

  print("DEALER CARDS: ")
  print_cards(dealer_cards, False)
  print("DEALER SCORE = ", dealer_score)

  # Check if player has a Blackjack
  if player_score == 21:
    print("PLAYER HAS A BLACKJACK")
    blackjacks += 1

  # Check if player busts
  if player_score > 21:
    print("PLAYER BUSTED!!! GAME OVER!!!")
    busts += 1

  input() 

  # Managing the dealer moves
  while dealer_score < 17:
    clear() 

    print("DEALER DECIDES TO HIT.....")

    # Dealing card for dealer
    dealer_card = random.choice(deck)
    dealer_cards.append(dealer_card)
    deck.remove(dealer_card)

    # Updating the dealer's score
    dealer_score += dealer_card.card_value

    # Updating player score in case player's card have ace in them
    c = 0
    while dealer_score > 21 and c < len(dealer_cards):
        if dealer_cards[c].card_value == 11:
            dealer_cards[c].card_value = 1
            dealer_score -= 10
            c += 1
        else:
            c += 1

    # print player and dealer cards
    print("PLAYER CARDS: ")
    print_cards(player_cards, False)
    print("PLAYER SCORE = ", player_score)

    print()

    print("DEALER CARDS: ")
    print_cards(dealer_cards, False)
    print("DEALER SCORE = ", dealer_score)      

    input()

  # TIE Game
  if dealer_score == player_score:
    print("TIE GAME!!!!")
    ties += 1
    bet = 0
    print_stats(player_name, funds, wins, losses, ties, blackjacks, busts)
    end_choice = input('Play again(Y/N)?: ')
    play_again = end_choice.upper()
    end_game = True
  
  # Dealer busts
  if dealer_score > 21:        
    print("DEALER BUSTED!!! YOU WIN!!!") 
    wins += 1
    funds += bet
    bet = 0
    print_stats(player_name, funds, wins, losses, ties, blackjacks, busts)
    end_choice = input('Play again(Y/N)?: ')
    play_again = end_choice.upper()
    end_game = True

  # Dealer gets a blackjack
  if dealer_score == 21:
    print("DEALER HAS A BLACKJACK!!! PLAYER LOSES")
    losses += 1
    funds -= bet
    bet = 0
    print_stats(player_name, funds, wins, losses, ties, blackjacks, busts)
    end_choice = input('Play again(Y/N)?: ')
    play_again = end_choice.upper()
    end_game = True

  # Player Wins
  elif player_score > dealer_score:
    print("PLAYER WINS!!!")
    wins += 1
    funds += bet
    bet = 0
    print_stats(player_name, funds, wins, losses, ties, blackjacks, busts)
    end_choice = input('Play again(Y/N)?: ')
    play_again = end_choice.upper()
    end_game = True                 

  # Dealer Wins
  else:
    print("DEALER WINS!!!")
    losses += 1
    funds -= bet
    bet = 0
    print_stats(player_name, funds, wins, losses, ties, blackjacks, busts)
    end_choice = input('Play again(Y/N)?: ')
    play_again = end_choice.upper()
    end_game = True                 

if name == 'main':

# The type of suit
suits = ["Spades", "Hearts", "Clubs", "Diamonds"]

# The suit value 
suits_values = {"Spades":"\u2664", "Hearts":"\u2661", "Clubs": "\u2667", "Diamonds": "\u2662"}

# The type of card
cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]

# The card value
cards_values = {"A": 11, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}

# The deck of cards
deck = []

# Loop for every type of suit
for suit in suits:

    # Loop for every type of card in a suit
    for card in cards:

        # Adding card to the deck
        deck.append(Card(suits_values[suit], card, cards_values[card]))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment