forked from menault/TD3_DEV51_Qualite_Algo
feat: manager that uses the words from the dictionnary in ~/res/
This commit is contained in:
51
src/WordManager.java
Normal file
51
src/WordManager.java
Normal file
@@ -0,0 +1,51 @@
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
public class WordManager {
|
||||
|
||||
private static final String FILE_PATH = "../res/hangman_words.txt";
|
||||
|
||||
private final Map<String, List<String>> wordsByDifficulty = new HashMap<>();
|
||||
|
||||
public WordManager() throws IOException {
|
||||
wordsByDifficulty.put("EASY", new ArrayList<>());
|
||||
wordsByDifficulty.put("MEDIUM", new ArrayList<>());
|
||||
wordsByDifficulty.put("HARD", new ArrayList<>());
|
||||
loadWords();
|
||||
}
|
||||
|
||||
private void loadWords() throws IOException {
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) {
|
||||
String line;
|
||||
String section = "";
|
||||
while ((line = reader.readLine()) != null) {
|
||||
line = line.trim();
|
||||
if (line.startsWith("#")) {
|
||||
section = line.substring(1).toUpperCase();
|
||||
} else if (!line.isEmpty() && wordsByDifficulty.containsKey(section)) {
|
||||
wordsByDifficulty.get(section).add(line.toLowerCase()); // make all words lowercase
|
||||
}
|
||||
}
|
||||
} catch (FileNotFoundException e) {
|
||||
throw new IOException("File not found: " + FILE_PATH);
|
||||
}
|
||||
}
|
||||
|
||||
public String getRandomWord(int difficulty) {
|
||||
String key = mapDifficulty(difficulty);
|
||||
List<String> list = wordsByDifficulty.get(key);
|
||||
if (list == null || list.isEmpty()) return null;
|
||||
|
||||
Random rand = new Random();
|
||||
return list.get(rand.nextInt(list.size()));
|
||||
}
|
||||
|
||||
private String mapDifficulty(int difficulty) {
|
||||
return switch (difficulty) {
|
||||
case 1 -> "EASY";
|
||||
case 2 -> "MEDIUM";
|
||||
case 3 -> "HARD";
|
||||
default -> "EASY"; // Default value
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user