Python Blackjack Simulator (With Full Code)

A pack of 52 cards can be used to play a huge variety of games. One of them is the famous Blackjack where players use given cards to get as close to the value 21 as possible. Why not do the same in Python ?

Blackjack Rules:

The rules are simple, you start with two cards. You can draw more cards, called Hit or stop with your set of cards, called Stand. You need to have a higher value than your opponent but not exceed 21. Here, Number Cards have their face value, Face Cards are worth 10 and Aces can be used as 1 or 11.

The main things to note while recreating this in Python:

  • Cards cannot repeat, i.e. a card drawn cannot be drawn again from the pack in the same round.
  • If you or the computer exceeds 21, you/it go(es) bust and lose(s) the round automatically.
  • If Aces are included in your hand, the program must be able to decide whether to use it as 11 or as 1. If the total exceeds 21 when Ace is used as 11, then its value must be changed to 1.
Keeping these things in mind, a few while loops, if-statements and lists is all that's required to write this Blackjack code:

Source Code: Click This Link

def blackjack():
    import random
    cardtype = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
    cards = []
    for ct in cardtype:
        cards.extend([ct for x in range(0,4)])

    def draw_card():
        card = random.choice(cards)
        cards.remove(card)
        return card

    def cardsum(cardlist):
        count = cardlist.count('A')
        cardlist = [x for x in cardlist if x != 'A']
        cardlist.extend(['A' for x in range(count)])
        sumofcards = 0
        for c in cardlist:
            if c.isdigit():
                sumofcards+=int(c)
            elif c in ['K','Q','J']:
                sumofcards+=10
            else:
                sumofcards+=11
                if sumofcards > 21:
                    sumofcards-=11
                    sumofcards+=1
        return sumofcards
                
    print('Your Cards: ')
    card1 = draw_card()
    card2 = draw_card()
    print(card1,' and ',card2)
    your_cards = [card1,card2]


    card1 = draw_card()
    card2 = draw_card()
    opp_cards = [card1,card2]
    print('Opponent open card: ',card2)



    while cardsum(your_cards) <= 21:
        stand_hit = int(input('\nFor stand, press 0 and for Hit, press 1: '))
        if stand_hit == 1:
            drawn_card = draw_card()
            your_cards.append(drawn_card)
            print("Drawn Card: ",drawn_card)
        else:
            break

    your_sum = cardsum(your_cards)
    print('Your Total: ',your_sum)
    print('\nOpponent\'s Turn\n')

    while cardsum(opp_cards) <= 21:
        if cardsum(opp_cards) <= 12:
            drawn_card = draw_card()
            opp_cards.append(drawn_card)
            print('Opponent Hits and Draws ',drawn_card)
        elif cardsum(opp_cards) > 12 and cardsum(opp_cards) < 15:
            opp_choice = random.choice([0,1])
            if opp_choice == 0:
                break
            else:
                drawn_card = draw_card()
                opp_cards.append(drawn_card)
                print('Opponent Hits and Draws ',drawn_card)
        else:
            break

    opp_sum = cardsum(opp_cards)
    print('Opponent Total: ',opp_sum)


    if your_sum > 21 and opp_sum <= 21:
        print('\nYou are Busted, Opponent Wins')
    elif opp_sum > 21 and your_sum <= 21:
        print('\nOpponent is Busted, You Win')
    elif opp_sum > your_sum:
         print('\nOpponent has higher value, Opponent Wins')
    elif opp_sum < your_sum:
         print('\nYou have higher value, You Win')
    else:
         print('\nSame Value, Tied')


blackjack()


I have created a function to draw a random card and delete that card from the pack so there is no repetition. There is also a function to calculate the sum of cards. The reason to create these functions is that they are used multiple times throughout the code so typing the same thing again and again is not advised.

The computer uses a simple logic to decide its move:
  • If the initial sum of cards is less than 12, it is quite safe to Hit, so Computer hits
  • If the initial sum of cards is between 12 and 15 and Computer hits, the result could go either way. So, Computer makes a random choice.
  • If the initial sum is greater than 16, A Hit is not very safe. So Computer stands.
Here is one of the many possible outputs:

Your Cards: 
9  and  Q
Opponent open card:  3

For stand, press 0 and for Hit, press 1: 0
Your Total:  19

Opponent's Turn

Opponent Hits and Draws  9
Opponent Total:  22

Opponent is Busted, You Win
>>>

The code gives you your cards randomly and gives the dealer two cards and opens one up. It gives you chance to hit or stand based on your cards and the calculations are done automatically. The opponent follows the process as mentioned above and in this case, draws a card that busts him, giving you a win. This is just one possible outcome. Why don't you play more games and share your outputs in the comment section ?

This simple code can be edited to suit the player's likes and make it a fun experience.

Want to check out other games with Python : PYTHON GAMES COMPILATION (thepygrammer.blogspot.com)

Want to learn how to make an Anagram Solver and Finder in Python: Python Anagram Solver and Finder


Comments

  1. Nice article, thank you for sharing wonderful information. I am happy to found your blog on the internet related on the topic of white label fantasy sports.
    You can also check: blackjack simulator software

    ReplyDelete
  2. I am to curious to try these code but just to practice before doing it on actual egames online

    ReplyDelete
  3. Вот тут можно узнать лучшую информацию про азартные игры, в том числе правила блэкджека, найти онлайн казино, что играть в блэкджек на деньги. Эта ифнормация содержится на азртном сайте про игры казино. Вся информация беплатная.

    ReplyDelete

Post a Comment