diff --git a/HangmanGUI.java b/HangmanGUI.java deleted file mode 100644 index 0a1bc9e..0000000 --- a/HangmanGUI.java +++ /dev/null @@ -1,263 +0,0 @@ -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import java.util.*; - -/** - * Hangman game GUI. - * Variables/methods and comments in English. - * User-facing texts remain in French. - */ -public class HangmanGUI extends JFrame { - private final String[] words = { - "ordinateur","voiture","maison","soleil","lumiere", - "fromage","chocolat","montagne","riviere","plage", - "oiseau","papillon","musique","chateau","livre", - "telephone","aventure","mystere","foret","fleur", - "chapeau","nuage","horloge","chaise","fenetre", - "paysage","bouteille","parapluie","clavier","souris", - "brouillard","village","histoire","cerise","pomme", - "banane","poisson","arbre","cascade","cheval" - }; - - private String secretWord; - private final Set found = new HashSet<>(); - private final Set tried = new HashSet<>(); - private int errors = 0; - private static final int MAX_ERRORS = 8; // 8 steps: base, post, beam, rope, head, body, arms, legs - private boolean gameOver = false; // indicates if the game is finished - - private final JLabel wordLbl = new JLabel("", SwingConstants.CENTER); - private final JLabel triedLbl = new JLabel("", SwingConstants.CENTER); - private final JLabel infoLbl = new JLabel("Entrez une lettre (a-z)", SwingConstants.CENTER); - private final JTextField input = new JTextField(); - private final JButton guessBtn = new JButton("Proposer"); - private final HangPanel hangPanel = new HangPanel(); - - /** Drawing panel for the hangman, progressive according to error count. */ - private static class HangPanel extends JPanel { - private int errors = 0; - - public void setErrors(int e) { - this.errors = Math.max(0, Math.min(e, MAX_ERRORS)); - repaint(); - } - - @Override - protected void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D gg = (Graphics2D) g; - gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - - int w = getWidth(), h = getHeight(); - int baseY = h - 40; // ground level - - if (errors >= 1) gg.drawLine(50, baseY, w - 50, baseY); - - if (errors >= 2) gg.drawLine(100, baseY, 100, 60); - - if (errors >= 3) gg.drawLine(100, 60, 220, 60); - - if (errors >= 4) gg.drawLine(220, 60, 220, 90); - - if (errors >= 5) gg.drawOval(200, 90, 40, 40); - - if (errors >= 6) gg.drawLine(220, 130, 220, 200); - - if (errors >= 7) { - gg.drawLine(220, 145, 190, 165); - gg.drawLine(220, 145, 250, 165); - } - - if (errors >= 8) { - gg.drawLine(220, 200, 200, 240); - gg.drawLine(220, 200, 240, 240); - } - } - } - - /** Entry point: create and show the game window. */ - public static void main(String[] args) { - SwingUtilities.invokeLater(() -> { - HangmanGUI app = new HangmanGUI(); - app.setVisible(true); - }); - } - - /** Constructor: window setup, UI setup, and start the game. */ - public HangmanGUI() { - super("Jeu du Pendu"); - setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - setSize(520, 520); - setLocationRelativeTo(null); - setupUI(); - startGame(); - } - - /** Prepare the layout and interactions. */ - private void setupUI() { - wordLbl.setFont(new Font(Font.MONOSPACED, Font.BOLD, 28)); - triedLbl.setFont(new Font("SansSerif", Font.PLAIN, 14)); - infoLbl.setFont(new Font("SansSerif", Font.PLAIN, 14)); - - JPanel top = new JPanel(new GridLayout(3, 1, 8, 8)); - top.add(wordLbl); - top.add(triedLbl); - top.add(infoLbl); - - JPanel controls = new JPanel(new BorderLayout(8, 8)); - controls.add(input, BorderLayout.CENTER); - controls.add(guessBtn, BorderLayout.EAST); - - hangPanel.setPreferredSize(new Dimension(480, 300)); - JPanel center = new JPanel(new BorderLayout()); - center.add(hangPanel, BorderLayout.CENTER); - - JPanel main = new JPanel(new BorderLayout(10, 10)); - main.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - main.add(top, BorderLayout.NORTH); - main.add(center, BorderLayout.CENTER); - main.add(controls, BorderLayout.SOUTH); - - setContentPane(main); - - guessBtn.addActionListener(e -> onGuess()); - input.addActionListener(e -> onGuess()); - addWindowListener(new WindowAdapter() { - @Override public void windowOpened(WindowEvent e) { input.requestFocusInWindow(); } - }); - } - - /** Start a game. */ - private void startGame() { - secretWord = pickWord(); - found.clear(); - tried.clear(); - errors = 0; - gameOver = false; - - input.setText(""); - input.setEditable(true); - guessBtn.setEnabled(true); - infoLbl.setText("Entrez une lettre (a-z)"); - updateUIState(); - } - - /** Handle a guess: validate input, update state, check for end of game. */ - private void onGuess() { - if (gameOver) return; // block input after game end - - String s = input.getText().trim().toLowerCase(Locale.ROOT); - if (s.length() != 1 || s.charAt(0) < 'a' || s.charAt(0) > 'z') { - infoLbl.setText("Veuillez entrer une seule lettre (a-z)."); - input.selectAll(); - input.requestFocusInWindow(); - return; - } - char c = s.charAt(0); - if (tried.contains(c)) { - infoLbl.setText("Lettre déjà essayée : " + c); - input.selectAll(); - input.requestFocusInWindow(); - return; - } - - tried.add(c); - boolean hit = false; - for (int i = 0; i < secretWord.length(); i++) { - if (Character.toLowerCase(secretWord.charAt(i)) == c) { - found.add(c); - hit = true; - } - } - if (!hit) { - errors++; - infoLbl.setText("Mauvaise lettre : " + c); - } else { - infoLbl.setText("Bonne lettre : " + c); - } - - updateUIState(); - input.selectAll(); - input.requestFocusInWindow(); - } - - /** Refresh labels/drawing and handle end-of-game. */ - private void updateUIState() { - wordLbl.setText(maskWord(secretWord, found)); - triedLbl.setText("Lettres essayées : " + joinChars(tried)); - hangPanel.setErrors(errors); - - if (isWin(secretWord, found)) { - infoLbl.setText("Bravo ! Vous avez trouvé le mot : " + secretWord); - wordLbl.setText(spaced(secretWord)); // pretty display of the word - gameOver = true; - disableInput(); - } else if (errors >= MAX_ERRORS) { - infoLbl.setText("Perdu ! Le mot était : " + secretWord); - wordLbl.setText(spaced(secretWord)); - gameOver = true; - disableInput(); - } - - // force UI refresh - revalidate(); - repaint(); - } - - /** Disable controls after the game ends. */ - private void disableInput() { - input.setEditable(false); - guessBtn.setEnabled(false); - } - - /** Pick a random word. */ - private String pickWord() { - Random rnd = new Random(); - return words[rnd.nextInt(words.length)].toLowerCase(Locale.ROOT); - } - - /** Build the masked word based on found letters. */ - private String maskWord(String secret, Set foundSet) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < secret.length(); i++) { - char ch = secret.charAt(i); - char lc = Character.toLowerCase(ch); - if (Character.isLetter(lc) && !foundSet.contains(lc)) sb.append('_'); - else sb.append(ch); - if (i < secret.length() - 1) sb.append(' '); - } - return sb.toString(); - } - - /** True if all letters have been found. */ - private boolean isWin(String secret, Set foundSet) { - for (int i = 0; i < secret.length(); i++) { - char lc = Character.toLowerCase(secret.charAt(i)); - if (Character.isLetter(lc) && !foundSet.contains(lc)) return false; - } - return true; - } - - /** Sort and join letters for display. */ - private String joinChars(Set set) { - java.util.List list = new ArrayList<>(set); - Collections.sort(list); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { - sb.append(list.get(i)); - if (i < list.size() - 1) sb.append(' '); - } - return sb.toString(); - } - - /** Add spaces between letters for nicer reading. */ - private String spaced(String s) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < s.length(); i++) { - sb.append(s.charAt(i)); - if (i < s.length() - 1) sb.append(' '); - } - return sb.toString(); - } -} diff --git a/res/mots_pendu.txt b/res/mots_pendu.txt deleted file mode 100644 index b10c068..0000000 --- a/res/mots_pendu.txt +++ /dev/null @@ -1,554 +0,0 @@ -#FACILE -banane -ceinture -maman -jupe -canard -grand -miroir -oiseau -neuf -dos -lune -fruit -lampe -pain -balle -blanc -enfant -mouton -gris -ane -pomme -tete -pigeon -maison -citrouille -arbre -poule -rat -ventre -jour -coq -renard -vache -sel -neige -bureau -poisson -bois -lunette -ami -petit -bouche -court -peigne -nuage -barbe -arbre -sucre -plage -fenetre -os -oreille -feuille -jour -poire -cle -lait -livre -eau -chat -herbe -fraise -route -main -air -tomate -aigle -yeux -raisin -seconde -bus -feu -tante -peau -cheveu -rouge -eau -porte -lapin -cle -jardin -oncle -pied -main -cerise -pied -paon -minute -pluie -robe -champ -ciel -oiseau -nuit -porte -frere -heure -vert -papa -couleur -coeur -noir -mur -mur -chemise -pingouin -lit -doigt -table -carotte -grenouille -orage -bleu -chapeau -bras -gant -plage -voisin -corbeau -mer -amie -chien -fromage -nez -chaud -zebre -femme -train -canari -velo -patate -orange -chaton -sol -serviette -fruit -pantalon -chiot -photo -etoile -souris -salon -fleur -poule -jambe -horloge -nez -manteau -verre -vieux -canard -homme -colombe -chat -montagne -poireau -cheval -ville -vallee -veste -pluie -fleur -neige -jaune -soeur -viande -feuille -oeuf -cravate -soleil -citron -lac -moto -abricot -singe -vent -tigre -rivière -papier -ecole -long -neige -brosse -cochon -rue -terre -riz -pont -porte -vent -toit -rocher -sac -chaussure -robe -salade -dent -crayon -lion -montre -foret -bateau -cuisine -voiture -chien -nuit -poisson -lune -lac -soleil -ours -savon -langue -chaise -froid -melon -clef -terre -voisine -chapeau -#MOYEN -serpent -orage -bracelet -savonnette -broche -parapluie -valise -helicoptere -histoire -coureur -brosse -galaxie -mouchoir -ete -veste -montagne -train -bijou -logiciel -dessin -fichier -fantome -baleine -nuage -foret -station -saladier -montagne -costume -minuteur -chateau -casque -clavier -menuisier -manteau -lezard -vallee -tableau -mystere -chapeau -shampoing -chaussure -port -aeroport -printemps -dauphin -ordinateur -theatre -fourchette -pneu -dentiste -lunette -acteur -salle -serveur -aventure -requin -gel -bague -moteur -rivière -bouteille -uniforme -couloir -batterie -remorque -bureau -station -tempete -arcenciel -tasse -docteur -tortue -vendeur -peintre -verglas -semaine -cravate -telephone -tracteur -montre -miroir -plume -magasin -musicien -plage -pantalon -essence -pingouin -cinema -camion -cascade -coussin -boucle -animal -cuisine -avion -parebrise -mois -acheteur -cabane -jardinier -bouteille -brouillard -porte -saison -toilette -voilier -hiver -bouteille -avion -horloge -glacier -musique -tortue -conducteur -fusée -carrosserie -ceinture -echelle -rideau -chambre -phare -peinture -journee -cactus -baleine -chaussure -voiture -frein -journal -internet -minute -caravane -collier -couteau -automne -lecteur -embrayage -danseur -piano -camionette -serpent -gare -eclair -souris -facteur -armoire -pendentif -boulanger -fenetre -ecran -serviette -bateau -rivière -verre -chanteur -lampe -miroir -assiette -tapis -auteur -couscous -neige -chemise -professeur -volant -concert -autruche -dossier -policier -perroquet -biscuit -seconde -plombier -tonnerre -salon -siege -garage -poesie -#DIFFICILE -adaptation -paradoxe -imaginatif -evaluation -constructif -parabole -contemplation -constellation -geometrie -atomique -transformation -hypotenuse -oxymore -metaphore -mathematique -cryptographie -anthropologie -combustion -stratosphere -chlorophylle -hemisphere -archipel -encyclopedie -biologique -chrysantheme -linguistique -cartographie -thermodynamique -rectangle -destructif -algorithmique -hydraulique -dichotomie -multiplication -conservation -organisation -hippopotame -moleculaire -manipulation -photosynthese -coordination -constitution -consideration -photosensible -radioactif -sphynx -restauration -rhythmique -bibliotheque -administration -neurologie -orthographique -parallaxe -acoustique -informatique -phonetique -conique -univers -entomologie -observation -phonetique -planetaire -cardiologue -onomatopee -labyrinthe -syntaxique -nucleaire -instinctif -representation -contradiction -isoceles -galaxie -antinomie -mythologie -decomposition -polygonal -ornithologie -cylindre -quantique -spherique -physique -subjectif -telepathie -distribution -grammaticale -asteroide -aristocratie -isotherme -comete -subatomique -archaeologie -optique -quadrilatere -technocratie -lexicale -linguistique -equilateral -psychologie -metamorphose -bacteriologie -collaboration -paraphrase -meteorologie -revolutionnaire -astronomie -hexagone -responsabilite -semantique -juridiction -gravitation -physiologie -cosmique -creatif -electrochoc -thermometre -orbite -conjoncture -inspiration -solaire -palindrome -parallelogramme -satellite -pseudonyme -lithographie -introspectif -xylophone -substantif -parlementaire -pragmatique -approximation -objectif -genetique -electronique -productif -interpretation -philosophie -chimique -caracteristique -communication -abstraction -ellipse -totalitaire -independance -pyramide -trapèze -democratie -prisme -extrapolation -economique -nebuleuse -anachronisme \ No newline at end of file diff --git a/src/GestionMotsPendu.class b/src/GestionMotsPendu.class deleted file mode 100644 index 008f719..0000000 Binary files a/src/GestionMotsPendu.class and /dev/null differ diff --git a/src/GestionMotsPendu.java b/src/GestionMotsPendu.java deleted file mode 100644 index d519d74..0000000 --- a/src/GestionMotsPendu.java +++ /dev/null @@ -1,51 +0,0 @@ -import java.io.*; -import java.util.*; - -public class GestionMotsPendu { - - private static final String CHEMIN_FICHIER = "../res/mots_pendu.txt"; - - private final Map> motsParDifficulte = new HashMap<>(); - - public GestionMotsPendu() throws IOException { - motsParDifficulte.put("FACILE", new ArrayList<>()); - motsParDifficulte.put("MOYEN", new ArrayList<>()); - motsParDifficulte.put("DIFFICILE", new ArrayList<>()); - chargerMots(); - } - - private void chargerMots() throws IOException { - try (BufferedReader reader = new BufferedReader(new FileReader(CHEMIN_FICHIER))) { - String ligne; - String section = ""; - while ((ligne = reader.readLine()) != null) { - ligne = ligne.trim(); - if (ligne.startsWith("#")) { - section = ligne.substring(1).toUpperCase(); - } else if (!ligne.isEmpty() && motsParDifficulte.containsKey(section)) { - motsParDifficulte.get(section).add(ligne); - } - } - } catch (FileNotFoundException e) { - throw new IOException("Fichier introuvable : " + CHEMIN_FICHIER); - } - } - - public String getMotAleatoire(int difficulte) { - String cle = convertirDifficulte(difficulte); - List liste = motsParDifficulte.get(cle); - if (liste == null || liste.isEmpty()) return null; - - Random rand = new Random(); - return liste.get(rand.nextInt(liste.size())); - } - - private String convertirDifficulte(int difficulte) { - return switch (difficulte) { - case 1 -> "FACILE"; - case 2 -> "MOYEN"; - case 3 -> "DIFFICILE"; - default -> "FACILE"; // Valeur par défaut - }; - } -} diff --git a/src/TestPendu.class b/src/TestPendu.class deleted file mode 100644 index 321ce8e..0000000 Binary files a/src/TestPendu.class and /dev/null differ diff --git a/src/TestPendu.java b/src/TestPendu.java deleted file mode 100644 index a6d86a6..0000000 --- a/src/TestPendu.java +++ /dev/null @@ -1,65 +0,0 @@ -import java.io.IOException; -import java.util.*; - -public class TestPendu { - public static void main(String[] args) { - try { - Scanner scanner = new Scanner(System.in); - GestionMotsPendu gestion = new GestionMotsPendu(); - - System.out.println("Bienvenue dans le jeu du pendu !"); - System.out.println("Choisissez la difficulté : 1 = Facile, 2 = Moyen, 3 = Difficile"); - int difficulte = scanner.nextInt(); - scanner.nextLine(); // consommer la fin de ligne - - String mot = gestion.getMotAleatoire(difficulte); - if (mot == null) { - System.out.println("Erreur : aucun mot disponible pour cette difficulté."); - return; - } - - char[] motCache = new char[mot.length()]; - Arrays.fill(motCache, '_'); - - Set lettresDevinees = new HashSet<>(); - int erreurs = 0; - int maxErreurs = 6; - - while (erreurs < maxErreurs && new String(motCache).contains("_")) { - System.out.println("\nMot : " + new String(motCache)); - System.out.println("Erreurs : " + erreurs + "/" + maxErreurs); - System.out.print("Devinez une lettre : "); - String input = scanner.nextLine().toLowerCase(); - if (input.isEmpty()) continue; - - char lettre = input.charAt(0); - if (lettresDevinees.contains(lettre)) { - System.out.println("Vous avez déjà essayé cette lettre !"); - continue; - } - - lettresDevinees.add(lettre); - if (mot.indexOf(lettre) >= 0) { - for (int i = 0; i < mot.length(); i++) { - if (mot.charAt(i) == lettre) motCache[i] = lettre; - } - System.out.println("Bien joué !"); - } else { - erreurs++; - System.out.println("Raté !"); - } - } - - if (new String(motCache).equals(mot)) { - System.out.println("\nFélicitations ! Vous avez trouvé le mot : " + mot); - } else { - System.out.println("\nVous avez perdu ! Le mot était : " + mot); - } - - scanner.close(); - - } catch (IOException e) { - System.err.println("Erreur lors du chargement des mots : " + e.getMessage()); - } - } -} diff --git a/src/WordManager.java b/src/WordManager.java index b42ca01..5548572 100644 --- a/src/WordManager.java +++ b/src/WordManager.java @@ -3,36 +3,41 @@ import java.util.*; public class WordManager { - private static final String FILE_PATH = "../res/hangman_words.txt"; + // --- Constant: path to word file --- + private static final String WORD_FILE = "../res/hangman_words.txt"; + // --- Map to store words by difficulty --- private final Map> wordsByDifficulty = new HashMap<>(); + // --- Constructor --- public WordManager() throws IOException { wordsByDifficulty.put("EASY", new ArrayList<>()); wordsByDifficulty.put("MEDIUM", new ArrayList<>()); wordsByDifficulty.put("HARD", new ArrayList<>()); - loadWords(); + loadWords(); // automatically load words when created } + // --- Load words from the file --- private void loadWords() throws IOException { - try (BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) { + try (BufferedReader reader = new BufferedReader(new FileReader(WORD_FILE))) { String line; String section = ""; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("#")) { - section = line.substring(1).toUpperCase(); + section = line.substring(1).toUpperCase(); // read difficulty section } else if (!line.isEmpty() && wordsByDifficulty.containsKey(section)) { - wordsByDifficulty.get(section).add(line.toLowerCase()); // make all words lowercase + wordsByDifficulty.get(section).add(line); } } } catch (FileNotFoundException e) { - throw new IOException("File not found: " + FILE_PATH); + throw new IOException("File not found: " + WORD_FILE); } } + // --- Get a random word based on difficulty (1 = Easy, 2 = Medium, 3 = Hard) --- public String getRandomWord(int difficulty) { - String key = mapDifficulty(difficulty); + String key = difficultyToKey(difficulty); List list = wordsByDifficulty.get(key); if (list == null || list.isEmpty()) return null; @@ -40,12 +45,13 @@ public class WordManager { return list.get(rand.nextInt(list.size())); } - private String mapDifficulty(int difficulty) { + // --- Convert int to difficulty key --- + private String difficultyToKey(int difficulty) { return switch (difficulty) { case 1 -> "EASY"; case 2 -> "MEDIUM"; case 3 -> "HARD"; - default -> "EASY"; // Default value + default -> "EASY"; // default difficulty }; } -} +} \ No newline at end of file