feat: manager that uses the words from the dictionnary in ~/res/

This commit is contained in:
2025-10-08 15:02:17 +02:00
parent 001cc1d32a
commit 3679e1a732

51
src/WordManager.java Normal file
View 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
};
}
}