1 7 8 package hangman; 9 10 16 public class Game 17 { 18 private String _targetWord; 19 private int _incorrectGuessesLeft; 20 private char[] _letters; 21 private boolean[] _guessed = new boolean[26]; 22 private boolean _win; 23 24 28 29 public boolean isWin() 30 { 31 return _win; 32 } 33 34 43 44 public char[] getLetters() 45 { 46 return _letters; 47 } 48 49 55 56 public int getIncorrectGuessesLeft() 57 { 58 return _incorrectGuessesLeft; 59 } 60 61 69 70 public boolean[] getGuessedLetters() 71 { 72 return _guessed; 73 } 74 75 81 82 83 public void start(String word) 84 { 85 _targetWord = word; 86 _incorrectGuessesLeft = 5; 87 _win = false; 88 89 int count = word.length(); 90 91 _letters = new char[count]; 92 93 for (int i = 0; i < count; i++) 94 _letters[i] = '_'; 95 96 for (int i = 0; i < 26; i++) 97 _guessed[i] = false; 98 } 99 100 114 115 public boolean makeGuess(char letter) 116 { 117 char ch = Character.toLowerCase(letter); 118 119 if (ch < 'a' || ch > 'z') 120 throw new IllegalArgumentException ("Must provide an alphabetic character."); 121 122 int index = ch - 'a'; 123 124 127 if (_guessed[index]) 128 return true; 129 130 _guessed[index] = true; 131 132 boolean good = false; 133 boolean complete = true; 134 135 for (int i = 0; i < _letters.length; i++) 136 { 137 if (_letters[i] != '_') 138 continue; 139 140 if (_targetWord.charAt(i) == ch) 141 { 142 good = true; 143 _letters[i] = ch; 144 continue; 145 } 146 147 151 complete = false; 152 } 153 154 if (good) 155 { 156 _win = complete; 157 158 return !complete; 159 } 160 161 162 if (_incorrectGuessesLeft == 0) 163 { 164 166 _letters = _targetWord.toCharArray(); 167 168 return false; 169 } 170 171 _incorrectGuessesLeft--; 172 173 175 return true; 176 } 177 } | Popular Tags |