(Game: hangman) Write a hangman game that randomly generates a word and prompts
ID: 3592759 • Letter: #
Question
(Game: hangman) Write a hangman game that randomly generates a word and prompts the user to guess one letter at a time, as shown in the sample run. Each letter in the word is displayed in an asterisk. When the user makes a correct guess, the actual letter is then displayed. When the user finishes a word, display the number of misses and ask the user whether to continue for another word. Declare an array to store words, as follows // Use any words you wish string words[] = {"write", "that", ); The following is a sample run: (Guess) Enter a letter in word ****> p (Guess) Enter a letter in word pr*r** p p is already in the word (Guess) Enter a letter in word pr**r**> o (Guess) Enter a letter in word pro*g (Guess) Enter a letter in word progr** n n is not in the word (Guess) Enter a letter in word progn**m (Guess) Enter a letter in word progr*m> a The word is program. You missed 1 time Do you want to guess for another word? Enter y or n>Explanation / Answer
#include<iostream>
#include<string>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main(){
string a[] = { "happy", "sad","action","thrill","open","close","green","blue","apple","orange"};
srand(time(NULL));
string ch;
string guess = "";
int ind = rand()%10;
string data = "" ;
for (int i = 0; i<a[ind].size(); i++)
data = data + "*";
int count = 0;
while(1){
while(1) {
cout << "(Guess) Enter a letter in word "<< data << " > ";
cin >> ch;
count++;
int miss_count = 0;
for (int i = 0; i<a[ind].size(); i++){
int found = 0;
if (a[ind][i] == ch[0]){
found = 1;
if (data[i] != ch[0])
data[i] = ch[0];
else
cout << ch[0] << " is already in the word. " << endl;
}
if (found == 0)
miss_count++;
}
if (data == a[ind]){
cout << "The word is " << data << ". You missed " << miss_count << " time" << endl;
break;
}
}
cout << "Do you want to guess for another word? enter y or n>";
cin >> ch;
if (ch[0] == 'n')
break;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.