Open In App

Hangman Game in Java

Improve
Improve
Like Article
Like
Save
Share
Report

Hangman is a popular word guessing game where the player endeavors to construct a lost word by speculating one letter at a time. After a certain number of off base surmises, the game finishes and the player loses. The game also finishes when the player accurately distinguishes all the letters of the lost word. The implementation of this game in Java is given below. 

Example:

Output
Welcome to HANGMAN GAME 
let’s play the game 
_ _ _ _ _ _ 
Your Guess: 
Input: s
Output
S is not present in the word. 
_ _ _ _ _ _ 
You have 4 guesses left. 
Your Guess: 
Input: m
Output
M is not present in the word. 
_ _ _ _ _ _ 
You have 3 guesses left. 
Your Guess: 
Input: d
Output
D is not present in the word. 
_ _ _ _ _ _ 
You have 2 guesses left. 
Your Guess: 
Input: t
Output
T is present in the word.
T_ _ _ T_ 
You have 2 guesses left. 
Your Guess: 
Input: o
Output
O is present in the word.
TO_ OT_ 
You have 2 guesses left. 
Your Guess: 
Input: y
Output
Y is present in the word.
TOYOT_ 
You have 2 guesses left. 
Your Guess: 
Input: a
Output
A is present in the word.
The word is: TOYOTA 
Well Played, you did it!!

Java is a general-purpose computer programming dialect that’s concurrent, class-based, object-oriented, and particularly designed to have as few dependencies as possible. Java has dedicated an entire library to Random numbers seeing its importance in day to day programming. nextInt(), a function, is used in this article’s code. This game is for beginners learning to code in Java and to give them a little brief about using strings, loops, and conditional statements.
 

Understanding the Game
 

A word has to be guessed by the player. So, the output screen will display the number of dashes representing the letters left to be guessed. Then the player will guess a letter. If that letter is present in the word then the program will replace the dashes with the letter at every place it appears. If the letter isn’t present in the word then the number of lifelines is reduced (which consists of finite no. of chances). The player wins the game as soon as all the letters of the word have been guessed correctly.

Game Plan:

The user should start by guessing the most occurring letters in the word which are vowels(a, e, i, o, u). Apart from the vowels, the other most commonly used letters are t, n, s, h, r, d and l.

Implementation of the game

In the program, a Class Game has been created in which a list of strings is created which consists of words. In the list of words, one word will be chosen randomly using a random module(java.util.Random) for the user to guess its letters. After choosing the word, all the letters are made uppercase using toUpperCase() function and then those letters are replaced by dashes. The maximum number of incorrect guesses allowed in the game is 5, if the user goes beyond that then the user will lose the game. In the while loop as the user starts guessing the letters, the correct guesses will replace the dashes by correct letters whereas the incorrect guesses will increase the variable counting the number of incorrect guesses by 1.

  • The first condition is used to inform the user about the lifelines left when the user has guessed the wrong letter.
  • The second condition is used to tell the user that the letters entered have already been guessed.
  • The third condition is to check whether the new letter guessed is present in the word or not, if they are correct then the dashes are replaced by those correct letters
  • If the letter is not present in the word, then the lifeline is reduced by 1.

The game is over if any one of the condition is satisfied: 

  • The user has guessed the whole word correctly.
  • The user’s lifelines have finished. 
     

Java




// Java program to implement
// Hangman game
  
import java.util.Scanner;
import java.util.Random;
  
class Game {
  
    static Scanner input;
    public static void hangman()
    {
        input = new Scanner(System.in);
  
        // array of strings containing words
        String[] company = { "Maruti", "Tata", "Suzuki",
                             "Ducati", "Toyota" };
        System.out.println(
            "    Welcome to HANGMAN GAME    ");
  
        Random obj = new Random();
        int Ran_num = obj.nextInt(5);
  
        // takes input of the word
        String word = (company[Ran_num]);
        word = word.toUpperCase();
  
        // To show the word in underscores
        String word1 = word.replaceAll("[A-Z]", "_ ");
  
        // play the game
        System.out.println("let's play the game");
        startGame(word, word1);
    }
    public static void startGame(String word, String word1)
    {
        // total guesses
        int guess_ = 0;
  
        // number of wrong guesses
        int wrong = 0;
  
        // for each guess
        String guess;
  
        // stores the guessed letter
        char letter;
  
        // stores if the letter was
        // already guessed
        boolean guessescontainsguess;
        String guesses = "";
        boolean guessinword;
  
        // while loop starts here
        while (wrong < 5 && word1.contains("_")) {
  
            System.out.println(word1 + "\n");
            int temp = 5 - wrong;
            if (wrong != 0) {
  
                // for picture 1
                System.out.println("You have " + temp
                                   + " guesses left.");
            }
  
            System.out.print("Your Guess:");
  
            // takes guess input
            guess = input.nextLine();
  
            // converts to uppercase
            // for comparison
            guess = guess.toUpperCase();
  
            // gets the first letter
            // as guessed letter
            letter = guess.charAt(0);
  
            guessescontainsguess
                = (guesses.indexOf(letter)) != -1;
  
            // stores every letter
            // guessed in guesses
            guesses += letter;
  
            // converts to uppercase for
            // comparison
            letter = Character.toUpperCase(letter);
            System.out.println();
  
            // if letter already guessed
            if (guessescontainsguess == true) {
  
                // already guessed letter
                System.out.println("You ALREADY guessed "
                                   + letter + ". \n");
            }
  
            // guessed letter is in the word
            guessinword = (word.indexOf(letter)) != -1;
  
            // if statement begins
            if (guessinword == true) {
  
                // print the letter
                System.out.println(
                    letter + " is present in the word.");
                System.out.print("\n");
  
                // find the letter positions
                // replace dashes with those
                // letter at valid positions
                for (int position = 0;
                     position < word.length(); position++) {
  
                    // guessed letter is equal to
                    // letter at position in word
                    // and word1 has previously does not
                    // have that letter
                    if (word.charAt(position) == letter
                        && word1.charAt(position)
                               != letter) {
  
                        word1 = word1.replaceAll("_ ", "_");
                        String word2;
                        word2 = word1.substring(0, position)
                                + letter
                                + word1.substring(position
                                                  + 1);
                        word2 = word2.replaceAll("_", "_ ");
                        word1 = word2;
                    }
                }
            }
  
            // if statement ends, else if begins
            else {
  
                // prints
                // wrong = wrong + 1, after every
                // wrong answer
                System.out.println(
                    letter
                    + " is not present in the word.");
                wrong++;
            }
  
            // guess_ = guess_ + 1, after every
            // attempt
            guess_++;
  
        } // while loop ends
  
        // if the lifelines finishes
        if (wrong == 5) {
            System.out.println(
                "YOU LOST!, maximum limit of incorrect guesses reached.");
        }
        else {
  
            // when solved
            System.out.print(
                "The word is: " + word1
                + "\n Well Played, you did it!!");
        }
    }
    public static void main(String[] args)
    {
        // play hangman game
        hangman();
    }
}


Output:

Hangman Game

Note: This is an interactive game, so play it in the console.



Last Updated : 26 Oct, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads