-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathHangmanGUI.java
More file actions
194 lines (163 loc) · 5.8 KB
/
HangmanGUI.java
File metadata and controls
194 lines (163 loc) · 5.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/**
* 🎮 Enhanced Hangman GUI Game
*
* 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: Sakshi (Hacktoberfest Contribution)
* Original Author: Pradyumn Pratap Singh (Strange)
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class HangmanGUI extends JFrame implements ActionListener {
// Word list with hints
private final Map<String, String> 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 guessed letters (e.g., "_ A _ A")
private char[] guessedWord;
// Game state variables
private int attempts = 6;
private int wins = 0;
private int losses = 0;
private Set<Character> usedLetters = new HashSet<>();
// Swing components
private JLabel wordLabel, attemptsLabel, messageLabel, usedLabel, scoreLabel;
private JTextField inputField;
private JButton guessButton, restartButton;
/**
* Constructor to set up the GUI and start the first game.
*/
public HangmanGUI() {
setupUI();
startNewGame();
}
/**
* Initializes GUI components and layout.
*/
private void setupUI() {
setTitle("🎮 Enhanced Hangman Game");
setSize(450, 320);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(7, 1, 5, 5));
wordLabel = new JLabel("", SwingConstants.CENTER);
wordLabel.setFont(new Font("Segoe UI", Font.BOLD, 28));
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);
inputField = new JTextField();
guessButton = new JButton("Guess");
restartButton = new JButton("Restart");
guessButton.addActionListener(this);
restartButton.addActionListener(e -> startNewGame());
JPanel bottomPanel = new JPanel(new FlowLayout());
bottomPanel.add(guessButton);
bottomPanel.add(restartButton);
add(wordLabel);
add(attemptsLabel);
add(messageLabel);
add(inputField);
add(usedLabel);
add(scoreLabel);
add(bottomPanel);
setVisible(true);
}
/**
* Starts or restarts a new round of the game.
*/
private void startNewGame() {
// Pick a random word
List<String> 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();
inputField.setText("");
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;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == guess) {
guessedWord[i] = guess;
correct = true;
}
}
if (!correct) {
attempts--;
messageLabel.setText("❌ Wrong! Attempts left: " + attempts);
messageLabel.setForeground(Color.RED);
} else {
messageLabel.setText("✅ Good guess!");
messageLabel.setForeground(Color.GREEN);
}
// Reveal hint if 3 attempts remain
if (attempts == 3) {
messageLabel.setText("<html>Hint: " + wordHints.get(word) + "</html>");
messageLabel.setForeground(new Color(0, 128, 255));
}
updateLabels();
if (new String(guessedWord).equals(word)) {
wins++;
messageLabel.setText("🎉 You Won! Word: " + word);
messageLabel.setForeground(new Color(0, 200, 0));
guessButton.setEnabled(false);
} 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");
}
/**
* Updates labels showing game state.
*/
private void updateLabels() {
wordLabel.setText(new String(guessedWord));
attemptsLabel.setText("Attempts left: " + attempts);
usedLabel.setText("Used letters: " + usedLetters.toString());
}
/**
* Main method to run the game.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(HangmanGUI::new);
}
}