This commit is contained in:
2025-10-08 12:23:02 +02:00
parent d074170b0f
commit 86537ff528
12 changed files with 1167 additions and 0 deletions

Binary file not shown.

View File

@@ -0,0 +1,45 @@
import java.io.*;
import java.util.*;
public class ChooseWord {
/* Fonction pour choisir un mot selon la difficulté */
public static String chooseTheWordByDifficulty(String difficulty) {
List<String> words = new ArrayList<>();
String difficultyDictio = "motsFacile.txt"; // par défaut
if (difficulty.equals("easy")) {
difficultyDictio = "motsFacile.txt";
} else if (difficulty.equals("medium")) {
difficultyDictio = "motsMoyen.txt";
} else if (difficulty.equals("hard")) {
difficultyDictio = "motsDifficiles.txt";
}
try (BufferedReader reader = new BufferedReader(new FileReader(difficultyDictio))) {
String line;
while ((line = reader.readLine()) != null) {
String word = line.trim().toLowerCase();
if (word.isEmpty()) continue;
words.add(word);
}
} catch (IOException e) {
e.printStackTrace();
}
if (words.isEmpty()) {
return "default";
}
Random rand = new Random();
if (difficulty.equals("hard")) {
// Pour "hard", on peut choisir deux mots concaténés
String first = words.get(rand.nextInt(words.size()));
String second = words.get(rand.nextInt(words.size()));
return first + " " + second;
} else {
return words.get(rand.nextInt(words.size()));
}
}
}

Binary file not shown.

View File

@@ -0,0 +1,88 @@
import java.util.*;
public class GameState {
private String word;
private char[] hiddenWord;
private int errors;
private Set<Character> triedLetters;
private static final int MAX_ERRORS = 9;
/* Constructeur : initialise le mot à deviner */
public GameState(String wordToGuess) {
this.word = wordToGuess.toLowerCase();
this.hiddenWord = new char[word.length()];
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == ' ') {
hiddenWord[i] = ' '; // espaces visibles dans les mots difficiles
} else {
hiddenWord[i] = '_';
}
}
this.triedLetters = new HashSet<>();
this.errors = 0;
}
/* Tente une lettre dans le mot */
public void tryLetter(char letter) {
letter = Character.toLowerCase(letter);
triedLetters.add(letter);
boolean found = false;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == letter) {
hiddenWord[i] = letter;
found = true;
}
}
if (!found) {
errors++;
}
}
/* Vérifie si une lettre a déjà été essayée */
public boolean hasTriedLetter(char letter) {
letter = Character.toLowerCase(letter);
return triedLetters.contains(letter);
}
/* Vérifie si le joueur a gagné */
public boolean isWon() {
for (char c : hiddenWord) {
if (c == '_') {
return false;
}
}
return true;
}
/* Vérifie si le joueur a perdu */
public boolean isLost() {
return errors >= MAX_ERRORS;
}
/* Retourne le nombre d'erreurs */
public int getErrors() {
return errors;
}
/* Retourne le mot caché avec espaces entre lettres */
public String getHiddenWord() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hiddenWord.length; i++) {
sb.append(hiddenWord[i]);
if (i < hiddenWord.length - 1) {
sb.append(' ');
}
}
return sb.toString();
}
/* Retourne le mot original */
public String getWord() {
return word;
}
}

Binary file not shown.

View File

@@ -0,0 +1,34 @@
import javax.swing.*;
import java.awt.*;
public class HangmanPanel extends JPanel {
private int errors = 0;
/* Met à jour le nombre d'erreurs et redessine */
public void setErrors(int errors) {
this.errors = errors;
repaint();
}
/* Dessine le pendu en fonction des erreurs */
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Structure du pendu
g.drawLine(50, 300, 200, 300);
g.drawLine(125, 300, 125, 50);
g.drawLine(125, 50, 250, 50);
g.drawLine(250, 50, 250, 80);
if (errors > 0) g.drawOval(230, 80, 40, 40); // tête
if (errors > 1) g.drawLine(250, 120, 250, 200); // corps
if (errors > 2) g.drawLine(250, 140, 220, 170); // bras gauche
if (errors > 3) g.drawLine(250, 140, 280, 170); // bras droit
if (errors > 4) g.drawLine(250, 200, 220, 250); // jambe gauche
if (errors > 5) g.drawLine(250, 200, 280, 250); // jambe droite
if (errors > 6) g.drawLine(230, 90, 270, 90); // yeux barres
if (errors > 7) g.drawString("X", 240, 100); // oeil gauche
if (errors > 8) g.drawString("X", 255, 100); // oeil droit
}
}

BIN
PenduWIlfried/main$1.class Normal file

Binary file not shown.

BIN
PenduWIlfried/main.class Normal file

Binary file not shown.

109
PenduWIlfried/main.java Normal file
View File

