113 lines
2.9 KiB
Java
113 lines
2.9 KiB
Java
package hangman;
|
|
/**
|
|
* Game contains the logic for game of hangman.
|
|
*
|
|
*/
|
|
public class Game {
|
|
|
|
protected String word;
|
|
protected int remaining_guesses;
|
|
protected StringBuffer display;
|
|
protected String correctGuess;
|
|
protected String badGuess;
|
|
|
|
/**
|
|
* Game constructor
|
|
* @param word - the word to be guessed
|
|
* @param guesses - number of incorrect guesses allowed
|
|
*/
|
|
public Game(String word, int guesses) {
|
|
this.word = word;
|
|
remaining_guesses = guesses;
|
|
correctGuess = "";
|
|
badGuess = "";
|
|
display = new StringBuffer();
|
|
for (int i = 0; i < word.length(); i++) {
|
|
char c = word.charAt(i);
|
|
if (Character.isLetter(c)) {
|
|
display.append("_");
|
|
} else {
|
|
display.append("#");
|
|
}
|
|
display.append(" ");
|
|
}
|
|
}
|
|
|
|
public String getWord() {
|
|
return word;
|
|
}
|
|
|
|
public int getRemainingGuesses() {
|
|
return remaining_guesses;
|
|
}
|
|
|
|
public String getDisplay() {
|
|
return display.toString();
|
|
}
|
|
|
|
/* return code from processGuess */
|
|
|
|
public static final int GOOD = 1;
|
|
public static final int BAD = 2;
|
|
public static final int WON = 3;
|
|
public static final int LOST = 4;
|
|
public static final int REPEAT_GOOD_GUESS = 5;
|
|
public static final int REPEAT_BAD_GUESS = 6;
|
|
|
|
/**
|
|
*
|
|
* @param c - the letter guessed
|
|
* @return code
|
|
*/
|
|
public int processGuess(char c) {
|
|
if (correctGuess.indexOf(c) >= 0) {
|
|
return REPEAT_GOOD_GUESS;
|
|
}
|
|
|
|
if (badGuess.indexOf(c) >= 0) {
|
|
remaining_guesses -= 1;
|
|
if (remaining_guesses <= 0 && display.indexOf("_") >= 0) {
|
|
return LOST;
|
|
} else {
|
|
return REPEAT_BAD_GUESS;
|
|
}
|
|
|
|
} else {
|
|
boolean found = false;
|
|
for (int i = 0; i < word.length(); i++) {
|
|
if (c == word.charAt(i)) {
|
|
found = true;
|
|
correctGuess += c;
|
|
display.replace(2 * i, 2 * i + 1, word.substring(i, i + 1));
|
|
}
|
|
}
|
|
if (!found) {
|
|
remaining_guesses -= 1;
|
|
badGuess += c;
|
|
if (remaining_guesses <= 0 && display.indexOf("_") >= 0) {
|
|
return LOST;
|
|
} else {
|
|
return BAD;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (display.indexOf("_") < 0) {
|
|
return WON;
|
|
} else {
|
|
return GOOD;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* user asks for a hint.
|
|
* @return code WON, LOST or GOOD.
|
|
*/
|
|
public int doHint() {
|
|
int k = display.indexOf("_");
|
|
char c = word.charAt(k / 2);
|
|
int rc = processGuess(c);
|
|
return rc;
|
|
}
|
|
}
|