Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1.Write a bool function, answerIsYes, that prompts the user to answer a question

ID: 3620993 • Letter: 1

Question



1.Write a bool function, answerIsYes, that prompts the user to answer a question. The question is the function’s constant string reference parameter. The parameter’s default value is “Is your answer‘Yes’?”. The function returns true if the user enters ‘y’, ‘ye’ or ‘yes’ using any combination of upper and lower case letters. The function returns false otherwise.



2.Rewrite Hangman’s main function to use the answerIsYes function appropriately.



3.The nextInt functions are overloaded functions. Note that the one-parameter nextInt function appears in the definition of two-parameter nextInt function. Further note that the no-parameter nextInt function does not appear in the definition of the one-parameter nextInt function. Rewrite the one-parameter nextInt function to use no-parameter nextInt function.



4.The readGuessFromUser does not work very well if the user enters a guess that contains more than one character or is not a letter of the alphabet. Modify the function to explicitly reject any character that is not a letter of the alphabet.



5.The getRandomSecretWord function reads the secret word file two times. The first time counts the number of words in the secret word file and the second time reads the secret word. The program would run a little faster if the program counted the number of words in the secret word file only once. Divide the function into two functions – getNumberOfSecretWords that gets the number of words in the secret word file and getRandomSecretWord that gets a random word from the secret word file. Call getNumberOfSecretWords once and call getRandomSecretWords as many times as needed.



6.The function, computeMaximumWrongGuessCount unconditionally returns the length of the secret word as the maximum wrong guess count. Rewrite the function to give more guesses to very short guesses and fewer guesses to very long words. For example, the maximum wrong guess count for words very short words can be a multiple of the word length; the maximum wrong guess count for very long words can be a fraction of the word length and the maximum wrong guess count for words of moderate length can be the word length.





---------------------------------------

#include <cassert>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <time.h>

using namespace std;

const string empty_string = "";

//hangMan prototypes
string getRandomSecretWord(const string& = "secretwords.txt");
void playHangman(const string&);
string buildMask(int, char = '*');
int computeMaximumWrongGuessCount(const string&);
char readGuessFromUser(const string&);
int countOccurences(char, const string&);
void updateMask(char, const string&, string&);

//random prototypes
void init(unsigned);
void init();
int nextInt();
int nextInt(int);
int nextInt(int, int);

//string prototypes
string trim(const string&);
string toupper(const string&);

int main(int argc, char* argv[])
{
    init();//initialize random number generator

    cout << "Do you want to play hangman? ";
    string answer;
    cin >> answer;
    answer = trim(answer);
    answer = toupper(answer);
    while(answer[0] == 'Y')
    {
        string random_secret_word = getRandomSecretWord();
        playHangman(random_secret_word);
        cout << "Do you want to play hangman? ";
        cin >> answer;
        answer = trim(answer);
        answer = toupper(answer);
    }
    return 0;
}
string getRandomSecretWord(const string& file_name)
{
    ifstream secret_words;
    secret_words.open(file_name.c_str());
    assert(secret_words);
    int secret_word_counter = 0;
    string secret_word;
    secret_words >> secret_word;
    while(!secret_words.eof())
    {
        secret_word_counter++;
        secret_words >> secret_word;
    }
    secret_words.close();
    secret_words.clear();
    int secret_word_number = nextInt(1, secret_word_counter);
    secret_words.open(file_name.c_str());
    assert(secret_words);
    for(int counter = 1; counter <= secret_word_number; counter++)
        secret_words >> secret_word;
    secret_words.close();
    return secret_word;
}
void playHangman(const string& original_secret_word)
{
    string secret_word = trim(original_secret_word);
    int secret_word_length = secret_word.length();
    assert(secret_word_length > 0);
    secret_word = toupper(secret_word);
    string mask = buildMask(secret_word_length);
    cout << mask << endl;
    int maximum_wrong_guess_count = computeMaximumWrongGuessCount(secret_word);
    string already_guessed_list = empty_string;
    int wrong_guess_count = 0;
    int right_guess_count = 0;
    do
    {
        char guess = readGuessFromUser(already_guessed_list);
        int n_occurences = countOccurences(guess, secret_word);
        if(n_occurences > 0)
        {
            right_guess_count = right_guess_count + n_occurences;
            already_guessed_list = already_guessed_list + guess;
            updateMask(guess, secret_word, mask);
            cout << mask << endl;
            if(n_occurences == 1)
                cout << guess << " appears 1 time in the secret word" << endl;
            else
                cout << guess << " appears " << n_occurences << " times in the secret word" << endl;
        }
        else
        {
            wrong_guess_count = wrong_guess_count + 1;
            already_guessed_list = already_guessed_list + guess;
            cout << guess << " did not appear in the secret word" << endl;
        }
    }
    while(wrong_guess_count <= maximum_wrong_guess_count &&
           right_guess_count < secret_word_length);

    if(right_guess_count == secret_word_length)
        cout << "You guessed the secret word" << endl;
    else
        cout << "You did not guess the secret word, "
             << secret_word << endl;
}
string buildMask(int word_length, char mask_char)
{
    string mask = empty_string;
    for(int counter = 0; counter < word_length; counter++)
        mask = mask + mask_char;
    return mask;
}
int computeMaximumWrongGuessCount(const string& parameter_word)
{
    string word = trim(parameter_word);
    int word_length = word.length();
    assert(word_length > 0);
    return word_length;
}
char readGuessFromUser(const string& already_guessed_list)
{
    cout << "Please enter a guess: ";
    char guess;
    cin >> guess;
    guess = toupper(guess);
    while(already_guessed_list.find(guess) != -1)
    {
    cout << "You already guessed " << guess << endl;
    cout << "Please enter a guess: ";
    cin >> guess;
    guess = toupper(guess);
    }
    return guess;
}
int countOccurences(char guess, const string& secret_word)
{
    int n_occurences = 0;
    int guess_pos = secret_word.find(guess);
    while(guess_pos != -1)
    {
        n_occurences++;
        guess_pos = secret_word.find(guess, guess_pos + 1);
    }
    return n_occurences;
}
void updateMask(char guess, const string& secret_word, string& mask)
{
    int guess_pos = secret_word.find(guess);
    while(guess_pos != -1)
    {
        mask[guess_pos] = guess;
        guess_pos = secret_word.find(guess, guess_pos + 1);
    }
}
//string functions
string toupper(const string& original)
{
string edited = empty_string;
int length = original.length();
for(int index = 0; index < length; index = index + 1)
{
    char symbol = original[index];
    if(islower(symbol))
       symbol = toupper(symbol);
    edited = edited + symbol;
}
return edited;
}
string trim(const string& original)
{
string trimmed = empty_string;
int left = 0;
int right = original.length() - 1;
while(left <= right && isspace(original[left]))
    left = left + 1;
while(left <= right && isspace(original[right]))
    right = right - 1;
if(left <= right)
     trimmed = original.substr(left, right - left + 1);
return trimmed;
}
//random functions
void init()
{
    srand(unsigned(time(NULL)));
}
void init(unsigned seed)
{
    srand(seed);
}
int nextInt()
{
    return rand();
}
int nextInt(int upper_bound)
{
    assert(upper_bound > 0);
    return rand() % upper_bound;
}
int nextInt(int lower_bound, int upper_bound)
{
    if(lower_bound > upper_bound)
    {
        int t = lower_bound;
        lower_bound = upper_bound;
        upper_bound = t;
    }
    int range = upper_bound - lower_bound + 1;
    int next_int = nextInt(range) + lower_bound;
    return next_int;
}

Explanation / Answer

I took the code and modified the changes per each request. I made comments throughout the code explaining what I changed and why. If you have any questions let me know.

 

 

#include <cassert>#include <iostream>#include <fstream>#include <string>#include <stdio.h>#include <time.h> using namespace std; const string empty_string = "";int secret_word_counter = 0;//Use of this global variable for part 5 may not be allowed //hangMan prototypes//string getRandomSecretWord(const string& = "secretwords.txt");string getRandomSecretWords(const string& = "secretwords.txt");int getNumberOfSecretWords(const string& = "secretwords.txt");void playHangman(const string&);string buildMask(int, char = '*');int computeMaximumWrongGuessCount(const string&);char readGuessFromUser(const string&);int countOccurences(char, const string&);void updateMask(char, const string&, string&); //random prototypesvoid init(unsigned);void init();int nextInt();int nextInt(int);int nextInt(int, int); //string prototypesstring trim(const string&);string toupper(const string&);
//Part 1 Implementedbool answerIsYes(string answer){ bool answerIsYes = false; answer = trim(answer);    answer = toupper(answer); if(answer[0] == 'Y') { answerIsYes = true; } else answerIsYes = false; return answerIsYes;}
int main(int argc, char* argv[]){    init();//initialize random number generator     cout << "Do you want to play hangman? ";    string answer; //Part 2 Impletemented - the trim and toupper functions are handled within the answerIsYes function bool answeredYes = false;    cin >> answer; answeredYes = answerIsYes(answer); if(answeredYes) //if statement added here outside of the while loop so that the getNumberOfSecretWords() is called only once since it doesnt change. { secret_word_counter = getNumberOfSecretWords(); }    while(answeredYes != false)    { string random_secret_word = getRandomSecretWords(); //new random word function added.        //string random_secret_word = getRandomSecretWords(); //old function commented out        playHangman(random_secret_word);        cout << "Do you want to play hangman? ";        cin >> answer; //Part 2 Impletemented - handles multiple games        answeredYes = answerIsYes(answer);    }    return 0;}int getNumberOfSecretWords(const string& file_name){ ifstream secret_words;    secret_words.open(file_name.c_str());    assert(secret_words);    int secret_counter = 0; string secret_word;    secret_words >> secret_word;    while(!secret_words.eof())    {        secret_counter++; secret_words >> secret_word;    } return secret_counter;}string getRandomSecretWords(const string& file_name){ ifstream secret_words;    secret_words.open(file_name.c_str());    assert(secret_words); string secret_word; while(!secret_words.eof())    {        secret_words >> secret_word;    } secret_words.close();    secret_words.clear(); int secret_word_number = nextInt(1, secret_word_counter);    secret_words.open(file_name.c_str());    assert(secret_words);    for(int counter = 1; counter <= secret_word_number; counter++)    secret_words >> secret_word;    secret_words.close(); return secret_word;}//string getRandomSecretWord(const string& file_name)//{//    ifstream secret_words;//    secret_words.open(file_name.c_str());//    assert(secret_words);//    int secret_word_counter = 0;//    string secret_word;//    secret_words >> secret_word;//    while(!secret_words.eof())//    {//        secret_word_counter++;//        secret_words >> secret_word;//    }//    secret_words.close();//    secret_words.clear();//    int secret_word_number = nextInt(1, secret_word_counter);//    secret_words.open(file_name.c_str());//    assert(secret_words);//    for(int counter = 1; counter <= secret_word_number; counter++)//        secret_words >> secret_word;//    secret_words.close();//    return secret_word;//}void playHangman(const string& original_secret_word){    string secret_word = trim(original_secret_word);    int secret_word_length = secret_word.length();    assert(secret_word_length > 0);    secret_word = toupper(secret_word);    string mask =  buildMask(secret_word_length);    cout << mask << endl;    int maximum_wrong_guess_count = computeMaximumWrongGuessCount(secret_word);    string already_guessed_list = empty_string;    int wrong_guess_count = 0;    int right_guess_count = 0;    do    {        char guess = readGuessFromUser(already_guessed_list);        int n_occurences = countOccurences(guess, secret_word);        if(n_occurences > 0)        {            right_guess_count = right_guess_count + n_occurences;            already_guessed_list = already_guessed_list + guess;            updateMask(guess, secret_word, mask);            cout << mask << endl;            if(n_occurences == 1)                cout << guess << " appears 1 time in the secret word" << endl;            else                cout << guess << " appears " << n_occurences << " times in the secret word" << endl;        }        else        {            wrong_guess_count = wrong_guess_count + 1;            already_guessed_list = already_guessed_list + guess;            cout << guess << " did not appear in the secret word" << endl;        }    }    while(wrong_guess_count < maximum_wrong_guess_count && //changed to less than instead of <= for the wrong guess count since the condition is checked after the loop. If this were a while loop instead of a do-while the <= could have stayed.           right_guess_count < secret_word_length);     if(right_guess_count == secret_word_length)        cout << "You guessed the secret word" << endl;    else        cout << "You did not guess the secret word, "              << secret_word <<  endl;}string buildMask(int word_length, char mask_char){    string mask = empty_string;    for(int counter = 0; counter < word_length; counter++)        mask = mask + mask_char;    return mask;}int computeMaximumWrongGuessCount(const string& parameter_word){    string word = trim(parameter_word); int max_guess = 0;    int word_length = word.length();    assert(word_length > 0); if(word_length < 5) { max_guess = word_length * 2; // For words less than 5 characters long it allows double the amount of guesses i.e. cat = 6 guesses } else if(word_length >=5 && word_length <= 10) { max_guess = word_length; //for medium sized words 5-10 chars, the word length is the max no. of guesses. i.e. happy = 5 guesses } else { max_guess = word_length / 2; //for longer words half the length of the word(rounded down) are allowed. i.e. typewritter = 5 guesses }    return max_guess;}char readGuessFromUser(const string& already_guessed_list){    cout << "Please enter a guess: ";    char guess; bool validEntry = false; //Added to ensure a valid letter is entered    cin >> guess; while(validEntry != true){//Loops until a letter of the alphabet is entered if(isalpha(guess)){ //Built in function for determining whether or nor a character is part of the alphabet validEntry = true; guess = toupper(guess); } else { cout << "Entry was not part of the alphabet. Try again." << endl; cin >> guess; } }     while(already_guessed_list.find(guess) != -1)    {      cout << "You already guessed " << guess << endl;      cout << "Please enter a guess: ";      cin >> guess;      guess = toupper(guess);    }    return guess;}int countOccurences(char guess, const string& secret_word){    int n_occurences = 0;    int guess_pos = secret_word.find(guess);    while(guess_pos != -1)    {        n_occurences++;        guess_pos = secret_word.find(guess, guess_pos + 1);    }    return n_occurences;}void updateMask(char guess, const string& secret_word, string& mask){    int guess_pos = secret_word.find(guess);    while(guess_pos != -1)    {        mask[guess_pos] = guess;        guess_pos = secret_word.find(guess, guess_pos + 1);    }}//string functionsstring toupper(const string& original){  string edited = empty_string;  int length = original.length();  for(int index = 0; index < length; index = index + 1)  {    char symbol = original[index];    if(islower(symbol))       symbol = toupper(symbol);    edited = edited + symbol;  }  return edited;}string trim(const string& original){  string trimmed = empty_string;  int left = 0;  int right = original.length() - 1;  while(left <= right && isspace(original[left]))    left = left + 1;  while(left <= right && isspace(original[right]))    right = right - 1;  if(left <= right)     trimmed = original.substr(left, right - left + 1);  return trimmed;}//random functionsvoid init(){    srand(unsigned(time(NULL)));}void init(unsigned seed){    srand(seed);}int nextInt(){    return rand();}int nextInt(int upper_bound){    assert(upper_bound > 0); //Part 3 Implemented. Normally the random number was created in the return.  //Instead replace the rand() with the nextInt function call which does the same thing.    return nextInt() % upper_bound; }int nextInt(int lower_bound, int upper_bound){    if(lower_bound > upper_bound)    {        int t = lower_bound;        lower_bound = upper_bound;        upper_bound = t;    }    int range = upper_bound - lower_bound + 1;    int next_int = nextInt(range) + lower_bound;    return next_int;}

 

If you have time to use my code, please have time to rate.