Question

In: Computer Science

JAVA MASTERMIND The computer will randomly select a four-character mastercode. Each character represents the first letter...

JAVA MASTERMIND

The computer will randomly select a four-character mastercode. Each character represents the first letter of a color from the valid color set. Our valid color choices will be: (R)ed, (G)reen, (B)lue and (Y)ellow. Any four-character combination from the valid color set could become the mastercode. For example, a valid mastercode might be: RGBB or YYYR.

The game begins with the computer randomly selecting a mastercode. The user is then given up to 6 tries to guess the mastercode. The user must guess the correct color sequence in the correct order. After each user guess, the computer responds indicating how many colors the user guessed correctly and how many of those were in the correct position. This information helps the user make a better (and hopefully more accurate) guess. If the user correctly guesses the code in 6 tries or less, the user wins the round. Otherwise, the user loses the round. After each round, the user is given the option to play another round, at which point the game either continues or ends. When the game is completely finished, some overall playing statistics should be displayed. This includes how many rounds the user won as well as lost, in addition to the user's overall winning percentage.

Sample Run

WELCOME TO MASTERMIND

<-- blank line

How to Play:

1. I will pick a 4 character color code out of the following colors: Yellow, Blue, Red, Green.

2. You try to guess the code using only the first letter of any color. Example if you type YGBR that means you guess Yellow, Green, Blue, Red.

3. I will tell you if you guessed any colors correct and whether or not you guess them in the right order.

<-- blank line

LET'S PLAY!

<-- blank line

Ok, I've selected my secret code. Try and guess it.

<--- Blank line

Enter guess #1 (e.g., YBRG ): ZZZZZ

Please enter a valid guess of correct length and colors

<--- Blank line

Enter guess #1 (e.g., YBRG ): YYYY

You have 2 colors correct

2 are in the correct position

<--- Blank line

Enter guess #2 (e.g., YBRG ): YBYY

You have 3 colors correct

3 are in the correct position

Enter guess #3 (e.g., YBRG ): YBYR

You have 3 colors correct

3 are in the correct position

Enter guess #4 (e.g., YBRG ): YBYG

You have 3 colors correct

3 are in the correct position

Enter guess #5 (e.g., YBRG ): YBYR

You have 3 colors correct

3 are in the correct position

Enter guess #6 (e.g., YBRG ): YBYB

That's correct! You win this round. Bet you can't do it again!

Play again (Y/N)? k

Please enter a valid response (Y/N):

Y

<--- Blank line

Ok, I've selected my secret code. Try and guess it.

<--- Blank line

Enter guess #1 (e.g., YBRG ): GBYG

That's correct! You win this round. Bet you can't do it again!

Play again (Y/N)? N

<--- Blank line

YOUR FINAL STATS:

Rounds Played: 2

Won: 2 Lost: 0

Winning Pct: 100.00%

Sample Run (user does not win)

<-- user makes several bad guesses before the output below

Enter guess #6 (e.g., YBRG ): yyyy

You have 1 colors correct

1 are in the correct position

No more guesses. Sorry you lose. My sequence was YRRR

Play again (Y/N)?

