Creating a Blackjack Game in Visual Basic

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

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!



About the Author

Hannes DuPreez

Hannes du Preez has been a Microsoft MVP for Visual Basic from 2008 to 2017. He loves technology and loves Visual Basic. He loves writing articles and proving that Visual Basic is more powerful than what most believe. You are most welcome to reach him at: ojdupreez1978@gmail.com

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date