/**
 * HangmanGame class
 * @author Philip Peng
 * @version Oct 17, 2007
 */


public class HangmanGame {

	private String answer;
	/*
	 * Note: StringBuilder is used instead of StringBuffer
	 * as the variables are only used by one thread and
	 * StringBuilder is more memory efficient (and
	 * methods are still mostly equivalent to/compatible with
	 * those in StringBuffer.
	 */
	//private StringBuffer guessBuffer;
	//private StringBuffer triedBuffer;
	private StringBuilder guessBuffer;
	private StringBuilder triedBuffer;
	
	public HangmanGame (String word) {
		answer = word;
		//guessBuffer = new StringBuffer();
		guessBuffer = new StringBuilder();
		for (int i = 0; i < answer.length(); i++) {
			guessBuffer.append('-');
		}
		//triedBuffer = new StringBuffer();
		triedBuffer = new StringBuilder();
	}
	
	public String getTried() {
		return triedBuffer.toString();
	}
	
	public String getGuessed() {
		return guessBuffer.toString();
	}
	
	public String getWord() {
		return answer;
	}
	
	public int tryLetter(char c) {
		
		// If already tried
		for (int i = 0; i < triedBuffer.length(); i++) {
			if (c == triedBuffer.charAt(i)) { return 0; } // Stops here if true
		}
		// If not already tried
		int result = -1; // No
		for (int j = 0; j < answer.length(); j++) {
			if (c == answer.charAt(j)) {
				guessBuffer.setCharAt(j,c);
				result = 1; // Yes
			}
		}
		// Add to triedBuffer
		for (int k = 0; k < triedBuffer.length(); k++) {
			if (Character.valueOf(c) < Character.valueOf(triedBuffer.charAt(k))) { // Alphabetic insertion
				triedBuffer.insert(k,c); // Insert after alphabetically
				return result; // Stops here and returns 
			}
		}
		// If bigger than all characters or triedBuffer is blank
		triedBuffer.append(c); // Add to end
		return result;
	}
	
}
