1. House Of Blackjack Codes
  2. Aol Blackjack Codes
  3. Blackjack C Program Codes
  4. Blackjack C++ Program

Code consistency: I see places where you surround equal sign with space (e.g. X = 0) and places where you don't (e.g. You should be more consistent. Refactor of displayhands: in this function, you have the same code repeated twice, once for the dealer and once for the player. There is opportunity to refactor the code by pulling the. $./blackjack 100 3 simple > url removed, login to view $ diff url removed, login to view url removed, login to view $ If diff reports any differences at all, you have a bug. Handing in and grading Use the submit280 program to submit the following files in project 4: url removed, login to view.

BlackJack Program Description

The code for the program begins with a clear (clc) statement to clear anything currently within the command window and workspace. Once this has run, three different arrays (assigned to variables deck, deck_value, and card_names) are then created. These arrays will serve as the basis for the rest of the following code. Once the arrays have been created, a print statement is used to create the welcome screen for the player, and an input is written to let the player choose when to proceed. After the game has been initialized the choice1 variable is set equal to 1 and a while loop that includes the rest of our code is set to run while that variable remains equivalent to 1 and stop if the variable’s value switches to 0. At the end of our code the choice1 variable is set equal to the player’s input, which will determine if the code should rerun again based on the player’s choice.

At the start of the code within the loop two variables are created, d and dealer_ace_card, to create the basis of a while loop that will run twice in order to deal two cards to the dealer. Within the loop, the program chooses a random number out of the length of the deck array using the randi and length operators. Once this number is chosen, it then goes to that position in the deck array and assigns the number to the variable card. The script then looks for the value associated with that card variable by going to the same position in the deck_value array and assigns that number to card_value2. The same process is used to get the correct position within the card_names string array. This value is assigned the variable card_name. In order to correctly hide the dealer’s first card, two if statements are included within the loop. If the code recognizes that it is the first time the loop has run (d = 1), it will store the first card in the variable first_card to be later displayed. However, if it is the second time the loop has run (d = 2) the code will print a message showing the dealer’s second card. Another if statement is then included to register if any of the cards dealt are an ace. If so, the value of dealer_ace_card is set equal to 1. This allows the code to register that there is an ace in the dealer’s hand. At the end of each iteration of the loop the deck array is updated to take out the card drawn. After the loop has been completed, the sum of the card values found is added together and assigned to the variable dealer_sum. In rare cases, the dealer may have drawn two aces at this point, which would make the dealer_sum 22. In order to account for this, an if statement was made to check if the dealer_sum is above 21 at this point. If so, one of the ace values is changed to 1 by subtracting 10 from the current dealer_sum.

Almost the exact same process described above is then repeated for the player. Two variables, i and ace_card, are created and a while loop is made to run twice. The variable card is chosen, then card_value and card_name are found in reference to that variable. An if statement is created to recognize if an ace has been drawn. For each iteration of the loop, the card drawn is displayed, and the value associated with that card is taken out of the deck array. After the loop has completed, a similar if statement is made to check if the player_sum has exceeded 21 at this point. If so, the value of one of the aces is changed to 1 by subtracting 10 from the player_sum. Then a print statement displays to the player the current total they have. At this point, the initial steps of the game have been completed.

Before proceeding to the player’s choices, the code first checks if either the player or the dealer have achieved BlackJack (21 in your starting hand). Three if statements are created to check these conditions. The first checks if the player_sum is equivalent to 21 while dealer_sum is not. If these conditions are met, a message is printed saying that the player has achieved BlackJack. The second does the reverse, checking if dealer_sum is equivalent to 21 while player_sum is not. If these conditions are met, a message is printed saying that the dealer has achieved BlackJack. The last runs if neither player_sum nor dealer_sum are equivalent to 21. If so, instructions are printed using an fprintf statement telling the player to choose 1 for hit and 0 for stand, and the next loop begins.

Blackjack C Program Code

