cplusplus
cplusplus

 

Introduction

The Hangman game is a popular word guessing game where players try to guess a hidden word by suggesting letters within a certain number of guesses.
The goal of this game is to guess the word correctly before running out of attempts, which are typically represented by drawing parts of a hangman figure.

Objective

The objective of this task is to implement the Hangman game using the C++ programming language. In this game, the program randomly selects a word from a list,
and the player must guess the word by inputting letters. The game will display the number of correct guesses and the remaining attempts. If the player guesses all letters of the word correctly within the given attempts, they win. If they run out of attempts, they lose.

Hangman Game Code in C++

#include 
#include 
#include 
#include 

using namespace std;

// Function to print the current state of the game (word with guessed letters)
void displayWord(const string &word, const string &guessedLetters) {
    for (int i = 0; i < word.length(); ++i) {
        if (guessedLetters.find(word[i]) != string::npos)
            cout << word[i] << " ";
        else
            cout << "_ ";
    }
    cout << endl;
}

// Function to check if the player has guessed the word correctly
bool isWordGuessed(const string &word, const string &guessedLetters) {
    for (int i = 0; i < word.length(); ++i) {
        if (guessedLetters.find(word[i]) == string::npos)
            return false;
    }
    return true;
}

int main() {
    string words[] = {"programming", "computer", "hangman", "game", "cplusplus"};
    int numWords = sizeof(words) / sizeof(words[0]);

    // Randomly select a word from the list
    srand(time(0));
    string word = words[rand() % numWords];

    string guessedLetters = "";  // Stores guessed letters
    int attempts = 6;  // Number of attempts before losing the game

    cout << "Welcome to the Hangman Game!" << endl; // Game loop while (attempts > 0) {
        cout << "\nWord to guess: ";
        displayWord(word, guessedLetters);
        cout << "Guessed letters: " << guessedLetters << endl;
        cout << "Remaining attempts: " << attempts << endl;
        
        cout << "Enter a letter to guess: "; char guess; cin >> guess;
        
        // Check if the letter is already guessed
        if (guessedLetters.find(guess) != string::npos) {
            cout << "You've already guessed that letter!" << endl;
            continue;
        }

        // Add the guessed letter to the guessedLetters string
        guessedLetters += guess;

        // Check if the guess is correct
        if (word.find(guess) == string::npos) {
            attempts--;  // Decrease attempts if the guess is incorrect
            cout << "Incorrect guess!" << endl;
        } else {
            cout << "Correct guess!" << endl;
        }

        // Check if the player has won
        if (isWordGuessed(word, guessedLetters)) {
            cout << "\nCongratulations! You've guessed the word: " << word << endl;
            break;
        }
    }

    if (attempts == 0) {
        cout << "\nSorry, you've lost! The word was: " << word << endl;
    }

    return 0;
}

Explanation of the Program Structure

The Hangman game in C++ is implemented using standard input and output. Here is an explanation of how the program works:

  • Word Selection: A predefined list of words is provided, and the program selects a random word using rand() function.
  • Display the Word: The displayWord() function shows the current state of the word, replacing unguessed letters with underscores (“_”).
  • Input Handling: The user is asked to input a letter. The program checks whether the input letter has already been guessed or not.
  • Guess Evaluation: If the guessed letter is correct, it is added to the list of guessed letters. If incorrect, the number of remaining attempts is decreased.
  • Game Over Conditions: The game ends if the player either guesses all letters of the word correctly (win) or runs out of attempts (lose).

How to Run the Program:

1. Copy the code into a C++ compiler or IDE like Code::Blocks, Visual Studio, or an online compiler.

2. Compile the program. In most IDEs, this can be done by pressing the “Build” or “Compile” button.

3. Run the program. The terminal or console window will display the game and prompt for inputs.

4. Play the game by guessing letters, and try to guess the word before you run out of attempts!

Copyright © 2024 Learn Programming. All Rights Reserved.

 

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.

13 thoughts on “Hangman Game in C++”
  1. I am extremely impressed with your writing skills and also with the layout in your blog. Is this a paid subject or did you customize it your self? Anyway stay up the excellent high quality writing, it’s rare to look a nice weblog like this one today!

  2. What you’re creating here is a true oasis of knowledge and inspiration! Every sentence is like a precious pearl, and together they form a fascinating necklace of wisdom. The only thing I found missing was slightly more detailed examples – that would have made it absolutely perfect!

  3. I intended to post you a very little remark just to say thanks a lot once again over the fantastic concepts you’ve documented at this time. This has been so particularly open-handed of people like you to allow unreservedly all that most of us could have supplied for an e book to help make some profit for themselves, notably seeing that you could possibly have tried it if you wanted. The things likewise acted like a great way to fully grasp that other individuals have the identical eagerness similar to my very own to learn somewhat more around this matter. I’m sure there are a lot more pleasurable occasions in the future for individuals that go through your blog post.

  4. Scopri Crazy Time con croupier dal vivo su un casino ADM sicuro con cashback settimanale e transazioni sicure.

    Crea il tuo account oggi e gioca con soldi reali ogni giorno!

    crazytime live stream [url=http://clearcreekgamefowl.com/]https://clearcreekgamefowl.com/[/url]

  5. تتضمن 888starz مصر مجموعة واسعة من الألعاب الرياضية والأحداث التي يمكن للمستخدمين المشاركة فيها
    888starz تسجيل الدخول [url=888starz.onl/eg]https://888starz.onl/eg/[/url]
    888starz Egypt تُقدم عروض وتخفيضات đặc biệt للمستخدمين الجدد

  6. 888starz مصر تهتم برعايه العملاء و توفير تجربة مميزه لهم
    8888 starz [url=https://www.888starz.onl/eg/]https://888starz.onl/eg/[/url]
    888starz مصر تُقدم فرصاً لمراهنة مباشرة على الأحداث الرياضية

  7. تعتبر 888starz من الشركات المرموقة فى مجال المراهنات الرياضية فى مصر
    تسجيل دخول 888starz [url=https://www.888starz.onl/eg]https://888starz.onl/eg/[/url]
    888starz Egypt تتميز بتوفر العديد من طرق الدفع الآمنة

  8. تعتبر 888starz من الشركات المرموقة فى مجال المراهنات الرياضية فى مصر
    ٨٨٨ ستارز [url=https://888starz.onl/eg/]https://888starz.onl/eg/[/url]
    888starz Egypt تتميز بتوفر العديد من طرق الدفع الآمنة

  9. تتضمن 888starz مصر مجموعة واسعة من الألعاب الرياضية والأحداث التي يمكن للمستخدمين المشاركة فيها
    كازينو 888 تسجيل الدخول [url=https://888starz.onl/eg]https://888starz.onl/eg/[/url]
    888starz Egypt تُمكن المستخدمين من المشاركة في بطولات دولية ومحلية

Leave a Reply to 888starz_jlOr Cancel reply

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

error

Enjoy this blog? Please spread the word :)