From 90645b7673f7bb1f17339bd8fbe5a05d08eb6585 Mon Sep 17 00:00:00 2001 From: gentil Date: Wed, 8 Oct 2025 11:19:33 +0200 Subject: [PATCH 1/9] =?UTF-8?q?chore:=20dico=20de=20750=20mots=20avec=203?= =?UTF-8?q?=20difficult=C3=A9s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- res/mots_pendu.txt | 554 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 554 insertions(+) create mode 100644 res/mots_pendu.txt diff --git a/res/mots_pendu.txt b/res/mots_pendu.txt new file mode 100644 index 0000000..b10c068 --- /dev/null +++ b/res/mots_pendu.txt @@ -0,0 +1,554 @@ +#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 From baab5c7ce2d11e9d2607a504aaf2d7b94eac2863 Mon Sep 17 00:00:00 2001 From: gentil Date: Wed, 8 Oct 2025 11:20:24 +0200 Subject: [PATCH 2/9] =?UTF-8?q?feat:=20jeu=20mvp=20fonctionnel=20avec=20di?= =?UTF-8?q?fficult=C3=A9s=20et=20compteur=20erreurs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/GestionMotsPendu.class | Bin 0 -> 2265 bytes src/GestionMotsPendu.java | 51 +++++++++++++++++++++++++++++ src/TestPendu.class | Bin 0 -> 2851 bytes src/TestPendu.java | 65 +++++++++++++++++++++++++++++++++++++ 4 files changed, 116 insertions(+) create mode 100644 src/GestionMotsPendu.class create mode 100644 src/GestionMotsPendu.java create mode 100644 src/TestPendu.class create mode 100644 src/TestPendu.java diff --git a/src/GestionMotsPendu.class b/src/GestionMotsPendu.class new file mode 100644 index 0000000000000000000000000000000000000000..008f71951657226bcf986c183789fe56bdab814b GIT binary patch literal 2265 zcmX^0Z`VEs1_oP(RxSo624;2!79Ivx1~x_pfvm)`ME#t^ymWp4q^#8B5=I6#o6Nk- z5<5l)W)00Sb_Nbc20^f*(vr*^eUHTA4Bx~8E(Uf6W=;lf1|D_>ULFQM27X2c0r%A6 zlFa-(-~5u|fYiK{Qbq>BTo604$R#r^Ei<_^rzDk;f!_yVnr~u(H3x$rBLkb8qqC=v zD?5WQBZDwP-m$1CvC=2AxP*&Ah=G}#L5xA1ok4H>F8~FVUP(m>7lR6eCMa687#T#7eGyzzl$n=qtr^C}pv0g9QlZPpAPiNJ znXeBq*;+GfdQn-kcYvD!I+VOqbM~o#V0c_m61V21KHD1Gr1T{8O+!j%y}3r zK+2I)14IEM14~I!W-bSV6(a+qGDx)z4}&d(9U}u*aY$tapz(1VDMyQV9zXe%`GUY z1gFg?PuEct!@^#FUia(t?7b)Z*gQ6h;OKWEa78Sc5WR zA|rz=*bSNa`k(~mmtW$RUz(TVT9KSu0Lpmm49PGHGxPO5{oxWE45^F^+HRT28JVd? z3YmE&Mfs&=AeSguDd0$oNer5xWS_yqkO_)D;pF_hvecrIOr)#~3ITU^h8$QS0uGv> z#JrUJTrP%eP<9Ps$md}wU?^l{U@6Y5N(IN7CrGZChoOX_l#ziwFSVk?Gp~e^fknep z(-UN3IVgfEKv9U2NT4yn$iV09;p*$@7w_ij?BVGe#K<6o6xEPKYt6{O>ztogT#}eq z5|)@#n##z)8JwA(msnC-l*-894$%O1u5V(24TKAhBB*|d2v`9qsWZ-6CVqjokVvu5}WT;|bWT*!7)EI<7#V-RRLk*Z; z%fQ0G2rAndm>B997#JXY1_ocP?F@`syBXLcw=-~VW#H16gMpucn?Z?zhryJAm%)R9kHLq5 zpP_+)0qme81}0De3UL&p2?Hww3j+f~$8H9t$lVMokwR+Q88o&tX!{81`Dt%sFo^U$ z#^9l|jlslMN62y;gY`@XejS!=4EEa?oc)&nf1tCC!EM(6n;-}4?qu*{Vwm~=43y)? z#BhKiNM|QQ2opp2^8Z`4w=sk-XAt&<(42lcy4x6HboMW2;PctdkQ6DDvYjDq|3(I8 z20?}-hD?SihAf6WhC+rY1_p*oh8l(h1}3mStr++i7#M^Y1Q|paL>NRFWEsR5lo-Sr zv>7BA%o!vZycwhzk{DzeG8u#zDjDP%Y8Yf0Y8m7h+8GoW8W|WEoESL&F^I4;C^4`z znEq!_Vqjrs;AUq~VrMXAXE0@8_{pH<#?BD+A5^cxWTF@t*%_i(e=;ySu`?uaA%!I) zLlc7&10y(ss~MOXSQ!`?9JQpkF{Jx~fKXhh#B;_zVns(yJIiKnt8m7#Nrt7#O4(7#I{77#LKA1eP=K z3rR0$;1ZHu&cG@pfUs4HfsKKIL5D$xL6> 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 new file mode 100644 index 0000000000000000000000000000000000000000..321ce8ea0d12ee921be95a91be206ac3a87bc21a GIT binary patch literal 2851 zcmX^0Z`VEs1_oP(HCzl#49x5dEIbUX3~Y=H0$GV=iTXK-dFlH8Nm;4MC5#MgHko;u zC3cJq%o>_u>W`3S; zeo1jaYFYt1kY1|>!Y2j`6Z%;L=A;?ydIoJ56`%(S%3{QR10b0*(exkcI(BLfFW#wRl`m61V2LlY8w$gTl}kq!@oE`uH;1AlsIiEn<1V@_&fNq%NgDkFoa zh9?$191I4G45qF{MX9Al3RVh z)8k?=VlZZBFyUb^1-Tn3K|w-?k%28IH7~s+gNwnO!GfK^l83>H!5Wrkz=_JSs3@_r zn2~`cEi)&Fk%3Jk+SwVD0&G!|o=0MFMsR8g7lRE0Gssd0P!e)vWMI{Zb_T_OGb00I zJV?Tohrx}(osoefIX|x?F*C22kwF?c)|@jEi-J=NOH=cbQ>`_lgcukYJb4(r7`z!7 z#B&p~Q=Rkkk`qh9GfOg@^Ye;J67x!m85z`&O@R2!8cRS5F)%Xtf(-LxWDwKv#2(fG zj0~bKsb!gYsZ|Q4d8rCHsU;;vsR~vKptKmo!w?Kgh^*iw2l7uS4?`Fz;<-!mee%mw zi<}dSQ$gYpJPeTxQH%`inZ>TT1tpc>q!I;^iQ!?0Wr$;BU`x(OEOIPiWMI+o)O6-z zNMJ~0XGr2zCtP-a99DM+DWtr^9^kj==T9+qEPtdLliTBVS3cxBe%1q!Lf#fg=N zS3=VjG$0f~Hsta!<|+@#c^ki?{%R7M7t+(b|@DW(yP znT<8W7#VnjOA?c_eG?17>e(44Ffs^ZQOeFRiIIUR+L@7oD>%QjC^^+F6J$Cc+zEQ1 zC}Ly~aLUgwDK05WEbvV&$;eMB=4WG=&c!f;VJ17nEKs7I&B&kvQVOXMGV{vvvs3jU zi5-$D+!B*Z@{1}N8D=0yGE^bNP>;mCl$_LJ6`%b4?9u{jOphUnplA%KEJ($o9NE9H z)P!k-b7D?TaArxWH3!37Mg|Tp-~18ds-URglL{^+53ejq z%!FFFl#xLVVxdA#eo--~rUB)`^wiwcyb^_!)MAhhuv-`zcsxOssdG+ZadB!fJHrY_ z233sU#}=yW467I!)JvfCK6tym;kjx+FpWc9Z(NN<#6*~VbF zht-Nzl2ssn2ZPye2Ajz340cv*%x3HYY-Svy?4lft7*6kIFp899-OgYyE-{s;4(Q(4B?V2qFmb;@@F%cFq?6Ua)TYch(Sh@ zMU;CRL$oN@0tPNgR#9$IuFw{4#^wJXfXpcdnZv->!p;cdm4bNxP2g?@8BsoyL3k5` zs3glShAOa&moo@J`PE>)_BMu^vF)%PhGVuLpaAII(XXs~VU}t9#Vq|A9Vqo~sAkV;w zBF4@zk)0upk&%Jn4?`F`gV7%bMaDl2l8iFH7+AS}GH@{|@caiQRd$Ac21a& 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()); + } + } +} From 15061d6afd3d3333f1bcff4581687fbe371ca7c1 Mon Sep 17 00:00:00 2001 From: akagunduz Date: Wed, 8 Oct 2025 12:17:50 +0200 Subject: [PATCH 3/9] bamba chameau --- HangmanGUI.java | 273 ++++++++++++++++++++++++++++++++++++++++++++++++ Jeu.java | 165 +++++++++++++++++++++++++++++ 2 files changed, 438 insertions(+) create mode 100644 HangmanGUI.java create mode 100644 Jeu.java diff --git a/HangmanGUI.java b/HangmanGUI.java new file mode 100644 index 0000000..7199b26 --- /dev/null +++ b/HangmanGUI.java @@ -0,0 +1,273 @@ +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.util.*; + +/** + * Interface graphique du jeu du Pendu. + * Noms de variables/fonctions en anglais (exigence), + * affichages et commentaires en français. + */ +public class HangmanGUI extends JFrame { + // --- Données du jeu --- + 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 étapes : base, poteau, poutre, corde, tête, corps, bras, jambes + private boolean gameOver = false; // indique si la partie est terminée + + // --- Éléments UI --- + 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(); + + /** Panneau de dessin du pendu, progressif selon le nombre d'erreurs. */ + 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; // niveau du sol + + // 1) base + if (errors >= 1) gg.drawLine(50, baseY, w - 50, baseY); + + // 2) poteau vertical + if (errors >= 2) gg.drawLine(100, baseY, 100, 60); + + // 3) poutre horizontale + if (errors >= 3) gg.drawLine(100, 60, 220, 60); + + // 4) corde + if (errors >= 4) gg.drawLine(220, 60, 220, 90); + + // 5) tête + if (errors >= 5) gg.drawOval(200, 90, 40, 40); + + // 6) corps + if (errors >= 6) gg.drawLine(220, 130, 220, 200); + + // 7) bras + if (errors >= 7) { + gg.drawLine(220, 145, 190, 165); // bras gauche + gg.drawLine(220, 145, 250, 165); // bras droit + } + + // 8) jambes + if (errors >= 8) { + gg.drawLine(220, 200, 200, 240); // jambe gauche + gg.drawLine(220, 200, 240, 240); // jambe droite + } + } + } + + /** Point d'entrée : crée et affiche la fenêtre du jeu. */ + public static void main(String[] args) { + SwingUtilities.invokeLater(() -> { + HangmanGUI app = new HangmanGUI(); + app.setVisible(true); + }); + } + + /** Constructeur : configure la fenêtre, l'UI et lance la partie. */ + public HangmanGUI() { + super("Jeu du Pendu"); + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + setSize(520, 520); + setLocationRelativeTo(null); + setupUI(); + startGame(); + } + + /** Prépare la mise en page et les actions de l'interface. */ + 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); + + // Actions + guessBtn.addActionListener(e -> onGuess()); + input.addActionListener(e -> onGuess()); // touche Entrée + addWindowListener(new WindowAdapter() { + @Override public void windowOpened(WindowEvent e) { input.requestFocusInWindow(); } + }); + } + + /** Démarre une partie (unique). */ + 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(); + } + + /** Traite une proposition : valide, met à jour et vérifie fin de partie. */ + private void onGuess() { + if (gameOver) return; // bloque toute saisie après fin + + 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(); + } + + /** Met à jour les libellés, le dessin, et gère la fin de partie. */ + 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)); // affichage propre du mot + gameOver = true; + disableInput(); + } else if (errors >= MAX_ERRORS) { + infoLbl.setText("Perdu ! Le mot était : " + secretWord); + wordLbl.setText(spaced(secretWord)); + gameOver = true; + disableInput(); + } + + // force le rafraîchissement de l'interface + revalidate(); + repaint(); + } + + /** Désactive les contrôles après la fin du jeu. */ + private void disableInput() { + input.setEditable(false); + guessBtn.setEnabled(false); + } + + /** Sélectionne un mot aléatoire. */ + private String pickWord() { + Random rnd = new Random(); + return words[rnd.nextInt(words.length)].toLowerCase(Locale.ROOT); + } + + /** Construit le mot masqué selon les lettres trouvées. */ + 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(); + } + + /** Vrai si toutes les lettres du mot ont été trouvées. */ + 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; + } + + /** Trie et joint les lettres pour affichage. */ + 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(); + } + + /** Ajoute des espaces entre les lettres pour une lecture plus claire. */ + 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/Jeu.java b/Jeu.java new file mode 100644 index 0000000..6929a2c --- /dev/null +++ b/Jeu.java @@ -0,0 +1,165 @@ +import java.util.Random; +import java.util.Set; +import java.util.HashSet; +import java.util.Locale; +import java.util.Scanner; + +public class Jeu { + // liste des etats a afficher + private static final String[] stages = new String[] { + "=========\n", + " |\n" + + " |\n" + + " |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " |\n" + + " |\n" + + " |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " |\n" + + " |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " O |\n" + + " |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " O |\n" + + " | |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " O |\n" + + " /|\\ |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " O |\n" + + " /|\\ |\n" + + " / \\ |\n" + + " |\n" + + "=========\n" + }; + + // fonction pour masquer le mot generer aleatoirement + static String maskWord(String secretWord, Set foundLetters) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < secretWord.length(); i++) { + char original = secretWord.charAt(i); + char c = Character.toLowerCase(original); + + if (!Character.isLetter(c)) { + sb.append(original); + } else if (foundLetters.contains(c)) { + sb.append(original); + } else { + sb.append('_'); + } + if (i < secretWord.length() - 1) sb.append(' '); + } + return sb.toString(); + } + + // fonction qui permet d'afficher les etats du pendu + static void drawHangman(int errors) { + int idx = Math.min(Math.max(errors, 0), stages.length - 1); + System.out.println(stages[idx]); + } + + // fonction qui permet de savoir si la partie est gagnee + static boolean isWin(String secretWord, Set foundLetters) { + for (int i = 0; i < secretWord.length(); i++) { + char c = Character.toLowerCase(secretWord.charAt(i)); + if (Character.isLetter(c) && !foundLetters.contains(c)) return false; + } + return true; + } + + public static void main(String[] args) { + String[] words = { + "ordinateur", "voiture", "maison", "soleil", "lumiere", + "fromage", "chocolat", "montagne", "rivière", "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" + }; + + Random random = new Random(); + String secretWord = words[random.nextInt(words.length)]; + + Set foundLetters = new HashSet<>(); + Set triedLetters = new HashSet<>(); + int errors = 0; + int maxErrors = stages.length - 1; + + Scanner scanner = new Scanner(System.in); + System.out.println("=== Jeu du Pendu ==="); + + while (true) { + drawHangman(errors); + System.out.println("Mot: " + maskWord(secretWord, foundLetters)); + System.out.println("Lettres essayées : " + triedLetters); + System.out.println("Erreurs : " + errors + "/" + maxErrors); + System.out.print("Propose une lettre: "); + + String input = scanner.nextLine().trim().toLowerCase(Locale.ROOT); + if (input.length() != 1 || !Character.isLetter(input.charAt(0))) { + System.out.println("Entrez une seule lettre."); + continue; + } + char letter = input.charAt(0); + if (triedLetters.contains(letter)) { + System.out.println("Déjà essayé."); + continue; + } + triedLetters.add(letter); + + boolean hit = false; + for (int i = 0; i < secretWord.length(); i++) { + if (Character.toLowerCase(secretWord.charAt(i)) == letter) { + foundLetters.add(letter); + hit = true; + } + } + if (!hit) { + errors++; + System.out.println("Mauvaise lettre."); + } else { + System.out.println("Bonne lettre !"); + } + + if (isWin(secretWord, foundLetters)) { + System.out.println("\nTu as trouvé " + secretWord); + drawHangman(errors); + break; + } + if (errors >= maxErrors) { + drawHangman(errors); + System.out.println("\nPerdu ! Le mot était " + secretWord); + break; + } + } + + scanner.close(); + } +} From d52b072c9280f8d93a46c585003f1f84490ef7ac Mon Sep 17 00:00:00 2001 From: akagunduz Date: Wed, 8 Oct 2025 14:33:48 +0200 Subject: [PATCH 4/9] chameauuuuuu --- Game.java | 172 ++++++++++++++++++++++++++++++++++++++++++++++++ HangmanGUI.java | 66 ++++++++----------- 2 files changed, 200 insertions(+), 38 deletions(-) create mode 100644 Game.java diff --git a/Game.java b/Game.java new file mode 100644 index 0000000..e9bfd29 --- /dev/null +++ b/Game.java @@ -0,0 +1,172 @@ +import java.util.Random; +import java.util.Set; +import java.util.HashSet; +import java.util.Locale; +import java.util.Scanner; + +/** + * Hangman console version. + * Code, variables and comments in English. + * Displayed text remains in French. + */ +public class Game { + + // Hangman visual stages + private static final String[] stages = new String[] { + "=========\n", + " |\n" + + " |\n" + + " |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " |\n" + + " |\n" + + " |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " |\n" + + " |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " O |\n" + + " |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " O |\n" + + " | |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " O |\n" + + " /|\\ |\n" + + " |\n" + + " |\n" + + "=========\n", + " +---+\n" + + " | |\n" + + " O |\n" + + " /|\\ |\n" + + " / \\ |\n" + + " |\n" + + "=========\n" + }; + + /** Build the masked word using found letters. */ + static String maskWord(String secretWord, Set foundLetters) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < secretWord.length(); i++) { + char original = secretWord.charAt(i); + char c = Character.toLowerCase(original); + + if (!Character.isLetter(c)) { + sb.append(original); + } else if (foundLetters.contains(c)) { + sb.append(original); + } else { + sb.append('_'); + } + if (i < secretWord.length() - 1) sb.append(' '); + } + return sb.toString(); + } + + /** Display the current hangman stage based on errors. */ + static void drawHangman(int errors) { + int idx = Math.min(Math.max(errors, 0), stages.length - 1); + System.out.println(stages[idx]); + } + + /** Check if all letters of the word have been found. */ + static boolean isWin(String secretWord, Set foundLetters) { + for (int i = 0; i < secretWord.length(); i++) { + char c = Character.toLowerCase(secretWord.charAt(i)); + if (Character.isLetter(c) && !foundLetters.contains(c)) return false; + } + return true; + } + + public static void main(String[] args) { + 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" + }; + + Random random = new Random(); + String secretWord = words[random.nextInt(words.length)]; + + Set foundLetters = new HashSet<>(); + Set triedLetters = new HashSet<>(); + int errors = 0; + int maxErrors = stages.length - 1; + + Scanner scanner = new Scanner(System.in); + System.out.println("=== Game du Pendu ==="); + + while (true) { + drawHangman(errors); + System.out.println("Mot: " + maskWord(secretWord, foundLetters)); + System.out.println("Lettres essayées : " + triedLetters); + System.out.println("Erreurs : " + errors + "/" + maxErrors); + System.out.print("Propose une lettre: "); + + String input = scanner.nextLine().trim().toLowerCase(Locale.ROOT); + if (input.length() != 1 || !Character.isLetter(input.charAt(0))) { + System.out.println("Entrez une seule lettre."); + continue; + } + char letter = input.charAt(0); + if (triedLetters.contains(letter)) { + System.out.println("Déjà essayé."); + continue; + } + triedLetters.add(letter); + + boolean hit = false; + for (int i = 0; i < secretWord.length(); i++) { + if (Character.toLowerCase(secretWord.charAt(i)) == letter) { + foundLetters.add(letter); + hit = true; + } + } + + if (!hit) { + errors++; + System.out.println("Mauvaise lettre."); + } else { + System.out.println("Bonne lettre !"); + } + + if (isWin(secretWord, foundLetters)) { + System.out.println("\nTu as trouvé " + secretWord); + drawHangman(errors); + break; + } + if (errors >= maxErrors) { + drawHangman(errors); + System.out.println("\nPerdu ! Le mot était " + secretWord); + break; + } + } + + scanner.close(); + } +} diff --git a/HangmanGUI.java b/HangmanGUI.java index 7199b26..0a1bc9e 100644 --- a/HangmanGUI.java +++ b/HangmanGUI.java @@ -4,12 +4,11 @@ import java.awt.event.*; import java.util.*; /** - * Interface graphique du jeu du Pendu. - * Noms de variables/fonctions en anglais (exigence), - * affichages et commentaires en français. + * Hangman game GUI. + * Variables/methods and comments in English. + * User-facing texts remain in French. */ public class HangmanGUI extends JFrame { - // --- Données du jeu --- private final String[] words = { "ordinateur","voiture","maison","soleil","lumiere", "fromage","chocolat","montagne","riviere","plage", @@ -20,14 +19,14 @@ public class HangmanGUI extends JFrame { "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 étapes : base, poteau, poutre, corde, tête, corps, bras, jambes - private boolean gameOver = false; // indique si la partie est terminée + 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 - // --- Éléments UI --- 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); @@ -35,7 +34,7 @@ public class HangmanGUI extends JFrame { private final JButton guessBtn = new JButton("Proposer"); private final HangPanel hangPanel = new HangPanel(); - /** Panneau de dessin du pendu, progressif selon le nombre d'erreurs. */ + /** Drawing panel for the hangman, progressive according to error count. */ private static class HangPanel extends JPanel { private int errors = 0; @@ -51,41 +50,33 @@ public class HangmanGUI extends JFrame { gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int w = getWidth(), h = getHeight(); - int baseY = h - 40; // niveau du sol + int baseY = h - 40; // ground level - // 1) base if (errors >= 1) gg.drawLine(50, baseY, w - 50, baseY); - // 2) poteau vertical if (errors >= 2) gg.drawLine(100, baseY, 100, 60); - // 3) poutre horizontale if (errors >= 3) gg.drawLine(100, 60, 220, 60); - // 4) corde if (errors >= 4) gg.drawLine(220, 60, 220, 90); - // 5) tête if (errors >= 5) gg.drawOval(200, 90, 40, 40); - // 6) corps if (errors >= 6) gg.drawLine(220, 130, 220, 200); - // 7) bras if (errors >= 7) { - gg.drawLine(220, 145, 190, 165); // bras gauche - gg.drawLine(220, 145, 250, 165); // bras droit + gg.drawLine(220, 145, 190, 165); + gg.drawLine(220, 145, 250, 165); } - // 8) jambes if (errors >= 8) { - gg.drawLine(220, 200, 200, 240); // jambe gauche - gg.drawLine(220, 200, 240, 240); // jambe droite + gg.drawLine(220, 200, 200, 240); + gg.drawLine(220, 200, 240, 240); } } } - /** Point d'entrée : crée et affiche la fenêtre du jeu. */ + /** Entry point: create and show the game window. */ public static void main(String[] args) { SwingUtilities.invokeLater(() -> { HangmanGUI app = new HangmanGUI(); @@ -93,7 +84,7 @@ public class HangmanGUI extends JFrame { }); } - /** Constructeur : configure la fenêtre, l'UI et lance la partie. */ + /** Constructor: window setup, UI setup, and start the game. */ public HangmanGUI() { super("Jeu du Pendu"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); @@ -103,7 +94,7 @@ public class HangmanGUI extends JFrame { startGame(); } - /** Prépare la mise en page et les actions de l'interface. */ + /** 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)); @@ -130,15 +121,14 @@ public class HangmanGUI extends JFrame { setContentPane(main); - // Actions guessBtn.addActionListener(e -> onGuess()); - input.addActionListener(e -> onGuess()); // touche Entrée + input.addActionListener(e -> onGuess()); addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { input.requestFocusInWindow(); } }); } - /** Démarre une partie (unique). */ + /** Start a game. */ private void startGame() { secretWord = pickWord(); found.clear(); @@ -153,9 +143,9 @@ public class HangmanGUI extends JFrame { updateUIState(); } - /** Traite une proposition : valide, met à jour et vérifie fin de partie. */ + /** Handle a guess: validate input, update state, check for end of game. */ private void onGuess() { - if (gameOver) return; // bloque toute saisie après fin + 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') { @@ -192,7 +182,7 @@ public class HangmanGUI extends JFrame { input.requestFocusInWindow(); } - /** Met à jour les libellés, le dessin, et gère la fin de partie. */ + /** Refresh labels/drawing and handle end-of-game. */ private void updateUIState() { wordLbl.setText(maskWord(secretWord, found)); triedLbl.setText("Lettres essayées : " + joinChars(tried)); @@ -200,7 +190,7 @@ public class HangmanGUI extends JFrame { if (isWin(secretWord, found)) { infoLbl.setText("Bravo ! Vous avez trouvé le mot : " + secretWord); - wordLbl.setText(spaced(secretWord)); // affichage propre du mot + wordLbl.setText(spaced(secretWord)); // pretty display of the word gameOver = true; disableInput(); } else if (errors >= MAX_ERRORS) { @@ -210,24 +200,24 @@ public class HangmanGUI extends JFrame { disableInput(); } - // force le rafraîchissement de l'interface + // force UI refresh revalidate(); repaint(); } - /** Désactive les contrôles après la fin du jeu. */ + /** Disable controls after the game ends. */ private void disableInput() { input.setEditable(false); guessBtn.setEnabled(false); } - /** Sélectionne un mot aléatoire. */ + /** Pick a random word. */ private String pickWord() { Random rnd = new Random(); return words[rnd.nextInt(words.length)].toLowerCase(Locale.ROOT); } - /** Construit le mot masqué selon les lettres trouvées. */ + /** 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++) { @@ -240,7 +230,7 @@ public class HangmanGUI extends JFrame { return sb.toString(); } - /** Vrai si toutes les lettres du mot ont été trouvées. */ + /** 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)); @@ -249,7 +239,7 @@ public class HangmanGUI extends JFrame { return true; } - /** Trie et joint les lettres pour affichage. */ + /** Sort and join letters for display. */ private String joinChars(Set set) { java.util.List list = new ArrayList<>(set); Collections.sort(list); @@ -261,7 +251,7 @@ public class HangmanGUI extends JFrame { return sb.toString(); } - /** Ajoute des espaces entre les lettres pour une lecture plus claire. */ + /** Add spaces between letters for nicer reading. */ private String spaced(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { From 3af3ed9e8af484951d99088a439ca587883921b0 Mon Sep 17 00:00:00 2001 From: akagunduz Date: Wed, 8 Oct 2025 14:37:25 +0200 Subject: [PATCH 5/9] maj --- Game.java | 172 ------------------------------------------------------ Jeu.java | 165 --------------------------------------------------- 2 files changed, 337 deletions(-) delete mode 100644 Game.java delete mode 100644 Jeu.java diff --git a/Game.java b/Game.java deleted file mode 100644 index e9bfd29..0000000 --- a/Game.java +++ /dev/null @@ -1,172 +0,0 @@ -import java.util.Random; -import java.util.Set; -import java.util.HashSet; -import java.util.Locale; -import java.util.Scanner; - -/** - * Hangman console version. - * Code, variables and comments in English. - * Displayed text remains in French. - */ -public class Game { - - // Hangman visual stages - private static final String[] stages = new String[] { - "=========\n", - " |\n" + - " |\n" + - " |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " |\n" + - " |\n" + - " |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " |\n" + - " |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " O |\n" + - " |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " O |\n" + - " | |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " O |\n" + - " /|\\ |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " O |\n" + - " /|\\ |\n" + - " / \\ |\n" + - " |\n" + - "=========\n" - }; - - /** Build the masked word using found letters. */ - static String maskWord(String secretWord, Set foundLetters) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < secretWord.length(); i++) { - char original = secretWord.charAt(i); - char c = Character.toLowerCase(original); - - if (!Character.isLetter(c)) { - sb.append(original); - } else if (foundLetters.contains(c)) { - sb.append(original); - } else { - sb.append('_'); - } - if (i < secretWord.length() - 1) sb.append(' '); - } - return sb.toString(); - } - - /** Display the current hangman stage based on errors. */ - static void drawHangman(int errors) { - int idx = Math.min(Math.max(errors, 0), stages.length - 1); - System.out.println(stages[idx]); - } - - /** Check if all letters of the word have been found. */ - static boolean isWin(String secretWord, Set foundLetters) { - for (int i = 0; i < secretWord.length(); i++) { - char c = Character.toLowerCase(secretWord.charAt(i)); - if (Character.isLetter(c) && !foundLetters.contains(c)) return false; - } - return true; - } - - public static void main(String[] args) { - 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" - }; - - Random random = new Random(); - String secretWord = words[random.nextInt(words.length)]; - - Set foundLetters = new HashSet<>(); - Set triedLetters = new HashSet<>(); - int errors = 0; - int maxErrors = stages.length - 1; - - Scanner scanner = new Scanner(System.in); - System.out.println("=== Game du Pendu ==="); - - while (true) { - drawHangman(errors); - System.out.println("Mot: " + maskWord(secretWord, foundLetters)); - System.out.println("Lettres essayées : " + triedLetters); - System.out.println("Erreurs : " + errors + "/" + maxErrors); - System.out.print("Propose une lettre: "); - - String input = scanner.nextLine().trim().toLowerCase(Locale.ROOT); - if (input.length() != 1 || !Character.isLetter(input.charAt(0))) { - System.out.println("Entrez une seule lettre."); - continue; - } - char letter = input.charAt(0); - if (triedLetters.contains(letter)) { - System.out.println("Déjà essayé."); - continue; - } - triedLetters.add(letter); - - boolean hit = false; - for (int i = 0; i < secretWord.length(); i++) { - if (Character.toLowerCase(secretWord.charAt(i)) == letter) { - foundLetters.add(letter); - hit = true; - } - } - - if (!hit) { - errors++; - System.out.println("Mauvaise lettre."); - } else { - System.out.println("Bonne lettre !"); - } - - if (isWin(secretWord, foundLetters)) { - System.out.println("\nTu as trouvé " + secretWord); - drawHangman(errors); - break; - } - if (errors >= maxErrors) { - drawHangman(errors); - System.out.println("\nPerdu ! Le mot était " + secretWord); - break; - } - } - - scanner.close(); - } -} diff --git a/Jeu.java b/Jeu.java deleted file mode 100644 index 6929a2c..0000000 --- a/Jeu.java +++ /dev/null @@ -1,165 +0,0 @@ -import java.util.Random; -import java.util.Set; -import java.util.HashSet; -import java.util.Locale; -import java.util.Scanner; - -public class Jeu { - // liste des etats a afficher - private static final String[] stages = new String[] { - "=========\n", - " |\n" + - " |\n" + - " |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " |\n" + - " |\n" + - " |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " |\n" + - " |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " O |\n" + - " |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " O |\n" + - " | |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " O |\n" + - " /|\\ |\n" + - " |\n" + - " |\n" + - "=========\n", - " +---+\n" + - " | |\n" + - " O |\n" + - " /|\\ |\n" + - " / \\ |\n" + - " |\n" + - "=========\n" - }; - - // fonction pour masquer le mot generer aleatoirement - static String maskWord(String secretWord, Set foundLetters) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < secretWord.length(); i++) { - char original = secretWord.charAt(i); - char c = Character.toLowerCase(original); - - if (!Character.isLetter(c)) { - sb.append(original); - } else if (foundLetters.contains(c)) { - sb.append(original); - } else { - sb.append('_'); - } - if (i < secretWord.length() - 1) sb.append(' '); - } - return sb.toString(); - } - - // fonction qui permet d'afficher les etats du pendu - static void drawHangman(int errors) { - int idx = Math.min(Math.max(errors, 0), stages.length - 1); - System.out.println(stages[idx]); - } - - // fonction qui permet de savoir si la partie est gagnee - static boolean isWin(String secretWord, Set foundLetters) { - for (int i = 0; i < secretWord.length(); i++) { - char c = Character.toLowerCase(secretWord.charAt(i)); - if (Character.isLetter(c) && !foundLetters.contains(c)) return false; - } - return true; - } - - public static void main(String[] args) { - String[] words = { - "ordinateur", "voiture", "maison", "soleil", "lumiere", - "fromage", "chocolat", "montagne", "rivière", "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" - }; - - Random random = new Random(); - String secretWord = words[random.nextInt(words.length)]; - - Set foundLetters = new HashSet<>(); - Set triedLetters = new HashSet<>(); - int errors = 0; - int maxErrors = stages.length - 1; - - Scanner scanner = new Scanner(System.in); - System.out.println("=== Jeu du Pendu ==="); - - while (true) { - drawHangman(errors); - System.out.println("Mot: " + maskWord(secretWord, foundLetters)); - System.out.println("Lettres essayées : " + triedLetters); - System.out.println("Erreurs : " + errors + "/" + maxErrors); - System.out.print("Propose une lettre: "); - - String input = scanner.nextLine().trim().toLowerCase(Locale.ROOT); - if (input.length() != 1 || !Character.isLetter(input.charAt(0))) { - System.out.println("Entrez une seule lettre."); - continue; - } - char letter = input.charAt(0); - if (triedLetters.contains(letter)) { - System.out.println("Déjà essayé."); - continue; - } - triedLetters.add(letter); - - boolean hit = false; - for (int i = 0; i < secretWord.length(); i++) { - if (Character.toLowerCase(secretWord.charAt(i)) == letter) { - foundLetters.add(letter); - hit = true; - } - } - if (!hit) { - errors++; - System.out.println("Mauvaise lettre."); - } else { - System.out.println("Bonne lettre !"); - } - - if (isWin(secretWord, foundLetters)) { - System.out.println("\nTu as trouvé " + secretWord); - drawHangman(errors); - break; - } - if (errors >= maxErrors) { - drawHangman(errors); - System.out.println("\nPerdu ! Le mot était " + secretWord); - break; - } - } - - scanner.close(); - } -} From 001cc1d32a59e23287a72c65148caa01a83da6a8 Mon Sep 17 00:00:00 2001 From: gentil Date: Wed, 8 Oct 2025 15:01:05 +0200 Subject: [PATCH 6/9] feat: dictionnaire de mots --- res/hangman_words.txt | 554 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 554 insertions(+) create mode 100644 res/hangman_words.txt diff --git a/res/hangman_words.txt b/res/hangman_words.txt new file mode 100644 index 0000000..2da5687 --- /dev/null +++ b/res/hangman_words.txt @@ -0,0 +1,554 @@ +#EASY +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 +#MEDIUM +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 +#HARD +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 From 3679e1a732e01f1dbf15525c8c0f94ad2dbed7ba Mon Sep 17 00:00:00 2001 From: gentil Date: Wed, 8 Oct 2025 15:02:17 +0200 Subject: [PATCH 7/9] 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 + }; + } +} From c3dc8f73edf9e2ee9db677639cea793405eb84a1 Mon Sep 17 00:00:00 2001 From: gentil Date: Wed, 8 Oct 2025 15:07:21 +0200 Subject: [PATCH 8/9] feat: timer, difficulty and score --- src/HangmanGUI.java | 306 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 306 insertions(+) create mode 100644 src/HangmanGUI.java diff --git a/src/HangmanGUI.java b/src/HangmanGUI.java new file mode 100644 index 0000000..cf452d2 --- /dev/null +++ b/src/HangmanGUI.java @@ -0,0 +1,306 @@ +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.util.*; +import java.util.Timer; +import java.util.TimerTask; + +/** + * Hangman GUI with difficulty selection, dynamic score, and timer. + * Uses WordManager for words. + * User-facing texts remain in French. + */ +public class HangmanGUI extends JFrame { + private WordManager manager; + + 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; + private boolean gameOver = false; + + // scoring and timing + private int baseScore = 200; + private int mistakePenalty = 15; + private double timePenaltyPerSecond = 1.0; + private long startTime; + + // UI components + 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 JLabel scoreLbl = new JLabel("Score: 0", SwingConstants.CENTER); + private final JLabel timerLbl = new JLabel("Temps: 0s", SwingConstants.CENTER); + private final JTextField input = new JTextField(); + private final JButton guessBtn = new JButton("Proposer"); + private final HangPanel hangPanel = new HangPanel(); + + private final String[] difficulties = {"Facile", "Moyen", "Difficile"}; + private final JComboBox difficultyCombo = new JComboBox<>(difficulties); + + private Timer timer; + + /** Drawing panel for hangman */ + 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; + + 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 */ + public static void main(String[] args) { + SwingUtilities.invokeLater(() -> { + try { + HangmanGUI app = new HangmanGUI(); + app.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + + /** Constructor */ + public HangmanGUI() throws Exception { + super("Jeu du Pendu"); + manager = new WordManager(); + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + setSize(560, 620); + setLocationRelativeTo(null); + setupUI(); + startGame(); + } + + /** Setup UI */ + 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)); + scoreLbl.setFont(new Font("SansSerif", Font.BOLD, 16)); + timerLbl.setFont(new Font("SansSerif", Font.BOLD, 16)); + + JPanel top = new JPanel(new GridLayout(6, 1, 8, 8)); + top.add(wordLbl); + top.add(triedLbl); + top.add(infoLbl); + + JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 5)); + scorePanel.add(scoreLbl); + scorePanel.add(timerLbl); + top.add(scorePanel); + + JPanel diffPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); + diffPanel.add(new JLabel("Difficulté:")); + diffPanel.add(difficultyCombo); + top.add(diffPanel); + + JButton restartBtn = new JButton("Rejouer"); + restartBtn.addActionListener(e -> startGame()); + JPanel restartPanel = new JPanel(); + restartPanel.add(restartBtn); + top.add(restartPanel); + + JPanel controls = new JPanel(new BorderLayout(8, 8)); + controls.add(input, BorderLayout.CENTER); + controls.add(guessBtn, BorderLayout.EAST); + + hangPanel.setPreferredSize(new Dimension(500, 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 new game */ + private void startGame() { + int diffIndex = difficultyCombo.getSelectedIndex(); // 0=Facile,1=Moyen,2=Difficile + int diffValue = diffIndex + 1; + secretWord = manager.getRandomWord(diffValue).toLowerCase(Locale.ROOT); + + found.clear(); + tried.clear(); + errors = 0; + gameOver = false; + startTime = System.currentTimeMillis(); + + input.setText(""); + input.setEditable(true); + guessBtn.setEnabled(true); + infoLbl.setText("Entrez une lettre (a-z)"); + updateUIState(); + + if (timer != null) timer.cancel(); + timer = new Timer(true); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + SwingUtilities.invokeLater(() -> { + updateScoreLabel(); + updateTimerLabel(); + }); + } + }, 0, 200); + } + + /** Handle guess */ + private void onGuess() { + if (gameOver) return; + + 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 (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(); + } + + /** Update UI */ + private void updateUIState() { + wordLbl.setText(maskWord(secretWord, found)); + triedLbl.setText("Lettres essayées : " + joinChars(tried)); + hangPanel.setErrors(errors); + updateScoreLabel(); + updateTimerLabel(); + + if (isWin(secretWord, found)) { + infoLbl.setText("Bravo ! Vous avez trouvé le mot : " + secretWord); + wordLbl.setText(spaced(secretWord)); + gameOver = true; + disableInput(); + } else if (errors >= MAX_ERRORS) { + infoLbl.setText("Perdu ! Le mot était : " + secretWord); + wordLbl.setText(spaced(secretWord)); + gameOver = true; + disableInput(); + } + } + + /** Update dynamic score */ + private void updateScoreLabel() { + long elapsedMillis = System.currentTimeMillis() - startTime; + double elapsedSeconds = elapsedMillis / 1000.0; + int score = (int) (baseScore - errors * mistakePenalty - elapsedSeconds * timePenaltyPerSecond); + scoreLbl.setText("Score: " + Math.max(score, 0)); + } + + /** Update dynamic timer */ + private void updateTimerLabel() { + long elapsedMillis = System.currentTimeMillis() - startTime; + int seconds = (int) (elapsedMillis / 1000); + timerLbl.setText("Temps: " + seconds + "s"); + } + + /** Disable input after end */ + private void disableInput() { + input.setEditable(false); + guessBtn.setEnabled(false); + if (timer != null) timer.cancel(); + } + + 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(); + } + + 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; + } + + 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(); + } + + 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(); + } +} From dfa47463b1608bc53e8dabb89f153681e33868a5 Mon Sep 17 00:00:00 2001 From: gentil Date: Wed, 8 Oct 2025 15:15:33 +0200 Subject: [PATCH 9/9] chore: remove unused files --- HangmanGUI.java | 263 ------------------ res/mots_pendu.txt | 554 ------------------------------------- src/GestionMotsPendu.class | Bin 2265 -> 0 bytes src/GestionMotsPendu.java | 51 ---- src/TestPendu.class | Bin 2851 -> 0 bytes src/TestPendu.java | 65 ----- src/WordManager.java | 26 +- 7 files changed, 16 insertions(+), 943 deletions(-) delete mode 100644 HangmanGUI.java delete mode 100644 res/mots_pendu.txt delete mode 100644 src/GestionMotsPendu.class delete mode 100644 src/GestionMotsPendu.java delete mode 100644 src/TestPendu.class delete mode 100644 src/TestPendu.java 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 008f71951657226bcf986c183789fe56bdab814b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2265 zcmX^0Z`VEs1_oP(RxSo624;2!79Ivx1~x_pfvm)`ME#t^ymWp4q^#8B5=I6#o6Nk- z5<5l)W)00Sb_Nbc20^f*(vr*^eUHTA4Bx~8E(Uf6W=;lf1|D_>ULFQM27X2c0r%A6 zlFa-(-~5u|fYiK{Qbq>BTo604$R#r^Ei<_^rzDk;f!_yVnr~u(H3x$rBLkb8qqC=v zD?5WQBZDwP-m$1CvC=2AxP*&Ah=G}#L5xA1ok4H>F8~FVUP(m>7lR6eCMa687#T#7eGyzzl$n=qtr^C}pv0g9QlZPpAPiNJ znXeBq*;+GfdQn-kcYvD!I+VOqbM~o#V0c_m61V21KHD1Gr1T{8O+!j%y}3r zK+2I)14IEM14~I!W-bSV6(a+qGDx)z4}&d(9U}u*aY$tapz(1VDMyQV9zXe%`GUY z1gFg?PuEct!@^#FUia(t?7b)Z*gQ6h;OKWEa78Sc5WR zA|rz=*bSNa`k(~mmtW$RUz(TVT9KSu0Lpmm49PGHGxPO5{oxWE45^F^+HRT28JVd? z3YmE&Mfs&=AeSguDd0$oNer5xWS_yqkO_)D;pF_hvecrIOr)#~3ITU^h8$QS0uGv> z#JrUJTrP%eP<9Ps$md}wU?^l{U@6Y5N(IN7CrGZChoOX_l#ziwFSVk?Gp~e^fknep z(-UN3IVgfEKv9U2NT4yn$iV09;p*$@7w_ij?BVGe#K<6o6xEPKYt6{O>ztogT#}eq z5|)@#n##z)8JwA(msnC-l*-894$%O1u5V(24TKAhBB*|d2v`9qsWZ-6CVqjokVvu5}WT;|bWT*!7)EI<7#V-RRLk*Z; z%fQ0G2rAndm>B997#JXY1_ocP?F@`syBXLcw=-~VW#H16gMpucn?Z?zhryJAm%)R9kHLq5 zpP_+)0qme81}0De3UL&p2?Hww3j+f~$8H9t$lVMokwR+Q88o&tX!{81`Dt%sFo^U$ z#^9l|jlslMN62y;gY`@XejS!=4EEa?oc)&nf1tCC!EM(6n;-}4?qu*{Vwm~=43y)? z#BhKiNM|QQ2opp2^8Z`4w=sk-XAt&<(42lcy4x6HboMW2;PctdkQ6DDvYjDq|3(I8 z20?}-hD?SihAf6WhC+rY1_p*oh8l(h1}3mStr++i7#M^Y1Q|paL>NRFWEsR5lo-Sr zv>7BA%o!vZycwhzk{DzeG8u#zDjDP%Y8Yf0Y8m7h+8GoW8W|WEoESL&F^I4;C^4`z znEq!_Vqjrs;AUq~VrMXAXE0@8_{pH<#?BD+A5^cxWTF@t*%_i(e=;ySu`?uaA%!I) zLlc7&10y(ss~MOXSQ!`?9JQpkF{Jx~fKXhh#B;_zVns(yJIiKnt8m7#Nrt7#O4(7#I{77#LKA1eP=K z3rR0$;1ZHu&cG@pfUs4HfsKKIL5D$xL6> 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 321ce8ea0d12ee921be95a91be206ac3a87bc21a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2851 zcmX^0Z`VEs1_oP(HCzl#49x5dEIbUX3~Y=H0$GV=iTXK-dFlH8Nm;4MC5#MgHko;u zC3cJq%o>_u>W`3S; zeo1jaYFYt1kY1|>!Y2j`6Z%;L=A;?ydIoJ56`%(S%3{QR10b0*(exkcI(BLfFW#wRl`m61V2LlY8w$gTl}kq!@oE`uH;1AlsIiEn<1V@_&fNq%NgDkFoa zh9?$191I4G45qF{MX9Al3RVh z)8k?=VlZZBFyUb^1-Tn3K|w-?k%28IH7~s+gNwnO!GfK^l83>H!5Wrkz=_JSs3@_r zn2~`cEi)&Fk%3Jk+SwVD0&G!|o=0MFMsR8g7lRE0Gssd0P!e)vWMI{Zb_T_OGb00I zJV?Tohrx}(osoefIX|x?F*C22kwF?c)|@jEi-J=NOH=cbQ>`_lgcukYJb4(r7`z!7 z#B&p~Q=Rkkk`qh9GfOg@^Ye;J67x!m85z`&O@R2!8cRS5F)%Xtf(-LxWDwKv#2(fG zj0~bKsb!gYsZ|Q4d8rCHsU;;vsR~vKptKmo!w?Kgh^*iw2l7uS4?`Fz;<-!mee%mw zi<}dSQ$gYpJPeTxQH%`inZ>TT1tpc>q!I;^iQ!?0Wr$;BU`x(OEOIPiWMI+o)O6-z zNMJ~0XGr2zCtP-a99DM+DWtr^9^kj==T9+qEPtdLliTBVS3cxBe%1q!Lf#fg=N zS3=VjG$0f~Hsta!<|+@#c^ki?{%R7M7t+(b|@DW(yP znT<8W7#VnjOA?c_eG?17>e(44Ffs^ZQOeFRiIIUR+L@7oD>%QjC^^+F6J$Cc+zEQ1 zC}Ly~aLUgwDK05WEbvV&$;eMB=4WG=&c!f;VJ17nEKs7I&B&kvQVOXMGV{vvvs3jU zi5-$D+!B*Z@{1}N8D=0yGE^bNP>;mCl$_LJ6`%b4?9u{jOphUnplA%KEJ($o9NE9H z)P!k-b7D?TaArxWH3!37Mg|Tp-~18ds-URglL{^+53ejq z%!FFFl#xLVVxdA#eo--~rUB)`^wiwcyb^_!)MAhhuv-`zcsxOssdG+ZadB!fJHrY_ z233sU#}=yW467I!)JvfCK6tym;kjx+FpWc9Z(NN<#6*~VbF zht-Nzl2ssn2ZPye2Ajz340cv*%x3HYY-Svy?4lft7*6kIFp899-OgYyE-{s;4(Q(4B?V2qFmb;@@F%cFq?6Ua)TYch(Sh@ zMU;CRL$oN@0tPNgR#9$IuFw{4#^wJXfXpcdnZv->!p;cdm4bNxP2g?@8BsoyL3k5` zs3glShAOa&moo@J`PE>)_BMu^vF)%PhGVuLpaAII(XXs~VU}t9#Vq|A9Vqo~sAkV;w zBF4@zk)0upk&%Jn4?`F`gV7%bMaDl2l8iFH7+AS}GH@{|@caiQRd$Ac21a& 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