Black Jack in VB.NET
Written By: Pedri
- 12 Jan 2008 -
Description: This tutorial teaches us to program a player vs dealer blackjack game using Visual Basic.NET
Dealing a New Game
Now let's create the function that allows us to deal a new game. First we need to find out what we know about this functionality. On the deal each player gets two cards. These two cards are dealt from the deck.
So let's start to create this functionality:
We're going to add the functionality to the button that we added earlier, and the result will be displayed in the two textboxes. Let's take a look at the structure (let's call it deal()).
Private Sub deal() End Sub
The easiest way to start off with this function is to take the ArrayList that we have, and get the next four items from it (two for you and two for the dealer). Basically well just have a variable that's constantly increased, and then well get the item in the deck ArrayList at the position represented by that counter. The code should look something like this:
Private Sub deal() Try Dim currentDeckPosition As Integer = 0 TextBox1.Text = "" TextBox2.Text = "" TextBox1.Text += deck(currentDeckPosition) currentDeckPosition += 1 TextBox1.Text += deck(currentDeckPosition) currentDeckPosition += 1 TextBox2.Text += deck(currentDeckPosition) currentDeckPosition += 1 TextBox2.Text += deck(currentDeckPosition) currentDeckPosition += 1 Catch ex As Exception End Try End Sub
You'll notice that I have added a try catch to the method. Basically we need to handle when the deck size is larger than the total amount of items in the deck. Once this happen we need to create a new deck. We'll get to this a bit later. First let's move some of the variable to global variable. Lets move currentDeckPosition to a global variable:
Private currentDeckPosition As Integer = 0
Now every time when the person clicks on the deal button he'll get a new card from the deck. Now lets handle the fact that once there's no more cards we need to create a new deck. For now we'll use the try catch function. We can clean this up at a later stage. So in the Catch ex As Exception let's add some functionality to clean the deck, and re-deal it. Basically we want to set the deck ArrayList to a new ArrayList and we want to reset the clause of the currentDeckPosition. Something like this:
deck = New ArrayList() currentDeckPosition = 0
Then we want to call the fillDeck() function, which will create a new deck, and then call the deal() function to create a new deal. Something like this will do for now:
This is what out catch function looks like now:
Catch ex As Exception currentDeckPosition = 0 deck = New ArrayList() fillDeck() deal() End Try
Now we basically have the functionality that will allow you to create a new game every time.
Now let's take a look at keeping score. We'll need to make some minor changes to our current functionality to allow us to use this.