From 2d005008789aa2b4317f36e59af3c74d3ee05354 Mon Sep 17 00:00:00 2001 From: SakshiDosani Date: Fri, 31 Oct 2025 23:58:13 +0530 Subject: [PATCH] Enhanced Hangman game with hints, score, and used letters tracking --- Java/Hangman/HangmanGUI.java | 182 ++++++++++++++++++++--------------- Java/Hangman/Readme.MD | 17 ++++ 2 files changed, 123 insertions(+), 76 deletions(-) create mode 100644 Java/Hangman/Readme.MD diff --git a/Java/Hangman/HangmanGUI.java b/Java/Hangman/HangmanGUI.java index aefe6eb..fd0811c 100644 --- a/Java/Hangman/HangmanGUI.java +++ b/Java/Hangman/HangmanGUI.java @@ -1,111 +1,142 @@ /** - * 🎮 Hangman GUI Game + * 🎮 Enhanced Hangman GUI Game * - * A simple word-guessing game using Java Swing. - * Players guess letters to figure out a hidden word. - * GUI displays the current word, remaining attempts, messages, and allows restarting. + * Features added for Hacktoberfest: + * ✅ Tracks used letters + * ✅ Provides hints after 3 wrong guesses + * ✅ Displays a score system (wins/losses) + * ✅ Adds color-coded messages for better UX * - * - * Author: Pradyumn Pratap Singh (Strange) + * Author: Sakshi (Hacktoberfest Contribution) + * Original Author: Pradyumn Pratap Singh (Strange) */ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import java.util.Random; +import java.util.*; public class HangmanGUI extends JFrame implements ActionListener { - // Array of possible words for the game - private String[] words = {"JAVA", "HANGMAN", "COMPUTER", "PROGRAMMING", "SWING"}; + // Word list with hints + private final Map wordHints = Map.of( + "JAVA", "A popular programming language", + "HANGMAN", "A classic word-guessing game", + "COMPUTER", "An electronic device for calculations", + "PROGRAMMING", "What developers love to do!", + "SWING", "A Java GUI toolkit" + ); // The current word to guess private String word; - // Array to store the current guessed letters (e.g., "_ A _ A") + // Array to store guessed letters (e.g., "_ A _ A") private char[] guessedWord; - // Remaining attempts before the game is over + // Game state variables private int attempts = 6; + private int wins = 0; + private int losses = 0; + private Set usedLetters = new HashSet<>(); // Swing components - private JLabel wordLabel, attemptsLabel, messageLabel; + private JLabel wordLabel, attemptsLabel, messageLabel, usedLabel, scoreLabel; private JTextField inputField; private JButton guessButton, restartButton; /** - * Constructor to set up the GUI and initialize the game. + * Constructor to set up the GUI and start the first game. */ public HangmanGUI() { - // Select a random word from the list - word = words[new Random().nextInt(words.length)]; - - // Initialize guessedWord array with underscores - guessedWord = new char[word.length()]; - for (int i = 0; i < guessedWord.length; i++) guessedWord[i] = '_'; + setupUI(); + startNewGame(); + } - // JFrame properties - setTitle("🎮 Hangman Game"); - setSize(400, 250); + /** + * Initializes GUI components and layout. + */ + private void setupUI() { + setTitle("🎮 Enhanced Hangman Game"); + setSize(450, 320); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); - setLayout(new GridLayout(5, 1, 5, 5)); + setLayout(new GridLayout(7, 1, 5, 5)); - // Label to display the guessed word - wordLabel = new JLabel(new String(guessedWord), SwingConstants.CENTER); - wordLabel.setFont(new Font("Segoe UI", Font.BOLD, 24)); + wordLabel = new JLabel("", SwingConstants.CENTER); + wordLabel.setFont(new Font("Segoe UI", Font.BOLD, 28)); - // Label to show remaining attempts - attemptsLabel = new JLabel("Attempts left: " + attempts, SwingConstants.CENTER); + attemptsLabel = new JLabel("", SwingConstants.CENTER); + messageLabel = new JLabel("", SwingConstants.CENTER); + usedLabel = new JLabel("", SwingConstants.CENTER); + scoreLabel = new JLabel("Score: 0 Wins | 0 Losses", SwingConstants.CENTER); - // Label to display messages or prompts - messageLabel = new JLabel("Enter a letter:", SwingConstants.CENTER); - - // Text field for player to enter a guess inputField = new JTextField(); - - // Buttons for guessing and restarting the game guessButton = new JButton("Guess"); restartButton = new JButton("Restart"); - // Add action listeners guessButton.addActionListener(this); - restartButton.addActionListener(e -> restartGame()); + restartButton.addActionListener(e -> startNewGame()); + + JPanel bottomPanel = new JPanel(new FlowLayout()); + bottomPanel.add(guessButton); + bottomPanel.add(restartButton); - // Add components to JFrame add(wordLabel); add(attemptsLabel); add(messageLabel); add(inputField); - - // Bottom panel for buttons - JPanel bottomPanel = new JPanel(new FlowLayout()); - bottomPanel.add(guessButton); - bottomPanel.add(restartButton); + add(usedLabel); + add(scoreLabel); add(bottomPanel); - // Make GUI visible setVisible(true); } + /** + * Starts or restarts a new round of the game. + */ + private void startNewGame() { + // Pick a random word + List keys = new ArrayList<>(wordHints.keySet()); + word = keys.get(new Random().nextInt(keys.size())); + + guessedWord = new char[word.length()]; + Arrays.fill(guessedWord, '_'); + attempts = 6; + usedLetters.clear(); + + // Update GUI + updateLabels(); + messageLabel.setText("Enter a letter:"); + messageLabel.setForeground(Color.BLACK); + guessButton.setEnabled(true); + inputField.setText(""); + } + /** * Handles the Guess button click event. */ @Override public void actionPerformed(ActionEvent e) { - String input = inputField.getText().toUpperCase(); // Convert to uppercase - inputField.setText(""); // Clear input field + String input = inputField.getText().toUpperCase(); + inputField.setText(""); - // Validate input - if (input.length() != 1) { - messageLabel.setText("Enter only one letter!"); + if (input.length() != 1 || !Character.isLetter(input.charAt(0))) { + messageLabel.setText("⚠️ Please enter a single letter!"); + messageLabel.setForeground(Color.ORANGE); return; } char guess = input.charAt(0); + if (usedLetters.contains(guess)) { + messageLabel.setText("You already tried '" + guess + "'!"); + messageLabel.setForeground(Color.GRAY); + return; + } + + usedLetters.add(guess); boolean correct = false; - // Check if the guessed letter is in the word for (int i = 0; i < word.length(); i++) { if (word.charAt(i) == guess) { guessedWord[i] = guess; @@ -113,50 +144,49 @@ public void actionPerformed(ActionEvent e) { } } - // Update attempts if guess is incorrect - if (!correct) attempts--; + if (!correct) { + attempts--; + messageLabel.setText("❌ Wrong! Attempts left: " + attempts); + messageLabel.setForeground(Color.RED); + } else { + messageLabel.setText("✅ Good guess!"); + messageLabel.setForeground(Color.GREEN); + } - // Update GUI labels - wordLabel.setText(new String(guessedWord)); - attemptsLabel.setText("Attempts left: " + attempts); + // Reveal hint if 3 attempts remain + if (attempts == 3) { + messageLabel.setText("Hint: " + wordHints.get(word) + ""); + messageLabel.setForeground(new Color(0, 128, 255)); + } + + updateLabels(); - // Check for win condition if (new String(guessedWord).equals(word)) { + wins++; messageLabel.setText("🎉 You Won! Word: " + word); + messageLabel.setForeground(new Color(0, 200, 0)); guessButton.setEnabled(false); - } - // Check for loss condition - else if (attempts == 0) { + } else if (attempts == 0) { + losses++; messageLabel.setText("💀 Game Over! Word: " + word); + messageLabel.setForeground(Color.RED); guessButton.setEnabled(false); } + + scoreLabel.setText("Score: " + wins + " Wins | " + losses + " Losses"); } /** - * Resets the game to start a new round. + * Updates labels showing game state. */ - private void restartGame() { - // Select a new random word - word = words[new Random().nextInt(words.length)]; - - // Reset guessed word - guessedWord = new char[word.length()]; - for (int i = 0; i < guessedWord.length; i++) guessedWord[i] = '_'; - - // Reset attempts - attempts = 6; - - // Update GUI labels + private void updateLabels() { wordLabel.setText(new String(guessedWord)); attemptsLabel.setText("Attempts left: " + attempts); - messageLabel.setText("Enter a letter:"); - - // Enable guess button - guessButton.setEnabled(true); + usedLabel.setText("Used letters: " + usedLetters.toString()); } /** - * Main method to start the game. + * Main method to run the game. */ public static void main(String[] args) { SwingUtilities.invokeLater(HangmanGUI::new); diff --git a/Java/Hangman/Readme.MD b/Java/Hangman/Readme.MD new file mode 100644 index 0000000..78de9d1 --- /dev/null +++ b/Java/Hangman/Readme.MD @@ -0,0 +1,17 @@ +# 🎮 Enhanced Hangman GUI + +This is an upgraded version of a Java Swing Hangman game — created as a **Hacktoberfest contribution**. + +### ✨ Features +- Tracks used letters +- Displays hints after 3 wrong attempts +- Shows a live score (wins/losses) +- Color-coded messages for feedback +- Simple, interactive GUI using Java Swing + +### 🚀 How to Run +1. Open the project in any Java IDE (like IntelliJ or VS Code with Java extensions). +2. Compile and run: + ```bash + javac HangmanGUI.java + java HangmanGUI