-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.java
More file actions
65 lines (57 loc) · 1.51 KB
/
Game.java
File metadata and controls
65 lines (57 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class Game {
public static final int MAX_MISSES = 7;
private String answer;
private String hits;
private String misses;
public Game(String answer) {
this.answer = answer.toLowerCase();
hits = "";
misses = "";
}
public String getAnswer() {
return answer;
}
private char normalizeGuess(char letter) {
if (! Character.isLetter(letter)) {
throw new IllegalArgumentException("A letter is required");
}
letter = Character.toLowerCase(letter);
if (misses.indexOf(letter) != -1 || hits.indexOf(letter) != -1) {
throw new IllegalArgumentException(letter + " has already been guessed");
}
return letter;
}
public boolean applyGuess(String letters) {
if (letters.length() == 0) {
throw new IllegalArgumentException("No letter found");
}
return applyGuess(letters.charAt(0));
}
public boolean applyGuess(char letter) {
letter = normalizeGuess(letter);
boolean isHit = answer.indexOf(letter) != -1;
if (isHit) {
hits += letter;
} else {
misses += letter;
}
return isHit;
}
public int getRemainingTries() {
return MAX_MISSES - misses.length();
}
public String getCurrentProgress() {
String progress = "";
for (char letter : answer.toCharArray()) {
char display = '-';
if (hits.indexOf(letter) != -1) {
display = letter;
}
progress += display;
}
return progress;
}
public boolean isWon() {
return getCurrentProgress().indexOf('-') == -1;
}
}