import java.util.Random; /** * * Mastermind.java * * Implements the game Mastermind. * * @version 1.0 Feb 15, 197 * @author Kwok-Bun Yue * @see http://ricis.cl.uh.edu/~yue/s97/4931/index.html * * Colors are defined as positive int: 1, 2, 3, 4, ... * * Because of space, this is not a clean design. * A better design is based on the MVC (Model-View-Controller) * pattern where the model (the application) contains methods * of the Mastermind game. The view includes GUI methods and * the controller controls the interaction between the model * and the view. * * In the current design, the Mastermind class contains methods * such as printHistory() that belongs to the view in the * MVC pattern. Because of the simplicity of the class, the * current design is simpler and quicker. * **/ class Mastermind { // constants public final static int STANDARD_NUM_OF_SLOTS = 4; public final static int STANDARD_NUM_OF_COLORS = 6; public final static int STANDARD_MAX_GUESSES = 30; // random number generator to generate solutions. private static Random RANDOM = new Random(); // private data members: ends with _. private int[][] guesses_; // history of guesses. private int[][] hints_; // history of hints. private int[] answer_; // answer of the game. private int currentGuess_; // current guess to make. private int numSlots_; // number of slots used. private int numColors_; // number of colors used. private int maxGuesses_; // max number of guesses. private boolean gameOver_; // true iff game is over. private boolean gameWon_; // true iff player guesses right. // constructors. public Mastermind() { this(STANDARD_NUM_OF_SLOTS, STANDARD_NUM_OF_COLORS, STANDARD_MAX_GUESSES); } public Mastermind(int maxGuesses) { this(STANDARD_NUM_OF_SLOTS, STANDARD_NUM_OF_COLORS, maxGuesses); } public Mastermind(int numSlots, int numColors) { this(numSlots, numColors, STANDARD_MAX_GUESSES); } public Mastermind(int numSlots, int numColors, int maxGuesses) { numSlots_ = numSlots; numColors_ = numColors; maxGuesses_ = maxGuesses; newGame(); } // public methods // Create a new game. public void newGame() { // initialize instant variables. currentGuess_ = 0; gameOver_ = false; gameWon_ = false; // allocate arrays. guesses_ = new int[maxGuesses_] [numSlots_]; hints_ = new int[maxGuesses_] [2]; // [0]: ox; [1]: cow. answer_ = new int[numSlots_]; // set the answer (solution). // each slot gets an integer from 1 to numColors_ for (int i=0; i= maxGuesses_) { gameWon_ = false; gameOver_ = true; } return true; } // Check whether game is won. public boolean gameWon() { return gameWon_; } // Check whether game is over. public boolean gameOver() { return gameOver_; } // Print the history of the guesses and hints. public void printHistory() { System.out.print("guess#\t"); for (int i=0; i= 0) { for (int j=0; j