In: Computer Science
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
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%