Let’s begin the journey of simulating Blackjack by coding it all out in Python. We won’t be going over every single line of code for the sake of brevity but the Github for the code will be available at the end of this article. It’s very likely that something like this has been done before, perhaps even done better, but let’s try it out anyways.
blackjack card counting
First, in order to simulate a game of Blackjack, we would need to code out a Blackjack game with all the necessary rules and regulations that come with it. To keep things simple, we would leave out options such as splitting, doubling down, surrendering, etc. Let’s keep the player options limited to hit or stay. Also, since we are measuring wins versus losses, we can eliminate the need for betting. However, betting size in a normal Blackjack game is important to know.
Let’s start by constructing several functions to help our Blackjack game run properly:
Each function serves an important purpose for running the game. In order blackjack card counting to simulate the creation of a playing card deck, we created the function which incorporates to “shuffle” the list of cards we created. Dealing a card is handled in which appends a new card by using the method to mimic the dealing of a card from the deck. The function reassigns the value of the ace from 11 to 1 in case the player or dealer goes over 21. These are probably the most notable functions from above, but that doesn’t mean the game can run without the rest.
This function deals cards to the dealer if the player decided to stay. This function follows the rules of every Blackjack dealer. It deals until the dealer reaches a value between 17 to 21 or until the dealer busts. It eventually compares the hand of the dealer to the hand of the player to determine who won.
Next, in order to count cards during the game, we created a Pandas DataFrame of the different card counting strategies and their specific values for every card:
In this code to create a DataFrame of card counting values, we exported a pickle of the DataFrame for use later on. Make sure that this pickle file is in the same folder as the Blackjack code in order for it to run properly.
Then, we added card counting functions to keep track of the count while the game is playing:
These functions keep track of the count throughout every round of Blackjack in the entire game. keeps track of the running count and keeps track of the true count, which is what players use to decide whether to hit or stay.
Now that we have all of our functions ready, we can run Blackjack. The code will allow player inputs so we can play the game to our heart’s content. Feel free to test out the Blackjack game in your own terminal or IDE.
There are two versions of this game:
Blackjack without counting cardsBlackjack with counting cards