Files
TD3_DEV51_brigitte_aissi/PenduWIlfried/main.java
2025-10-08 12:28:34 +02:00

92 lines
2.8 KiB
Java

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;
/*Fonction main*/
public static void main(String[] args) {
String selectedWord = ChooseWord.chooseTheWord();
gameState = new GameState(selectedWord);
createInterface();
}
/*Fonction pour créer l'interface*/
public static void createInterface() {
JFrame window = new JFrame("HangmanGame");
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);
/*evenement du bouton*/
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleLetterInput();
}
});
window.setVisible(true);
}
/*Fonction pour mettre à jour le pendu*/
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.");
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()) {
messageLabel.setText("Congratulations! You've won!");
inputField.setEditable(false);
} else if (gameState.isLost()) {
messageLabel.setText("You lost! Word was: " + gameState.getWord());
inputField.setEditable(false);
} else {
messageLabel.setText("Keep guessing...");
}
}
}