Hangman game in Java

In this Java Program, we implement the popular game Hangman in Java. So let’s start learning how to create a hangman game in Java.

Overview of Hangman game in Java:

Firstly, we should know what kind of game Hangman is and how do we play it.
Hence, the following rules explain how Hangman is played:

  1. The first player thinks of a word which ideally should be a noun like a name of a place,animal,thing etc, but should make sure it is not a Name of a person, or any slang or informal words.
  2. The word is then displayed as XXXX with the number of Xs equal to the length of the guessed word.
  3. The second player/guesser now has to guess the word and has limited chances or lives to do so.
  4. Once the guesser says an alphabet, if the word contains that letter and is guessed right, the other player will write it in all the correct positions of the word to be guessed.
  5. However,if the guessed letter does not occur in the word, the guesser loses a life and has lesser chances to guess the word currently.
  6. Once the guesser is coming close to guessing the word, he can attempt to guess the whole word and if he guesses it right, he/she has won the game.
  7. And for every wrong guess, the lives reduce and the guesser can run out of lives, hence losing the game.
  8. Also, while guessing the word, if a guessed letter is not in the word, it is written separately on the side, so that the guesser does not waste a chance on the same word again.

Implementation of Hangman game in Java:

  • The game will first ask the user to type a word that the 2nd person/guesser will then guess.
  • The word will be censored by the program.
  • The program will tell the guesser if their guessed letter is in the word or not.
  • It will also show the progress of the censored word after each guess.
  • If the user already guessed the letter before, the program will tell the user of that and show their previous guesses without repeating any letters.
  • On guessing the word successfully, the program will show the number of attempts at the end.

Program:

import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.Scanner;
class Hangman
{
    public static void main(String[] args) 
    {
        int chances = 0;
        Set<String> prevGuesses = new HashSet<>();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the word for guesser: ");
        String wordToGuess = input.nextLine().toUpperCase();
        int length = wordToGuess.length();
        char[] wordToGuessChars = wordToGuess.toCharArray(); //creates character array of strings
        char[] censor = wordToGuess.toCharArray();
        System.out.println("Your secret word is: "); // prints an array of chars with the same length as string
        for (int index = 0; index < length; index++) 
       {
            censor[index] = '_ ';
        }
        while (!String.valueOf(censor).equals(wordToGuess)) 
        {
            //Initialize all variables in loop
            boolean correct = false; //lets the user know if the letter is in the word or not
            boolean repeated = false; //check if user guessed the same letter twice
            for (int a = 0; a < length; a++) 
            {
                System.out.print(censor[a]);//prints the censored secret word
            }
            System.out.println();
            System.out.println("Type your guess: ");
            String currentGuess = input.next().toUpperCase().substring(0, 1);
            char currentGuessChar = currentGuess.charAt(0); //gets char data from scanner
            if (prevGuesses.contains(currentGuess))            //checks if user already guessed the letter previously
            {
                System.out.println("You already guessed this letter! Try again. Your previous guesses were: ");
                System.out.println(prevGuesses.stream().reduce("", String::concat));
                repeated = true;
            }
            prevGuesses.add(currentGuess);
            //if the guess is not a duplicated guess, it checks if the guessed letter is in the word
            if (!repeated) 
            {
                int times = 0; //number of times a letter is in the word
                for (index = 0; index < length; index++) 
                {
                    if (wordToGuessChars[index] == currentGuessChar) 
                    {
                        censor[index] = currentGuessChar;  //replaces _ with guessed letter in caps
                        correct = true;
                        times++;
                    }
                }
                if (correct) 
                {
                    System.out.println("The letter " + currentGuessChar + " is in the secret word! There are " + times + " " + currentGuessChar + " 's in the word. Revealing the letter(s): ");
                } 
                else 
                {
                    System.out.println("Sorry, the letter is not in the word. Your secret word:  ");
                }
                System.out.println();
            }
            chances++;
        }
        System.out.println("You guessed the entire word " + wordToGuess.toUpperCase() + " correctly! It took you " + chances + " attempts!");
    }
}
  

Output of code:

Enter the word for guesser: 
Apple
Your secret word is: 
_ _ _ _ _
Type your guess: 
z
Sorry, the letter is not in the word. Your secret word:  

_ _ _ _ _
Type your guess: 
p
The letter P is in the secret word! There are 2 P 's in the word. Revealing the letter(s): 

_PP_ _
Type your guess: 
w
Sorry, the letter is not in the word. Your secret word:  

_PP_ _
Type your guess: 
a
The letter A is in the secret word! There are 1 A 's in the word. Revealing the letter(s): 

APP_ _
Type your guess: 
l
The letter L is in the secret word! There are 1 L 's in the word. Revealing the letter(s): 

APPL_
Type your guess: 
e
The letter E is in the secret word! There are 1 E 's in the word. Revealing the letter(s): 

You guessed the entire word APPLE correctly! It took you 6 attempts!

As shown above, this game is fun and all the rules are followed and explained clearly.
Hence, we have successfully implemented Hangman in Java.
You can also refer to:

Leave a Reply

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