import java.io.*; import java.util.StringTokenizer; // maybe to break down the input. /** * * MastermindTester.java * * Implements a tester in the Mastermind game. * javadoc format * @version 1.0 Feb 15, 1997 * @author Kwok-Bun Yue * @see http://ricis.cl.uh.edu/~yue/s97/4931/index.html * **/ class MastermindTester { // constants final static int NUM_SLOTS = 4; final static int NUM_COLORS = 6; final static int MAX_GUESSES = 30; // Create an input stream for the standard input. static DataInputStream dis = new DataInputStream(System.in); // main program body. public static void main(String[] args) throws IOException { // Create a new Mastermind game. Mastermind mastermind = new Mastermind(NUM_SLOTS, NUM_COLORS, MAX_GUESSES);; int[] guess; // current guess made int[] hints = new int[2]; // hints of the guess: hints[0]: # of ox. hints[1]: # of cows. while (true) { // play one game: one game per iteration of the while loop. System.out.println("\nWelcome to a new mastermind game.\n"); while (true) { // get one guess from the player. guess = getPlayerGuess(NUM_SLOTS, NUM_COLORS); mastermind.makeGuess(guess, hints); System.out.println("Current guess and hint history:\n\n"); mastermind.printHistory(); if (mastermind.gameWon()) { System.out.println("Congratulation! You won! \n\n"); break; } else if (mastermind.gameOver()) { System.out.println("Sorry! Maximum number of guesses reached!"); break; } } if (! moreGame()) break; mastermind.newGame(); // The class Mastermind must provide a constructor, makeGuess, // printHistory, gameWon, gameOver and newGame. } } // helper methods. static int[] getPlayerGuess(int numSlots, int numColors) throws IOException { int[] result = new int[numSlots]; String inLine; StringTokenizer st; System.out.println("Please supply the colors of each slot of your guess:\n"); for (int i=0; i < numSlots; i++) { // get the guess for one slot. System.out.print("The (integer) color of slot " + (i+1)); System.out.print(" [1 to " + numColors + "]: "); System.out.flush(); //get the string input, convert to an integer and store in the // current result element. st = new StringTokenizer(dis.readLine()); result[i] = Integer.parseInt(st.nextToken()); } System.out.println(); return result; } static boolean moreGame() throws IOException { while (true) { System.out.println("Do you want to play another game? [y/n]"); String inLine = dis.readLine(); if (inLine.charAt(0) == 'y' || inLine.charAt(0) == 'Y') return true; if (inLine.charAt(0) == 'n' || inLine.charAt(0) == 'N') return false; } } }