The next loop is a while loop that is created to run while player_sum is less than 21 and dealer_sum is not equal to 21. At the start of the loop, variable choice is set equal to the input of the question “Would you like to hit or stand?:” From the printed instructions above, the player knows to input 1 for hit and 0 for stand. An if statement has been created in order to ensure that the input is equivalent to 1 or 0. If the input isn’t equivalent then a print statement will run showing there is an invalid input and the player will be prompted with the input again. If the input of the variable choice is equivalent to 1, then another card will be drawn from the deck using the same process outlined above. A random number is taken out of the deck array and assigned to card. Then the card variable is used in order to get the corresponding values from deck_value and card_names, and the card variable chosen will be taken out of the deck array. Lastly, an if statement will be used to check if the variable ace_card is equivalent to 1 and the player_sum is greater than 21. If both conditions are met, the program displays a message showing that the player will bust if the ace stays the value it is currently, player_sum will have 10 subtracted from its total to account for the ace’s change of 11 to 1, and the ace_card variable will be set equal to 0 once again in order to show it has accounted for the ace. At this point the player will be prompted again with the same input asking to hit or stand. If the player chooses 1 then another card is drawn in the same fashion as above. If the player chooses 0, the code knows to display the player’s final total stored in player_sum and to break out of the code. The loop will also end if player_sum exceeds 21 as values are added.

Once the loop has ended, an if statement is set to to check if player_sum has exceeded 21, and if so to display that the player has busted. An elseif is included to run if the starting_player_sum doesn’t equal 21, the player_sum is less than or equal to 21, and the dealer_sum doesn’t equal 21. If these logicals are found to all be true the dealer’s first card and starting total is printed and the next loop begins. The next loop is a while loop set to run while dealer_sum is less than player_sum or dealer_sum is less than 17. The loop displays that the dealer has hit and then includes an input in order to slow down the outputs shown in the command window. The exact same process for the previous loop is used except the values are stored in card_value2 and added to the dealer_sum. If statements are also included to check for an ace and change the value if needed. An if statement within the loop checks if dealer_sum is greater than 21. If so the program will print that the dealer has busted and break out of the code. At the end of each iteration of the loop another input is included in order to let the player choose when to proceed. After the loop, an if statement is included to display the dealer has stood if he has gotten a value higher than player_sum or tied with player_sum at a value of 17 or above. Then multiple if and elseif statements are included to compare the values of player_sum and dealer_sum. If dealer_sum is greater than player_sum without going over 21, the dealer wins, if player_sum is greater than dealer_sum without going over 21, the player wins, if both variables are equivalent it’s a tie, and if both variables go above 21 the dealer wins. All of these are associated with the proper print statement. At this point the player is asked if they would like to play again. If so, the code restarts again at the start of paragraph 2.

Variables

  1. deck – An array of numbers 1 through 52. This will serve as all the cards within our deck
  2. deck_value – An array in equal size to the deck array. Includes all the possible values that a card could be and puts the value in the same position as that of the deck array.
  3. card_names – A string array of the same size as deck and deck_value. Includes the name of all cards within the deck put within a correlated position to display the correct card name with the associated value.
  4. choice1 – A variable initially set equal to 1 that determines whether the rest of the code within the while loop will run based on the players input after the first run.
  5. d – Allows the dealer to draw their inital hand while d is not greater than 2.
  6. dealer_ace_card – Determines if the dealer has an ace within their hand. Whenever the dealer draws an ace, the value of this variable changes
  7. card – Chooses a random number out of the length of deck and then goes to that position within the deck array.
  8. card_value2 – Reads what number the card variable landed on and goes to that position within the deck_value array.
  9. card_name – Reads the value of card and goes that position within the card_names string array.
  10. first_card – Stores what the first card drawn by the dealer was, but doesn’t display it.
  11. shown_sumStores the known second card value.
  12. dealer_sum – The total that the dealer has from the cards that have been drawn.
  13. i – Allows the player to draw their initial hand while i is not greater than 2.
  14. ace_card – Determines if the player has an ace within their hand. Whenever the players draws an ace, the value of this variable changes.
  15. card_value – Similar to card_value2, it records the number that the card variable landed on and goes to that position within the deck_value array, but for the player
  16. player_sum – The total that the player has from the cards that have been drawn.
  17. starting_player_sum – Keeps the total of the players first two cards to let the code recognize if the player got BlackJack.
  18. choice – Set equal to the input the player chooses. Lets the code know what to run based off if the player chooses hit or stand.

