-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordleGame.java
More file actions
78 lines (63 loc) · 2.29 KB
/
WordleGame.java
File metadata and controls
78 lines (63 loc) · 2.29 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
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.ArrayList;
public class WordleGame implements GuessChecker {
private String targetWord;
private int maxGuesses;
private int currentGuess;
private ArrayList<String> guessHistory;
private boolean gameOver;
public WordleGame(String targetWord, int maxGuesses) {
this.targetWord = targetWord;
this.maxGuesses = maxGuesses;
this.currentGuess = 0;
this.guessHistory = new ArrayList<>();
this.gameOver = false;
}
public LetterResult[] checkGuess(String guess) {
LetterResult[] results = new LetterResult[5];
// Create a array of letters in the target word
int[] targetLetterCount = new int[26]; // for a-z
for (char c : targetWord.toCharArray()) {
targetLetterCount[c - 'a']++;
}
for (int i = 0; i < 5; i++) {
char guessLetter = guess.charAt(i);
if (guessLetter == targetWord.charAt(i)) {
results[i] = new LetterResult(guessLetter, LetterState.CORRECT);
// Reduce the count of available letters
targetLetterCount[guessLetter - 'a']--;
}
}
for (int i = 0; i < 5; i++) {
if (results[i] != null) continue;
char guessLetter = guess.charAt(i);
if (targetLetterCount[guessLetter - 'a'] > 0) {
results[i] = new LetterResult(guessLetter, LetterState.PRESENT);
// Reduce the count of available letters
targetLetterCount[guessLetter - 'a']--;
} else {
results[i] = new LetterResult(guessLetter, LetterState.ABSENT);
}
}
guessHistory.add(guess);
currentGuess++;
if (guess.equals(targetWord) || currentGuess >= maxGuesses) {
gameOver = true;
}
return results;
}
public boolean isGameOver() {
return gameOver;
}
public boolean hasWon(String guess) {
return guess.equals(targetWord);
}
public boolean hasGuessesLeft() {
return currentGuess < maxGuesses;
}
public String getTargetWord() {
return targetWord;
}
public ArrayList<String> getGuessHistory() {
return guessHistory;
}
}