{"id":262,"date":"2023-09-07T10:09:16","date_gmt":"2023-09-07T16:09:16","guid":{"rendered":"https:\/\/rasulnazriev.tech\/?p=262"},"modified":"2025-07-30T15:51:09","modified_gmt":"2025-07-30T21:51:09","slug":"python-blackjack-game","status":"publish","type":"post","link":"https:\/\/rasulnazriev.tech\/?p=262","title":{"rendered":"Python Blackjack Game"},"content":{"rendered":"\n<p>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. <\/p>\n\n\n\n<p>Here is the code for the card.py <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#The class below improvises the real card\n\nclass Card:\n    def __init__(self, suit, face, value):\n        self._suit = suit\n        self._face = face\n        self._value = value\n\n    #Gets the value of the card\n    def get_value(self):\n        return self._value\n    \n    #Sets the value of the card\n    def set_value(self, v):\n        self._value = v\n        return self._value \n\n    #String representation\n    def __str__(self):\n        return ( str(self._face) + &quot; of &quot; + str(self._suit)  )\n\n\n#Test client\n\ndef main():\n    c = Card (&quot;Heart&quot;, &quot;Two&quot;, 1) \n\n    print(&quot;First Card: &quot; )\n    print(c)\n    print (c.get_value())\n    print( &quot;New set value is&quot;, c.set_value(11) )\n\n    c2 = Card(&quot;Clubs&quot;, &quot;Ace&quot;, 1)\n\n    print(c2)\n\nif __name__ == &#039;__main__&#039;:\n    main()\n<\/pre><\/div>\n\n\n<p>Here is the player.py<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom card import Card\nfrom deck import Deck\n\n\nclass Player:   #Creates a player with a name, balance and #hand from deck\n\n    def __init__(self,name,balance, deck):        \n                          \n        card1 = deck.deal()    #Assigning a card to the #player \n        card2 = deck.deal()    #Assigning the second card #to the player from the same deck \n\n        self._name = name  #Name of the player\n        self._balance = balance #Balance\n        self._hand = &#x5B;card1, card2] #Initial hand, that is #2 cards\n        \n\n    def print_hand(self):  #Prints hand, that is how many #cards the player has\n        if len(self._hand) &gt;= 2:        #Making sure the #player has original amount of cards or more\n            for i in range(len(self._hand)):    \n                print(self._hand&#x5B;i])\n        else:\n            print(&quot;Player has no cards&quot;)  #Player has got #no cards since the player cannot have 1 card in the game\n\n    def print_first(self):\n        print(self._hand&#x5B;0])\n\n    def clear(self):\n        self._hand = &#x5B;]\n\n    def deal_card(self,d):\n        card = d.deal()\n        self._hand.append(card)\n        return self._hand\n    \n    def print_balance(self):\n        print(&#039;Your balance: $&#039; + str(self._balance) )\n\n    def get_balance(self):          #returns the player&#039;s   #balance\n        return self._balance\n\n    def bet(self,amount):            #Bets the amount if #player&#039;s balance is &gt;= amount.\n        if  self._balance &gt;= amount:\n            self._balance-= amount\n            return True\n        else:\n            return False\n    #Adds to players balance the amount\n    def win(self, amount):\n        self._balance+=amount\n\n    #Gives hand value\n    def hand_value(self):\n        sum1 = 0\n        for i in range(len(self._hand)):\n            sum1+= self._hand&#x5B;i].get_value()\n        return sum1\n        \n    def blackjack(self):    #Checks the blackjack\n        sum1 = 0\n        for i in range(len(self._hand)):\n            sum1+= self._hand&#x5B;i].get_value()\n        if sum1==21:\n            return True\n        else:\n            return False\n    \n    \n    def ace_change_value(self):       #Changes  Ace value #to 1 if one Ace is present; otherwise all to 1 except one\n        count = 0\n        new_count = 0\n\n        for c in self._hand:\n            if c.get_value() == 11:\n                count+=1\n                if count == 1:\n                    c.set_value(1)\n                if count == 3:\n                    c.set_value(1)\n<\/pre><\/div>\n\n\n<p>Here is the code for the deck.py <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport random\nfrom card import Card\n\n#The program creates a class Deck which creates shuffled #52-card deck \n\nclass Deck:     #Creates deck of cards\n\n    def __init__(self):    \n\n        seq1 = &#x5B;&#039;2&#039;,&#039;3&#039;,&#039;4&#039;,&#039;5&#039;,&#039;6&#039;,&#039;7&#039;,&#039;8&#039;,&#039;9&#039;,&#039;10&#039;]\n        seq2 = &#x5B;&quot;Hearts&quot;, &quot;Diamonds&quot;, &quot;Clubs&quot;, &quot;Spades&quot;]\n        seq3 = &#x5B;&quot;Jack&quot;, &quot;Queen&quot;, &quot;King&quot;,&quot;Aces&quot;]\n\n        newdeck = &#x5B;]\n\n        for s in seq2:\n            for n in seq1:\n                newdeck.append(s+ &quot; &quot; + n)\n            for f in seq3:\n                newdeck.append(s+ &quot; &quot; + f)\n        random.shuffle(newdeck)\n        self._deck = newdeck\n\n\n    def print_deck(self):   #Prints deck of cards. This is #for test client\n        print(self._deck) \n    \n\n    def deal(self):      #Takes a random card from deck, #removes it and returns it as Card type object\n\n       seq1 = &#x5B; &#039;2&#039;,&#039;3&#039;,&#039;4&#039;,&#039;5&#039;,&#039;6&#039;,&#039;7&#039;,&#039;8&#039;,&#039;9&#039;,&#039;10&#039;]\n       seq2 = &#x5B;&quot;Hearts&quot;, &quot;Diamonds&quot;, &quot;Clubs&quot;, &quot;Spades&quot;]\n       seq3 = &#x5B;&quot;Jack&quot;, &quot;Queen&quot;, &quot;King&quot;]\n        \n\n       card1 = random.choice(self._deck)\n       self._deck.remove(card1)\n\n       temp_card1 = card1.split() #Temporary list to produce the card&#039;s value\n            \n\n    #To get the suit, face and value of the card, the two #for loops have been created below\n       for i in range(2):\n            if temp_card1&#x5B;i] in seq1:\n                face_card = temp_card1&#x5B;i]\n                value_card = int(temp_card1&#x5B;i])\n            elif temp_card1&#x5B;i] in seq2:\n                suit_card = temp_card1&#x5B;i]  \n            elif temp_card1&#x5B;i] in seq3:\n                face_card = temp_card1&#x5B;i]\n                value_card = 10\n            else: \n                face_card = temp_card1&#x5B;i]\n                value_card = 11\n\n       card1 = Card(suit_card,face_card,value_card)\n\n       return card1\n\n\n    def deck_size(self):    #returns size of the deck\n        count = 0\n        for i in range (len(self._deck)):\n            count+=1\n        return count\n\n    def refill(self):   #refills and reshuffles the deck\n            seq1 = &#x5B;&#039;2&#039;,&#039;3&#039;,&#039;4&#039;,&#039;5&#039;,&#039;6&#039;,&#039;7&#039;,&#039;8&#039;,&#039;9&#039;,&#039;10&#039;]\n            seq2 = &#x5B;&quot;Hearts&quot;, &quot;Diamonds&quot;, &quot;Clubs&quot;, &quot;Spades&quot;]\n            seq3 = &#x5B;&quot;Jack&quot;, &quot;Queen&quot;, &quot;King&quot;,&quot;Aces&quot;]\n\n            newdeck = &#x5B;]\n\n            for s in seq2:\n                for n in seq1:\n                    newdeck.append(s+ &quot; &quot; + n)\n                for f in seq3:\n                    newdeck.append(s+ &quot; &quot; + f)\n            random.shuffle(newdeck)\n            self._deck = newdeck\n\n\n\ndef main():\n    d = Deck()\n    card1 = d.deal()\n    print(d.deck_size())\n    d.refill()\n    print(d.deck_size())\n\n\nif __name__ == &#039;__main__&#039;:\n    main()\n\n\n\n<\/pre><\/div>\n\n\n<p>Now the client code is blackjack.py. Here is the client code. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#-----------------------------\n# By Rasul Nazriev\n# Client of card.py player.py and deck.py \n#The program replicates the real card game -- Blackjack\n# blackjack.py\n#--------------------------------\n\n\n#Importing necessary modules\nimport sys\nfrom card import Card\nfrom player import Player\nfrom deck import Deck\n\n#Necessary initialization\n\nd = Deck()\nname = input(&quot;Type your name: &quot;) \nbalance = int ( input (&quot;Type your balance: $&quot;) )\np = Player(name, balance, d)\ndealer = &quot;Dealer&quot;\nbalance_d = 1\ndealer = Player(dealer, balance_d, d )\n\n\n#The function checks if the player wants to play again \n\ndef play_again():\n    global var_play\n    play = input(&quot;Do you want to play again? (Please type &#039;yes&#039; or &#039;no&#039;)  &quot;)\n    if play == &quot;yes&quot;:\n        p.clear()\n        dealer.clear()\n        var_play = True\n    else:\n        var_play = False\n\n#The below function displays player&#039;s cards and one card of the Dealer\n\ndef show_cards_first():\n    print( &quot;******************&quot; )\n    print( &quot;******************&quot; )\n    print( &quot;Your cards are: &quot; )\n    p.print_hand() \n    print( &quot;******************&quot; )\n    print( &quot;******************&quot; )\n    print( &quot;Dealer&#039;s cards are: &quot;) \n    dealer.print_first()\n    print( &quot;******************&quot; )\n    print( &quot;******************&quot; )\n\n#The function below displays all cards\n\ndef show_cards():\n    print( &quot;******************&quot; )\n    print( &quot;******************&quot; )\n    print( &quot;Your cards are: &quot; )\n    p.print_hand() \n    print( &quot;******************&quot; )\n    print( &quot;******************&quot; )\n    print( &quot;Dealer&#039;s cards are: &quot;) \n    dealer.print_hand()\n    print( &quot;******************&quot; )\n    print( &quot;******************&quot; )\n\n#The function below gives new cards and checks lenght of the deck \ndef new_cards():\n\n    if d.deck_size()&gt;20:\n\n        p.clear()\n        dealer.clear()\n        p.deal_card(d)\n        p.deal_card(d)\n        dealer.deal_card(d)\n        dealer.deal_card(d)\n    else:\n        d.refill()\n        p.clear()\n        dealer.clear()\n        p.deal_card(d)\n        p.deal_card(d)\n        dealer.deal_card(d)\n        dealer.deal_card(d)\n\n#The function below checks some initial conditions\n\ndef first_phase():\n    if p.hand_value()&gt;21:\n        p.ace_change_value()\n        if p.hand_value()&gt;21:\n            print(&quot;You are busted&quot;)\n            return &quot;Loss&quot;\n        elif p.hand_value()&lt;21:\n            pass\n    elif p.hand_value()&lt;21:\n        pass\n\n\n#In case, player chooses to stand. The function below simulates dealer&#039;s turn\n\ndef dealer_turn():\n    global result_dealer_turn\n    result_dealer_turn =0\n    #In case dealer hand value is less than 17, the program should keep giving dealer cards\n    if dealer.hand_value()&lt; 17:\n        while dealer.hand_value()&lt;17:\n            dealer.deal_card(d)\n\n    if dealer.hand_value()&gt;21:\n        dealer.ace_change_value()   #Taking into account that ace can be 1 or 11\n        if dealer.hand_value()&gt;21:\n            show_cards()\n            print(&quot;You win!&quot;)\n            result_dealer_turn = &quot;Win&quot;\n            \n        elif dealer.hand_value() == 21:\n            show_cards()\n            print(&quot;You lost&quot;)\n            result_dealer_turn = &quot;Loss&quot;\n            \n        else:\n            dealer_turn()\n\n    elif dealer.hand_value() == 21:\n        show_cards()\n        print(&quot;You lost!&quot;) \n        result_dealer_turn = &quot;Loss&quot;\n        \n    elif dealer.hand_value() &gt;16 and dealer.hand_value()&lt;p.hand_value():\n        show_cards()\n        print(&quot;You win!&quot;)\n        result_dealer_turn = &quot;Win&quot;\n        \n    elif dealer.hand_value ()&gt; 16 and dealer.hand_value()&gt;p.hand_value():\n        show_cards()\n        print(&quot;You lost&quot;)\n        result_dealer_turn = &quot;Loss&quot;\n        \n    elif dealer.hand_value() == p.hand_value():\n        show_cards()\n        print(&quot;It&#039;s a tie&quot;)\n        result_dealer_turn = &quot;Tie&quot;\n        \n\n    \n\n#The function belows checks blackjack conditions\n            \ndef blackjack_cond():\n    global blackjack \n    blackjack = 0\n    if p.blackjack() == True and dealer.blackjack() == True:\n        print(&quot;It is a tie&quot;)\n        print( &quot;******************&quot; )\n        print( &quot;******************&quot; )\n        blackjack = &quot;Tie&quot;\n    elif p.blackjack () == True and dealer.blackjack() == False:\n        print(&quot;You win!&quot;)\n        print( &quot;******************&quot; )\n        print( &quot;******************&quot; ) \n        blackjack = &quot;Win&quot;\n\n#The functions below checks whether player wants to hit or stand, and performs actions accordingly\n\ndef hit_stand():\n    global result_hit_stand\n    result_hit_stand = 0\n    move = input (&quot;Would you like to hit or stand? (Please type &#039;hit&#039; or &#039;stand&#039; )  \\n&quot; )\n    if move == &#039;hit&#039;:\n        p.deal_card(d)\n        if p.hand_value()&gt;21:\n            p.ace_change_value()    #Taking into account that ace can be 1 or 11\n        if p.hand_value()&gt;21:\n            show_cards()\n            print(&quot;You are busted!&quot;)\n            result_hit_stand = &quot;Loss&quot;\n            \n        elif p.hand_value()==21:\n            show_cards()\n            print(&quot;You won!&quot;)\n            result_hit_stand = &quot;Win&quot;\n            \n    \n        elif p.hand_value()&lt;21:\n            show_cards_first()\n            hit_stand()\n    else:\n        dealer_turn()\n\n\n#The function below checks whether player typed negative bet or bet more than his balance\n\ndef bet_checker(balance):\n    global bet\n    bet = int ( input (&quot;Type your bet: $&quot;) )\n    if bet&gt;balance:\n        print(&quot;You crazy? You cannot bet more than your balance&quot;)\n        bet_checker(balance)\n    elif bet&lt;0:\n        print(&quot;Please type positive numbers&quot;)\n        bet_checker(balance)\n\n    elif bet&lt;= balance:\n        p.bet(bet)\n\n#Test client. Could also do the below code in the global code, but I preferred to keep things neat.\n\ndef main():\n    #Checking the balance \n    bet_checker(balance)\n\n    #Giving initial cards\n    show_cards_first()\n\n    #Counter for some conditions below\n    counter = 0\n\n    while True:\n        counter+=1\n        if counter&gt;1:   #In case player wants to play again, I need to set new bet checker, cards, and I need to show those cards\n            bet_checker(p.get_balance())\n            new_cards()\n            show_cards_first()\n\n        blackjack_cond()    #Checking blackjack in the first place\n\n        if blackjack == &quot;Tie&quot;:\n            p.win(bet)\n            p.print_balance()\n            play_again()\n            if var_play == True:\n                continue\n            else:\n                break\n                     \n\n        elif blackjack == &quot;Win&quot;:\n            p.win(bet*2)\n            p.print_balance()\n            play_again()\n            if var_play == True:\n                continue\n            else:\n                break \n       \n        \n        if first_phase() == &quot;Loss&quot;:\n            p.print_balance()\n            play_again()\n            if var_play == True:\n                continue\n            else:\n                break \n       \n            \n\n        hit_stand() #Checking hit or stand conditions below\n\n        if result_hit_stand== &quot;Win&quot;:\n            p.win(bet*2.5)\n            p.print_balance()\n            play_again()\n            if var_play == True:\n                continue\n            else:\n                break \n       \n            \n        elif result_hit_stand == &quot;Loss&quot;:\n            p.print_balance()\n            play_again()\n            if var_play == True:\n                continue\n            else:\n                break \n       \n            \n        #No need to call dealer_turn function as hit_stand() functions calls dealer_turn function \n        #Dealer turn function contains result_dealer_turn global variable\n\n        if result_dealer_turn == &quot;Win&quot;:\n            p.win(bet*2)\n            p.print_balance()\n            play_again()\n            if var_play == True:\n                continue\n            else:\n                break \n       \n        elif result_dealer_turn == &quot;Loss&quot;:\n            p.print_balance()\n            play_again()\n            if var_play == True:\n                continue\n            else:\n                break \n       \n            \n\n        elif result_dealer_turn == &quot;Tie&quot;:\n            p.win(bet)\n            p.print_balance()\n            play_again()\n            if var_play == True:\n                continue\n            else:\n                break \n       \n            \n\n\nif __name__ == &#039;__main__&#039;:\n    main() \n\n\n\n\n<\/pre><\/div>\n\n\n<p>Note: It is important to place the client and other modules in the same directory; otherwise, the client may not work. <\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":280,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-262","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorised"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=\/wp\/v2\/posts\/262","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=262"}],"version-history":[{"count":13,"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=\/wp\/v2\/posts\/262\/revisions"}],"predecessor-version":[{"id":278,"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=\/wp\/v2\/posts\/262\/revisions\/278"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=\/wp\/v2\/media\/280"}],"wp:attachment":[{"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=262"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=262"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/rasulnazriev.tech\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=262"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}