From 3679e1a732e01f1dbf15525c8c0f94ad2dbed7ba Mon Sep 17 00:00:00 2001 From: gentil Date: Wed, 8 Oct 2025 15:02:17 +0200 Subject: [PATCH] feat: manager that uses the words from the dictionnary in ~/res/ --- src/WordManager.java | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/WordManager.java diff --git a/src/WordManager.java b/src/WordManager.java new file mode 100644 index 0000000..b42ca01 --- /dev/null +++ b/src/WordManager.java @@ -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> 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 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 + }; + } +}