Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Our game of blackjack is a simple card game simulation where you play against th

ID: 3701645 • Letter: O

Question

Our game of blackjack is a simple card game simulation where you play against the computer. The goal is to beat the computer by getting closer to 21 without going over.

NOTE: You may only write this program in java using conditional statements and loops.


Points:
1 – 10 - worth the value
Face cards - are worth 10 points
Aces – If dealt to the player, the player can choose whether it’s worth 1 or 11 points. If dealt to
the computer, it’s automatically worth 11 points.

Play:
The player starts the game with $50. Play begins with the player placing a bet. The computer deals 2 cards to the player and 2 to itself. The player sees his own card values, but can only see one of the computer’s card values. After the deal, the player can choose to receive more cards (one at a time) in order to get closer to 21. When the player doesn’t want any more cards, it’s the computer’s turn. The computer must take more cards until it has at least 17 points. The computer cannot take any cards if it has 17 or more points.

Scoring:
If the player’s score is closer to 21 (without going over) than the computer’s, the player wins whatever he bet. If the computer is closer to 21 (without going over), if the player goes over (regardless of whether the computer does or not) or if there is a tie, the computer wins (and the player loses his bet).

Explanation / Answer

Hi, this program will need the classes defined in Card.java, Deck.java, Hand.java, and BlackjackHand.java and the main file Blackjack.java.

Blackjack.java:

package game;

import java.util.Scanner;

/*
   This program lets the user play Blackjack. The computer
   acts as the dealer. The user has a stake of $50, and
   makes a bet on each game. The user can leave at any time,
   or will be kicked out when he loses all the money.
   House rules: The dealer hits on a total of 16 or less
   and stands on a total of 17 or more. Dealer wins ties.
   A new deck of cards is used for each game.
*/

public class Blackjack {
   static Scanner scanner = new Scanner(System.in);
   public static void main(String[] args) {

      int money;          // Amount of money the user has.
      int bet;            // Amount user bets on a game.
      boolean userWins;   // Did the user win the game?
    
      System.out.println("Welcome to the game of blackjack.");
    
      money = 50; // User starts with $50.

      while (true) {
          System.out.println("You have " + money + " dollars.");
          do {
             System.out.println("How many dollars do you want to bet? (Enter 0 to end.)");
             bet = scanner.nextInt();
             if (bet < 0 || bet > money)
                 System.out.println("Your answer must be between 0 and " + money + '.');
          } while (bet < 0 || bet > money);
          if (bet == 0)
             break;
          userWins = playBlackjack();
          if (userWins)
             money = money + bet;
          else
             money = money - bet;
          System.out.println();
          if (money == 0) {
             System.out.println("Looks like you've are out of money!");
             break;
          }
      }
    
      System.out.println();
      System.out.println("You leave with $" + money + '.');

   } // end main()


   static boolean playBlackjack() {
         // Let the user play one game of Blackjack.
         // Return true if the user wins, false if the user loses.

      Deck deck;                  // A deck of cards. A new deck for each game.
      BlackjackHand dealerHand;   // The dealer's hand.
      BlackjackHand userHand;     // The user's hand.
    
      deck = new Deck();
      dealerHand = new BlackjackHand();
      userHand = new BlackjackHand();

      /* Shuffle the deck, then deal two cards to each player. */
    
      deck.shuffle();
      dealerHand.addCard( deck.dealCard() );
      dealerHand.addCard( deck.dealCard() );
      userHand.addCard( deck.dealCard() );
      userHand.addCard( deck.dealCard() );
    
      System.out.println();
      System.out.println();
    
      /* Check if one of the players has Blackjack (two cards totaling to 21).
         The player with Blackjack wins the game. Dealer wins ties.
      */
    
      if (dealerHand.getBlackjackValue() == 21) {
           System.out.println("Dealer has the " + dealerHand.getCard(0)
                                   + " and the " + dealerHand.getCard(1) + ".");
           System.out.println("User has the " + userHand.getCard(0)
                                     + " and the " + userHand.getCard(1) + ".");
           System.out.println();
           System.out.println("Dealer has Blackjack. Dealer wins.");
           return false;
      }
    
      if (userHand.getBlackjackValue() == 21) {
           System.out.println("Dealer has the " + dealerHand.getCard(0)
                                   + " and the " + dealerHand.getCard(1) + ".");
           System.out.println("User has the " + userHand.getCard(0)
                                     + " and the " + userHand.getCard(1) + ".");
           System.out.println();
           System.out.println("You have Blackjack. You win.");
           return true;
      }
    
      /* If neither player has Blackjack, play the game. First the user
          gets a chance to draw cards (i.e., to "Hit"). The while loop ends
          when the user chooses to "Stand". If the user goes over 21,
          the user loses immediately.
      */
    
      while (true) {
        
           /* Display user's cards, and let user decide to Hit or Stand. */

           System.out.println();
           System.out.println();
           System.out.println("Your cards are:");
           for ( int i = 0; i < userHand.getCardCount(); i++ )
              System.out.println("    " + userHand.getCard(i));
           System.out.println("Your total is " + userHand.getBlackjackValue());
           System.out.println();
           System.out.println("Dealer is showing the " + dealerHand.getCard(0));
           System.out.println("Hit (H) or Stand (S)? ");
           String userAction; // User's response, 'H' or 'S'.
           do {
              userAction = scanner.next().toUpperCase();
              if (!userAction.equals("H") && !userAction.equals("S"))
                  System.out.println("Please respond H or S: ");
           } while (!userAction.equals("H") && !userAction.equals("S"));

           /* If the user Hits, the user gets a card. If the user Stands,
              the loop ends (and it's the dealer's turn to draw cards).
           */

           if ( userAction.equals("S")) {
                   // Loop ends; user is done taking cards.
               break;
           }
           else { // userAction is 'H'. Give the user a card.
                   // If the user goes over 21, the user loses.
               Card newCard = deck.dealCard();
               userHand.addCard(newCard);
               System.out.println();
               System.out.println("User hits.");
               System.out.println("Your card is the " + newCard);
               System.out.println("Your total is now " + userHand.getBlackjackValue());
               if (userHand.getBlackjackValue() > 21) {
                   System.out.println();
                   System.out.println("You busted by going over 21. You lose.");
                   System.out.println("Dealer's other card was the "
                                                      + dealerHand.getCard(1));
                   return false;
               }
           }
         
      } // end while loop
    
      /* If we get to this point, the user has Stood with 21 or less. Now, it's
         the dealer's chance to draw. Dealer draws cards until the dealer's
         total is >= 17. If dealer goes over 21, the dealer loses.
      */

      System.out.println();
      System.out.println("User stands.");
      System.out.println("Dealer's cards are");
      System.out.println("    " + dealerHand.getCard(0));
      System.out.println("    " + dealerHand.getCard(1));
      while (dealerHand.getBlackjackValue() <= 16) {
         Card newCard = deck.dealCard();
         System.out.println("Dealer hits and gets the " + newCard);
         dealerHand.addCard(newCard);
         if (dealerHand.getBlackjackValue() > 21) {
            System.out.println();
            System.out.println("Dealer busted by going over 21. You win.");
            return true;
         }
      }
      System.out.println("Dealer's total is " + dealerHand.getBlackjackValue());
    
      /* If we get to this point, both players have 21 or less. We
         can determine the winner by comparing the values of their hands. */
    
      System.out.println();
      if (dealerHand.getBlackjackValue() == userHand.getBlackjackValue()) {
         System.out.println("Dealer wins on a tie. You lose.");
         return false;
      }
      else if (dealerHand.getBlackjackValue() > userHand.getBlackjackValue()) {
         System.out.println("Dealer wins, " + dealerHand.getBlackjackValue()
                          + " points to " + userHand.getBlackjackValue() + ".");
         return false;
      }
      else {
         System.out.println("You win, " + userHand.getBlackjackValue()
                          + " points to " + dealerHand.getBlackjackValue() + ".");
         return true;
      }

   } // end playBlackjack()


} // end class Blackjack

BlackjackHand.java:

package game;


/*
   A subclass of the Hand class that represents a hand of cards
   in the game of Blackjack. To the methods inherited form Hand,
   it adds the method getBlackjackHand(), which returns the value
   of the hand for the game of Blackjack.
*/

public class BlackjackHand extends Hand {

     public int getBlackjackValue() {
            // Returns the value of this hand for the
            // game of Blackjack.

         int val;      // The value computed for the hand.
         boolean ace; // This will be set to true if the
                       //   hand contains an ace.
         int cards;    // Number of cards in the hand.

         val = 0;
         ace = false;
         cards = getCardCount();

         for ( int i = 0; i < cards; i++ ) {
                 // Add the value of the i-th card in the hand.
             Card card;    // The i-th card;
             int cardVal; // The blackjack value of the i-th card.
             card = getCard(i);
             cardVal = card.getValue(); // The normal value, 1 to 13.
             if (cardVal > 10) {
                 cardVal = 10;   // For a Jack, Queen, or King.
             }
             if (cardVal == 1) {
                 ace = true;     // There is at least one ace.
             }
             val = val + cardVal;
          }

             // Now, val is the value of the hand, counting any ace as 1.
             // If there is an ace, and if changing its value from 1 to
             // 11 would leave the score less than or equal to 21,
             // then do so by adding the extra 10 points to val.

          if ( ace == true && val + 10 <= 21 )
              val = val + 10;

          return val;

     } // end getBlackjackValue()

} // end class BlackjackHand


Hand.java:

package game;

/*
    An object of type Hand represents a hand of cards. The maximum number of
    cards in the hand can be specified in the constructor, but by default
    is 5. A utility function is provided for computing the value of the
    hand in the game of Blackjack.
*/

import java.util.Vector;

public class Hand {

   private Vector<Card> hand; // The cards in the hand.

   public Hand() {
       // Create a Hand object that is initially empty.
       hand = new Vector<Card>();
   }

   public void clear() {
       // Discard all the cards from the hand.
       hand.removeAllElements();
   }

   public void addCard(Card c) {
       // Add the card c to the hand. c should be non-null. (If c is
       // null, nothing is added to the hand.)
       if (c != null)
           hand.addElement(c);
   }

   public void removeCard(Card c) {
       // If the specified card is in the hand, it is removed.
       hand.removeElement(c);
   }

   public void removeCard(int position) {
       // If the specified position is a valid position in the hand,
       // then the card in that position is removed.
       if (position >= 0 && position < hand.size())
           hand.removeElementAt(position);
   }

   public int getCardCount() {
       // Return the number of cards in the hand.
       return hand.size();
   }

   public Card getCard(int position) {
       // Get the card from the hand in given position, where positions
       // are numbered starting from 0. If the specified position is
       // not the position number of a card in the hand, then null
       // is returned.
       if (position >= 0 && position < hand.size())
           return (Card) hand.elementAt(position);
       else
           return null;
   }

   public void sortBySuit() {
       // Sorts the cards in the hand so that cards of the same suit are
       // grouped together, and within a suit the cards are sorted by value.
       // Note that aces are considered to have the lowest value, 1.
       Vector<Card> newHand = new Vector<Card>();
       while (hand.size() > 0) {
           int pos = 0; // Position of minimal card.
           Card c = (Card) hand.elementAt(0); // Minumal card.
           for (int i = 1; i < hand.size(); i++) {
               Card c1 = (Card) hand.elementAt(i);
               if (c1.getSuit() < c.getSuit() || (c1.getSuit() == c.getSuit() && c1.getValue() < c.getValue())) {
                   pos = i;
                   c = c1;
               }
           }
           hand.removeElementAt(pos);
           newHand.addElement(c);
       }
       hand = newHand;
   }

   public void sortByValue() {
       // Sorts the cards in the hand so that cards of the same value are
       // grouped together. Cards with the same value are sorted by suit.
       // Note that aces are considered to have the lowest value, 1.
       Vector<Card> newHand = new Vector<Card>();
       while (hand.size() > 0) {
           int pos = 0; // Position of minimal card.
           Card c = (Card) hand.elementAt(0); // Minumal card.
           for (int i = 1; i < hand.size(); i++) {
               Card c1 = (Card) hand.elementAt(i);
               if (c1.getValue() < c.getValue() || (c1.getValue() == c.getValue() && c1.getSuit() < c.getSuit())) {
                   pos = i;
                   c = c1;
               }
           }
           hand.removeElementAt(pos);
           newHand.addElement(c);
       }
       hand = newHand;
   }

Deck.java:

package game;

/*
    An object of type Deck represents an ordinary deck of 52 playing cards.
    The deck can be shuffled, and cards can be dealt from the deck.
*/

public class Deck {

   private Card[] deck; // An array of 52 Cards, representing the deck.
   private int cardsUsed; // How many cards have been dealt from the deck.

   public Deck() {
       // Create an unshuffled deck of cards.
       deck = new Card[52];
       int cardCt = 0; // How many cards have been created so far.
       for (int suit = 0; suit <= 3; suit++) {
           for (int value = 1; value <= 13; value++) {
               deck[cardCt] = new Card(value, suit);
               cardCt++;
           }
       }
       cardsUsed = 0;
   }

   public void shuffle() {
       // Put all the used cards back into the deck, and shuffle it into
       // a random order.
       for (int i = 51; i > 0; i--) {
           int rand = (int) (Math.random() * (i + 1));
           Card temp = deck[i];
           deck[i] = deck[rand];
           deck[rand] = temp;
       }
       cardsUsed = 0;
   }

   public int cardsLeft() {
       // As cards are dealt from the deck, the number of cards left
       // decreases. This function returns the number of cards that
       // are still left in the deck.
       return 52 - cardsUsed;
   }

   public Card dealCard() {
       // Deals one card from the deck and returns it.
       if (cardsUsed == 52)
           shuffle();
       cardsUsed++;
       return deck[cardsUsed - 1];
   }

} // end class Deck


Card.java:

package game;

/*
   An object of class card represents one of the 52 cards in a
   standard deck of playing cards. Each card has a suit and
   a value.
*/

public class Card {

   public final static int SPADES = 0, // Codes for the 4 suits.
           HEARTS = 1, DIAMONDS = 2, CLUBS = 3;

   public final static int ACE = 1, // Codes for the non-numeric cards.
           JACK = 11, // Cards 2 through 10 have their
           QUEEN = 12, // numerical values for their codes.
           KING = 13;

   private final int suit; // The suit of this card, one of the constants
                           // SPADES, HEARTS, DIAMONDS, CLUBS.

   private final int value; // The value of this card, from 1 to 11.

   public Card(int theValue, int theSuit) {
       // Construct a card with the specified value and suit.
       // Value must be between 1 and 13. Suit must be between
       // 0 and 3. If the parameters are outside these ranges,
       // the constructed card object will be invalid.
       value = theValue;
       suit = theSuit;
   }

   public int getSuit() {
       // Return the int that codes for this card's suit.
       return suit;
   }

   public int getValue() {
       // Return the int that codes for this card's value.
       return value;
   }

   public String getSuitAsString() {
       // Return a String representing the card's suit.
       // (If the card's suit is invalid, "??" is returned.)
       switch (suit) {
       case SPADES:
           return "Spades";
       case HEARTS:
           return "Hearts";
       case DIAMONDS:
           return "Diamonds";
       case CLUBS:
           return "Clubs";
       default:
           return "??";
       }
   }

   public String getValueAsString() {
       // Return a String representing the card's value.
       // If the card's value is invalid, "??" is returned.
       switch (value) {
       case 1:
           return "Ace";
       case 2:
           return "2";
       case 3:
           return "3";
       case 4:
           return "4";
       case 5:
           return "5";
       case 6:
           return "6";
       case 7:
           return "7";
       case 8:
           return "8";
       case 9:
           return "9";
       case 10:
           return "10";
       case 11:
           return "Jack";
       case 12:
           return "Queen";
       case 13:
           return "King";
       default:
           return "??";
       }
   }

   public String toString() {
       // Return a String representation of this card, such as
       // "10 of Hearts" or "Queen of Spades".
       return getValueAsString() + " of " + getSuitAsString();
   }

} // end class Card

Output:

Welcome to the game of blackjack.
You have 50 dollars.
How many dollars do you want to bet? (Enter 0 to end.)
20


Your cards are:
    9 of Clubs
    King of Spades
Your total is 19

Dealer is showing the 4 of Spades
Hit (H) or Stand (S)?
A
Please respond H or S:
S

User stands.
Dealer's cards are
    4 of Spades
    4 of Diamonds
Dealer hits and gets the King of Clubs
Dealer's total is 18

You win, 19 points to 18.

You have 70 dollars.
How many dollars do you want to bet? (Enter 0 to end.)
0

You leave with $70.

Thanks :) Please upvote if this solves your query :)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote