Hangman Game in C++

Build a Hangman Game in C++(Source Code)

Build a Hangman Game in C++

Hello, coders. Welcome to the codewithrandom blog. In this article, we will learn how to create Hangman Game using C++.

Let us first understand what is the Hangman Game and is its objective.

In the Hangman game, the computer selects a word at random from a list of possible words. The answer is this word was selected randomly. The player then attempts to guess the word one letter at a time. When a user guesses a letter in the response, all instances of that letter are shown to the user. So basically, the game gives the user the option of entering a word to guess, having the computer select a random word from a file, or adding a new word to the file. The user must then guess the word by selecting letters until they either guess the word correctly or run out of guesses.

Creating Advanced Calculator using C++ (Source Code)

What is the advantage of the Hangman game?

The Hangman game provides a challenge that encourages the students to predict words depending on the subject given. It’s a great way to practice spelling, enhance your vocabulary, and keep your attention on the teaching and learning process moving forward.

Overview of the UI:

*********** HANGMAN IN C++ ***********
(E)please Enter a word
(C) Computer chooses a word
(A)Add a new word to list
(Q) Quit
Enter your choice (E – C – Q):
Then the user continues to play the game as per their choice of selection from the options.

Hangman Game Source code:

The Hangman Man game is easy to code. It is a simple game created using the C++ programming language in this project. You can directly use this code by copying it into your IDE to understand the work and then can create the project.

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <fstream>
#include <cstring>

using namespace std;

inline void type_of_word(char f);


int main()
{   char c,h,ch,ch1,ch2;
    char word[25];
    char word2[25];

    int l,i,ng,n,k,x;

do{
    do{
        c='\0';
        cout<<"\n\t\t    *********** HANGMAN IN C++ ***********\n\n";

        cout<<"(E)please Enter a word\n\n(C) Computer chooses word\n\n(A)";
        cout<<"Add new word to list\n\n(Q) Quit\n\n\nEnter your choice (E - C - Q): ";
        cin>>ch2;
       }while (ch2!='C' && ch2!='c' && ch2!='E' && ch2!= 'e' &&
                ch2!='Q' && ch2!= 'q'&& ch2!='A' && ch2!= 'a');
    if (ch2 == 'Q' || ch2=='q')  exit (0);

    if (ch2 == 'C' || ch2=='c')

    {
        ifstream fin("hangword.txt");
        if(!fin) {
        cout<<"File missing, aborting.\n\nYou are missing a file of name";
        cout<<"**hangword.txt**\n\nLocate it, then place it next to the program file.\n\n";
        system("pause"); return 0;}
        for (i=0;!fin.eof();i++)   fin.getline(word,25);
        fin.close();

        do {
        x=rand();
        }while(x>i || x<0);

        ifstream finn("hangword.txt");
        for (i=0;!finn.eof();i++)
        {finn>>c; finn.getline(word,25); if (x==i) break;}
        finn.close();
    }

  if (ch2 == 'A' || ch2=='a')

    {
        ofstream fout("hangword.txt",ios::app);
        if(!fout) {//clrscr();
        cout<<"File missing, aborting.\n\nYou are missing a file of name"
        " **hangword.txt**\n\nLocate it, then place it next to the program"
        " file.\n\n"; system("pause"); return 0;}
        cin.get();
        cout<<"Choose the topic of your word\n\n(M) Movie\n\n(A) Animal\n\n(P)"
        " Sport\n\n(S) Song\n\nEnter your choice (A-P-S-M) : ";
        cin>>h;
        cin.get();
        //clrscr();
        cout<<"\n\nThe word should not exceed 25 letters\n\nEnter the word : ";
        cin.getline(word,25);
        fout<<h<<word<<endl;
        fout.close();

    }


   if (ch2 == 'E' || ch2=='e')
     {// clrscr();
       cin.get();
       cout<<"\t\t\t Type the word :  ";
       cin.getline (word, 25);
     }
 if (ch2 == 'E' || ch2=='e' || ch2 == 'C' || ch2=='c')
{
l=strlen(word);
char choosen[25]="\0";
n=0;k=0;

 for(i=0;i<=24;i++)
   {
    if (word[i]=='\0') {word2[i]='\0';break;}
    if (word[i]==' ')  {word2[i]=' ';  n++;}
    if (word[i]!=' ')  word2[i]='-';
   }
ng=l+2-n;     //only 2 guesses extra
   do{
   there:  type_of_word(c);
     if (k!=0)  cout<<"\n\n\t\t\tChoosen letters : "<<choosen<<"\n";
     cout<<"\n\n\n\t\t\t      "<<word2<<"\n\n\nYou have "<<ng
     << " guesses left, choose a letter : ";
     cin>>ch; cin.get();
     for (i=0;i<25;i++) if (choosen[i]==ch) {//clrscr();
     cout<<"\a\t\t     !!You have choosen "<<ch<<" already!!\n";goto there;}
     ng--; choosen [k]=ch; choosen [k+1]=',';k+=2;

     for (i=0;i<=24;i++)
     if (word[i]==ch || word[i]==ch+32 || word[i]==ch-32) word2[i]=ch;
     if (!strcmpi (word2,word)) {cout<<"\n\t\t\t      "<<strupr(word)
     <<"\n\n\t\t\tCongratulations  :-()\n"; break;}

    }while(ng>0 || !strcmpi (word2,word));


if (strcmpi (word2,word))  cout<<"\nSorry, maybe next time.\n\nThe word was : "
<<strupr(word)<<endl;
}

cout<<"\nWould you like to play again??? (Y - N) : ";
cin>>ch1;  cin.get();

}while (ch1=='y' || ch1=='Y');
      system("PAUSE");
      return 0;
}

inline void type_of_word(char f)

{    if (f=='m') cout<<"\t\t\t\tMOVIE";
     if (f=='a') cout<<"\t\t\t\tANIMAL";
     if (f=='p') cout<<"\t\t\t\tSPORT";
     if (f=='s') cout<<"\t\t\t\tSONG";
}

// End of Code

Now let us understand the code:-

  • After writing the header of the code with the required libraries for input and output operations, string operations, and file operations. Header files are as follows – <iostream>, <cstdlib, <cstdio>, <fstream>, <cstring>.
  • Now we will define an inline function called ‘type_of_word’ which takes a char type variable as a parameter. It displays the matching category of the word that the user has guessed.
  • The main() function will start by initializing some char type variables and arrays which will be used throughout the code. It uses a do-while loop which allows the user to play multiple games. Another do-while loop is used inside the do-while loop which will allow the user to select between inputting a word, letting the computer choose a word, adding a new word, or exiting the game. The program will quit if the user decides to quit.
  • If the user selects (C) option – Computer chooses word, the program will just read from a file of words and then select a random word from it.
  • If the user selects (A) Add new word to list, the program asks for the word and its category before adding it to the word file. If the user choose to enter a word, they are prompted to do so.
  • Now after the selection/input of a word, the program starts a loop where the user is invited to guess a letter. Then checks to see if the letter is in the word and, if so, replaces it with the guessed letter. It also counts the amount of answers given by the user and displays the hangman appropriately.
  • The program shows a congratulating message for the user if they correctly guess the term. When the user’s guesses run out, the program shows the right word.
  • Finally, the program asks user if they would like to play again and restarts the loop if they choose to play again. The program ends with a system(“PAUSE”); statement that waits for a user input before exiting.
  • This sums up our project of Hangman Game using C++.\

Creating an Employee Database Management project using C++

Output Of Hangman Game:-

Here is an example to show how the Hangman game works

Hangman Game in C++

Selecting option (E).

Hangman Game in C++

Now we will have 5 guesses to guess the letters of the word.

Hangman Game in C++

Hangman Game in C++

Build Tic Tac Toe Game Code in C++ Using Array

Conclusion:-

We have reached the end of this article and have many more projects in C++ coming so stay tuned. We have started with awesome and fun projects for you all to understand C++. Learning C++ by creating fun projects makes learning easy and interesting.

If you enjoyed the article and learned something new today, let us know in the comments.

Thank you.

Happy Reading! 🙂



Leave a Reply