Question

Write a Java program to simulate Blackjack. The program should be as basic as possible while...

Write a Java program to simulate Blackjack. The program should be as basic as possible while following the rules below. Thanks

a. There is one deck of cards

b. Cards are drawn randomly using (Shuffle() method)

c. The value of a hand is computed by adding the values of the cards in hand

d. The value of a numeric card such as four is its numerical value

e. The value of a face card is 10

f. Ace is either 1 or 11

g. Ace is 11 unless it puts the total value of the hand over 21

h. Second, third or fourth ace are all counted as 1

i. Generate a random number between 16-21. Keep drawing as many cards (AddCard() method) as needed until the total value of the hand is equal or greater than its random number

j. You dont need to re-shuffle the remaining cards after each drawing

k. You should have a class Hand, in which you compute and return the value of a hand based on the above rules

l. You should have a "public class BlackjackHand extends Hand", which notifies the user if it is a Blackjack(only two cards are drawn with the total value of 21)

m. Log all drawn cards and the total value of a hand

n. Sort 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. Cards are sorted into order of increasing value. Note that aces are considered to have the lowest value.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.ArrayList;

import java.util.Random;

import java.util.Scanner;

import java.util.*;

class Deck

{

public static final int HEARTS = 0;

public static final int DIAMONDS = 1;

public static final int SPADES = 2;

public static final int CLUBS = 3;

public static final int JACK = 11;

public static final int QUEEN = 12;

public static final int KING = 13;

public static final int ACE = 14;

private ArrayList<Card> deck;

//This creates a deck. A deck starts as a list of 52 cards.

//We loop through each suit and rank and construct a card and

//add it to the deck.

public Deck()

{

deck = new ArrayList<Card>();

for(int rank = 2; rank <= ACE; rank++)

{

for(int suit = HEARTS; suit <= CLUBS; suit++)

{

Card card = new Card(rank, suit);

deck.add(card);

}

}

shuffle();//Shuffling the cards for the first time.

}

//This getter method returns the ArrayList of cards.

public ArrayList getCards()

{

return deck;

}

//This deals the first card from the deck by removing it.

public Card deal()

{

return deck.remove(0);

}

//This shuffles the deck by making 52 swaps of cards positions.

public void shuffle()

{

for(int i = 0; i < deck.size(); i++)

{

Random r = new Random();

int randomIndex = r.nextInt(52);

Card one = deck.get(i);

Card two = deck.get(randomIndex);

deck.set(i,two);

deck.set(randomIndex,one);

}

}

}

class Hand

{

@Override

public String toString() {

return "Hand [cards=" + cards + "]";

}

public static final int HEARTS = 0;

public static final int DIAMONDS = 1;

public static final int SPADES = 2;

public static final int CLUBS = 3;

public static final int JACK = 11;

public static final int QUEEN = 12;

public static final int KING = 13;

public static final int ACE = 14;

private ArrayList <Card> cards;

//This constructor sets up our hand by initializing our ArrayList.

public Hand()

{

cards = new ArrayList<Card>();

}

//This adds a card to our hand.

public void addCard(Card c)

{

cards.add(c);

}

//This returns the value of the hand as an integer.

//The value of the hand is the sum of the values of the individual cards.

//There is also an adjustment made for the value of an ace

//which can be 11 or 1 depending on the situation.

public int getValue()

{

int sum = 0;

int aceCount = 0;

for(Card c: cards)

{

sum += c.getValue();

if(c.getRank() == ACE)

{

aceCount++;

}

}

while(sum > 21 && aceCount > 0)

{

sum -= 10;

aceCount--;

}

return sum;

}

//Return if this hand has a blackjack.

public boolean hasBlackJack()

{

return getValue() == 21 && cards.size() == 2;

}

//Return if the hand is busted, which means it has value

//greater than 21.

public boolean busted()

{

return getValue() > 21;

}

public ArrayList<Card> getCards()

{

return cards;

}

}

class Card

{

public static final int HEARTS = 0;

public static final int DIAMONDS = 1;

public static final int SPADES = 2;

public static final int CLUBS = 3;

public static final int JACK = 11;

public static final int QUEEN = 12;

public static final int KING = 13;

public static final int ACE = 14;

//This represents the rank of the card, the value from 2 to Ace.

private int rank;

//This represents the suit of the card, one of hearts, diamonds, spades, or clubs.

private int suit;

//This represents the value of the card, which is 10 for face cards or 11 for an Ace.

private int value;

//The reason for the two X's in the front provide padding so numbers

//have their String representation for their corresponding index.

private String[]ranks = {"X","X","Two of ","Three of ","Four of ","Five of ","Six of ","Seven of ","Eight of ","Eight of ","Nine of ","Ten of ","Jack of ","Queen of ", "King of ","Ace of "};

//The String array makes it easier to get the String value of the Card for its suit.

private String[]suits = {"Hearts","Diamonds","Spades","Clubs"};

//This is the constructor to create a new card.

//To create a new card we pass in its rank and its suit.

public Card(int r, int s)

{

rank = r;

suit = s;

}

public void setRank(int rank)

{

this.rank = rank;

}

public void setValue(int value)

{

this.value = value;

}

//This getter method returns the rank of the cards an an integer.

public int getRank()

{

return rank;

}

//This getter method returns the suit of the cards an integer.

public int getSuit()

{

return suit;

}

//This getter method returns the value of the card as an integer.

//For facecards the value is 10, which is different than their rank

//underlying value.

//Four aces the default value is 11.

public int getValue()

{

int value = rank;

if(rank > 10)

{

value = 10;

}

if(rank == ACE)

{

value = 11;

}

return value;

}

//This utility method converts from a rank integer to a String.

public String rankToString(int r)

{

return ranks[r];

}

//This utility method converts from a suit integer to a String.

public String suitToString(int s)

{

return suits[s];

}

//Returns the String version of the suit.

public String getSuitAsString()

{

return suitToString(suit);

}

//Returns the String version of the rank.

public String getRankAsString()

{

return rankToString(rank);

}

//This toString method returns the String representation of a card

//which will be two characters.

//For instance, the two of hearts would return 2HEARTS.

//Face cards have a short string so the ace of spades would return AceSpades.

public String toString()

{

String rankString = ranks[rank];

String suitString = suits[suit];

return rankString + suitString;

}

}

class Randomizer

{

public static Random theInstance = null;

public Randomizer()

{

}

public static Random getInstance()

{

if(theInstance == null)

{

theInstance = new Random();

}

return theInstance;

}

//Returns a random boolean value.

public static boolean nextBoolean()

{

return Randomizer.getInstance().nextBoolean();

}

//This method simulated a wieghted coin flip which will return

//true with the probability passed as a parameter.

public static boolean nextBoolean(double probability)

{

return Randomizer.nextDouble() < probability;

}

//This method returns a random integer.

public static int nextInt()

{

return Randomizer.getInstance().nextInt();

}

//This method returns a random integer between 0 and n, exclusive.

public static int nextInt(int n)

{

return Randomizer.getInstance().nextInt(n);

}

//Returns a number between min and mix, inclusive.

public static int nextInt(int min, int max)

{

return min + Randomizer.nextInt(max - min + 1);

}

//Returns a random double between 0 and 1.

public static double nextDouble()

{

return Randomizer.getInstance().nextDouble();

}

//Returns a random double between min and max.

public static double nextDouble(double min, double max)

{

return min + (max - min) * Randomizer.nextDouble();

}

}

public class Blackjack

{

private static final int HEARTS = 0;

private static final int DIAMONDS = 1;

private static final int SPADES = 2;

private static final int CLUBS = 3;

  

private static final int JACK = 11;

private static final int QUEEN = 12;

private static final int KING = 13;

private static final int ACE = 14;

  

// The starting bankroll for the player.

private static final int STARTING_BANKROLL = 100;

public static String readLine(String str){

System.out.println(str);

Scanner sc = new Scanner(System.in);

return sc.nextLine();

}

public static int readInt(String str){

System.out.println(str);

Scanner sc = new Scanner(System.in);

return sc.nextInt();

}

  

/**

* Ask the player for a move, hit or stand.

*

* @return A lowercase string of "hit" or "stand"

* to indicate the player's move.

*/

private String getPlayerMove()

{

while(true)

{

String move = readLine("Enter move (hit/stand): ");

move = move.toLowerCase();

  

if(move.equals("hit") || move.equals("stand"))

{

return move;

}

System.out.println("Please try again.");

}

}

  

/**

* Play the dealer's turn.

*

* The dealer must hit if the value of the hand is less

* than 17.

*

* @param dealer The hand for the dealer.

* @param deck The deck.

*/

private void dealerTurn(Hand dealer, Deck deck)

{

while(true)

{

System.out.println("Dealer's hand");

System.out.println(dealer);

  

int value = dealer.getValue();

System.out.println("Dealer's hand has value " + value);

  

readLine("Enter to continue...");

  

if(value < 17)

{

System.out.println("Dealer hits");

Card c = deck.deal();

dealer.addCard(c);

  

System.out.println("Dealer card was " + c);

  

if(dealer.busted())

{

System.out.println("Dealer busted!");

break;

}

}

else

{

System.out.println("Dealer stands.");

break;

}

}

}

  

/**

* Play a player turn by asking the player to hit

* or stand.

*

* Return whether or not the player busted.

*/

private boolean playerTurn(Hand player, Deck deck)

{

while(true)

{

String move = getPlayerMove();

  

if(move.equals("hit"))

{

Card c = deck.deal();

System.out.println("Your card was: " + c);

player.addCard(c);

System.out.println("Player's hand");

System.out.println(player.toString());

  

if(player.busted())

{

return true;

}

}

else

{

// If we didn't hit, the player chose to

// stand, which means the turn is over.

return false;

}

  

}

}

  

/**

* Determine if the player wins.

*

* If the player busted, they lose. If the player did

* not bust but the dealer busted, the player wins.

*

* Then check the values of the hands.

*

* @param player The player hand.

* @param dealer The dealer hand.

* @return

*/

private boolean playerWins(Hand player, Hand dealer)

{

if(player.busted())

{

return false;

}

  

if(dealer.busted())

{

return true;

}

  

return player.getValue() > dealer.getValue();

}

  

/**

* Check if there was a push, which means the player and

* dealer tied.

*

* @param player The player hand.

* @param dealer The dealer hand.

* @return

*/

private boolean push(Hand player, Hand dealer)

{

return player.getValue() == dealer.getValue();

}

  

/**

* Find the winner between the player hand and dealer

* hand. Return how much was won or lost.

*/

private double findWinner(Hand dealer, Hand player, int bet)

{

if(playerWins(player, dealer))

{

System.out.println("Player wins!");

  

if(player.hasBlackJack())

{

return 1.5 * bet;

}

  

return bet;

}

else if(push(player, dealer))

{

System.out.println("You push");

return 0;

}

else

{

System.out.println("Dealer wins");

return -bet;

}

}

  

/**

* This plays a round of blackjack which includes:

* - Creating a deck

* - Creating the hands

* - Dealing the round

* - Playing the player turn

* - Playing the dealer turn

* - Finding the winner

*

* @param bankroll

* @return The new bankroll for the player.

*/

private double playRound(double bankroll)

{

int bet = readInt("What is your bet? ");

Deck deck = new Deck();

deck.shuffle();

  

Hand player = new Hand();

Hand dealer = new Hand();

  

player.addCard(deck.deal());

dealer.addCard(deck.deal());

player.addCard(deck.deal());

dealer.addCard(deck.deal());

  

System.out.println("Player's Hand");

System.out.println(player);

  

  

System.out.println("Dealer's hand");

boolean playerBusted = playerTurn(player, deck);

  

if(playerBusted)

{

System.out.println("You busted :(");

}

readLine("Enter for dealer turn...");

dealerTurn(dealer, deck);

  

double bankrollChange = findWinner(dealer, player, bet);

  

bankroll += bankrollChange;

  

System.out.println("New bankroll: " + bankroll);

  

return bankroll;

}

  

/**

* Play the blackjack game. Initialize the bankroll and keep

* playing roudns as long as the user wants to.

*/

public void run()

{

double bankroll = STARTING_BANKROLL;

System.out.println("Starting bankroll: " + bankroll);

while(true)

{

bankroll = playRound(bankroll);

  

String playAgain = readLine("Would you like to play again? (Y/N)");

if(playAgain.equalsIgnoreCase("N"))

{

break;

}

}

  

System.out.println("Thanks for playing!");

}

public static void main(String args[]){

Blackjack b = new Blackjack();

b.run();

}

  

}

===================================
See Output

Starting bankrolL: 100.0 What is your bet? 12 Players Hand Hand [cards [Ten of Hearts, Seven of Diamonds]] Dealers hand Ent

