Java
Java

 

Introduction

Hangman is a classic word-guessing game where the player must guess a hidden word by suggesting letters. Each incorrect guess results in a part of the hangman figure being drawn. The objective is to guess the word before the figure is fully drawn.

In this Java implementation, we will create a simple console-based Hangman game where the user will be prompted to guess letters one by one. The game will track incorrect guesses and display a partial hangman figure. The game ends when the player guesses the word or the figure is fully drawn.

Objective

The objective of this program is to create a console-based Hangman game in Java that:

  • Randomly selects a word for the player to guess.
  • Allows the player to input guesses for letters in the word.
  • Displays the current state of the word after each guess.
  • Tracks incorrect guesses and displays a simple hangman figure.
  • Ends the game when the word is guessed or the figure is fully drawn.

Code

import java.util.Random;
import java.util.Scanner;

public class HangmanGame {
    
    private static final String[] WORDS = {"JAVA", "HANGMAN", "PROGRAMMING", "COMPUTER", "DEVELOPER"};
    private static String selectedWord;
    private static StringBuilder currentWord;
    private static int incorrectGuesses;
    private static final int MAX_INCORRECT_GUESSES = 6;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Select a random word from the list
        selectedWord = WORDS[new Random().nextInt(WORDS.length)];
        currentWord = new StringBuilder("_".repeat(selectedWord.length()));
        incorrectGuesses = 0;

        System.out.println("Welcome to Hangman!");
        
        // Game loop
        while (incorrectGuesses < MAX_INCORRECT_GUESSES && currentWord.indexOf("_") != -1) {
            System.out.println("\nCurrent word: " + currentWord);
            System.out.println("Incorrect guesses: " + incorrectGuesses + "/" + MAX_INCORRECT_GUESSES);
            System.out.println("Guess a letter:");

            char guess = scanner.next().toUpperCase().charAt(0);

            if (isGuessCorrect(guess)) {
                System.out.println("Good guess!");
            } else {
                incorrectGuesses++;
                System.out.println("Incorrect guess!");
            }

            displayHangman();
        }

        if (currentWord.indexOf("_") == -1) {
            System.out.println("\nCongratulations! You guessed the word: " + selectedWord);
        } else {
            System.out.println("\nGame over! The correct word was: " + selectedWord);
        }
        
        scanner.close();
    }

    // Check if the guessed letter is correct and update the current word
    private static boolean isGuessCorrect(char guess) {
        boolean isCorrect = false;
        for (int i = 0; i < selectedWord.length(); i++) {
            if (selectedWord.charAt(i) == guess && currentWord.charAt(i) == '_') {
                currentWord.setCharAt(i, guess);
                isCorrect = true;
            }
        }
        return isCorrect;
    }

    // Display the hangman figure based on the number of incorrect guesses
    private static void displayHangman() {
        System.out.println("\nHangman:");
        switch (incorrectGuesses) {
            case 0:
                System.out.println("  ---");
                System.out.println("  |  |");
                System.out.println("     |");
                System.out.println("     |");
                System.out.println("     |");
                System.out.println("     |");
                break;
            case 1:
                System.out.println("  ---");
                System.out.println("  |  |");
                System.out.println("  O  |");
                System.out.println("     |");
                System.out.println("     |");
                System.out.println("     |");
                break;
            case 2:
                System.out.println("  ---");
                System.out.println("  |  |");
                System.out.println("  O  |");
                System.out.println("  |  |");
                System.out.println("     |");
                System.out.println("     |");
                break;
            case 3:
                System.out.println("  ---");
                System.out.println("  |  |");
                System.out.println("  O  |");
                System.out.println(" /|  |");
                System.out.println("     |");
                System.out.println("     |");
                break;
            case 4:
                System.out.println("  ---");
                System.out.println("  |  |");
                System.out.println("  O  |");
                System.out.println(" /|\\ |");
                System.out.println("     |");
                System.out.println("     |");
                break;
            case 5:
                System.out.println("  ---");
                System.out.println("  |  |");
                System.out.println("  O  |");
                System.out.println(" /|\\ |");
                System.out.println(" /   |");
                System.out.println("     |");
                break;
            case 6:
                System.out.println("  ---");
                System.out.println("  |  |");
                System.out.println("  O  |");
                System.out.println(" /|\\ |");
                System.out.println(" / \\ |");
                System.out.println("     |");
                break;
        }
    }
}

Program Explanation

This Java program implements a simple console-based Hangman game. Here’s a breakdown of its components:

  • Words Array: A list of possible words to choose from is defined in the WORDS array. A random word is selected from this list each time the game starts.
  • Game Loop: The main game loop continues until the player either guesses the word correctly or makes 6 incorrect guesses. After each guess, the program checks if the guessed letter is correct, updates the current word, and displays the current hangman figure based on the number of incorrect guesses.
  • Guess Validation: The isGuessCorrect() function checks if the guessed letter is present in the word and updates the current word accordingly.
  • Hangman Display: The displayHangman() function prints the hangman figure based on the number of incorrect guesses made so far. It shows a progressively drawn figure starting from a simple head and progressing to a fully drawn figure with limbs.
  • End Condition: The game ends when the player correctly guesses the word or when they make 6 incorrect guesses. The program prints a success message or a game-over message accordingly.

How to Run the Program

To run the program, follow these steps:

  1. Save the code in a file named HangmanGame.java.
  2. Open a terminal or command prompt and navigate to the directory where the file is saved.
  3. Compile the program with the Java compiler:
    javac HangmanGame.java
  4. Run the program:
    java HangmanGame
  5. The program will display the Hangman game. Follow the on-screen instructions to guess letters and try to complete the word before the hangman is fully drawn.
© 2024 Learn Programming

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)