Creating a Blackjack Game in Visual Basic

I love card games. My wife and I will spend hours outside playing card games and relaxing. On some occasions, we would try our luck at local casinos. I usually play Blackjack whereas my wife would play slot machines. Today, I will show you the basics on how to make a Blackjack game as well as how to create your own playing cards.

Blackjack

Blackjack is a comparing card game between a player and dealer. This means that players compete against the dealer but not against other players. The objective of the game is to beat the dealer in one of the following ways:

  • Get 21 points on the player’s first two cards (this is called “blackjack“), without the dealer getting a blackjack.
  • Reach a final score higher than the dealer without exceeding 21.
  • Let the dealer draw additional cards until his or her hand exceeds 21, causing the dealer to “bust.”

Playing Blackjack

The player or players are dealt a two-card hand and add together the value of their cards. Face cards—such as kings, queens, and jacks—are counted as ten points each. The player and the dealer can count an ace as either 1 point or 11 points. All other cards are counted as the numeric value shown on the card.

After receiving their first two cards, players have the option of taking an additional card, or getting a “hit.” In a given round, the player or the dealer wins by having a score of 21 or by having the higher score that is less than 21.

First Project

The aim of this project is to show you how easy it is to create a Blackjack game albeit without cards, yet the logic remains. Create a Visual Basic Windows Forms project and design your form to resemble Figure 1:

Our Design
Figure 1: Our Design

You are welcome to name your objects to your liking. Just keep in mind that my names might differ from yours.

Add the following code for the button labeled “Deal:

   Private Sub btnDeal_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles btnDeal.Click

      lblPlayer.Text = RandomNumber(21)
      lblDealer.Text = RandomNumber(21)

      btnDeal.Enabled = False

      If lblPlayer.Text = "21" Then

         MessageBox.Show("Player Wins!")

      End If

      If lblDealer.Text = "21" Then

         MessageBox.Show("Dealer Wins!")

      End If

      If lblPlayer.Text = 0 Then

         lblPlayer.Text = RandomNumber(21)

      End If

      If lblDealer.Text = 0 Then

         lblDealer.Text = RandomNumber(21)

      End If

   End Sub

The two labels (lblPlayer and lblDealer)’s Text get set to a number that gets returned by the RandomNumber function, which we will add shortly. Four tests are being done:

  • Test if the Player’s total is 21
  • Test if the Dealer’s total is 21. Based on these two tests, a potential winner can immediately be identified, so that the next game can commence.
  • Test if the Player’s total is 0.
  • Test if the Dealer’s total is 0. This indicates that a new game has been started.

Add the RandomNumber function:

   Public Function RandomNumber(ByVal intNum As Integer) _
         As Integer

      Dim rRnd As New Random(System.DateTime.Now.Millisecond)

      Return rRnd.Next(1, intNum)

   End Function

This function generates a random number between 1 and the supplied value.

Add the following code for the button labeled “Hit:”

   Private Sub btnHit_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles btnHit.Click

      lblPlayer.Text = Val(lblPlayer.Text) + RandomNumber(21)
      lblDealer.Text = Val(lblDealer.Text) + RandomNumber(21)

      If lblPlayer.Text >= 21 Then

         MessageBox.Show("Dealer Wins!")

      End If

      If lblDealer.Text >= 21 Then

         MessageBox.Show("Player Wins!")

      End If

      If lblPlayer.Text >= 21 & lblDealer.Text >= 21 Then

         MessageBox.Show("Draw!")

      End If

   End Sub

Every time the Hit button gets pressed, the current score of both players gets increased to a randomly generated number. If the Player’s score is above 21, the Dealer should win and vice versa. If both exceed 21, the game is a draw.

Add the following code for the “Stay” and Reset buttons:

   Private Sub btnStay_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles btnStay.Click

      If Val(lblPlayer.Text) >= Val(lblDealer.Text) Then

         MessageBox.Show("Player Wins!")

      Else

         MessageBox.Show("Dealer Wins!")

      End If

   End Sub

   Private Sub btnReset_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles btnReset.Click

      lblPlayer.Text = ""
      lblDealer.Text = ""

      btnDeal.Enabled = True

   End Sub.

When you stay, the two scores get compared and a winner is chosen. Reset clears the scores and allows you to start over.

Second Project

With this project, you will learn how to simulate a real working deck of cards.

Create a new Visual Basic Console Application.

Add a new class to your project—I have named mine “Enums“—and enter the following code:

Public Enum eSuit

   Spades
   Clubs

   Diamonds
   Hearts

End Enum

Public Enum eRank

   Ace
   Two
   Three
   Four
   Five
   Six
   Seven
   Eight
   Nine
   Ten
   Jack
   Queen
   King

End Enum

Here, you have created two Enumerations. One Enum is to identify the Suit of a card and the other the Rank, or number, of a card. Add another class to the project and name it “Card,” for example. My Card class definition looks like the following:

Public Class clsCard
   Implements IComparable(Of clsCard

Add the Card class’ Properties:

   Private sSuit As eSuit
   Private rRank As eRank

   Public Property Suit() As eSuit

      Get

         Return sSuit

      End Get

      Private Set(value As eSuit)

         sSuit = value

      End Set

   End Property

   Public Property Rank() As eRank

      Get

         Return rRank

      End Get

      Private Set(value As eRank)

         rRank = value

      End Set

   End Property

These two properties are to determine which Suit and the Rank the card has. Add the constructor:

   Public Sub New(tempRank As eRank, tempSuit As eSuit)

      Rank = tempRank
      Suit = tempSuit

   End Sub

Add a method:

   Function CompareTo(temp As HTG_Cards.clsCard) As Integer _
      Implements IComparable(Of HTG_Cards.clsCard).CompareTo

      If Rank <> temp.Rank Then

         Return Rank.CompareTo(temp.Rank)

      End If

      Return Suit.CompareTo(temp.Suit)

   End Function

The CompareTo method allows the Card object to be compared to other Card objects. We will make use of this method to compare two different cards for similarities.

Add a class to be used for the Deck. Add the following properties to your Deck class:

   Private Shared rndRandom As New Random()
   Private lstCards As List(Of clsCard)

   Public Property Cards() As List(Of clsCard)

      Get

         Return lstCards

      End Get

      Private Set(value As List(Of clsCard))

         lstCards = value

      End Set

   End Property

The Cards property returns a list of cards. Add the constructor:

   Private Sub New()

      Cards = New List(Of clsCard)()

   End Sub

Add a method to create a deck of cards:

   Public Shared Function CreateDeck() As clsDeck

      Dim dDeck As New clsDeck()

      For i As Integer = 0 To 3

         For j As Integer = 0 To 12

            dDeck.Cards.Add(New clsCard(DirectCast(j, eRank), _
               DirectCast(i, eSuit)))

         Next

      Next

      Return dDeck

   End Function

The CreateDeck function loops through the four Suits (Diamonds, Hearts, Clubs, and Spades) and adds each Ranked (Ace to King) card to the Deck object. This produces 52 cards. Add a Shuffle Sub procedure:

   Public Sub ShuffleDeck()

      Dim lstCards As New List(Of clsCard)(Cards)

      Cards.Clear()

      While lstCards.Count > 0

         Dim Index As Integer = _
            rndRandom.[Next](lstCards.Count)

         Dim card = lstCards(Index)
         lstCards.RemoveAt(Index)

         Cards.Add(card)

      End While

   End Sub

This procedure selects a random card, deletes it from the list of cards, and then adds it to the Cards list. Now, we need to make use of the cards! Add the following code to your Module:

   Public Sub Main()

      Dim dDeck1 = clsDeck.CreateDeck()
      Dim dDeck2 = clsDeck.CreateDeck()

      dDeck1.ShuffleDeck()
      dDeck2.ShuffleDeck()

      For i As Integer = 0 To dDeck1.Cards.Count - 1

         If (dDeck1.Cards(i).Rank <> dDeck2.Cards(i).Rank) _
               OrElse (dDeck1.Cards(i).Suit <> _
               dDeck2.Cards(i).Suit) Then

            Console.WriteLine("Not the Same!")
            Console.ReadLine()

      End If

      Next


   End Sub

This creates two card Decks and Shuffles each. The loop checks for similarities between the two chosen cards.

Conclusion

Using logic to create games is a valuable skill. As you can tell, creating a Blackjack game is quite easy. Go ahead and explore similar games!

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read