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%
JAVA MASTERMIND The computer will randomly select a four-character mastercode. Each character rep...
Please help with this Intro to programming in C assignment! Intro to Programming in C-Large Program 3 - Hangman Game Assignment purpose: User defined functions, character arrays, c style string member functions Write an interactive program that will allow a user to play the game of Hangman. You will need to: e You will use four character arrays: o one for the word to be guessed (solution) o one for the word in progress (starword) o one for all of...
Hello! we are using Python to write this program. we are supposed to use loops in this assignment. I would greatly appreciate the help! Thank you! Write a program that allows the user to play a guessing game. The game will choose a "secret number", a positive integer less than 10000. The user has 10 tries to guess the number. Requirements: we would have the program select a random number as the "secret number". However, for the purpose of testing...
For this lab you will write a Java program that plays a simple Guess The Word game. The program will prompt the user to enter the name of a file containing a list of words. These words mustbe stored in an ArrayList, and the program will not know how many words are in the file before it starts putting them in the list. When all of the words have been read from the file, the program randomly chooses one word...
Code in JAVA.................... Guess the Number In this activity, you will write a REST server to facilitate playing a number guessing game known as "Bulls and Cows". In each game, a 4-digit number is generated where every digit is different. For each round, the user guesses a number and is told the exact and partial digit matches. An exact match occurs when the user guesses the correct digit in the correct position. A partial match occurs when the user guesses...
IN BASIC JAVA and using JAVA.UTIL.RANDOM write a program will randomly pick a number between one and 100. Then it will ask the user to make a guess as to what the number is. If the guess is incorrect, but is within the range of 1 to 100, the user will be told if it is higher or lower and then asked to guess again. If the guess was outside the valid range or not readable by Scanner class, a...
For this lab you will write a Java program using a loop that will play a simple Guess The Number game. Th gener e program will randomly loop where it prompt the user for a ate an integer between 1 and 200 (including both 1 and 200 as possible choices) and will enter a r has guessed the correct number, the program will end with a message indicating how many guesses it took to get the right answer and a...
Note wordBank, an array of 10 strings (char *s). Your program should do the following: 1. Select a word at random from the wordBank. This is done for you. 2. On each turn display the word, with letters not yet guessed showing as *'s, and letters that have been guessed showing in their correct location 3. The user should have 10 attempts (?lives?). Each unsuccessful guess costs one attempt. Successful guesses do NOT count as a turn. 4. You must...
For a C program hangman game: Create the function int play_game [play_game ( Game *g )] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) (Also the link to program files (hangman.h and library file) is below the existing code section. You can use that to check if the code works) What int play_game needs to do mostly involves calling other functions you've already...
I have to use java programs using netbeans. this course is introduction to java programming so i have to write it in a simple way using till chapter 6 (arrays) you can use (loops , methods , arrays) You will implement a menu-based system for Hangman Game. Hangman is a popular game that allows one player to choose a word and another player to guess it one letter at a time. Implement your system to perform the following tasks: Design...
Original question IN JAVA Show the user a number of blank spaces equal to the number of letters in the word For cat, you would show _ _ _. Prompt a user to guess a letter until they have run out of guesses or guessed the full word By default, the user should be able to make 7 failed guesses before they lose the game. If the user guesses a letter that is in the target word, it does not...