Thanks, PLEASE UPVOTE if helpful

Add a comment
Know the answer?
Add Answer to:
Write a Java program to simulate Blackjack. The program should be as basic as possible while...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Create A Header file and A CPP File for this we want to simulate drawing cards...

    Create A Header file and A CPP File for this we want to simulate drawing cards from a deck,with or without replacement. With replacement means that the card is placed back in the deck after having been drawn. You will want to design a class that represents a deck of card (52 cards. 13 cards: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) The class is to be called “aDeckOfCards”. And it should generate a...

  • NEED HELP TO CREATE A BLACKJACK GAME WITH THE UML DIAGRAM AND PROBLEM SOLVING TO GET...

    NEED HELP TO CREATE A BLACKJACK GAME WITH THE UML DIAGRAM AND PROBLEM SOLVING TO GET CODE TO RUN!! THANKS Extend the DeckofCards and the Card class in the book to implement a card game application such as BlackJack, Texas poker or others. Your game should support multiple players (up to 5 for BlackJack). You must build your game based on the Cards and DeckofCards class from the book. You need to implement the logic of the game. You can...

  • How do I start this c++ code homework? Write a code in C++ for a BlackJack...

    How do I start this c++ code homework? Write a code in C++ for a BlackJack card game using the following simplified rules: Each card has a numerical value. Numbered cards are counted at their face value (two counts as 2 points, three, 3 points, and so on) An Ace count as either 1 point or 11 points (whichever suits the player best) Jack, queen and king count 10 points each The player will compete against the computer which represents...

  • Using C++ Create a Blackjack program with the following features: Single player game against the dealer....

    Using C++ Create a Blackjack program with the following features: Single player game against the dealer. Numbered cards count as the number they represent (example: 2 of any suit counts as 2) except the Aces which can count as either 1 or 11, at the discretion of the player holding the card. Face cards count as 10. Player starts with $500. Player places bet before being dealt a card in a new game. New game: Deal 2 cards to each...

  • Please write the program in python: 3. Design and implement a simulation of the game of...

    Please write the program in python: 3. Design and implement a simulation of the game of volleyball. Normal volleyball is played like racquetball, in that a team can only score points when it is serving. Games are played to 15, but must be won by at least two points. 7. Craps is a dice game played at many casinos. A player rolls a pair of normal six-sided dice. If the initial roll is 2, 3, or 12, the player loses....

  • Create a simplified Blackjack game using the Deck and Card classes (download the attached files to...

    Create a simplified Blackjack game using the Deck and Card classes (download the attached files to start).  There is also a "TestCard" class that creates a Deck and runs some simple code. You may choose to use this file to help you get started with your game program. 1) Deal 2 cards to the "player" and 2 cards to the "dealer".  Print both the player's cards, print one of the dealer's cards. Print the total value of the player's hand. 2) Ask...

  • IN JAVA - COMMENT CODE WELL Write a class named Card which will represent a card...

    IN JAVA - COMMENT CODE WELL Write a class named Card which will represent a card from a deck of cards. A card has a suit and a face value. Suits are in order from low to high: Clubs, Diamonds, Hearts and Spades. The card values from low to high: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, and Ace. Write a Deck class that contains 52 cards. The class needs a method named shuffle that...

  • Given these three classes: Card, DeckOfCards, and DeckOfCardsTest. Extend the DeckofCards class to implement a BlackJack...

    Given these three classes: Card, DeckOfCards, and DeckOfCardsTest. Extend the DeckofCards class to implement a BlackJack class, which implements a BlackJack game. Please do not use any java applet on the coding. Hint: Use a test class to test above classes. Pulic class Card {    private final String face; // face of card ("Ace", "Deuce", ...)    private final String suit; // suit of card ("Hearts", "Diamonds", ...)    // two-argument constructor initializes card's face and suit    public...

  • Need a blackjack code for my assignment its due in 3 hours: it has to include...

    Need a blackjack code for my assignment its due in 3 hours: it has to include classes and object C++. Create a fully functioning Blackjack game in three separate phases. A text based version with no graphics, a text based object oriented version and lastly an object oriented 2D graphical version. Credits (money) is kept track of throughout the game by placing a number next to the player name. Everything shown to the user will be in plain text. No...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT