Question: You will design a program in C++ that plays hangman
using classes (polymorphism and inheritance)....
Hangman Game
CODE:
#include <iostream>
#include <cstdlib>
#include<ctime>
#include <string>
using namespace std;
int NUM_TRY=8; //A classic Hangman game has 8 tries. You can
change if you want.
int checkGuess (char, string, string&); //function to
check the guessed letter
void main_menu();
string message = "Play!"; //it will always display
int main(int argc, char *argv[])
{
string name;
char letter;
string word;
string words[] = //These are the list of 10 three lettered
words.
{ //You can change them as per your requirement.
"man",
"van",
"tan",
"hop",
"pop",
"two",
"six",
"may",
"low",
"out",
};
srand(time(NULL));
int n=rand()% 10; //Random function to genterate random words
from the given list
word=words[n];
string hide_m(word.length(),'X'); // This function is used to
hide the actuall word to be guessed.
//The mask selected is 'X' so the word will show as 'XXX' till
you guess the correct letters.
while (NUM_TRY!=0)
{
main_menu();
cout << "\n" << hide_m;
cout << "\nGuess a letter: ";
cin >> letter;
if (checkGuess(letter, word, hide_m)==0)
{
message = "Wrong letter.";
NUM_TRY = NUM_TRY - 1;
}
else
{
message = "NICE! You guessed a letter";
}
if (word==hide_m)
{
message = "Congratulations! You got it!";
main_menu();
cout << "\nThe word is : " << word <<
endl;
break;
}
}
if(NUM_TRY == 0)
{
message = "NOOOOOOO!...you've been hanged.";
main_menu();
cout << "\nThe word was : " << word <<
endl;
}
cin.ignore();// used to discard everything in the input
stream
cin.get();
return 0;
}
int checkGuess (char guess, string secretword, string
&guessword)
{
int i;
int matches=0;
int len=secretword.length();
for (i = 0; i< len; i++)
{
if (guess == guessword[i])
return 0;
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
void main_menu()
{
system("cls");
cout<<"\nHangman Game!";
cout << "\nYou have " << NUM_TRY << " tries
to try and guess the word.";
cout<<"\n"+message;
}
//*end of code*
So here is the code of the Hangman guessing game.