Required Decomposition

  1. displayInstructions() - Displays the welcome message and game instructions.
  2. getRandomColor() - Accepts a random object as a parameter and returns a single character representing the first letter of the valid color set (R, G, B or Y). You can accomplish this by generating a random number 1-4 and then having each number correlate to a character representing a color.
  3. buildMasterCode() - Accepts a random object as a parameter and returns a String representing the random 4-character mastercode selected by the computer. There is one important caveat. You are not allowed to return a masterCode of YYYY from this method. Should such a mastercode be generated, you must re-generate a different mastercode until you have one that is not equal to YYYY. This methods calls getRandomColor() multiple times to assist in building the string.
  4. displayStats() - Accepts two int parameters representing how many rounds were played as well as how many times the user won the round. Displays number of times the user the won and lost as well as the user's winning percentage. For the winning percentage, it should be displayed using a printf with two decimal places and accommodate printing up to a possible perfect winning percentage of 100%.
  5. isValidColor() - Accepts a char parameter and returns true if the character represents the first letter of a valid color set (R, G, B, Y) and false otherwise.
  6. isValidGuess() - Accepts a String parameter representing the user's guess at the mastercode. Returns true if the user's guess is a valid guess of correct length with valid values from the color set and false otherwise. Note that being a valid guess has nothing to do with the guess being correct. We are strictly talking about validity with respect to the length and color choices. A valid guess is any string of four characters long containing valid color codes after all spaces have been removed (in other words, "Y B R G" is a valid guess once the spaces have been removed). This method will call isValidColor() to assist in validating the user's guess.
  7. getValidGuess() -- Accepts two parameters, a Scanner object for reading user input and an int value representing which number guess this is for the user (the user only gets 6 guesses). This method reads the user guess and validates it (uppercase or lowercase is acceptable). If the guess is not a valid guess, an error message is displayed and the user prompted again for a valid guess. This method calls isValidGuess() to assist in validating the user's input and removing whitespace. This method returns a validated String representing the user's guess to the calling method.
  8. countCorrectColors() - Accepts two String parameters representing the mastercode and the guess. Returns an int value representing the number of colors guessed correctly by the user as compared to the mastercode irrespective of whether or not those colors are in the correct position.
  9. countCorrectPositions() - Accepts two String parameters representing the mastercode and the guess. Returns an int value representing the number of colors guessed correctly in their correct position by the user as compared to the mastercode.
  10. checkGuess() - Accepts two String parameters representing the mastercode and the guess. Returns a boolean value indicating whether or not the user won the round based upon their guess. If the user did not win the round, the user should be informed how many colors they guessed correctly and whether any of those were in the correct position. This method calls countCorrectColors() and countCorrectPositions() to assist in determining what information to display to the user.
  11. playOneRound() - Accepts a Scanner object and a String representing the masterCode. Returns a boolean indicating whether or not the user won this round. Allows the user up to 6 guesses before the user automatically loses the round. This method calls getValidGuess() and checkGuess() to assist in processing the user's guess.
  12. getUserChoice() - Accepts a Scanner object and returns a character representing a valid user's choice as to whether or not they would like to play another round. Valid choices are Y or N, but naturally you should let the user enter this in lower or uppercase.
  13. main() - The main is the controlling method or manager of the game, continuing to play a new round of mastermind until the user decides to quit the game. Once the game has ended, the stats should be displayed.

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// MasterMind.java

import java.util.Random;

import java.util.Scanner;

import org.omg.CORBA.OMGVMCID;

public class MasterMind {

                // method to display the instructions

                static void displayInstructions() {

                                System.out.println("WELCOME TO MASTERMIND");

                                System.out.println();

                                System.out.println("How to Play:");

                                System.out

                                                               .println("1. I will pick a 4 character color "

                                                                                               + "code out of the following colors: Yellow, Blue, Red, Green.");

                                System.out

                                                               .println("2. You try to guess the code using only the first letter of any color. "

                                                                                               + "Example if you type YGBR that means you guess Yellow, Green, Blue, Red.");

                                System.out

                                                               .println("3. I will tell you if you guessed any colors "

                                                                                               + "correct and whether or not you guess them in the right order.");

                                System.out.println("\nLET'S PLAY!\n");

                }

                // method to generate a random color code (R,G,B or Y)

                static char getRandomColor(Random random) {

                                // creating an array of possible characters

                                char colors[] = { 'R', 'G', 'B', 'Y' };

                                // generating a random index, returning element at that index

                                return colors[random.nextInt(colors.length)];

                }

                // method to create and return the master code

                static String buildMasterCode(Random random) {

                                // starting with code YYYY

                                String code = "YYYY";

                                // looping until a code other than YYYY is generated

                                while (code.equals("YYYY")) {

                                               // calling getRandomColor 4 times, concatenating the values

                                               code = "" + getRandomColor(random) + getRandomColor(random)

                                                                               + getRandomColor(random) + getRandomColor(random);

                                }

                                return code;

                }

                // method to display final stats

                static void displayStats(int roundsPlayed, int numWins) {

                                System.out.println("YOUR FINAL STATS:");

                                System.out.println("Rounds Played: " + roundsPlayed);

                                System.out.println("Won: " + numWins + " Lost: "

                                                               + (roundsPlayed - numWins));

                                // finding and displaying win % with 2 decimal digits precision

                                double winPct = (double) numWins / roundsPlayed;

                                winPct *= 100;

                                System.out.printf("Winning Pct: %.2f%%", winPct);

                }

                // method to validate the color code

                static boolean isValidColor(char c) {

                                // checking if character c is R,G,B or Y

                                return "RGBY".contains("" + c);

                }

                // method to validate the guess

                static boolean isValidGuess(String guess) {

                                // removing spaces

                                guess = guess.replace(" ", "");

                                if (guess.length() == 4) {

                                               // valid length

                                               for (int i = 0; i < guess.length(); i++) {

                                                               if (!isValidColor(guess.charAt(i))) {

                                                                               // not valid color

                                                                               return false;

                                                               }

                                               }

                                               return true; // valid color and length

                                }

                                return false; // invalid length

                }

                // method to get a valid guess from user

                static String getValidGuess(Scanner scanner, int guessCount) {

                                String guess = "";

                                // looping until a valid guess is entered

                                while (!isValidGuess(guess)) {

                                               System.out.print("Enter guess #" + guessCount + " (e.g., YBRG): ");

                                               guess = scanner.nextLine().toUpperCase();

                                               if (!isValidGuess(guess)) {

                                                               System.out

                                                                                               .println("Please enter a valid guess of correct length and colors\n");

                                               }

                                }

                                // removing spaces

                                guess = guess.replace(" ", "");

                                return guess;

                }

                // method to count correct colors in the guess

                static int countCorrectColors(String master, String guess) {

                                int count = 0;

                                // creating a copy of master

                                String temp = master;

                                int index = 0;

                                // looping through guess

                                for (int i = 0; i < guess.length(); i++) {

                                               // checking if current character of guess exists in temp

                                               index = temp.indexOf(guess.charAt(i));

                                               if (index != -1) {

                                                               // exists

                                                               count++;

                                                               // removing character from temp

                                                               temp = temp.substring(0, index) + temp.substring(index + 1);

                                               }

                                }

                                return count;

                }

                // method to count the colors in correct positions

                static int countCorrectPositions(String master, String guess) {

                                int count = 0;

                                for (int i = 0; i < guess.length(); i++) {

                                               if (master.charAt(i) == guess.charAt(i)) {

                                                               count++;

                                               }

                                }

                                return count;

                }

                // method to check guess, return true if it is correct

                static boolean checkGuess(String master, String guess) {

                                // finding correct colors and positions

                                int correctColors = countCorrectColors(master, guess);

                                int correctPos = countCorrectPositions(master, guess);

                                if (correctPos == master.length()) {

                                               // win

                                               System.out

                                                                               .println("That's correct! You win this round. Bet you can't do it again!");

                                               return true;

                                } else {

                                               // not win

                                               System.out.println("You have " + correctColors + " colors correct");

                                               System.out.println(correctPos + " are in the correct position");

                                               return false;

                                }

                }

                // method to play one round of game, return true if user won

                static boolean playOneRound(Scanner scanner, String master) {

                                int guessCount = 1;

                                int max = 6;

                                // looping until all guess is exhausted or player wins

                                while (guessCount <= max) {

                                               String guess = getValidGuess(scanner, guessCount);

                                               if (checkGuess(master, guess)) {

                                                               //win

                                                               return true;

                                               } else {

                                                               //wrong guess

                                                               guessCount++;

                                               }

                                }

                                System.out.println("No more guesses. Sorry you lose. My sequence was "

                                                               + master);

                                return false;

                }

               

                //method to get a valid user choice Y or N

                static char getUserChoice(Scanner scanner) {

                                System.out.print("Play again (Y/N)? ");

                                String input = "";

                                while (!input.equalsIgnoreCase("Y") && !input.equalsIgnoreCase("N")) {

                                               input = scanner.nextLine();

                                               if (!input.equalsIgnoreCase("Y") && !input.equalsIgnoreCase("N")) {

                                                               System.out.println("Please enter a valid response (Y/N):");

                                               }

                                }

                                return input.toUpperCase().charAt(0);

                }

                public static void main(String[] args) {

                                //displaying instructions

                                displayInstructions();

                                char play = 'Y';

                                int games = 0;

                                int wins = 0;

                                Scanner scanner = new Scanner(System.in);

                                Random random = new Random();

                                //looping and playing until user chooses to stop

                                while (play == 'Y') {

                                               //building master code

                                               String master = buildMasterCode(random);

                                               System.out

                                                                               .println("Ok, I've selected my secret code. Try and guess it.\n");

                                               //playing one round

                                               if (playOneRound(scanner, master)) {

                                                               //win

                                                               wins++;

                                               }

                                               //getting choice to continue or stop

                                               play = getUserChoice(scanner);

                                               games++;

                                               System.out.println();

                                }

                                //displaying stats

                                displayStats(games, wins);

                }

}

/*OUTPUT*/

WELCOME TO MASTERMIND

How to Play:

1. I will pick a 4 character color code out of the following colors: Yellow, Blue, Red, Green.

2. You try to guess the code using only the first letter of any color. Example if you type YGBR that means you guess Yellow, Green, Blue, Red.

3. I will tell you if you guessed any colors correct and whether or not you guess them in the right order.

LET'S PLAY!

Ok, I've selected my secret code. Try and guess it.

Enter guess #1 (e.g., YBRG): brbr

You have 2 colors correct

2 are in the correct position

Enter guess #2 (e.g., YBRG): brgr

You have 4 colors correct

3 are in the correct position

Enter guess #3 (e.g., YBRG): BRGG

That's correct! You win this round. Bet you can't do it again!

Play again (Y/N)? Y

Enter guess #1 (e.g., YBRG): zzzz

Please enter a valid guess of correct length and colors

Enter guess #1 (e.g., YBRG): YBRG

You have 4 colors correct

0 are in the correct position

Enter guess #2 (e.g., YBRG): gRGR

You have 3 colors correct

2 are in the correct position

Enter guess #3 (e.g., YBRG): rrGR

You have 3 colors correct

3 are in the correct position

Enter guess #4 (e.g., YBRG): rrgb

That's correct! You win this round. Bet you can't do it again!

Play again (Y/N)? y

Ok, I've selected my secret code. Try and guess it.

Enter guess #1 (e.g., YBRG): yyyy

You have 1 colors correct

1 are in the correct position

Enter guess #2 (e.g., YBRG): ygyr

You have 3 colors correct

2 are in the correct position

Enter guess #3 (e.g., YBRG): ygbr

You have 4 colors correct

2 are in the correct position

Enter guess #4 (e.g., YBRG): yrbg

You have 4 colors correct

1 are in the correct position

Enter guess #5 (e.g., YBRG): yyrg

You have 3 colors correct

2 are in the correct position

Enter guess #6 (e.g., YBRG): ybrb

You have 4 colors correct

3 are in the correct position

No more guesses. Sorry you lose. My sequence was YBRR

Play again (Y/N)? n

YOUR FINAL STATS:

Rounds Played: 3

Won: 2 Lost: 1

Winning Pct: 66.67%


Related Solutions

Suppose that we randomly select 50 billing statements from each of the computer databases of the...
Suppose that we randomly select 50 billing statements from each of the computer databases of the Hotel A, the Hotel B, and the Hotel C chains, and record the nightly room rates. The means and standard deviations for the data are given in the table. Hotel A Hotel B Hotel C Sample Average ($) 140 180 120 Sample Standard Deviation   17.7   22.6   12.5 (a) Find a 95% confidence interval for the difference in the average room rates for the Hotel...
Suppose that we randomly select 50 billing statements from each of the computer databases of the...
Suppose that we randomly select 50 billing statements from each of the computer databases of the Hotel A, the Hotel B, and the Hotel C chains, and record the nightly room rates. The means and standard deviations for the data are given in the table. Hotel A Hotel B Hotel C Sample Average ($) 140 180 120 Sample Standard Deviation   17.7   22.6   12.5 (a) Find a 95% confidence interval for the difference in the average room rates for the Hotel...
Suppose that we randomly select 50 billing statements from each of the computer databases of the...
Suppose that we randomly select 50 billing statements from each of the computer databases of the Hotel A, the Hotel B, and the Hotel C chains, and record the nightly room rates. The means and standard deviations for the data are given in the table. Hotel A Hotel B Hotel C Sample Average ($) 140 180 120 Sample Standard Deviation   17.7   22.6   12.5 (a) Find a 95% confidence interval for the difference in the average room rates for the Hotel...
A password is a string of ten characters, where each character is a lowercase letter, a...
A password is a string of ten characters, where each character is a lowercase letter, a digit, or one of the eight special characters !, @, #, $, %, &, (, and ). A password is called awesome, if it contains at least one digit or at least one special character. Determine the number of awesome passwords.
In Java, write a program that finds the first character to occur 3 times in a...
In Java, write a program that finds the first character to occur 3 times in a given string? EX. Find the character that repeats 3 times in "COOOMMPUTERRRR"
(In java) Return a copy of the string with only its first character capitalized. You may...
(In java) Return a copy of the string with only its first character capitalized. You may find the Character.toUpperCase(char c) method helpful NOTE: Each beginning letter of each word should be capitalized. For example, if the user were to input: "United States of America " --> output should be "United States of America" NOT "United states of america" -------------------------------------- (This code is given) public class Class1 { public static String capitalize(String str) {     //add code here } }
According to an English professor, the following information represents the percent of times that each letter...
According to an English professor, the following information represents the percent of times that each letter is used in the English language: E = 11.16%, A = 8.5%, I = 7.54%, O = 7.16%, U = 3.63% (E.g. 11.16% of letters found in any writing sample will be letter E's) Choose a paragraph of at least 30 words from any written source and count the number of times each vowel shows up in your paragraph. Then, perform a goodness-of-fit test...
To compare three brands of computer keyboards, four data entry specialists were randomly selected. Each specialist...
To compare three brands of computer keyboards, four data entry specialists were randomly selected. Each specialist used all three keyboards to enter the same kind of text material for 10 minutes, and the number of words entered per minute was recorded. The data obtained are given in the following table: Keyboard Brand Data Entry Specialist A B C 1 77 67 63 2 71 62 59 3 74 63 59 4 67 57 54 a. Test the null hypothesis H0...
In the equation SEND + MORE = MONEY each letter represents a different digit (0-9). The...
In the equation SEND + MORE = MONEY each letter represents a different digit (0-9). The addition is done in the usual way from right to left, first adding D and E to obtain Y (possibly with a carry-over), then adding N and R, and so on. Solve this problem using linear programming with integer and binary variables. (No credit is given for a solution without the appropriate spreadsheet model in Excel.)
A computer system uses passwords that contain exactly 5 characters, and each character is 1 of...
A computer system uses passwords that contain exactly 5 characters, and each character is 1 of the 3 lowercase letters (a, b, c) or 3 upper case letters (A, B, C) or the 5 odd digits (1, 3, 5, 7, 9). Let Ω denote the set of all possible passwords, and let A and B denote the events that consist of passwords with only letters or only integers, respectively. Determine the probability that a password contains at least 1 uppercase...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT