Question

You will write a two-class Java program that implements the Game of 21. This is a...

You will write a two-class Java program that implements the Game of 21. This is a fairly simple game where a player plays against a “dealer”. The player will receive two and optionally three numbers. Each number is randomly generated in the range 1 to 11 inclusive (in notation: [1,11]). The player’s score is the sum of these numbers. The dealer will receive two random numbers, also in [1,11]. The player wins if its score is greater than the dealer’s score and is also less than or equal to 21. A tie goes to the dealer.
The player may wager an amount of money before receiving each number. If the player wins, the wager is added to the player’s total money. If the player loses, the wager is subtracted from the player’s total money.
The game is played as follows:
The player starts with a total amount of money, 100.00 in this case.  
The dealer asks for an initial bet from the player. This is called an “ante”. The amount of money the player can bet has to be less than or equal to the player’s total amount of money.
Then, the dealer generates a random number for the player. That is added to the player’s score, which is initially zero. The dealer then generates a random number for itself and adds that to the dealer’s score.
The player may place a bet with the same betting conditions as mentioned above.
Then, the dealer generates another number for the player and for itself.
Another bet may be placed by the player.
The dealer then asks if the player wants one more number. If yes, the dealer generates another random number for the player.  
Finally, the dealer checks if the player has won. If so, the player’s total money is the sum of the player’s initial money and the total bets the player has made. If the player has lost, the player’s total money is the initial money minus the total amount the player has bet.
The Program Structure.
The program consists of two Java class definitions: Dealer21 and Driver21. The specification for these class definitions is as follows.
Dealer21.java
This class simulates the dealer. The dealer manages the state of the game, including the player’s money, bets, and the score for both player and dealer, and generates random numbers. The dealer also determines the winner of the game.
Member variable declarations (name, data type, purpose):
dealerScore, integer, the sum of the numbers generated for the dealer.
playerScore, integer, the sum of the numbers generated for the player.  
playerBet, double, the sum of the bets placed by the player.
playerMoney, double, the player’s initial amount of money.
rand, Random, generates random numbers for the game.
Methods
Constructors: There are two constructors. One takes no parameters, and one takes a single parameter- an integer (could also be a long integer), which will serve as the seed for the instance of Random. Both constructors call the init method (see below), which initializes the first four member variables listed above. In addition to calling init, the first constructor creates an instance of Random using its no-parameter constructor, while the second constructor passes the seed value to the Random constructor (refer to the java.util.Random class in the Java API if necessary).
Private methods:
init: no parameters, no return value. Initializes dealer and player scores to 0, the player bet to 0.0, and the player money to 100.00.
generateNum: no parameters, returns an integer, which is a (uniform) random number in the range 1 to 11, inclusive.
Public methods:
getPlayerBet: no parameters, returns a double, the player’s aggregate bet.

getPlayerMoney: no parameters, returns a double, the player’s money.
getPlayerScore: no parameters, returns an integer, the player’s aggregate score.
getDealerScore: no parameters, returns an integer, the dealer’s aggregate score.
playerWins: no parameters, returns Boolean: true if the player wins, false otherwise.
The player wins if the dealer's score is not 21 and the player's score is less than or equal to 21 and the player's score is greater than the dealer's score.
placeBet: takes a double parameter- the amount of the player’s bet, returns boolean.
Checks if the amount the player has bet so far plus the bet passed in is less than or equal to the player's total money. If this is true, it adds the amount passed in to the player's current bet and returns true, otherwise, the bet passed in is not added and false is returned.
generatePlayerNumber: no parameters, returns an integer, a number in [1,11].
Calls generateNum, adds this number to the player's score, and returns the number generated.
generateDealerNumber no parameters, returns an integer, a number in [1,11].
Calls generateNum, adds this number to the dealer's score, and returns the number generated.

Driver21.java
This class handles console interactions with the player (user). It creates an instance of Dealer21 and uses its public methods (API) to play the game.  
Member variables: none.
Methods: main.
An instance of Dealer21 is created in main. Its methods are called to play the game. Actually, you will write two statements to create the Dealer21 instance: one will call the no-parameter constructor, and one will call the constructor that takes a seed value as a parameter. Comment out the first statement. Use the seed version during development and testing. The seed you use will determine the numbers generated during the game.
The rest of the code in the main method must produce the same output as in the following examples. Use the strings in the example in your code. Use a single java.util.Scanner instance to take the user’s input. Use the nextInt and next Scanner class methods.
Example 1:

You must reproduce this output exactly. Of course, the numbers will change for each run. None of the numbers that appear in the example above should be “hard-coded” in the Driver21 code. For example, this is a statement where the number 100 is hard-coded:
System.out.println("You have 100.00 money to bet with.");
This number should be obtained from the Dealer object. This is the correct way to write the statement:
System.out.println("You have "+dealer.getPlayerMoney()+" money to bet with.");
All numbers seen in the output above should be obtained from the Dealer object.

Another example follows, where the player does not want a third number (answers “N”):



Notice that the same “random” numbers were generated in both examples. This is because the same seed, 1234567, was used. You may use any integer for a seed number.
What happens if a player bet is higher than the player’s resources? The player bet is a running sum of all bets the player has made. The next bet a player makes has to be less than or equal to the difference of the player bet and the player total money. If the bet is too high, the placeBet method returns false. The bet will not be accepted. Since we are not using loops in this project, the game moves on.  

The following example shows what the program does in the case of a bet that was too high.


There are many refinements that could be made to this program. As with all software, new ideas come to mind once you observe the program in action. This is why good coding practices are so important: software is malleable and is constantly changing. Good design and good coding make modification much easier to achieve.

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

**************************************************Code **************************************

import java.util.*;

class Dealer21 {
    // Instance variables
    private int dealerScore = 0;
    private int playerScore = 0;
    private double playerBet = 0;
    private double playerMoney = 0;
    private Random rand;

    private void init() {
        // This function is used to initialize the all the instance variables
        playerScore = 0;
        dealerScore = 0;
        playerBet = 0;
        playerMoney = 100.0;
    }

    public Dealer21() {
        // No parameter constructor creating the random object and calling init function
        rand = new Random();
        init();
    }

    public Dealer21(int seed) {
        // Constructor with one parameter and creating the random object with seed and calling init method
        rand = new Random(seed);
        init();
    }

    public void addMoneyToPlayer(double money) {
        // Used to add/subtract the money to player money
        playerMoney += money;
    }

    private int generateNum() {
        // This function is used to generate a number between 1 and 11
        return rand.nextInt(11) + 1;
    }

    public double getPlayerBet() {
        // Used to return the player bet
        return playerBet;
    }

    public double getPlayerMoney() {
        // Used to return the player money
        return playerMoney;
    }

    public double getPlayerScore() {
        // Used to return the player score
        return playerScore;
    }

    public double getDealerScore() {
        // Used to return the dealer score
        return dealerScore;
    }

    public boolean playerWins() {
        // This function checks whether player wins or not by checking the given condition returns true if wins
        if (dealerScore != 21 && playerScore < 21 && playerScore > dealerScore) {
            return true;
        }
        return false;
    }

    public boolean placeBet(double bet) {
        // Checks for whether bet can be placed or not if yes then add to the bet and returns true else returns false
        if ((playerBet + bet) <= playerMoney) {
            playerBet += bet;
            return true;
        }
        return false;
    }

    public int generatePlayerNumber() {
        // This is public function generating the number for player and returns that number
        int num = generateNum();
        System.out.println("PlayerNumber:" + num);
        playerScore += num;
        return num;
    }

    public int generateDealerNumber() {
        // This is the public function for generating the number for dealer and returns it
        int num = generateNum();
        System.out.println("DealerNumber:" + num);
        dealerScore += num;
        return num;
    }

}

public class Driver21 {
    // This is the Driver class
    public static void main(String args[]) {
        double bet;
        // Main method from here we will call the all the functions and takes the input from user
        // And decides the who is the winner
        boolean status;
        String option;
        Scanner in = new Scanner(System.in);
        // Creating object for the Scanner class for taking the data from the user
        //Dealer21 obj = new Dealer21();
        int seed = (int) Math.random() * 1000;
        Dealer21 obj = new Dealer21(seed);
        // Creating the object for dealer class to deal with it
        System.out.println("Player Money:" + obj.getPlayerMoney());
        // Printing initial player money
        for (int i = 0; i < 2; i++) {
            System.out.println("Enter the bet:");
            // Asking the user to enter the bet
            bet = in.nextDouble();
            status = obj.placeBet(bet);
            if (status) {
                // Here we will generate the random numbers for the player and dealer
                obj.generatePlayerNumber();
                obj.generateDealerNumber();
            } else {
                // Displaying the message if bet can't be placed
                System.out.println("You have " + obj.getPlayerMoney() + " money to bet with.");
            }
        }
        System.out.println("Wants one more number:");
        // Asking the user to want another number if yes generate one more number for player
        option = in.next().toLowerCase();
        if (option == "y") {
            obj.generateDealerNumber();
        }
        status = obj.playerWins();
        // Checking who is winning and displaying the scores of player and dealer
        System.out.println("PlayerScore:" + obj.getPlayerScore() + "->DealerScore:" + obj.getDealerScore());
        if (status) {
            System.out.println("Player Wins");
            obj.addMoneyToPlayer(obj.getPlayerBet());
        } else {
            System.out.println("Dealer wins");
            obj.addMoneyToPlayer(-obj.getPlayerBet());
        }
        System.out.println("Player Money:" + obj.getPlayerMoney());
        // Final player money

    }
}

*****************************Code Screens*****************************************

1 import java.util.*; class Dealer21 { 3 4 Instance variables private int dealerScore 0; private int playerScore0; private dopublic double getPlayerBet() 41 42 43 /Used to return the player bet return playerBet; 45 public double getPlayerMoney) 47 48System.out.printin(PlayerNumber: num) playerScorenum; return num; 82 83 84 85 86 87 public int generateDealerNumber) This i121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 else 7Displaying the

*****************************Output Screens*****************************************

javasys1091@sys1091:-/IdeaProjects/ds/src$ javac Driver21.java sys1091@sys1091:~/IdeaProjects/ds/src$ java Driver21 Player Mosys1091@sys1091: /IdeaProjects/ds/src$ javac Driver21.java sys1091@sys1091: /IdeaProjects/ds/src$ java Driver21 Player Money

Add a comment
Know the answer?
Add Answer to:
You will write a two-class Java program that implements the Game of 21. This is a...
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
  • JAVA We will write a psychic game program in which a player guesses a number randomly...

    JAVA We will write a psychic game program in which a player guesses a number randomly generated by a computer. For this project, we need 3 classes, Player, PsychicGame, and Driver. Description for each class is as following: Project Folder Name: LB05 1. Player class a.Input - nickName : nick name of the player - guessedNumber : a number picked for the player will be assigned randomly by a computer later. b. Process - constructor: asks a user player’s nickName...

  • Please i need helpe with this JAVA code. Write a Java program simulates the dice game...

    Please i need helpe with this JAVA code. Write a Java program simulates the dice game called GAMECrap. For this project, assume that the game is being played between two players, and that the rules are as follows: Problem Statement One of the players goes first. That player announces the size of the bet, and rolls the dice. If the player rolls a 7 or 11, it is called a natural. The player who rolled the dice wins. 2, 3...

  • For this assignment, your job is to create a simple game called Opoly. The objectives of...

    For this assignment, your job is to create a simple game called Opoly. The objectives of this assignment are to: Break down a problem into smaller, easier problems. Write Java methods that call upon other methods to accomplish tasks. Use a seed value to generate random a sequence of random numbers. Learn the coding practice of writing methods that perform a specific task. Opoly works this way: The board is a circular track of variable length (the user determines the...

  • 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...

  • This java assignment will give you practice with classes, methods, and arrays. Part 1: Player Class...

    This java assignment will give you practice with classes, methods, and arrays. Part 1: Player Class Write a class named Player that stores a player’s name and the player’s high score. A player is described by:  player’s name  player’s high score In your class, include:  instance data variables  two constructors  getters and setters  include appropriate value checks when applicable  a toString method Part 2: PlayersList Class Write a class that manages a list...

  • programming language: C++ *Include Line Documenatations* Overview For this assignment, write a program that will simulate...

    programming language: C++ *Include Line Documenatations* Overview For this assignment, write a program that will simulate a game of Roulette. Roulette is a casino game of chance where a player may choose to place bets on either a single number, the colors red or black, or whether a number is even or odd. (Note: bets may also be placed on a range of numbers, but we will not cover that situation in this program.) A winning number and color is...

  • For this lab you will write a Java program that plays the dice game High-Low. In...

    For this lab you will write a Java program that plays the dice game High-Low. In this game a player places a bet on whether the sum of two dice will come up High (totaling 8 or higher), Low (totaling 6 or less) or Sevens (totaling exactly 7). If the player wins, they receive a payout based on the schedule given in the table below: Choice Payout ------ ------ High 1 x Wager Low 1 x Wager Sevens 4 x...

  • USE PYTHON ONLY Please write a Python program to let you or the user play the...

    USE PYTHON ONLY Please write a Python program to let you or the user play the game of rolling 2 dice and win/lose money. Initially, you have 100 dollars in your account, and the dealer also has 100 dollars in his/her account. You would be asked to enter a bet to start the game. If your bet is zero, the game would be stopped immediately. Otherwise, dealer would roll 2 dice and get a number from ( random.randint(1, 6) +...

  • JAVA program. I have created a game called GuessFive that generates a 5-digit random number, with...

    JAVA program. I have created a game called GuessFive that generates a 5-digit random number, with individual digits from 0 to 9 inclusive. (i.e. 12345, 09382, 33044, etc.) The player then tries to guess the number. With each guess the program displays two numbers, the first is the number of correct digits that are in the proper position and the second number is the sum of the correct digits. When the user enters the correct five-digit number the program returns...

  • For your final project you will incorporate all your knowledge of Java that you learned in this class by programming the game of PIG. The game of Pig is a very simple jeopardy dice game in which two p...

    For your final project you will incorporate all your knowledge of Java that you learned in this class by programming the game of PIG. The game of Pig is a very simple jeopardy dice game in which two players race to reach 100 points. Each turn, a player repeatedly rolls a die until either a 1 is rolled or the player holds and scores the sum of the rolls (i.e. the turn total). At any time during a player's turn,...

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