Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

so i am trying to code Master mind in java and there are still errors that i am

ID: 3536207 • Letter: S

Question

so i am trying to code Master mind in java and there are still errors that i am unable to fix, for example, the incorrect numbers are accepted (i know to put an error exception), the hints can sometimes come out wrong, and i dont know how to print a list of previously entered guesses. This is what i have so far.


import java.util.Scanner;

public class MasterMind {

/** Creates random combination for player to guess. The level of difficutly chosen

* will change the number of values used to create the combination.

*/

public static ArrayList<Integer> randomCombo(ArrayList<Integer> combo, int highest) {

for(int i = 0; i < 4; i++) {

if(highest < 10) {

combo.add((int)((Math.random() * highest) + 1));

} else {

combo.add((int)(Math.random() * highest));

}

}

return combo;

}

/** Determine the difficulty level of the game. */

public static int highest(int difficulty) {

if(difficulty == 1) {

return 6;

} else if (difficulty == 2) {

return 8;

} else {

return 10;

}

}

/** Determines the max number of turns the game will play. */

public static int turns(int difficulty) {

if((difficulty == 1) || (difficulty == 2)) {

return 12;

} else {

return 15;

}

}

/** Provides the player with hints after each of their guess. "X" means a number

* matches the combination and is in the correct position. "x" means a number

* matches the combination and is in the wrong position. "-" means the number

* is not found within the combination.

*/

public static String hint(ArrayList<Integer> guess, ArrayList<Integer> pattern) {

// Keeps track of number of 'X'

int position = 0;

// Keeps track of number of 'x'

int number = 0;

// Provides clues to player

String clues = " ";

// Gives 'X'

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

// Compares values based on position between guess and pattern Array Lists

if(guess.get(i) == pattern.get(i)) {

position++;

clues += "X ";

// Removes value from the Array Lists to ensure they are not read twice

guess.remove(i);

pattern.remove(i);

// Resets the for-loop to start from the beginning. Ensures no value is skipped

i = -1;

}

}

// Gives 'x'

for(int j = 0; j < guess.size(); j++) {

// Checks the pattern Array List for values in the guess Array List

if(pattern.contains(guess.get(j))) {

number++;

clues += "x ";

// Removes values found from both Array Lists to prevent values from being read twice

pattern.remove(guess.get(j));

guess.remove(j);

// Resets for-loop to start from beginning. Ensures no value is skipped

j = -1;

}

}

// Provides remaining clue

if(number + position < 4) {

for(int k = 0; k < (4 - (number + position)); k++) {

clues += "- ";

}

}

return clues;

}

/** Determines if player's guess was correct. */

public static boolean isCorrect(ArrayList<Integer> guess, ArrayList<Integer> pattern) {

return (guess.get(0) == pattern.get(0)) && (guess.get(1) == pattern.get(1))

&& (guess.get(2) == pattern.get(2)) && (guess.get(3) == pattern.get(3));

}

public static void main(String[] args) {

// Keeps track of number of guess made by player

int attempt = 0;

// Will ensure the player only inputs 4 values with each guess

int guessNumber = 0;

// Will be assigned difficulty level

int range = 0;

Scanner level = new Scanner(System.in);

System.out.println("Welcome to the game of MasterMind.");

System.out.println("The hints given after each guess are made up of X's, x's and -'s.");

System.out.println("Each X means one of the numbers in your guess is in the correct position.");

System.out.println("Each x means a number is correct but in the wrong position.");

System.out.println("Each - means a number did not match.");

System.out.print("Please select difficulty 1, 2, or 3 (1 = easy, 2 = medium, 3 = hard): ");

int difficulty = level.nextInt();

// Calls highest method to determine difficulty level

range = highest(difficulty);

ArrayList<Integer> combo = new ArrayList<Integer>();

// Calls turn method to determine number of tunes

int stop = turns(difficulty);

// Calls randomCombo method to create random combination

randomCombo(combo, range);

// Records players guess

while (attempt <= stop) {

// Resets the combination after the hints method because the hints method

// removes values from the combination Array List. This Array List must

// be reset to all each guess to be compared to the original combination

ArrayList<Integer> combination = new ArrayList<Integer>();

for(int a = 0; a < combo.size(); a++) {

combination.add(combo.get(a));

}

// Resets users guess after every guess attempt

ArrayList<Integer> guess = new ArrayList<Integer>();

System.out.print("Please enter your guess ");

if(difficulty == 1) {

System.out.println("using numbers 1-6.");

} else if (difficulty == 2) {

System.out.println("using numbers 1-8.");

} else{

System.out.println("using numbers 0-9.");

}

// Player's guess

while(guessNumber < 4) {

System.out.print("Please enter a positive integer: ");

Scanner test = new Scanner(System.in);

guess.add(test.nextInt());

guessNumber++;

}

// Checks if player's guess is correct. If not, provides hints

if(isCorrect(guess, combination)) {

break;

} else {

System.out.print(hint(guess, combination));

}

attempt++;

guessNumber = 0;

System.out.println();

}

if(attempt < 15) {

System.out.println("Congratulatoins! You won!");

} else {

System.out.println("YOU LOSE!!!");

}

}

}

Explanation / Answer

import java.io.*;

import java.util.*;




//MasterMind main class, generates the game and user interface

public class MasterMind

{

//input from the keyboard

private Scanner keyboard;

private String input;

//user decides which mode to use, 4 holes and 6 colors, or 5 holes and 7 colors.

private static int mode;

private final int STANDARD_MODE = 6;

private final int CHALLENGE_MODE = 7;

//two-dimensional array stores all guesses and key pegs

private char[][] guess;

private char[][] key;

//char arry stores the answer generated by the computer

private char[] answer;

//class object MMAnswer generates the answer for each game

private MMAnswer answerGenerator;

//boolean value indicates the play wins the game

private boolean winner;

//class object MMGuess compares the guesses to the answer

//and provides scores of each game including hits and number of guesses

private MMGuess guessEvaluator;

private int totalHits;

private int totalGuesses;

private int guessCount;

private int hintsUsed = 0; // The amount of times someuse used a hint

/**

* MasterMind constructor with mode setting

* @param mode the integer indicates the number of colors of the game,

* 6: 4 holes and 6 colors; 7: 5 holes and 7 colors

*/

public MasterMind(int mode)

{

MasterMind.mode = mode;

keyboard = new Scanner(System.in);

winner = false;

totalHits = 0;

answerGenerator = new MMAnswer(STANDARD_MODE);

answer = answerGenerator.getAnswer();

totalGuesses = 0;

guessCount = 0;

guess = new char[30][mode - 2];

key = new char[30][mode - 2];

}//MasterMind constructor with mode setting


/**

* MasterMind constructor enables the keyboard input

*/

public MasterMind()

{

keyboard = new Scanner(System.in);

}//MasterMind constructor



public static void main(String[] args) throws IOException

{

//make sure the input is in correct format

boolean successfulStart = false;

MasterMind MMGame;

int mode = 0;

//a loop generates multiple games as long as the play would like to continue

do

{

successfulStart = false;

//a minimal initialized game enables the keyboard input

MMGame = new MasterMind();

//ask user to play or quit the game

successfulStart = MMGame.startNewGame();

//check the answer from the user and starts the game

if (successfulStart)

{

//ask the user for the difficulty level of the game, 2 modes

MMGame.setMode();

//generate a new game with the user-defined mode setting

mode = MMGame.getMode();

MMGame = new MasterMind(mode);

//generate answer based on the user-defined mode

MMGame.answerGenerator = new MMAnswer(mode);

MMGame.answer = MMGame.answerGenerator.getAnswer();

//a loop asks the user to input all the guesses, each loop generates one guess

//displays the key pegs, scores and total number of guesses at the end of each guess

do

{

//ask the user to input one guess contains desired number of holes, 4 or 5, based on the user-defined mode

//store each guess into the two-dimensional array

MMGame.guess[MMGame.totalGuesses] = MMGame.getGuess();

//compares the guess to the answer

MMGame.guessEvaluator = new MMGuess(MMGame.guess[MMGame.totalGuesses], MMGame.answer);

//check whether the user wins the game

MMGame.winner = MMGame.guessEvaluator.evaluateGuess();

//store each key into the two-dimensional arry for each guess

MMGame.key[MMGame.totalGuesses] = MMGame.guessEvaluator.getKey();

//calculate the total score from scores of individual guesses

//Perfect match earns 2 points, close match earns 1 point

MMGame.totalHits += MMGame.guessEvaluator.getSingleHits();

// Compute the total number of guesses

MMGame.guessCount++;


//display the key pegs for each guess

System.out.print(" Your hits: ");

for(int i = MMGame.key[MMGame.totalGuesses].length - 1; i >= 0; i--)

System.out.print(MMGame.key[MMGame.totalGuesses][i] + " ");

/*System.out.println(" X = right color and right position, 2 points " +

"x = right color but wrong position, 1 point " +

"0, color not exist");

System.out.println("--------------------------------------------------------------------");

//display the total points from scores of individual guesses

System.out.print("Total points earned: " + MMGame.totalHits + " ");

//calculate and display the number of guesses that the user made

MMGame.totalGuesses ++;

System.out.println("Total number of guesses: " + MMGame.totalGuesses);

System.out.println("********************************************************************");*/

}

//check whether the user wins the game

//if not, ask the user whether continue the game or start over or need a hint before next guess

while (!MMGame.winner && MMGame.continueCurrentGame());

//the current game ends if the user wins the game

if (MMGame.winner)

{

// Show Contratulations and single game stats

System.out.println("Congratulations! You win!");

System.out.println("********************************************************************");

System.out.println("It took you " + MMGame.guessCount + " guesses.");

System.out.println("You Averaged " + MMGame.totalHits / ((double) MMGame.guessCount) + " Points Per Guess.");

// Save the game data

// class object MMStatistics generates the Statistics Controller for each game

MMStatistics statsController = new MMStatistics();

statsController.setMode(mode);

statsController.saveStats(MMGame.guessCount);

}

}

//game over if the user is not ready for the game

else

{

break;

}

}

//a new game will start if the user is ready for a new game

while (successfulStart);

}//main

/**

* Asks the user whether the user wants to start a new game

* System exits if the user doesn't want to play

* @return successfulStart

* <br> user's answer for want to play?

*/

public boolean startNewGame() throws IOException

{

//keeps track of valid input

boolean successfulStart = false;

//a loop prompts the user with the same question if the input is not valid

do

{

System.out.println("Ready to start a new game? y = yes, n = no, s = show stats");

input = keyboard.nextLine();

if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes"))

{

successfulStart = true;

return true;

}

else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no"))

{

System.out.println("Thank you for playing! Bye!");

successfulStart = true;

return false;

}

else if (input.equalsIgnoreCase("s") || input.equalsIgnoreCase("show stats"))

{

System.out.println("*****************************************************");

System.out.println("MasterMind Statistics");

System.out.println("***************************");

System.out.println("Standard Mode");

MMStatistics stats = new MMStatistics();

stats.setMode(STANDARD_MODE);

stats.displayStats();

System.out.println("***************************");

System.out.println("Advanced Mode");

stats.setMode(CHALLENGE_MODE);

stats.displayStats();

System.out.println("*****************************************************");

successfulStart = false;

}

else

{

System.out.println("Error in reading your input.");

successfulStart = false;

}

}

//keep looping if the input is not valid

while(!successfulStart);

return successfulStart;

}//startNewGame()

/**

* Sets the mode of the game based on user's input

* @return successfulSetMode

* <br> valid input of the user's answer to which difficulty level want to play?

*/

public boolean setMode()

{

//keeps track of valid input

boolean successfulSetMode = false;

//a loop prompts the user with the same question if the input is not valid

do

{

System.out.println("Please choose: s = standard mode ( use 6 colors and 4 holes)");

System.out.println(" c = challenge mode( use 7 colors and 5 holes)");

input = keyboard.nextLine();

if (input.equalsIgnoreCase("s"))

{

mode = STANDARD_MODE;

successfulSetMode = true;

return true;

}

else if (input.equalsIgnoreCase("c"))

{

mode = CHALLENGE_MODE;

successfulSetMode = true;

return true;

}

else

{

System.out.println("Error in reading your input.");

successfulSetMode = false;

}

}

//keep looping if the input is not valid

while (!successfulSetMode);

return successfulSetMode;

}//setMode()

/**

* Gets the user-defined game mode

* @return mode

* <br> the user-defined game mode

*/

public int getMode()

{

return mode;

}//getMode()

/**

* loops to input 4 or 5 colors for each guess

* @return guess[]

* <br> the guessed colors defined by the user

*/

public char[] getGuess()

{

//user will enter one color at a time

int colorPosition = 1;

//keep track of the valid input for each color

boolean successfulGetGuess = false;


//a loop keeps asking the user to enter the correct number of colors for a guess

do

{

//4 colors need for a guess in the standard mode

if (mode == STANDARD_MODE)

{

guess[totalGuesses] = new char[4];

System.out.println("Please choose four colors from:");

System.out.println("r = red o = orange y = yellow g = green b = blue i = indigo");

successfulGetGuess = getColorInput(colorPosition);


for(colorPosition = 2; colorPosition <= 4 && successfulGetGuess; colorPosition ++)

{

successfulGetGuess = false;

successfulGetGuess = getColorInput(colorPosition);

}

}

//5 colors needed for a guess in the challenge mode

if (mode == CHALLENGE_MODE)

{

guess[totalGuesses] = new char[5];

System.out.println("Please choose the colors for 5 holes from:");

System.out.println("r = red o = orange y = yellow g = green b = blue i = indigo v = violet");

successfulGetGuess = getColorInput(colorPosition);


for (colorPosition = 2; colorPosition <= 5 && successfulGetGuess; colorPosition ++)

{

successfulGetGuess = false;

successfulGetGuess = getColorInput(colorPosition);

}

}

//reminds the user if errors occur in the input

if (!successfulGetGuess)

{

System.out.println("Problem with getting your guess.");

}

}

//keep looping if the input is invalid and ask the user whether wants to continue or start over or get a hint

while ((!successfulGetGuess) && continueCurrentGame());

//display the guess defined by the user

System.out.print(" Your guess: ");

for (int i = 0; i <= guess[totalGuesses].length - 1; i++)

{

System.out.print(guess[totalGuesses][i] + " ");

}

System.out.println();

return guess[totalGuesses];

}//getGuess()

/**

* Prompts the user to guess one color at indicated position

* @param colorPosition

* the position of the color in the guess

* @return successfulGetColor

* <br>indicates the input of the guessed color from the user is valid

*/

public boolean getColorInput(int colorPosition)

{

//keeps track of the valid input for each color

boolean successfulGetColor = false;

//choose from 6 colors in the standard mode

if (mode == STANDARD_MODE)

{

do

{

System.out.print(colorPosition + ": ");

input = keyboard.nextLine();

if ( input.equalsIgnoreCase("r") || input.equalsIgnoreCase("red"))

{

guess[totalGuesses][colorPosition - 1] = 'r';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("o") || input.equalsIgnoreCase("orange"))

{

guess[totalGuesses][colorPosition - 1] = 'o';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yellow"))

{

guess[totalGuesses][colorPosition - 1] = 'y';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("g") || input.equalsIgnoreCase("green"))

{

guess[totalGuesses][colorPosition - 1] = 'g';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("b") || input.equalsIgnoreCase("blue"))

{

guess[totalGuesses][colorPosition - 1] = 'b';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("i") || input.equalsIgnoreCase("indigo"))

{

guess[totalGuesses][colorPosition - 1] = 'i';

successfulGetColor = true;

return true;

}

else

{

System.out.println("Error in reading you input.");

successfulGetColor = false;

}

}

while (!successfulGetColor);

return successfulGetColor;

}

//choose from 7 colors in the standard mode

if (mode == CHALLENGE_MODE)

{

do

{

System.out.print(colorPosition + ": ");


input = keyboard.nextLine();

if ( input.equalsIgnoreCase("r") || input.equalsIgnoreCase("red"))

{

guess[totalGuesses][colorPosition - 1] = 'r';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("o") || input.equalsIgnoreCase("orange"))

{

guess[totalGuesses][colorPosition - 1] = 'o';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yellow"))

{

guess[totalGuesses][colorPosition - 1] = 'y';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("g") || input.equalsIgnoreCase("green"))

{

guess[totalGuesses][colorPosition - 1] = 'g';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("b") || input.equalsIgnoreCase("blue"))

{

guess[totalGuesses][colorPosition - 1] = 'b';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("i") || input.equalsIgnoreCase("indigo"))

{

guess[totalGuesses][colorPosition - 1] = 'i';

successfulGetColor = true;

return true;

}

else if (input.equalsIgnoreCase("v") || input.equalsIgnoreCase("violet"))

{

guess[totalGuesses][colorPosition - 1] = 'v';

successfulGetColor = true;

return true;

}

else

{

System.out.println("Error in reading you input.");

successfulGetColor = false;

}

}

while (!successfulGetColor);

return successfulGetColor;

}

return successfulGetColor;

}//getColorInput(int)


/**

* Prompts the user whether continue the current game or start a new game or need a hint;

* displays the summary of all guesses before continue to enter a new guess

* @return successfulContinueCurrentGame

* <br> user's answer to whether wants to continue or start over

*/

public boolean continueCurrentGame()

{

boolean successfulContinueCurrentGame = false;

//loops if the input is not valid

do

{

System.out.println(" Would you like to continue or start a new game or get a hint? " +

"c = continue s = start a new game h = hint.");

input = keyboard.nextLine();

//display a summary of all the guesses before continue to enter a new guess

if (input.equalsIgnoreCase("c") || input.equalsIgnoreCase("continue"))

{

/*System.out.println("********************************************************************");

System.out.println("Summary guesses:");

for (int i = 0; i <= totalGuesses - 1; i++)

{

System.out.println(i + 1);


for (int j = 0; j <= guess[totalGuesses - 1].length - 1; j++)

{

System.out.print(guess[i][j] + " ");

}

System.out.println();

for (int j = key[totalGuesses].length - 1; j >= 0; j--)

{

System.out.print(key[i][j] + " ");

}

System.out.println();


}

System.out.println("********************************************************************");*/


return true;

}

//start a new game

else if (input.equalsIgnoreCase("s") || input.equalsIgnoreCase("start"))

return false;

else if (input.equalsIgnoreCase("h") || input.equalsIgnoreCase("hint"))

{

MMHint hint = new MMHint(answer, hintsUsed);

hintsUsed = hint.getHint();

return true;

}

//invalid input

else

{

System.out.println("Error in reading your input.");

successfulContinueCurrentGame = false;

}

}

//loops if the input is invalid

while (!successfulContinueCurrentGame);

return successfulContinueCurrentGame;

}//continueCurrentGame()

}//MasterMind main class


/**

* This class tells the user a hint based on the answer

*/

class MMHint

{

private char[] answer;

private int guessesUsed = 0;

/**

* Constructs a MMHint object which gives the user a hint

* @param guesses

* the amount of guesses used

* @param answer

* the char array indicates the answer made by the computer

*/

public MMHint(char[] answer, int guesses)

{

this.answer = answer;

this.guessesUsed = guesses;


}


/**

* @return output based on the amount of guesses used

*/

public int getHint()

{

if (guessesUsed < answer.length)

{

System.out.println("There is at least one " + answer[guessesUsed] + " peg.");

}

guessesUsed++;

return guessesUsed;

}


//tester for MMHint class

public static void main (String args[])

{

MMAnswer testAnswer = new MMAnswer(6);

System.out.println(testAnswer.getAnswer());

for (int i = 0; i<4; i++)

{

MMHint hint = new MMHint(testAnswer.getAnswer(), i);

hint.getHint();

}

}//tester for MMHint class

}//MMHint class



/**

* This class compares the guesses made by the user to the answer made by the computer and

* keeps track of the score of each guess

*/

class MMGuess

{

private char[] answer;

private char[] key;

private char[] guess;

private boolean[] guessUsed;

private boolean[] answerUsed;

private int singleHits;

/**

* Constructs a MMGuess object which compares two char arrays.

* @param guess

* the char array indicates the guess made by the user

* @param answer

* the char array indicates the answer made by the computer

*/

public MMGuess(char[] guess, char[] answer)

{

this.answer = answer;

this.guess = guess;

//the lengths of the key, guess and answer are determined by the mode passed from the main game

key = new char[answer.length];

guessUsed = new boolean[answer.length];

answerUsed = new boolean[answer.length];

singleHits = 0;

for(int i = 0; i <= answer.length - 1; i++)

{

key[i] = '0';

guessUsed[i] = false;

answerUsed[i] = false;


}


}//MMGuess(char[], char[])



/**

* Compares the guess to the answer and generates the key pegs

* @return checks whether the guess perfectly matches the answer

*/

public boolean evaluateGuess()

{

//checks whether the guessed color is the perfect match (right color, right position)

for (int i = 0; i <= answer.length - 1; i++)

{

if (guess[i] == answer[i] && guessUsed[i] == false && answerUsed[i] == false)

{

key[i] = 'X';

guessUsed[i] = true;

answerUsed[i] = true;

//2 points for a perfect match

singleHits += 2;

}

}

//checks whether the non-perfect matched color is a close match

for (int i = 0; i <= answer.length - 1; i++)

{

if (guessUsed[i] == false)

{

for (int j = 0; j <= answer.length - 1; j ++)

{

if (guess[i] == answer[j] && guessUsed[i] == false && answerUsed[j] == false)

{

key[i] = 'x';

guessUsed[i] = true;

answerUsed[j] = true;

//1 point for a close match

singleHits ++;

}

}

}

}

//check whether the guess perfectly matches the answer, if yes, the user wins the game

if (singleHits == 2 * key.length)

return true;

else

return false;

}//evaluateGuess()

/**

* Returns the key pegs generated by comparing individual color in the guess and answer

* @return a char array containing the key pegs

*/

public char[] getKey()

{

Arrays.sort(key);

return key;

}//getKey()



/**

* Returns the score of each guess by comparing it to the answer

* @return the score of each guess

*/

public int getSingleHits()

{

return singleHits;

}//getSingleHits()



/**

* Returns a String object representing this MMGuess object.

* @Override toString in class Object

* @return a string representation of this object.

*/

public String toString()

{

return "MMGuess [answer=" + Arrays.toString(answer) + ", key="

+ Arrays.toString(key) + ", guess=" + Arrays.toString(guess)

+ ", guessUsed=" + Arrays.toString(guessUsed) + ", answerUsed="

+ Arrays.toString(answerUsed) + ", singleHits=" + singleHits + " ]";

}//toString()



//tester for MMGuess class

public static void main (String args[])

{

char[] testGuess1 = {'r','o','g','c'};

char[] testAns1 = {'r','o','g','c'};

MMGuess tester1 = new MMGuess(testGuess1, testAns1);

if (tester1.evaluateGuess())

System.out.println("win");

if (!tester1.evaluateGuess())

System.out.println("lose");

System.out.println(tester1);

char[] testGuess2 = {'c','o','g','c'};

char[] testAns2 = {'r','o','o','c'};

MMGuess tester2 = new MMGuess(testGuess2, testAns2);

if (tester2.evaluateGuess())

System.out.println("win");

if (!tester2.evaluateGuess())

System.out.println("lose");

System.out.println(tester2);

}//tester for MMGuess class

}//MMGuess class


/**

* This class generates a set of colors randomly from either 6 or 7 author-defined colors

*/

class MMAnswer

{

private char[] answer;

private final int STANDARD_MODE = 6;

private final int CHALLENGE_MODE = 7;

/**

* Constructs a new MMAnswer object with the user-defined game mode passed from main game

* @param args

*/

public MMAnswer (int mode)

{

// Generate answer for standard mode: use six colors and four holes

// Allows duplicate

if ( mode == STANDARD_MODE )

{

// contain four holes

answer = new char[4];

// radomly select 4 colors from 6 colors

int rand;

// first color

rand = 1 + (int)(Math.random() * 6);

answer[0] = convert(rand);

// second color

rand = 1 + (int)(Math.random() * 6);

answer[1] = convert(rand);

// third color

rand = 1 + (int)(Math.random() * 6);

answer[2] = convert(rand);

// fourth color

rand = 1 + (int)(Math.random() * 6);

answer[3] = convert(rand);

}

// Generates answer for challenge mode: use seven colors and five holes

// Allows duplicate

if ( mode == CHALLENGE_MODE )

{

// contain 5 holes

answer = new char[5];

// radomly select 5 colors from 7 colors

int rand;

// first color

rand = 1 + (int)(Math.random() * 7);

answer[0] = convert(rand);

// second color

rand = 1 + (int)(Math.random() * 7);

answer[1] = convert(rand);

// third color

rand = 1 + (int)(Math.random() * 7);

answer[2] = convert(rand);

// fourth color

rand = 1 + (int)(Math.random() * 7);

answer[3] = convert(rand);

// fifth color

rand = 1 + (int)(Math.random() * 7);

answer[4] = convert(rand);

}

}//MMAnswer(int mode)

/**

* Converts the random integer into corresponding color represented by the first character

* @param answerIndex the position of the color in the answer

*/

private char convert(int answerIndex)

{

switch ( answerIndex )

{

//red

case 1 : return 'r';

//orange

case 2 : return 'o';

//yellow

case 3 : return 'y';

//green

case 4 : return 'g';

//magenta

case 5 : return 'b';

//cyan

case 6 : return 'i';

//pink

case 7 : return 'v';

}


return 'x';

}//convert(int)

/**

* Returns the answer generated by the computer

*/

public char[] getAnswer()

{

return answer;

}



// tester of MMAnswer class

public static void main (String args[]) {

MMAnswer standAns = new MMAnswer(6);

System.out.println(standAns.getAnswer());

MMAnswer chanAns = new MMAnswer(7);

System.out.println(chanAns.getAnswer());

}//tester

}//MMAnswer class



/**

* This class reads and writes to text files

* Files are saved in the following format, one line for each mode

*

*/

class MMStatistics

{

private String FILE;

int totalGames = 0; // The total number of games played

int MAX_SIZE = 101; // The Maximum # of guesses a user can have before they automatically lose

int [] guessArray = new int[MAX_SIZE]; // Holds the number of users with the correct answer (where index = guesses)

int mode;

public void setMode(int currentMode)

{

mode = currentMode;

}

private void loadStats()throws IOException

{

// Change the file if they are playing advanced mode

if (mode == 7)

{

FILE = "AdvancedMasterMind.txt";

} else {

FILE = "StandardMasterMind.txt";

}

// Variables

String line; // Full line from file

int guessCount = 0; // The amount of guesses it took to get the correct answer

boolean hasTotal = false;

int tokenItem; // A token from the document loaded


// Open File to begin reading

BufferedReader br = new BufferedReader(new FileReader(FILE));


// Read next line and process it if it exists

while ( (line = br.readLine()) != null)

{ // Stop if there is not another line


// Begin Tokenizing the whole line for multiple values

StringTokenizer token = new StringTokenizer(line);

// Process whole line adding each value into the array

while (token.hasMoreTokens())

{// Doesnt allow for the array to be overloaded

// Get Token from the file

tokenItem = Integer.parseInt(token.nextToken());

// Checks to see if the first line has been read.

// The first line contains the total games played

if (hasTotal)

{

if (tokenItem != 0)

{

guessArray[guessCount] = tokenItem;

}

} else {

totalGames = tokenItem;

hasTotal = true;

}

// Increase line number (Corresponds to the number of guesses it took)

guessCount++;

}

}


br.close(); // Close BufferedReader

}

public void displayStats() throws IOException

{


loadStats(); // Get the statistics

int guessCount = 0; // Counter for # of guesses it took to correctly guess the MasterMind

System.out.println(totalGames + " Total Games Played");


for (int i=0; i<MAX_SIZE;i++)

{

// Display all of the stats if there was someone who correctly guesses

if (guessArray[i] != 0)

{

System.out.println(guessArray[i] + " users took " + guessCount + " guess(es) to successfully solve the MasterMind. (" + (guessArray[i] / ((double) totalGames)) * 100 + "%)");

}

guessCount++;

}

}

public void saveStats(int guessesUntilSuccess) throws IOException

{

loadStats(); // Retreive All Data

totalGames++; // Increase the total games played

// Add the users total guesses into array

guessArray[guessesUntilSuccess] = guessArray[guessesUntilSuccess] + 1;

// Create file to write to

BufferedWriter writer = new BufferedWriter(new FileWriter(FILE));

// Write the first line (Total number of guesses)

writer.write(Integer.toString(totalGames));

// Write each value in array to file, separated by lines

for (int i = 1; i < MAX_SIZE; i++)

{

writer.newLine();

writer.write(Integer.toString(guessArray[i]));

}


writer.close(); // Close BufferedWriter


}


// tester of MMFile class

public static void main (String args[]) throws IOException

{

MMStatistics test = new MMStatistics();

test.displayStats();

/*

for (int i = 0; i<1000; i++) {

test.saveStats(1+(int)(Math.random() * 100));

}

test.displayStats();

*/

//test.loadStats();


}//tester

}//MMAnswer class