@@ -0,0 +1,109 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class main {
public static GameState gameState;
public static JLabel wordLabel;
public static HangmanPanel hangmanPanel;
public static JTextField inputField;
public static JLabel messageLabel;
public static long startTime;
public static long endTime;
public static int score;
/* Fonction main */
public static void main(String[] args) {
String difficulty = chooseDifficulty();
String selectedWord = ChooseWord.chooseTheWordByDifficulty(difficulty);
gameState = new GameState(selectedWord);
startTime = System.currentTimeMillis();
createInterface();
}
/* Fonction pour choisir la difficulté */
public static String chooseDifficulty() {
String[] options = {"Easy", "Medium", "Hard"};
int choice = JOptionPane.showOptionDialog(null, "Choose difficulty level:",
"Difficulty Selection", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, options, options[0]);
if (choice == 0) return "easy";
else if (choice == 1) return "medium";
else if (choice == 2) return "hard";
else return "easy"; // défaut
}
/* Fonction pour créer l'interface */
public static void createInterface() {
JFrame window = new JFrame("Hangman Game");
window.setSize(800, 600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BorderLayout());
wordLabel = new JLabel(gameState.getHiddenWord(), SwingConstants.CENTER);
wordLabel.setFont(new Font("Arial", Font.BOLD, 40));
window.add(wordLabel, BorderLayout.NORTH);
hangmanPanel = new HangmanPanel();
window.add(hangmanPanel, BorderLayout.CENTER);
JPanel inputPanel = new JPanel();
inputField = new JTextField(2);
JButton submitButton = new JButton("Try Letter");
messageLabel = new JLabel("Enter a letter:");
inputPanel.add(messageLabel);
inputPanel.add(inputField);
inputPanel.add(submitButton);
window.add(inputPanel, BorderLayout.SOUTH);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleLetterInput();
}
});
window.setVisible(true);
}
/* Fonction pour gérer la saisie d'une lettre */
public static void handleLetterInput() {
String input = inputField.getText().toLowerCase();
if (input.length() != 1 || !Character.isLetter(input.charAt(0))) {
messageLabel.setText("Enter a single valid letter.");
return;
}
char letter = input.charAt(0);
inputField.setText("");
if (gameState.hasTriedLetter(letter)) {
messageLabel.setText("Letter already tried.");
return;
}
gameState.tryLetter(letter);
wordLabel.setText(gameState.getHiddenWord());
hangmanPanel.setErrors(gameState.getErrors());
if (gameState.isWon()) {
endTime = System.currentTimeMillis();
long elapsedSeconds = (endTime - startTime) / 1000;
score = 1000 - (gameState.getErrors() * 50) - ((int) elapsedSeconds * 10);
if (score < 0) score = 0;
messageLabel.setText("Congrats! You won! Score: " + score + " Time: " + elapsedSeconds + "s");
inputField.setEditable(false);
} else if (gameState.isLost()) {
messageLabel.setText("You lost! Word was: " + gameState.getWord());
inputField.setEditable(false);
} else {
messageLabel.setText("Keep guessing...");
}
}
}

View File

@@ -0,0 +1,87 @@
petit chat
grand arbre
voiture rouge
soleil brillant
fleur jaune
eau claire
montagne haute
ciel bleu
oiseau chanteur
jardin secret
livre ancien
musique douce
temps froid
rue calme
pont vieux
chien fidèle
nuit noire
lune pleine
feu rapide
vent fort
mer agitée
plage dorée
neige blanche
herbe verte
clé perdue
main droite
pied gauche
nez fin
main froide
jour gris
fête joyeuse
rire franc
sac lourd
boue épaisse
seau plein
bête sauvage
chaton joueur
fromage frais
café noir
bois dur
miel doux
âne têtu
nager vite
jouet cassé
roi puissant
reine belle
vase fragile
fleur fanée
voix douce
temps perdu
sable chaud
neuf brillant
souris rapide
pont solide
coeur tendre
lait frais
pied nu
faux plat
rare gemme
tôt matin
lent pas
fin courte
rue étroite
rose rouge
arête dure
doux parfum
sec désert
haut sommet
bas fond
lent mouvement
fer solide
vers libre
vent froid
sel fin
sou dur
rat gris
vin rouge
oui clair
non net
jus sucré
riz blanc
sel épais
jeu amusant
air frais
eau pure
sol dur
feu vif

File diff suppressed because it is too large Load Diff

110
PenduWIlfried/motsMoyen.txt Normal file
View File

@@ -0,0 +1,110 @@
ordinateur
téléphone
bibliothèque
calendrier
aventure
document
ordinateur
musicien
ordinateur
philosophie
restaurant
chocolat
photographie
laboratoire
impression
pédagogique
température
municipale
conversation
influence
architecture
horizon
incroyable
profession
développement
expérience
recherche
université
télévision
ordinateur
démocratie
connaissance
créativité
éducation
électronique
exercice
information
intelligence
organisation
participation
présentation
recommandation
réussite
situation
stratégie
technologie
travail
valeur
véhicule
vocabulaire
vulnérable
architecture
automobile
bibliothèque
biographie
catégorie
champion
climatique
collection
communication
compétence
conférence
connaissance
construction
consultation
contribution
coordination
déclaration
démonstration
développement
différence
difficulté
diplomatie
économie
éducation
électrique
électronique
élément
émotion
entreprise
équipe
espace
essentiel
exemple
expérience
exposition
fabrication
famille
fonction
formation
génération
gestion
habitation
histoire
identité
immédiat
importance
individu
industrie
information
initiative
instruction
intégration
intérêt
introduction
investissement
invitation
journaliste
justification
langue