import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Random; import java.util.ArrayList; /** Implement the features of the hangman game. */ public class Game { private ArrayList list; private String answer; private String display; private int numBadGuesses; private boolean [] alreadyGuessed; private static final int MAX_BAD_GUESSES = 8; public Game() { // answer = "everything"; setAnswer(); // The display string must be equal in length to answer. display = ""; for (int i = 0; i < answer.length(); ++i) display += "."; numBadGuesses = 0; alreadyGuessed = new boolean [26]; for (int i = 0; i < alreadyGuessed.length; ++i) alreadyGuessed[i] = false; } public void setAnswer() { list = new ArrayList(); try { Scanner in = new Scanner(new FileInputStream("words.txt")); while (in.hasNextLine()) { String word = in.nextLine(); list.add(word); } } catch(FileNotFoundException e) { System.out.printf("Fatal error - no dictionary file\n"); System.exit(1); } // Now, pick a random number from 0 to size-1 Random g = new Random(); int position = g.nextInt(list.size()); // Let's make sure all letters lowercase! answer = list.get(position).toLowerCase(); } /** The most important function is play. */ public void play(char choice) { // We've decided to check for already-guessed letter first. // Check to see if this letter already guessed. // If it has, write diff error msg, ++ # bad guesses. // Second, see if the letter is in the word at all. // If it isn't, write error msg, and ++ number of bad guesses. // // If we make it this far, the letter is in the word. // Search entire answer string for this letter, and reveal // each occurrence in the display string. // Don't forget to keep track of the guess. // have we guessed this letter already? // We could do it this way too: position = choice - 'a' String alphabet = "abcdefghijklmnopqrstuvwxyz"; int position = alphabet.indexOf(choice); if (alreadyGuessed[position]) { System.out.printf("You already guessed that letter!\n"); ++numBadGuesses; return; } // Even if the guess is wrong, keep track of it. if (answer.indexOf(choice) == -1) { System.out.printf("Sorry, your letter is not in the word.\n"); ++numBadGuesses; alreadyGuessed[choice - 'a'] = true; return; } for (int i = 0; i < answer.length(); ++i) { // If the letter matches, then change the corresponding // char in the display string to my choice. // Conceptually, display[i] = choice, but display is String! // Also, 'display.charAt(i) = choice' is close but wrong. if (choice == answer.charAt(i)) display = display.substring(0, i) + choice + display.substring(i+1); } // Finally, record this guess. alreadyGuessed[choice - 'a'] = true; } public boolean win() { return display.equals(answer); } public boolean lose() { return numBadGuesses >= MAX_BAD_GUESSES; } public String toString() { return display + " bad guesses = " + numBadGuesses; } public String getAnswer() { return answer; } }