CS206 Homework 1:  Arrays, keyboard inputs and error checking

Due: Thursday, Sep 9, 2004

Mastermind! [100pts]

Write a program that implements a game of mastermind.

The program selects a random set of digits (i.e. a secret code), whose length is specified by a variable say digits, and the user has to guess them in a finite number of rounds, also specified by a variable say rounds. The program reports the number of digits selected by the user that match the hidden digits. The number of digits that are correctly placed as well as incorrectly placed are reported. For example, if the secret code is 1 2 2 5, and the user guesses 3 1 2 2, then the program reports that there is 1 digit in place (the 2 that is the third digit), and 2 digits out of place (1 and the other 2).

The game stops when the user guesses the digits selected by the program or when the maximum number of rounds allowed has been reached.

Copy the class files Mastermind.class and Guess.class from /home/dxu/handouts/ to your home directory, and run them (java Mastermind) to get and idea how this program behaves.

Additional requirements/hint

  1. Write a method genCode to generate the secret code randomly. Use the Java math library function Math.random(). Math.random() will randomly generate a float ranging anywhere from 0.0 to 1.0.
  2. Both the secret code (consisting of 4 digits by default) and the user's guess will be stored in int arrays of size specified by digits. You may not use larger arrays.
  3. Have two counters that keep track of how many digits are in place and out of place, respectively. You need to think of a way to mark off digits that have already been matched, so as to avoid counting them repeatedly.
  4. The two variables digits and rounds are defined to be 4 and 10 by default. This provides a reasonable level of game difficulty in the beginning. However, as one gets better with the game, one might want to increase the difficulty. That can be done either by raising the number of digits to guess, or lowering the maximum number of rounds allowed.
  5. Write your program so that the only thing one needs to do to make the program work for different number of digits or different number of rounds is to change the corresponding variable. Therefore, make sure you are refering to these variables through out your program, whether sepcifiying array sizes or running for loop counters through the arrays.
  6. Have your program take commandline arguments, in the following format:
  7. The program expect input of digits from the user in the following format: 1 1 1 1 (for 4 digits) followed by return. Make sure to indicate error and prompt the user again if input is given in the wrong format: