In: Computer Science
/* Below is the modified program of yours with added feature of polymorphism and inheritance. Polymorphism because the function checkGuess () is overloaded because it is declared in base as well as derived class and inheritance is used because a base class is derived in derive class */
#include <iostream>
#include <cstdlib>
#include<ctime>
#include <string>
using namespace std;
class Base {
public:
int checkGuess (){}
int NUM_TRY=8;
string message = "Play!";
};
class Derived: public Base //inheritance
{
public:
int checkGuess (char guess, string secretword, string
&guessword) // polymorphism
{
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(int NUM_TRY,string message)
{
cout<<"\nHangman Game!";
cout << "\nYou have " << NUM_TRY << " tries to
try and guess the word.";
cout<<"\n"+message;
}
};
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;
}
int main()
{string name;
char letter;
string word;
Derived d=Derived();
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');
while (d.NUM_TRY!=0)
{
d.main_menu(d.NUM_TRY,d.message);
cout << "\n" << hide_m;
cout << "\nGuess a letter: ";
cin >> letter;
if (d.checkGuess(letter, word, hide_m)==0)
{
d.message = "Wrong letter.";
d.NUM_TRY = d.NUM_TRY - 1;
}
else
{
d.message = "NICE! You guessed a letter";
}
if (word==hide_m)
{
d.message = "Congratulations! You got it!";
cout << "\nThe word is : " << word << endl;
break;
}
}
if(d.NUM_TRY == 0)
{
d.message = "NOOOOOOO!...you've been hanged.";
d.main_menu(d.NUM_TRY,d.message);
cout << "\nThe word was : " << word <<
endl;
}
cin.ignore();// used to discard everything in the input
stream
cin.get();
return 0;
}