Hello everyone! This post is dedicated to creating a blackjack card game in Python programming language. I started by creating classes card.py, player.py, and deck.py. There are comments in the code to help you to understand the code. I am assuming the reader knows the rules of the Blackjack game. If not, please familiarize yourself with the Blackjack game in order to understand the modules.
Here is the code for the card.py
#The class below improvises the real card
class Card:
def __init__(self, suit, face, value):
self._suit = suit
self._face = face
self._value = value
#Gets the value of the card
def get_value(self):
return self._value
#Sets the value of the card
def set_value(self, v):
self._value = v
return self._value
#String representation
def __str__(self):
return ( str(self._face) + " of " + str(self._suit) )
#Test client
def main():
c = Card ("Heart", "Two", 1)
print("First Card: " )
print(c)
print (c.get_value())
print( "New set value is", c.set_value(11) )
c2 = Card("Clubs", "Ace", 1)
print(c2)
if __name__ == '__main__':
main()
Here is the player.py
from card import Card
from deck import Deck
class Player: #Creates a player with a name, balance and #hand from deck
def __init__(self,name,balance, deck):
card1 = deck.deal() #Assigning a card to the #player
card2 = deck.deal() #Assigning the second card #to the player from the same deck
self._name = name #Name of the player
self._balance = balance #Balance
self._hand = [card1, card2] #Initial hand, that is #2 cards
def print_hand(self): #Prints hand, that is how many #cards the player has
if len(self._hand) >= 2: #Making sure the #player has original amount of cards or more
for i in range(len(self._hand)):
print(self._hand[i])
else:
print("Player has no cards") #Player has got #no cards since the player cannot have 1 card in the game
def print_first(self):
print(self._hand[0])
def clear(self):
self._hand = []
def deal_card(self,d):
card = d.deal()
self._hand.append(card)
return self._hand
def print_balance(self):
print('Your balance: $' + str(self._balance) )
def get_balance(self): #returns the player's #balance
return self._balance
def bet(self,amount): #Bets the amount if #player's balance is >= amount.
if self._balance >= amount:
self._balance-= amount
return True
else:
return False
#Adds to players balance the amount
def win(self, amount):
self._balance+=amount
#Gives hand value
def hand_value(self):
sum1 = 0
for i in range(len(self._hand)):
sum1+= self._hand[i].get_value()
return sum1
def blackjack(self): #Checks the blackjack
sum1 = 0
for i in range(len(self._hand)):
sum1+= self._hand[i].get_value()
if sum1==21:
return True
else:
return False
def ace_change_value(self): #Changes Ace value #to 1 if one Ace is present; otherwise all to 1 except one
count = 0
new_count = 0
for c in self._hand:
if c.get_value() == 11:
count+=1
if count == 1:
c.set_value(1)
if count == 3:
c.set_value(1)
Here is the code for the deck.py
import random
from card import Card
#The program creates a class Deck which creates shuffled #52-card deck
class Deck: #Creates deck of cards
def __init__(self):
seq1 = ['2','3','4','5','6','7','8','9','10']
seq2 = ["Hearts", "Diamonds", "Clubs", "Spades"]
seq3 = ["Jack", "Queen", "King","Aces"]
newdeck = []
for s in seq2:
for n in seq1:
newdeck.append(s+ " " + n)
for f in seq3:
newdeck.append(s+ " " + f)
random.shuffle(newdeck)
self._deck = newdeck
def print_deck(self): #Prints deck of cards. This is #for test client
print(self._deck)
def deal(self): #Takes a random card from deck, #removes it and returns it as Card type object
seq1 = [ '2','3','4','5','6','7','8','9','10']
seq2 = ["Hearts", "Diamonds", "Clubs", "Spades"]
seq3 = ["Jack", "Queen", "King"]
card1 = random.choice(self._deck)
self._deck.remove(card1)
temp_card1 = card1.split() #Temporary list to produce the card's value
#To get the suit, face and value of the card, the two #for loops have been created below
for i in range(2):
if temp_card1[i] in seq1:
face_card = temp_card1[i]
value_card = int(temp_card1[i])
elif temp_card1[i] in seq2:
suit_card = temp_card1[i]
elif temp_card1[i] in seq3:
face_card = temp_card1[i]
value_card = 10
else:
face_card = temp_card1[i]
value_card = 11
card1 = Card(suit_card,face_card,value_card)
return card1
def deck_size(self): #returns size of the deck
count = 0
for i in range (len(self._deck)):
count+=1
return count
def refill(self): #refills and reshuffles the deck
seq1 = ['2','3','4','5','6','7','8','9','10']
seq2 = ["Hearts", "Diamonds", "Clubs", "Spades"]
seq3 = ["Jack", "Queen", "King","Aces"]
newdeck = []
for s in seq2:
for n in seq1:
newdeck.append(s+ " " + n)
for f in seq3:
newdeck.append(s+ " " + f)
random.shuffle(newdeck)
self._deck = newdeck
def main():
d = Deck()
card1 = d.deal()
print(d.deck_size())
d.refill()
print(d.deck_size())
if __name__ == '__main__':
main()
Now the client code is blackjack.py. Here is the client code.
#-----------------------------
# By Rasul Nazriev
# Client of card.py player.py and deck.py
#The program replicates the real card game -- Blackjack
# blackjack.py
#--------------------------------
#Importing necessary modules
import sys
from card import Card
from player import Player
from deck import Deck
#Necessary initialization
d = Deck()
name = input("Type your name: ")
balance = int ( input ("Type your balance: $") )
p = Player(name, balance, d)
dealer = "Dealer"
balance_d = 1
dealer = Player(dealer, balance_d, d )
#The function checks if the player wants to play again
def play_again():
global var_play
play = input("Do you want to play again? (Please type 'yes' or 'no') ")
if play == "yes":
p.clear()
dealer.clear()
var_play = True
else:
var_play = False
#The below function displays player's cards and one card of the Dealer
def show_cards_first():
print( "******************" )
print( "******************" )
print( "Your cards are: " )
p.print_hand()
print( "******************" )
print( "******************" )
print( "Dealer's cards are: ")
dealer.print_first()
print( "******************" )
print( "******************" )
#The function below displays all cards
def show_cards():
print( "******************" )
print( "******************" )
print( "Your cards are: " )
p.print_hand()
print( "******************" )
print( "******************" )
print( "Dealer's cards are: ")
dealer.print_hand()
print( "******************" )
print( "******************" )
#The function below gives new cards and checks lenght of the deck
def new_cards():
if d.deck_size()>20:
p.clear()
dealer.clear()
p.deal_card(d)
p.deal_card(d)
dealer.deal_card(d)
dealer.deal_card(d)
else:
d.refill()
p.clear()
dealer.clear()
p.deal_card(d)
p.deal_card(d)
dealer.deal_card(d)
dealer.deal_card(d)
#The function below checks some initial conditions
def first_phase():
if p.hand_value()>21:
p.ace_change_value()
if p.hand_value()>21:
print("You are busted")
return "Loss"
elif p.hand_value()<21:
pass
elif p.hand_value()<21:
pass
#In case, player chooses to stand. The function below simulates dealer's turn
def dealer_turn():
global result_dealer_turn
result_dealer_turn =0
#In case dealer hand value is less than 17, the program should keep giving dealer cards
if dealer.hand_value()< 17:
while dealer.hand_value()<17:
dealer.deal_card(d)
if dealer.hand_value()>21:
dealer.ace_change_value() #Taking into account that ace can be 1 or 11
if dealer.hand_value()>21:
show_cards()
print("You win!")
result_dealer_turn = "Win"
elif dealer.hand_value() == 21:
show_cards()
print("You lost")
result_dealer_turn = "Loss"
else:
dealer_turn()
elif dealer.hand_value() == 21:
show_cards()
print("You lost!")
result_dealer_turn = "Loss"
elif dealer.hand_value() >16 and dealer.hand_value()<p.hand_value():
show_cards()
print("You win!")
result_dealer_turn = "Win"
elif dealer.hand_value ()> 16 and dealer.hand_value()>p.hand_value():
show_cards()
print("You lost")
result_dealer_turn = "Loss"
elif dealer.hand_value() == p.hand_value():
show_cards()
print("It's a tie")
result_dealer_turn = "Tie"
#The function belows checks blackjack conditions
def blackjack_cond():
global blackjack
blackjack = 0
if p.blackjack() == True and dealer.blackjack() == True:
print("It is a tie")
print( "******************" )
print( "******************" )
blackjack = "Tie"
elif p.blackjack () == True and dealer.blackjack() == False:
print("You win!")
print( "******************" )
print( "******************" )
blackjack = "Win"
#The functions below checks whether player wants to hit or stand, and performs actions accordingly
def hit_stand():
global result_hit_stand
result_hit_stand = 0
move = input ("Would you like to hit or stand? (Please type 'hit' or 'stand' ) \n" )
if move == 'hit':
p.deal_card(d)
if p.hand_value()>21:
p.ace_change_value() #Taking into account that ace can be 1 or 11
if p.hand_value()>21:
show_cards()
print("You are busted!")
result_hit_stand = "Loss"
elif p.hand_value()==21:
show_cards()
print("You won!")
result_hit_stand = "Win"
elif p.hand_value()<21:
show_cards_first()
hit_stand()
else:
dealer_turn()
#The function below checks whether player typed negative bet or bet more than his balance
def bet_checker(balance):
global bet
bet = int ( input ("Type your bet: $") )
if bet>balance:
print("You crazy? You cannot bet more than your balance")
bet_checker(balance)
elif bet<0:
print("Please type positive numbers")
bet_checker(balance)
elif bet<= balance:
p.bet(bet)
#Test client. Could also do the below code in the global code, but I preferred to keep things neat.
def main():
#Checking the balance
bet_checker(balance)
#Giving initial cards
show_cards_first()
#Counter for some conditions below
counter = 0
while True:
counter+=1
if counter>1: #In case player wants to play again, I need to set new bet checker, cards, and I need to show those cards
bet_checker(p.get_balance())
new_cards()
show_cards_first()
blackjack_cond() #Checking blackjack in the first place
if blackjack == "Tie":
p.win(bet)
p.print_balance()
play_again()
if var_play == True:
continue
else:
break
elif blackjack == "Win":
p.win(bet*2)
p.print_balance()
play_again()
if var_play == True:
continue
else:
break
if first_phase() == "Loss":
p.print_balance()
play_again()
if var_play == True:
continue
else:
break
hit_stand() #Checking hit or stand conditions below
if result_hit_stand== "Win":
p.win(bet*2.5)
p.print_balance()
play_again()
if var_play == True:
continue
else:
break
elif result_hit_stand == "Loss":
p.print_balance()
play_again()
if var_play == True:
continue
else:
break
#No need to call dealer_turn function as hit_stand() functions calls dealer_turn function
#Dealer turn function contains result_dealer_turn global variable
if result_dealer_turn == "Win":
p.win(bet*2)
p.print_balance()
play_again()
if var_play == True:
continue
else:
break
elif result_dealer_turn == "Loss":
p.print_balance()
play_again()
if var_play == True:
continue
else:
break
elif result_dealer_turn == "Tie":
p.win(bet)
p.print_balance()
play_again()
if var_play == True:
continue
else:
break
if __name__ == '__main__':
main()
Note: It is important to place the client and other modules in the same directory; otherwise, the client may not work.