Learn how to create a Hangman Game in java. Follow our step-by-step guide to develop this classic word guessing game and enhance your Java programming skills.
In the realm of programming, games often serve as excellent projects to apply and demonstrate key concepts. One such classic game is Hangman, where players guess letters to reveal a hidden word before running out of attempts. In this blog post, we’ll explore the development of a Hangman game using Java Swing, a popular GUI toolkit for Java applications.
Overview of the Hangman GUI Class
The Hangman GUI
class is the core of our Hangman game. It provides the structure and functionality necessary to create an interactive and engaging gaming experience.
The Game Logic
Before we dive into the GUI implementation, let’s take a look at the game logic. The Hangman game is a classic guessing game where the player tries to guess a word by suggesting letters. For each letter that is not in the word, the player loses an attempt. The game continues until the player guesses the word or runs out of attempts.
In our implementation, we’ll use a HashSet
to keep track of the guessed letters, and an array to represent the word to be guessed. We’ll also use a timer to limit the game to 60 seconds.
Game Initialization and Layout
The game begins by initializing necessary variables such as the array of words to guess from, the hidden word itself, and the guessed letters. The graphical user interface (GUI) layout is set up using Java’s Border Layout, which organizes components into distinct regions such as north, south, east, west, and center. Each region serves a specific purpose:
- Top Panel: Displays crucial game information including the hidden word represented by underscores, remaining attempts, and a countdown timer for added challenge.
- Center Panel: Houses an input field where players can enter their guesses—either a single letter or the entire word they think is hidden.
- Bottom Panel: Contains interactive buttons for guessing and restarting the game, along with an area to display incorrect guesses made by the player.
NOTE
You can get it’s code from Git Hub Repository
The GUI Implementation
Now, let’s create the hangman Game with GUI in java. We’ll use a JFrame
as the main window, and add several components to it:
- A
JLabel
to display the word to be guessed - A
JLabel
to display the attempts remaining - A
JLabel
to display the time remaining - A
JTextField
to input the player’s guess - A
JButton
to submit the guess - A
JButton
to restart the game - A
JTextArea
to display the incorrect guesses
We’ll use a BorderLayout
to arrange the components in a logical manner. The top panel will contain the word, attempts, and time labels. The center panel will contain the input field and message label. The bottom panel will contain the guess and restart buttons, as well as the incorrect guesses area.
The Guess Button Listener
When the player submits a guess, we’ll use an ActionListener
to event handling in java. We’ll check if the input is a single letter or a word, and update the game state accordingly. If the guess is correct, we’ll update the word label and check if the player has won. If the guess is incorrect, we’ll decrement the attempts and update the attempts label.
Java timer implementation
We’ll use a Timer
to limit the game to 60 seconds. Every second, we’ll decrement the time remaining and update the timer label. If the time runs out, we’ll end the game and display a game over message.
Game Logic and Event Handling in java
The heart of the game lies in its logic and event handling mechanisms. A specialized GuessButtonListener
class manages user interactions, validating input against the hidden word, updating game states, and providing real-time feedback to the player. This listener ensures that the game responds appropriately to correct and incorrect guesses, updates the display accordingly, and triggers game-over conditions when necessary, such as when all attempts are exhausted or time runs out.
The Restart Button
When the player clicks the restart button, we’ll reset the game state and start a new game.
Running the Game
Finally, we’ll create a main
method to launch the game. We’ll use SwingUtilities.invokeLater
to ensure that the GUI is created on the event dispatch thread.
Conclusion
This Java Swing implementation of Hangman demonstrates the power of GUI programming in creating interactive games. It not only provides a fun and challenging gaming experience but also serves as a practical example of how to integrate user interface elements, game logic and event handling in Java applications. Whether you’re a beginner learning Java or an experienced developer exploring game development, Hangman offers a rewarding project to sharpen your skills.
Source Code of hangman Game in java
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Timer;
import java.util.TimerTask;
class HangmanGUI extends JFrame {
private String[] words = {"java", "python", "hangman", "programming", "openai"};
private String word;
private char[] guessedWord;
private int attempts = 6;
private boolean won = false;
private HashSet<Character> guessedLetters = new HashSet<>();
private JLabel wordLabel, attemptsLabel, messageLabel, timerLabel;
private JTextField inputField;
private JTextArea incorrectGuessesArea;
private JButton guessButton, restartButton;
private Timer timer;
private int timeLeft = 60; // 60 seconds timer
public HangmanGUI() {
setTitle("Hangman Game");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
initializeGame();
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(3, 1));
topPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
wordLabel = new JLabel("Word: " + new String(guessedWord));
wordLabel.setFont(new Font("Arial", Font.BOLD, 24));
topPanel.add(wordLabel);
attemptsLabel = new JLabel("Attempts remaining: " + attempts);
attemptsLabel.setFont(new Font("Arial", Font.PLAIN, 16));
topPanel.add(attemptsLabel);
timerLabel = new JLabel("Time remaining: " + timeLeft + " seconds");
timerLabel.setFont(new Font("Arial", Font.PLAIN, 16));
topPanel.add(timerLabel);
add(topPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(2, 1));
centerPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
messageLabel = new JLabel("Enter a letter or guess the word:");
messageLabel.setFont(new Font("Arial", Font.PLAIN, 18));
centerPanel.add(messageLabel);
inputField = new JTextField();
inputField.setFont(new Font("Arial", Font.PLAIN, 18));
centerPanel.add(inputField);
add(centerPanel, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
bottomPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
guessButton = new JButton("Guess");
guessButton.setFont(new Font("Arial", Font.PLAIN, 18));
guessButton.addActionListener(new GuessButtonListener());
buttonPanel.add(guessButton);
restartButton = new JButton("Restart");
restartButton.setFont(new Font("Arial", Font.PLAIN, 18));
restartButton.addActionListener(e -> restartGame());
buttonPanel.add(restartButton);
bottomPanel.add(buttonPanel, BorderLayout.NORTH);
incorrectGuessesArea = new JTextArea("Incorrect guesses: ");
incorrectGuessesArea.setEditable(false);
incorrectGuessesArea.setFont(new Font("Arial", Font.PLAIN, 16));
bottomPanel.add(new JScrollPane(incorrectGuessesArea), BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
startTimer();
}
private void initializeGame() {
word = words[(int) (Math.random() * words.length)];
guessedWord = new char[word.length()];
for (int i = 0; i < guessedWord.length; i++) {
guessedWord[i] = '_';
}
guessedLetters.clear();
attempts = 6;
timeLeft = 60;
won = false;
}
private void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
timeLeft--;
timerLabel.setText("Time remaining: " + timeLeft + " seconds");
if (timeLeft <= 0) {
timer.cancel();
gameOver();
}
}
}, 1000, 1000);
}
private void gameOver() {
messageLabel.setText("Time's up! Game over! The word was: " + word);
guessButton.setEnabled(false);
}
private void restartGame() {
initializeGame();
wordLabel.setText("Word: " + new String(guessedWord));
attemptsLabel.setText("Attempts remaining: " + attempts);
timerLabel.setText("Time remaining: " + timeLeft + " seconds");
messageLabel.setText("Enter a letter or guess the word:");
incorrectGuessesArea.setText("Incorrect guesses: ");
guessButton.setEnabled(true);
startTimer();
}
private class GuessButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String input = inputField.getText();
inputField.setText("");
inputField.requestFocus();
if (input.length() == 1) {
char guess = input.charAt(0);
if (guessedLetters.contains(guess)) {
messageLabel.setText("You have already guessed that letter. Try again.");
return;
}
guessedLetters.add(guess);
boolean correctGuess = false;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == guess) {
guessedWord[i] = guess;
correctGuess = true;
}
}
if (!correctGuess) {
attempts--;
incorrectGuessesArea.append(guess + " ");
attemptsLabel.setText("Attempts remaining: " + attempts);
if (attempts == 0) {
messageLabel.setText("Game over! The word was: " + word);
guessButton.setEnabled(false);
} else {
messageLabel.setText("Incorrect guess. Try again.");
}
} else {
wordLabel.setText("Word: " + new String(guessedWord));
if (new String(guessedWord).equals(word)) {
won = true;
messageLabel.setText("Congratulations! You guessed the word: " + word);
guessButton.setEnabled(false);
} else {
messageLabel.setText("Correct guess. Keep going!");
}
}
} else if (input.equalsIgnoreCase(word)) {
won = true;
wordLabel.setText("Word: " + word);
messageLabel.setText("Congratulations! You guessed the word: " + word);
guessButton.setEnabled(false);
} else {
attempts--;
attemptsLabel.setText("Attempts remaining: " + attempts);
if (attempts == 0) {
messageLabel.setText("Game over! The word was: " + word);
guessButton.setEnabled(false);
} else {
messageLabel.setText("Incorrect guess. Try again.");
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
HangmanGUI game = new HangmanGUI();
game.setVisible(true);
});
}
}