Over/Under 7 Program Description

The game starts off with saying clear and clc which removes all previous stored values for variables and empty’s the command window. The variable play is put in place for a while loop that contains the whole game to keep the game running without having to restart. The coins variable is also not included in the while loop so that it does not reset while the player loops back to the top of the game multiple times, it will remain constant through every run until they end the game. The while play1 encompasses the actual gameplay to create the loop of continuous play if desired. The next step is to create the visual displays by using the my_scene and dice_sprites variables. The code uses fprintf statements to tell the player their initial coin value and the options for choosing their bet of over or under. Then an input command is given to give the choice variable a value. A while loop is set up after that reads the input choice and checks if the input was not one of the given options, if not it says invalid bet and prompts the input statement for a correct input. When the correct input for choice is set, the same steps occur with the bet amount. An input statement calls for the player to insert the amount of coins they wish to bet and a while loop checks that bet to make sure it is not more coins than they currently have. When a valid bet is set the next step is to randomize two dice values by using the randi(6,1,2) function. This randomly generates a number 1 through 6 twice. Then using the sum(dice_roll) command, the two dice values are summed up and printed out using the fprintf command. The draw_scene variable is then used to match both of the dice rolls to the proper visual dice display. The next step is for a series of if elseif statements to compare the choice of the bet against the sum of the dice rolled. It first checks if the variable choice was given a value of 2 and the bet was greater than 7. If it was, an fprintf command says the player won and it changes the value of coins to initial coins plus the bet of coins. The elseif statement checks if the value of choice was not equal to 2 and the sum being greater than 7. This results in a loss signaling the fprintf command to say the player loses and changes the value of coins to be the initial coins minus the lost bet. This process is repeated with two more identical if elseif statements that checks based off of the other choice options. After the choice is checked and the correct win loss function is executed the next step of the code is to check the current total of the coins. Using an if statement, the value of coins is checked to see if it equals 0, if so the game is over because the player lost all their coins. The game will then exit the game loop and the player will have to rerun the code to start back over with a fresh set of coins. The player then is prompted with an input statement that asks if they would like to play again. Once again, a while loop is used to ensure the player has to input a valid answer to playing again and setting the play variable with a correct value. A final if statement checks if the value of play is 1 then it goes back to the top just like the first while loop indicates and plays the game again. If the value of play is 0 the game thanks the player for playing using an fprintf statement, then exits the game loop thus ending the code.

Variables

  1. play=1 This variable is created so it can be used at the end of the code, an if statement checks to see the new value of play from the input, defending on the input the game will stay in the loop or not
  2. coins=1000 This is the starting amount for betting and is edited later throughout the game
  3. bet= input this will be the amount of coins placed into the pot for the dice roll
  4. my_scene = simpleGameEngine(‘retro_simple_dice.png’,16,16,8) This creates the image display for the dice
  5. dice_sprites = 1:6 This sets up the variables for different sprites
  6. choice = input This is where the player puts in their bet which is then checked in an if else statement against the sum of the dice
  7. dice_roll = randi(6,1,2); this creates a random roll of a dice
  8. dice_sum = sum(dice_roll) this then sums of up the value of the two dice

Home > Articles > Programming > Visual Basic

House Of Blackjack Codes

  1. Blackjack, Anyone?
< BackPage 5 of 8Next >

Blackjack, Anyone?

The sample program shows how to call many of the clsDeck methods, but it doesn't show them in action in a real game. In the next chapter you'll design a complete card game called Poker Squares, but for now, something a little simpler is in order. It's time to create a bare-bones version of blackjack.

