Hangman Game in Java

In this article, you will learn how to write the Hangman Game in Java. Hangman is a word-guessing game that involves two participants: the word-setter and the guesser.

The game is usually played on paper, but it can also be implemented as a computer program or mobile app. The objective of the guesser is to identify a secret word chosen by the word-setter, one letter at a time before the full image of a “hangman” is drawn.

The Rules of the Game:

Hangman is typically played with two participants: the “word-setter” and the “guesser.” The word-setter secretly chooses a word, and the guesser’s task is to decipher it. The word is represented by a row of dashes, each representing a letter. The guesser tries to guess letters one by one, and for every incorrect guess, a part of the hangman is drawn on the gallows. The game continues until the guesser successfully identifies the word or the hangman is fully drawn.

Strategic Guessing and Word Knowledge:

Hangman is not merely a game of luck but also a test of strategic thinking and word knowledge. Savvy players often begin by guessing frequently occurring letters in the English language, such as “E,” “T,” “A,” “I,” and “N.” As the game progresses, they might employ word association and contextual clues to make educated guesses. The ability to analyze patterns and discern common word structures becomes essential in successfully cracking the word.

How Does Hangman Game Work?

Here’s how the game works step by step:

  1. Word Selection: The word-setter secretly chooses a word from a predetermined list or category. The word should be long enough to provide a challenge but not too difficult to make guessing impossible.
  2. Display of the Word: The guesser is shown the number of letters in the secret word represented by dashes or underscores. For example, if the secret word is “hangman,” the guesser would see “_ _ _ _ _ _ _.”
  3. Guessing Letters: The guesser starts the game by guessing a letter. If the guessed letter is present in the secret word, all occurrences of that letter are revealed in their respective positions. For example, if the guesser guesses “a,” the display would be “_ _ _ _ _ a _.”
  4. Incorrect Guesses: If the guessed letter is not in the secret word, the word-setter begins drawing parts of the hangman on a gallows. The hangman is usually drawn in stages, typically starting with a head, body, arms, legs, and finally, the noose.
  5. Limited Attempts: The game continues with the guesser guessing one letter at a time. The guesser’s attempts are limited, usually represented by the number of hangman parts that can be drawn (e.g., head, body, arms, legs, and noose for five attempts).
  6. Game End: The game ends when one of the following conditions is met:
    • a) The guesser correctly identifies the entire word before the hangman is fully drawn. In this case, the guesser wins.
    • b) The hangman is fully drawn (i.e., all attempts are used up), and the guesser fails to guess the word. In this case, the word-setter wins.

Hangman Game Program Building Steps

Let’s go through the Hangman game program step by step:

  1. The program begins by importing the required java.util.Scanner class to read input from the user.
  2. It also imports java.util.Random to generate a random number, which will be used to select a word from the predefined list of words.
  3. The program initializes an array words containing several words that can be used as the secret word for the Hangman game.
  4. The program generates a random number within the range of the words array length using Random and selects a word as the secretWord based on the random number index.
  5. It initializes an array guessedLetters of characters, which will keep track of the guessed letters and the revealed letters in the secret word. Initially, all elements are set to ‘_’ (underscore) to represent unknown letters.
  6. The program sets the attempts variable to store the number of incorrect attempts allowed to guess the secret word.
  7. The program displays a welcome message to the player, introducing the Hangman game and the objective of guessing the secret word.
  8. The game loop starts, which will continue until the player correctly guesses the word or runs out of attempts.
  9. Within the game loop, the program displays the current state of the guessedLetters array to the player, showing the known letters and underscores for unknown letters.
  10. The player is prompted to enter a guess by typing a letter, and the input is read using the Scanner class.
  11. The program checks if the player’s input is a valid letter using the isLetter method, which ensures that the player does not enter numbers, symbols, or multiple characters.
  12. If the player’s guess is a valid letter, the program proceeds to check if the guessed letter is present in the secret word.
  13. If the guessed letter is correct and exists in the secret word, the program reveals all occurrences of the guessed letter in the guessedLetters array.
  14. If the guessed letter is incorrect and not in the secret word, the player loses one attempt, and a message is displayed indicating the incorrect guess and the remaining attempts.
  15. The program continues the game loop until the player successfully guesses the entire word (all letters are revealed) or runs out of attempts.
  16. If the player correctly guesses the word, the program displays a congratulatory message, showing the guessed word and the number of attempts taken.
  17. If the player runs out of attempts before guessing the word, the program displays a message indicating that the game is lost and reveals the secret word.
  18. Finally, the Scanner is closed to release system resources.

Java Program for Hangman Game

package com.javacodepoint.game;

import java.util.Scanner;

public class HangmanGame {
	
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);

		String[] words = { "programming", "java", "computer", "hangman", "algorithm", "game" };
		String secretWord = words[(int) (Math.random() * words.length)].toLowerCase();
		char[] guessedLetters = new char[secretWord.length()];
		int attempts = 6;

		for (int i = 0; i < guessedLetters.length; i++) {
			guessedLetters[i] = '_';
		}

		System.out.println("Welcome to Hangman!");
		System.out.println("You have " + attempts + " attempts to guess the word.");

		while (attempts > 0) {
			System.out.println("Current word: " + String.valueOf(guessedLetters));

			System.out.print("Guess a letter: ");
			char guess = scanner.next().toLowerCase().charAt(0);

			if (!isLetter(guess)) {
				System.out.println("Invalid input. Please enter a letter.");
				continue;
			}

			boolean found = false;
			for (int i = 0; i < secretWord.length(); i++) {
				if (secretWord.charAt(i) == guess) {
					guessedLetters[i] = guess;
					found = true;
				}
			}

			if (!found) {
				attempts--;
				System.out.println("Incorrect guess. You have " + attempts + " attempts left.");
			}

			if (String.valueOf(guessedLetters).equals(secretWord)) {
				System.out.println("Congratulations! You guessed the word: " + secretWord);
				break;
			}
		}

		if (attempts == 0) {
			System.out.println("Sorry, you ran out of attempts. The word was: " + secretWord);
		}

		scanner.close();
	}

	private static boolean isLetter(char c) {
		return (c >= 'a' && c <= 'z');
	}
}

OUTPUT:

Welcome to Hangman!
You have 6 attempts to guess the word.
Current word: ____
Guess a letter: g
Current word: g___
Guess a letter: m
Current word: g_m_
Guess a letter: a
Current word: gam_
Guess a letter: e
Congratulations! You guessed the word: game

Conclusion

Hangman is not only a fun and engaging word game but also an educational tool that helps improve vocabulary and spelling skills. Overall, the Hangman game program allows the player to guess a randomly selected word letter by letter, with each incorrect guess resulting in the drawing of a hangman figure.

See also: Rock Paper Scissors Game in Java | Tic-Tac-Toe Game in Java

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *