Skip to content

Instantly share code, notes, and snippets.

@mjhea0
Last active May 1, 2024 17:03
Show Gist options
  • 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()
@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