Creating Blackjack's User Interface

The first step is to create the game's user interface. Perform the following steps:

  1. Start a new Standard EXE Visual Basic project.

  2. Set the form's properties to the values listed here:

    Name = CardForm

    AutoRedraw = True

    BackColor = Black

    Caption = 'Blackjack'

    Height = 6015

    ScaleMode = Pixel

    Width = 8250

  3. Add three CommandButton controls to the form, giving them the property values listed here:

    CommandButton #1

    Name = cmdStartGame

    Caption = '&Start Game'

    Height = 33

    Left = 19

    Top = 320

    Width = 89

    CommandButton #2

    Name = cmdHit

    Caption = '&Hit'

    Height = 33

    Left = 341

    Top = 320

    Width = 89

    CommandButton #3

    Name = cmdStay

    Caption = 'S&tay'

    Height = 33

    Left = 443

    Top = 320

    Width = 89

  4. Add a Timer control to the form.

Aol Blackjack Codes

You've now completed blackjack's user interface. Figure 8.6 shows what your main form will look like at this point. In the next section, you'll add handlers for the program's various controls.

Figure 8.6
The completed user interface.

Adding the Object Handlers

Next, you need to associate code with the various objects—the form, buttons, and timer—that make up the user interface. To accomplish this task, perform the following steps:

Blackjack C Program Codes

  1. Double-click the form to bring up the code window, and add the following form handlers to it. You can either type the code or copy it from the BlackJack1.txt file, which you can find in the Chap08Code directory of this book's CD-ROM.

Listing 8.8 The Form Handlers

Analysis - The Form_Load subroutine, which Visual Basic calls when the user starts the program, disables the Hit and Stay buttons (Lines 2 and 4) and the starts a new game by simulating a click on the Start Game button (Line 4). Line 8 in the Form_Unload subroutine removes the frmCards form from memory at the same time the main form closes.
  1. Add to the code window the CommandButton handlers in Listing 8.9. You can either type the code or copy it from the BlackJack2.txt file, which you can find in the Chap08Code directory of this book's CD-ROM.

Listing 8.9 The CommandButton Handlers

Analysis - The cmdHit_Click subroutine responds to the Hit button. Line 2 increases the player's card count, and Line 3 deals another card into the player's hand. A call to GetCardTotal (Line 5) gets the player's current score, and if the total is over 21 (Line 6), the game is over (Lines 7 to 9).
Analysis - The cmdStartGame_Click subroutine responds to the Start Game button. Line 14 clears the screen, and Lines 16 and 17 enable the Hit and Stay buttons. Then, Lines 18 and 19 create a new Deck object and shuffle it. Lines 20 and 21 initialize the card counts, and Lines 22 to 24 print the 'DEALER'S HAND' label. Lines 25 and 26 deal two cards to the dealer, one of them face down, while Line 30 does the same thing for the player's hand, except this time both cards are dealt face-up.
Analysis - The cmdStay_Click subroutine responds to the Stay button. Lines 34 and 35 disable the Hit and Stay buttons in preparation for the dealer's turn. Line 36 turns on the timer, which gets the dealer's turn going.
  1. Add to the code window the Timer handler shown in Listing 8.10. You can either type the code or copy it from the BlackJack3.txt file, which you can find in the Chap08Code directory of this book's CD-ROM.

Listing 8.10 The Timer Handler

Analysis - The Timer1_Timer subroutine implements the computer player and gets called for each timer event. Line 2 gets the dealer's current card total. If the total is greater than 21, Line 4 notifies the player that the dealer has busted and Line 5 turns off the timer. If the dealer's total is greater than 16, the dealer stays (Lines 8 and 9) and the current game ends (Line 10). Finally, if the dealer's total is less than or equal to 16, Lines 12 to 14 add a card to the dealer's hand.

Completing the Game

Almost there! After you add the general game subroutines and the required modules, you'll be ready to play blackjack. Here are the final steps:

  1. Add to the code window the general game subroutines shown in Listing 8.11. You can either type the code or copy it from the BlackJack4.txt file, which you can find in the Chap08Code directory of this book's CD-ROM.

Listing 8.11 The General Subroutines

Analysis - The GetCardTotal function calculates the card total for the player or dealer, depending upon the value of the plyer parameter. You'll study this function in detail later in this chapter. The EndGame subroutine shows the dealer's hand (Line 30), gets the player's and dealer's card totals (Lines 31 and 32), deletes the deck (Line 33), sets the game's buttons (Lines 34 to 36), and displays a message telling the player who won (Lines 37 to 45).
  1. Add to the top of the code window the variable declarations and enumerations in Listing 8.12. You can either type the code or copy it from the BlackJack5.txt file, which you can find in the Chap08Code directory of this book's CD-ROM.

Blackjack C++ Program

Listing 8.12 The Declarations

  1. Add the Cards.frm form and the clsCard.cls, clsDeck.cls, and Cards.bas modules to the project, just as you did with the previous demo program.

  2. Save the game's main form as CardForm.frm and the project file as BlackJack.vbp.

Blackjack c++ program

You've now completed the blackjack program.

Playing Blackjack

When you run the program, you see the screen shown in Figure 8.7. The dealer's hand is at the top of the screen, and the player's hand is at the bottom. The objective of the game is to get as close to 21 as you can without going over. (The cards 2 through 10 are worth 2–10 points. All face cards count as 10 points, and an ace can count as either 1 or 11 points.)

Figure 8.7
The main blackjack screen.

To draw a card, press Enter or click the Hit button. Continue to draw until you're ready to stop, and then click the Stay button. If you haven't gone over 21, the dealer then begins to draw cards. The dealer must continue to draw until it reaches 17 or better. The winning hand is the one that's closest to 21 without going over (see Figure 8.8).

Figure 8.8
Winning at blackjack.

Programming Blackjack

Program

Obviously, this program isn't a complete blackjack game. Many of the game's details are ignored (like doubling-down and insurance), there's no betting, and each game is only a single hand. However, the program does demonstrate how you can use the clsDeck and clsCard classes when programming an actual game. Much of the code in the program needs no explanation. However, one function, GetCardTotal, is the heart of the game and worthy of close examination.

GetCardTotal analyzes a blackjack hand and comes up with a total. This might seem like a trivial task until you recall that an ace can count as either 1 or 11 points. Moreover, a hand might have as many as four aces, further complicating the point-counting process.

To keep this task simple, GetCardTotal assumes that it will count all aces in a hand as the same value. The point value that the program chooses depends on the hand's point total. (Obviously, the program will never use 11 as an ace point value if the hand has more than one ace, because two 11-point aces will bring the hand to over 21.)

First, the program determines how many cards are in the hand by calling NumCardsInHand:

This clsDeck method takes as its single parameter the number of the hand to check. The program uses the value returned from NumCardsInHand to set up a For loop that looks at each card in the hand. In the loop, the program first calculates the value of the current card:

Program

This calculation results in a value from 0 to 12 (ace to king). If the card's value is greater than 10, indicating a face card (jack, queen, or king), the program sets the card's value to Ten:

(The constants range from Ace, which equals 0, to King, which equals 12. Therefore, Ten is actually the integer value 9, not 10 as you might think.)

If the card turns out to be an ace, the program increments the number of aces in the hand and sets value to 10:

The program first assumes that it will treat the ace as a high card that is worth one point more than the face cards.

Next, the program adds the value of the current card to the total so far:

Because the card values range from 0 to 12, the added point value is actually value+1.

After totaling the values of all cards in the hand, the program checks whether the hand is over 21. If it is, and it contains aces, the program subtracts 10 for each ace in the hand so that the values of the aces all change to 1:

The function then returns the total to the calling method:

That's all there is to analyzing a blackjack hand (although this is a simplified version of the game). Now you're ready to move on to more challenging card games.

Related Resources

There are currently no related titles. Please check back later.

Coments are closed
Scroll to top