/** models a word to be guessed in HangMan, the number of guesses,
 *  plus the currently guessed portion.
 */
public class TargetWord {
  // the true word to guess, the portion guessed so far,
  // and the characters used.  The portion guessed so far
  // defaults to "****" (we assume four-letter words).
  private String trueWord, guessedWord = "****",
    usedCharacters = "";

  /** construct a word to be guessed.
   *  precondition: the word to be guessed is four-letter
   */
  public TargetWord(String s){
    trueWord= s.toUpperCase();
  }

  /** guess a character, and modify guessedWord if
   *  it contains instances of that character
   */
  public void guess(String s) {
    // make s upper case for consistency
    s= s.toUpperCase();
    // add s to the list of characters already guessed
    usedCharacters = usedCharacters + s + ",";

    // Rebuild guessedWord by replacing asterisks with
    // s where appropriate.  We check for s starting
    // from positions 0, 1, 2, and 3, to ensure we
    // get every possible instance of s.  This approach
    // was suggested by student Xam-Nhi Ha
    buildGuess(s,0);
    buildGuess(s,1);
    buildGuess(s,2);
    buildGuess(s,3);
  }

  /** buildGuess: rebuild guessedWord by checking whether
   *  the user's guess occurs at or after fromPos, and
   *  inserting it into guessedWord if it does.
   */
  private void buildGuess(String s, int fromPos) {
    int index= trueWord.indexOf(s, fromPos);
    // increment index, since we'll temporarily
    // place s into "#"+guessedWord
    index= index + 1;
    guessedWord= "#"+guessedWord;
    // store s in one of 5 positions:
    guessedWord= guessedWord.substring(0,index) + s +
      guessedWord.substring(index+1);
    // Remove the junk first character
    guessedWord= guessedWord.substring(1);
  }

  /** allGuessed: returns true if guessedWord equals
   *  trueWord.
   */
  public boolean allGuessed() {
    return trueWord.equals(guessedWord);
  }

    // toString: show the letters guessed correctly
    // and incorrectly as a string.
    public String toString() {
	String result= guessedWord;
	result += "\nto be guessed: " + trueWord + "\n";
	result += "Used: " + usedCharacters;
	return result;
    }
}

