Question

In: Computer Science

in c++ please In this program you are going to have several files to turn in...

in c++ please

In this program you are going to have several files to turn in (NOT JUST ONE!!)

  • hangman.h – this is your header file – I will give you a partially complete header file to start with.
  • hangman.cpp – this is your source file that contains your main function
  • functions.cpp – this is your source file that contains all your other functions
  • wordBank.txt – this is the file with words for the game to use.  You should put 10 words in this text file.

COMPILE THIS WAY:
g++ -Wall -std=c++11 hangman.cpp functions.cpp –o hangman

PROGRAM DESCRIPTION:

You will create a C++ program that will allow the user to play the game Hangman.  Hangman is traditionally a paper & pencil game.  One player thinks of a word and the other player tries to guess it by suggesting letters that may be in the word.  Your program will be player one, by pulling a word from a “word bank” and then player two is the user of your program.  The game is over when one of two things happen:

  • The user correctly completes the word.
  • The user incorrectly guesses a letter six times.

ARRAYS

You will have four arrays.  Three of the arrays will be C-Strings (NOT C++ STRING CLASS STRINGS!!!).  

  • Character array of size 21 (20 characters plus one null-terminator) that will hold the word read in from the “word bank”.  You may assume that the game only plays with words, not phrases.  (No spaces).
    char word[21];
  • Character array of size 21 (20 characters plus one null-terminator) that will at first hold all underscores.  Then, as the user makes correct guesses, the underscores will be replaced with the correct letters.  This means you will have to assign each element to an underscore ‘_’  before the user starts to make any guesses.
    char underScores[21];
  • Character array of size 27 (26 characters plus one null-terminator).  Initialize this array when you define it to all the uppercase letters in the alphabet.  “ABCDEFGHIJKLMNOPQRSTUVWXYZ”.  
    char alphabet[27] = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
  • Boolean array of size 26 (26 boolean values).  This array will have a true/false toggle for each letter of the alphabet.  If the user has guessed the letter B, then this array at element 1 will have the value of true.  Assign false to each element before the user starts to make any guesses.  
    bool userGuesses[26];

WORD BANK

You will have to create an input file called wordBank.txt.  You need to manually type in TEN or more words to this file.  Your program will not be outputting to this file.  wordBank.txt will be used as an input file only.  Here is one of my wordBank.txt files to see what I mean.  Please do not use my words – make up your own!

FUNCTION:  INT MAIN()

  • Open the input file wordBank.txt.  If the file can’t open, print out a message that a word could not be found in the word bank.
  • Allow the user to play this game (run the program) multiple times.  

SETTING UP FOR THE GAME

  • Set all the elements of the userGuesses array to false
  • Using a loop, set all elements of the underScores array to the underscore character ‘_’.  
  • Set the stage variable to zero (the starting stage)
  • Read in a word from the input file (get the word) – make sure that if the user runs the program multiple times that they get a different word each time from the file.

GAME PLAY

  • While the game has not ended (user is not at stage 6 yet and they have not guessed the word), then do the following:
    • Call the printWord function sending the word array and the underScores array as arguments.
    • Call the printStage function sending the stage variable as an argument.
    • Call the printLettersGuessed function sending the userGuesses array and alphabet array as arguments.
    • Ask the user for their guess.  If it is a lowercase letter, then you need to make it an uppercase letter.  
      cout << “  WHAT LETTER DO YOU GUESS?  “;
      cin >> letter;
      letter = toupper(letter); //the toupper function will make letter uppercase.

      Make sure the letter is not a letter already guessed.  If it is a letter they have already guessed, then force the user to enter in a different letter.  
    • Take the usersGuesses array and make the letter they just guessed true instead of false.  For example, if they guessed the letter ‘C’ then you will need to make usersGuesses[2] = true;
    • Find out if the letter that they guessed is inside the chosen word from the word bank.
      • If the letter guessed is found in the word array, then print out CORRECT! And then put the letter in the underScores array in the same location as the wordFromFile array.
        underScores[x] = word[x];  // where x is an integer incremented by the for loop.
      • If there were no letters found, then print out WRONG!, increment the stage number.  If the stage number is already 6, then call the printStage() function.
      • Tell the user to press enter to continue.
    • Find out if the user has guessed every letter in the word, because if they have, then the game is done and the loop will stop.  
      • Find out the length of the chosen word
        wordLength = strlen(word);
      • Do a special string comparison that will compare two words up to a given length.  The function is strncmp() that you will need to use.  If the chosen word (word array) and theunderScores array match, then the user has guessed the word and the game is over.  Print out a message that the user won the game.

Function:  void printStage(int)

This function will accept as a parameter the current stage and print out the respective diagram to the screen.  Each time the user guesses, a diagram is printed out.  The diagram represents the user being closer and closer to being “hanged” – which is why the game is called Hangman.  At the beginning of the game, the diagram starts at stage 0.  The user will stay at stage 0 (zero) until he or she guesses incorrectly, and then he/she will advance one stage to stage 1.  There are 7 stages (stage 0 to stage 6) to represent the user guessing incorrectly six times.  If the user gets to stage 6, they lose the game.  I have already provided this function for you!

Function:  void printWord(char[], char[])

This function will print out the letters in the word that have already been correctly guessed.  At the beginning of the game, this function should just print out underscores to represent each letter.  This lets the user know how many letters is in the word they are trying to guess.

WORD:  _ _ _ _ _ _ _

Then, as the user guesses a letter, replace the underscore with the letter:

WORD:  W _ _ _ _ _ _

How the function should work:

  • Figure out the length of the character array word (use strlen c-string function)
  • Use a loop to go through as many iterations as the length of word
    • Print out each character of the underScores[] array.  It should be the same length as word.
    • For example, if the word array is ‘R’’A’’V’’E’’N’, then the string length is 5.  Write a for loop that will iterate five times printing out the characters in underScores[] array.  The underScores array may have more than 5 characters in it, but you will only print out 5.

Function:  void printLettersGuessed(bool[], char[])

This function will print out all the letters the user has guessed so far (correct & incorrect).

LETTERS YOU HAVE ALREADY GUESSED:  Q W X Z

How the function should work:

  • Starting at 0, for every element up until 25, if the current element of usersGuesses is true, then output the letter (from the alphabet array) of the same element.  
  • Make sure you print out: “ LETTERS YOU HAVE ALREADY GUESSED:  “ before you print out the letters.

Solutions

Expert Solution

// File Name: Hangman.h
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <ctime>
#define MAXR 10
#define MAXC 40
using namespace std;

// Function to display help
void help();

// Function to read the secret words from the file and stores it in matrix
int readFile(char [][MAXC]);

// Function to generate a random number between 0 and number of words and returns it
int randomSecretWord(int);

// Function to display the guessed characters
void displayGuesses(unsigned char [], int);

// Function to accept and return a guessed character from the user if it is not already guessed
char readGuess(unsigned char [], int);

// Function to reset the guess array for next game
void resetGuesses(unsigned char []);

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

// File Name: HangmanFunctions.cpp
# include "Hangman.h"

// Function to display help
void help()
{
cout<<" WELCOME TO the Hangman Game!\n";
cout<<"\n Please read the following instructions before you play.";
cout<<"\n - You will b presented with a word to be guessed (a secret word of dashes)";
cout<<"\n - Guess letters one at a time";
cout<<"\n - You will have 5 letters guesses.";
cout<<"\n - Each time a letter is guessed,";
cout<<"\n \t if it is in the word it will be placed in the dash word.";
cout<<"\n - The dash word will be presented each time";
cout<<"\n - After guessing 5 letters, you will have the opportunity to to guess the word.";
cout<<"\n HAVE FUN!";
}// End of function

// Function to read the secret words from the file and stores it in matrix
int readFile(char secretWord[][MAXC])
{
// File pointer declared
ifstream fp;
// To store number of words
int len = 0;

// Opens the file for reading
fp.open("wordBank.txt");

// Checks if the file cannot be opened display error message and stop
if(!fp)
{
printf("ERROR: The file cannot be opened for reading");
exit(0);
}// End of if condition

// Loops till end of the file
while(!fp.eof())
{
// Reads a word from file and stores it in len index position
fp>>secretWord[len];

// Increase the record counter by one
len++;
}// End of while loop

// Close the file
fp.close();
// Returns record counter
return len;
}// End of function

// Function to generate a random number between 0 and number of words and returns it
int randomSecretWord(int numberOfWords)
{
return (rand() % (numberOfWords - 0)) + 0;
}// End of function

// Function to display the guessed characters
void displayGuesses(unsigned char guesses[], int index)
{
// Loops variable
int c;
cout<<"\n\n Already guessed characters: ";
// Loops till number of character available in the parameter array guesses
for(c = 0; c < index; c++)
// Displays the current guessed character
cout<<guesses[c]<<" ";
cout<<endl;
}// End of function

// Function to accept and return a guessed character from the user if it is not already guessed
char readGuess(unsigned char guesses[], int index)
{
// Loops variable
int c;
// To store the character guessed by the user
char guess;
// To store character already guessed or not
int success;

// Loops till user enters character not guessed earlier
do
{
// Initializes -1 for not guessed earlier
success = -1;

cout<<"\n Enter a letter you think is in the word: ";
fflush(stdin);

// Accepts a guess character
cin>>guess;

// Converts the character to upper case
guess = toupper(guess);

// Loops till number of character available in the parameter array guesses
for(c = 0; c < index; c++)
{
// Checks if current character is equals to user entered character
if(guesses[c] == guess)
{
// Displays the message
cout<<endl<<guess<<" already guessed.";
// Assigns the loop variable value as found
success = c;
// Come out of the loop
break;
}// End of if condition
}// End of for loop

// Checks if success value is -1 then the character is not available in the parameter
// array guesses (user entered character is not guessed earlier)
if(success == -1)
// Returns the character
return guess;
}while(1);// End of do - while loop
}// End of function

// Function to reset the guess array for next game
void resetGuesses(unsigned char guesses[])
{
// Loops till number of character available in the parameter array guesses
for(int c = 0; c < 26; c++)
// Resets each index position to null
guesses[c] = ' ';
}// End of function
-------------------------------------------------------------------------------------------------------------------------

// File Name: HangmanMain.cpp
#include "HangmanFunctions.cpp"

// main function definition
int main()
{
// Use current time as seed for random generator
srand(time(NULL));
// To store user choice to continue play or not
char choice;
// To store guess letter entered by the user
char guess;
// Creates a secret word
char secretWord [MAXR][MAXC];

// Counter for how many success guess tries made
int successTries = 0;
// Counter for current guess letter
int currentLetters = 1;
// To store success or failure
int success;
// Counter for number of attempts made
int totalAttempt = 0;
// Index position for the character guessed by the user
int index;
// Calls the function to display help
help();
// Defines a character array to store the character guessed by the user
unsigned char guesses[26];
// Calls the function to read file and stores the words in matrix
// Return value as number of words stored
int numberOfWords = readFile(secretWord);
// Loops variable
int c;

// Loops till user choice is not 'N' or 'n'
do
{
// Calls the function to reset the already guessed character array to null
resetGuesses(guesses);
// Calls the function to generate random number between 0 and number of words
int pos = randomSecretWord(numberOfWords);
// Stores the length of the secret word at generated random index position
int len = strlen(secretWord[pos]);
// Creates user guess word of
char userGuess [len];
cout<<"\n Secret: "<<secretWord[pos];
int unsuccess = 0;
// Loops till length of the secret word and assigns '-'
for(c = 0; c < len; c++)
userGuess[c] = '-';
// Assigns null character at the end
userGuess[c] = '\0';

// Displays user guess current status
cout<<"\n ----------------------------------------------------";
cout<<"\n Let's begin, you will be entering 5 letters one by one";
cout<<"\n\t "<<userGuess;

// Sets the number of success tries, total attempts and current letter to 0 for each play
successTries = 0;
totalAttempt = 0;
currentLetters = 0;
index = 0;

// Loops till guessed all letters of the word
do
{
// Initializes success to 0 for not success for each letter guessed
success = 0;
// Increase the number of attempts by one
totalAttempt++;
// Displays which letter number
cout<<"\n (This is letter "<<currentLetters<<")";

// Calls the function to guess a character
guess = readGuess(guesses, index);
// Stores the guessed character
guesses[index++] = guess;
// Calls the function to display already guessed characters
displayGuesses(guesses, index);
cout<<"\n ******************************************** \n";
// Loops 6 times
for (c = 0; c < len; c++)
{
// Checks if the guess character is equals to current character of secret word
if (guess == secretWord[pos][c])
{
// Assigns the guess character at c index position of user guess array
userGuess[c] = guess;
// Set the success to 1
success = 1;
// Increase the success tries by one
successTries++;
// Increase the current letters by one
currentLetters++;
}// End of if condition
}// End of for loop

// Checks if success value is one then rightly guessed the character
if(success == 1)
cout<<"\n The letter %c is in the word! "<<guess;
// Otherwise guess character is wrong
else
{
cout<<"\n The letter %c is not in the word! "<<guess;

// Increase the counter by one
cout<<"\n Your unsuccess attempt: "<<++unsuccess;
}// End of else

cout<<"\n ******************************************** \n";

// Displays current user guess status array
cout<<"\n Here are the letters guessed so far: \n\t"<<userGuess;
// Checks if unsuccess is greater than 5 then come out of the loop
if(unsuccess > 5)
break;
}while(successTries < len); // Loops till number of success tries is less than length

// Displays total number of attempt made by the user to guess the word
cout<<"\n Your total attempt = "<<totalAttempt;

fflush(stdin);
// Accepts user choice to play again or not
cout<<"\n\n Would you like to play another game (Y/ N): ";
cin>>choice;

// Checks if user choice is 'N' or 'n' then stop
if(choice == 'N' || choice == 'n')
break;
}while(1); // End of do - while loop
}// End of main function

Sample Output:

WELCOME TO the Hangman Game!

Please read the following instructions before you play.
- You will b presented with a word to be guessed (a secret word of dashes)
- Guess letters one at a time
- You will have 5 letters guesses.
- Each time a letter is guessed,
if it is in the word it will be placed in the dash word.
- The dash word will be presented each time
- After guessing 5 letters, you will have the opportunity to to guess the word.
HAVE FUN!
Secret: DEMO
----------------------------------------------------
Let's begin, you will be entering 5 letters one by one
----
(This is letter 0)
Enter a letter you think is in the word: y


Already guessed characters: Y

********************************************

The letter %c is not in the word! Y
Your unsuccess attempt: 1
********************************************

Here are the letters guessed so far:
----
(This is letter 0)
Enter a letter you think is in the word: w


Already guessed characters: Y W

********************************************

The letter %c is not in the word! W
Your unsuccess attempt: 2
********************************************

Here are the letters guessed so far:
----
(This is letter 0)
Enter a letter you think is in the word: z


Already guessed characters: Y W Z

********************************************

The letter %c is not in the word! Z
Your unsuccess attempt: 3
********************************************

Here are the letters guessed so far:
----
(This is letter 0)
Enter a letter you think is in the word: e


Already guessed characters: Y W Z E

********************************************

The letter %c is in the word! E
********************************************

Here are the letters guessed so far:
-E--
(This is letter 1)
Enter a letter you think is in the word: x


Already guessed characters: Y W Z E X

********************************************

The letter %c is not in the word! X
Your unsuccess attempt: 4
********************************************

Here are the letters guessed so far:
-E--
(This is letter 1)
Enter a letter you think is in the word: m


Already guessed characters: Y W Z E X M

********************************************

The letter %c is in the word! M
********************************************

Here are the letters guessed so far:
-EM-
(This is letter 2)
Enter a letter you think is in the word: d


Already guessed characters: Y W Z E X M D

********************************************

The letter %c is in the word! D
********************************************

Here are the letters guessed so far:
DEM-
(This is letter 3)
Enter a letter you think is in the word: p


Already guessed characters: Y W Z E X M D P

********************************************

The letter %c is not in the word! P
Your unsuccess attempt: 5
********************************************

Here are the letters guessed so far:
DEM-
(This is letter 3)
Enter a letter you think is in the word: m

M already guessed.
Enter a letter you think is in the word: v


Already guessed characters: Y W Z E X M D P V

********************************************

The letter %c is not in the word! V
Your unsuccess attempt: 6
********************************************

Here are the letters guessed so far:
DEM-
Your total attempt = 9

Would you like to play another game (Y/ N): n


Related Solutions

Code in C++ please You are going to write a program for Computer test which will...
Code in C++ please You are going to write a program for Computer test which will read 10 multiple choice questions from a file, order them randomly and provide the test to the user. When the user done the program must give the user his final score
in C++ For this program, you are going to implement a stack using an array and...
in C++ For this program, you are going to implement a stack using an array and dynamic memory allocation. A stack is a special type of data structure that takes in values (in our case integers) one at a time and processes them in a special order. Specifically, a stack is what's called a first-in-last-out (FILO) data structure. That is to say, the first integer inserted into the stack is the last value to be processed. The last value in...
C# PLEASE Lab7B: For this lab, you’re going to write a program that prompts the user...
C# PLEASE Lab7B: For this lab, you’re going to write a program that prompts the user for the number of GPAs to enter. The program should then prompt the user to enter the specified number of GPAs. Finally, the program should print out the graduation standing of the students based on their GPAs. Your program should behave like the sample output below. Sample #1: Enter the number of GPAs: 5 GPA #0: 3.97 GPA #1: 3.5 GPA #2: 3.499 GPA...
C++ Goals: Write a program that works with binary files. Write a program that writes and...
C++ Goals: Write a program that works with binary files. Write a program that writes and reads arrays to and from binary files. Gain further experience with functions. Array/File Functions Write a function named arrayToFile. The function should accept three arguments: the name of file, a pointer to an int array, and the size of the array. The function should open the specified file in binary made, write the contents into the array, and then close the file. write another...
Confused about going through this C program. Thank you Program Specifications: *********************************************** ** MAIN MENU **...
Confused about going through this C program. Thank you Program Specifications: *********************************************** ** MAIN MENU ** *********************************************** A) Enter game results B) Current Record (# of wins and # of losses and # of ties) C) Display ALL results from all games WON D) Display ALL results ordered by opponent score from low to high. E) Quit Your program will have a menu similar to the example above. The game results will simply be the score by your team and...
C++ PLEASE---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In this program, you will analyze an array
C++ PLEASE---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In this program, you will analyze an array of 10 characters storing a gene sequence. You will be given a subsequence of 3 characters to look for within this array. If the subsequence is found, print the message: Subsequence <XXX> found at index <i>. Where i is the starting index of the subsequence in the array. Otherwise, print Subsequence <XXX> not found. The array of characters and the subsequence will be given through standard input. Read them and...
C Programming Language: For this lab, you are going to create two programs. The first program...
C Programming Language: For this lab, you are going to create two programs. The first program (named AsciiToBinary) will read data from an ASCII file and save the data to a new file in a binary format. The second program (named BinaryToAscii) will read data from a binary file and save the data to a new file in ASCII format. Specifications: Both programs will obtain the filenames to be read and written from command line parameters. For example: - bash$...
i need an example of a program that uses muliple .h and .cpp files in c++...
i need an example of a program that uses muliple .h and .cpp files in c++ if possible.
WRITE ONLY THE TO DO'S   in FINAL program IN C++ (necessary cpp and header files are...
WRITE ONLY THE TO DO'S   in FINAL program IN C++ (necessary cpp and header files are witten below) "KINGSOM.h " program below: #ifndef WESTEROS_kINGDOM_H_INCLUDED #define WESTEROS_KINGDOM_H_INCLUDED #include <iostream> namespace westeros { class Kingdom{         public:                 char m_name[32];                 int m_population; };         void display(Kingdom&);                      } #endif } Kingdom.cpp Program below: #include <iostream> #include "kingdom.h" using namespace std; namespace westeros {         void display(Kingdom& pKingdom) {                 cout << pKingdom.m_name << ", population " << pKingdom.m_population << endl;                                                               FINAL:...
Please do not answer if you do not have sufficient knowledge or if you are going...
Please do not answer if you do not have sufficient knowledge or if you are going to give a sentence as an answer. Background information: Evaluate the International Macroeconomic context of Australia's 2020 economic performance – current policy challenges and likely future directions. Is Australia well positioned to recover in 2021? Question: Explain in 500 words using The RER and internal and external balance- automatic mechanisms of adjustment- Where is Australia currently on the SWAN diagram - possible policy interventions?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT