Exo 3 appliqué

This commit is contained in:
Aissi Jude Christ
2025-10-08 14:57:57 +02:00
parent 9869c9b289
commit 7270ba1a20
20 changed files with 216 additions and 36 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -12,6 +12,7 @@ public class HangedGameGUI {
private Set<Character> guessedLetters;
private int lives;
// Composants de l'interface
private JFrame frame;
private JLabel wordLabel;

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -3,15 +3,20 @@ import java.util.*;
public class ChooseWord {
/*Fonction pour choisir le mot aléatoirement*/
public static String chooseTheWord() {
/*Fonction pour choisir le mot selon la difficulté*/
public static String chooseTheWord(String difficulty) {
String filename = getFilenameByDifficulty(difficulty);
List<String> words = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("motsFacile.txt"))) {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
words.add(line.trim().toLowerCase());
String word = line.trim().toLowerCase();
// Filtre selon la difficulté
if (isValidForDifficulty(word, difficulty)) {
words.add(word);
}
}
}
} catch (IOException e) {
@@ -25,4 +30,26 @@ public class ChooseWord {
Random rand = new Random();
return words.get(rand.nextInt(words.size()));
}
private static String getFilenameByDifficulty(String difficulty) {
switch (difficulty.toLowerCase()) {
case "facile": return "motsFacile.txt";
case "moyen": return "motsMoyen.txt";
case "difficile": return "motsDifficiles.txt";
default: return "motsFacile.txt";
}
}
private static boolean isValidForDifficulty(String word, String difficulty) {
switch (difficulty.toLowerCase()) {
case "facile":
return word.length() < 8 && !word.contains(" ");
case "moyen":
return word.length() >= 8 && !word.contains(" ");
case "difficile":
return word.contains(" "); // Phrases avec espaces
default:
return true;
}
}
}

Binary file not shown.

View File

@@ -7,13 +7,19 @@ public class GameState {
private int errors;
private Set<Character> triedLetters;
private static final int MAX_ERRORS = 9;
private long startTime;
private int score;
private String difficulty;
public GameState(String wordToGuess) {
public GameState(String wordToGuess, String difficulty) {
this.word = wordToGuess.toLowerCase();
this.difficulty = difficulty;
this.hiddenWord = new char[word.length()];
Arrays.fill(hiddenWord, '_');
this.triedLetters = new HashSet<>();
this.errors = 0;
this.score = 0;
this.startTime = System.currentTimeMillis();
}
/*Fonction pour essayer une lettre*/
@@ -32,15 +38,58 @@ public class GameState {
if (!found) {
errors++;
}
// Mettre à jour le score après chaque tentative
updateScore();
}
/*Fonction pour vérifier si une lettre à déjà été essayé*/
/*Calculer le score*/
private void updateScore() {
long currentTime = System.currentTimeMillis();
long timeElapsed = (currentTime - startTime) / 1000; // en secondes
int baseScore = 1000;
int timeBonus = Math.max(0, 300 - (int)timeElapsed) * 2; // Bonus temps
int errorPenalty = errors * 50; // Pénalité erreurs
int difficultyMultiplier = getDifficultyMultiplier();
score = Math.max(0, (baseScore + timeBonus - errorPenalty) * difficultyMultiplier);
}
private int getDifficultyMultiplier() {
switch (difficulty.toLowerCase()) {
case "facile": return 1;
case "moyen": return 2;
case "difficile": return 3;
default: return 1;
}
}
/*Fonction pour obtenir le score final*/
public int getFinalScore() {
if (isWon()) {
updateScore(); // Dernier calcul
return score;
}
return 0; // Score 0 si perdu
}
/*Fonction pour obtenir le temps écoulé*/
public long getTimeElapsed() {
return (System.currentTimeMillis() - startTime) / 1000;
}
/*Fonction pour obtenir la difficulté*/
public String getDifficulty() {
return difficulty;
}
// Les autres méthodes restent inchangées...
public boolean hasTriedLetter(char letter) {
letter = Character.toLowerCase(letter);
return triedLetters.contains(letter);
}
/*Fonction pour vérifier si on a gagné*/
public boolean isWon() {
for (char c : hiddenWord) {
if (c == '_') {
@@ -50,17 +99,14 @@ public class GameState {
return true;
}
/*Fonction pour vérifier si on a perdu*/
public boolean isLost() {
return errors >= MAX_ERRORS;
}
/*Fonction pour voir le nombre d'erreur*/
public int getErrors() {
return errors;
}
/*Fonction pour voir le mot caché*/
public String getHiddenWord() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hiddenWord.length; i++) {
@@ -72,7 +118,6 @@ public class GameState {
return sb.toString();
}
/*Fonction pour voir le mot*/
public String getWord() {
return word;
}

Binary file not shown.

View File

@@ -15,6 +15,11 @@ public class HangmanPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Amélioration visuelle
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 12));
g.drawString("Erreurs: " + errors + "/9", 10, 20);
g.drawLine(50, 300, 200, 300);
g.drawLine(125, 300, 125, 50);
g.drawLine(125, 50, 250, 50);

Binary file not shown.

Binary file not shown.

View File

@@ -2,7 +2,6 @@ import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class main {
public static GameState gameState;
@@ -10,59 +9,132 @@ public class main {
public static HangmanPanel hangmanPanel;
public static JTextField inputField;
public static JLabel messageLabel;
public static JLabel scoreLabel;
public static JLabel timeLabel;
public static Timer timer;
/*Fonction main*/
public static void main(String[] args) {
String selectedWord = ChooseWord.chooseTheWord();
gameState = new GameState(selectedWord);
showDifficultySelection();
}
/*Fonction pour sélectionner la difficulté*/
public static void showDifficultySelection() {
JFrame selectionFrame = new JFrame("Sélection de Difficulté");
selectionFrame.setSize(400, 300);
selectionFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
selectionFrame.setLayout(new GridLayout(4, 1));
JLabel titleLabel = new JLabel("Choisissez la difficulté:", SwingConstants.CENTER);
titleLabel.setFont(new Font("Arial", Font.BOLD, 20));
JButton easyButton = new JButton("FACILE - Mots courts (< 8 lettres)");
JButton mediumButton = new JButton("MOYEN - Mots longs (≥ 8 lettres)");
JButton hardButton = new JButton("DIFFICILE - Phrases (2 mots)");
easyButton.addActionListener(e -> startGame("facile", selectionFrame));
mediumButton.addActionListener(e -> startGame("moyen", selectionFrame));
hardButton.addActionListener(e -> startGame("difficile", selectionFrame));
selectionFrame.add(titleLabel);
selectionFrame.add(easyButton);
selectionFrame.add(mediumButton);
selectionFrame.add(hardButton);
selectionFrame.setVisible(true);
}
/*Fonction pour démarrer le jeu*/
public static void startGame(String difficulty, JFrame selectionFrame) {
selectionFrame.dispose();
String selectedWord = ChooseWord.chooseTheWord(difficulty);
gameState = new GameState(selectedWord, difficulty);
createInterface();
startTimer();
}
/*Fonction pour créer l'interface*/
public static void createInterface() {
JFrame window = new JFrame("HangmanGame");
JFrame window = new JFrame("HangmanGame - Difficulté: " + gameState.getDifficulty());
window.setSize(800, 600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BorderLayout());
// Panel d'information (score et temps)
JPanel infoPanel = new JPanel(new GridLayout(1, 3));
JLabel difficultyLabel = new JLabel("Difficulté: " + gameState.getDifficulty(), SwingConstants.CENTER);
difficultyLabel.setFont(new Font("Arial", Font.BOLD, 16));
scoreLabel = new JLabel("Score: 0", SwingConstants.CENTER);
scoreLabel.setFont(new Font("Arial", Font.BOLD, 16));
timeLabel = new JLabel("Temps: 0s", SwingConstants.CENTER);
timeLabel.setFont(new Font("Arial", Font.BOLD, 16));
infoPanel.add(difficultyLabel);
infoPanel.add(scoreLabel);
infoPanel.add(timeLabel);
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");
inputField.setFont(new Font("Arial", Font.BOLD, 20));
JButton submitButton = new JButton("Essayer la lettre");
messageLabel = new JLabel("Enter a letter:");
messageLabel = new JLabel("Entrez une lettre:");
inputPanel.add(messageLabel);
inputPanel.add(inputField);
inputPanel.add(submitButton);
window.add(infoPanel, BorderLayout.NORTH);
window.add(wordLabel, BorderLayout.CENTER);
window.add(hangmanPanel, BorderLayout.WEST);
window.add(inputPanel, BorderLayout.SOUTH);
/*evenement du bouton*/
/*événement du bouton*/
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleLetterInput();
}
});
/*événement de la touche Entrée*/
inputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleLetterInput();
}
});
window.setVisible(true);
inputField.requestFocus();
}
/*Fonction pour mettre à jour le pendu*/
/*Fonction pour démarrer le chronomètre*/
public static void startTimer() {
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateDisplay();
}
});
timer.start();
}
/*Fonction pour mettre à jour l'affichage*/
public static void updateDisplay() {
timeLabel.setText("Temps: " + gameState.getTimeElapsed() + "s");
scoreLabel.setText("Score: " + gameState.getFinalScore());
}
/*Fonction pour gérer la saisie de lettre*/
public static void handleLetterInput() {
System.out.println(gameState.getWord());
System.out.println(gameState.getWord().length());
String input = inputField.getText().toLowerCase();
if (input.length() != 1 || !Character.isLetter(input.charAt(0))) {
messageLabel.setText("Enter a single valid letter.");
messageLabel.setText("Entrez une seule lettre valide.");
return;
}
@@ -70,22 +142,52 @@ public class main {
inputField.setText("");
if (gameState.hasTriedLetter(letter)) {
messageLabel.setText("Letter already tried.");
messageLabel.setText("Lettre déjà essayée.");
return;
}
gameState.tryLetter(letter);
wordLabel.setText(gameState.getHiddenWord());
hangmanPanel.setErrors(gameState.getErrors());
updateDisplay();
if (gameState.isWon()) {
messageLabel.setText("Congratulations! You've won!");
timer.stop();
int finalScore = gameState.getFinalScore();
messageLabel.setText("Félicitations ! Vous avez gagné ! Score: " + finalScore);
inputField.setEditable(false);
showEndGameMessage(true, finalScore);
} else if (gameState.isLost()) {
messageLabel.setText("You lost! Word was: " + gameState.getWord());
timer.stop();
messageLabel.setText("Perdu ! Le mot était: " + gameState.getWord());
inputField.setEditable(false);
showEndGameMessage(false, 0);
} else {
messageLabel.setText("Keep guessing...");
messageLabel.setText("Continuez... Erreurs: " + gameState.getErrors() + "/" + 9);
}
}
/*Fonction pour afficher le message de fin de jeu*/
public static void showEndGameMessage(boolean won, int score) {
String message = won ?
"FÉLICITATIONS !\nVous avez gagné !\nScore final: " + score + "\nTemps: " + gameState.getTimeElapsed() + "s" :
"DOMAGE !\nVous avez perdu.\nLe mot était: " + gameState.getWord() + "\nVoulez-vous réessayer ?";
int optionType = won ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.QUESTION_MESSAGE;
int choice = JOptionPane.showConfirmDialog(null,
message,
"Partie Terminée",
JOptionPane.DEFAULT_OPTION,
optionType);
if (!won || choice == JOptionPane.OK_OPTION) {
// Retour au menu principal
SwingUtilities.invokeLater(() -> {
JFrame currentFrame = (JFrame) SwingUtilities.getWindowAncestor(inputField);
currentFrame.dispose();
showDifficultySelection();
});
}
}
}