CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Thread: [RESOLVED] Need help for a C++ hangman game

  1. #1
    Join Date
    Oct 2020
    Posts
    4

    [RESOLVED] Need help for a C++ hangman game

    I have to write a source code for a hangman game, but I run into a problem where the number of guesses left only decrease when the guess is actually correct. Any help to fix this problem?

    Source code so far:

    Code:
    #include <iostream>
    #include <string>
    #include "hangman.h"
    
    using std::string;
    
    int main() {
        // Word the player needs to guess (randomly selected)
        string word = chooseWord(); 
      
        // Initialise the "uncovered" word that is shown to the player: the uncovered
        // word is obtained by replacing each letter from the original word (variable
        // word) with an underscore (i.e. _).
        string workingCopy = createWorkingCopy(word);
      
        // This variable indicates whether or not the game is over
        bool done = false; 
      
        int wrongGuesses = 0; // Number of wrong guesses
        int maxWrongGuesses = 6; // Maximum number of wrong guesses (don't change)
      
        // Draw the empty gallow
        showHangman(0); 
      
        // Game loop (each iteration is a round of the game)
        while (!done) {
            printGameState(maxWrongGuesses, wrongGuesses);
            printWorkingCopy(workingCopy);
           
            /** Part 1: input next guess **********************************************/
            char guess = '\0';
    
            // TODO: replace the following line with your implementation
            //PART1_readCharacter(guess);
            std::cout<< "Your guess: ";
            std::cin>> guess;
        
            /** Part 2: update working copy *******************************************/
            bool found = false;
    
            // TODO: replace the following line with your implementation
            //PART2_updateWorkingCopy(word, guess, workingCopy, found);
            for (int i=0; i<word.length(); ++i) 
                if (guess == word[i]) 
                {
                    { 
                    found = true; 
                    workingCopy.at (i)=word[i];
                    }
     
                    if (!found)
                    { 
                    }
        
                   /** Part 3: update game state *********************************************/
                   // TODO: replace the following line with your implementation
                   //PART3_updateGameState(word, workingCopy, found, maxWrongGuesses, done, wrongGuesses);
    
                   if (workingCopy == word)
                   {
                       done = true;
                       std::cout<< "you've won, the word was " << word<<".";
                   }
     
                   if (found = false) ;
    
                   {
                        wrongGuesses++;
      
                        if (wrongGuesses == maxWrongGuesses)
                        {
                            done = true;
                            std::cout<< "you've lost, the word was "<< word <<"."; }
                        }
                   }
            }
    
        return 0;  
    }
    Last edited by 2kaud; October 3rd, 2020 at 07:54 AM. Reason: Added code tags

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,289

    Re: Need help for a C++ hangman game

    [When posting code, please code tags with formatted code so that it is readable. Go Advanced, select the formatted code and click #]

    I've re-formatted the code in post #1 so that the various blocks can be seen easily.

    Code:
    if (found = false) ;
    All this does is set found to false. For equality, use ==. Also having ; at the end means that irrespective of the result of the test, no other statements are executed.


    Code:
    { 
                    found = true; 
                    workingCopy.at (i)=word[i];
    }
    Having these statements within their own block which is within another block makes no sense here.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.7.7)

  3. #3
    Join Date
    Oct 2020
    Posts
    4

    Re: Need help for a C++ hangman game

    I've fixed the first part and the game works, but the autograder still detects it as not good enough. I'm unsure how to fix the second part about the block. We are given this help to make the game.



    Part 2:

    This part involves checking if the guessed character occurs in the word, and updating the workingCopy accordingly: by replacing the underlines at the respective position(s) by the guessed character. Variable found indicates if the guessed character was found in the word.

    Example (found): If variable word is set to "success", variable workingCopy still contains the initial underlines ("_______") and the current guess is 'c', then two actions must be performed:

    Variable found must be set to true, because 'c' occurs in the word "success"
    All occurrences of the letter 'c' must be uncovered in the working copy, thus variable workingCopy must be changed to have the content "__cc___"


    Example (not found): If variable word is set to "success", variable workingCopy still contains the initial underlines ("_______") and the current guess is 'x', then the following is important:

    Variable found must remain false (because 'x' does not occur in "success"
    Variable workingCopy must not be changed.


    Part 3:

    This part is about determining if the game continues, or if it is already won or lost.


    If the player made a correct guess and we uncovered at least one further character in the working copy (in which case variable found has value true), and if variable workingCopy now equals variable word, then the game has been won. Two things must happen in this case:

    Set variable done to true, to indicate that the game must not continue.

    Call printYouWon(word), which will output the result of the game (in a format required by the autograder).


    Otherwise, if the player guessed incorrectly (in which case variable found is false), variable wrongGuesses must be incremented by one. If this variable is afterwards equal to maxWrongGuesses then the game is lost, in which case the following two things must happen:

    Set variable done to true, to indicate that the game must not continue.

    Call printYouLost(word), which will output the result of the game (in a format required by the autograder).

    In all other situations, just make sure that variable done remains false. This ensures that the game continues.



    I see how the block makes no sense, but what other way is there to do part 2 of the tasks.

  4. #4
    Join Date
    Oct 2020
    Posts
    4

    Re: Need help for a C++ hangman game

    I fixed the first part and the game works, but the autograder still detects it as not good enough. We have this help to finish the task:


    Part 2:

    This part involves checking if the guessed character occurs in the word, and updating the workingCopy accordingly: by replacing the underlines at the respective position(s) by the guessed character. Variable found indicates if the guessed character was found in the word.

    Example (found): If variable word is set to "success", variable workingCopy still contains the initial underlines ("_______") and the current guess is 'c', then two actions must be performed:

    Variable found must be set to true, because 'c' occurs in the word "success"

    All occurrences of the letter 'c' must be uncovered in the working copy, thus variable workingCopy must be changed to have the content "__cc___"

    Example (not found): If variable word is set to "success", variable workingCopy still contains the initial underlines ("_______") and the current guess is 'x', then the following is important:

    Variable found must remain false (because 'x' does not occur in "success"

    Variable workingCopy must not be changed.


    Part 3

    This part is about determining if the game continues, or if it is already won or lost.

    If the player made a correct guess and we uncovered at least one further character in the working copy (in which case variable found has value true), and if variable workingCopy now equals variable word, then the game has been won. Two things must happen in this case:

    Set variable done to true, to indicate that the game must not continue.
    Call printYouWon(word), which will output the result of the game (in a format required by the autograder).

    Otherwise, if the player guessed incorrectly (in which case variable found is false), variable wrongGuesses must be incremented by one. If this variable is
    afterwards equal to maxWrongGuesses then the game is lost, in which case the following two things must happen:

    Set variable done to true, to indicate that the game must not continue.
    Call printYouLost(word), which will output the result of the game (in a format required by the autograder).

    In all other situations, just make sure that variable done remains false. This ensures that the game continues.



    I see how the block makes no sense, but looking at the tasks (part 2 especially), how would you include found = true to be relevant elsewhere.

  5. #5
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,289

    Re: Need help for a C++ hangman game

    Consider this. You haven't posted the used functions so I've used temp versions so that the code compiles:

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    string chooseWord()
    {
    	return "hangman";
    }
    
    string createWorkingCopy(const string& word)
    {
    	return string(word.size(), '_');
    }
    
    void showHangman(int) {}
    
    void printGameState(int max, int wrong)
    {
    	cout << "Wrong guesses: " << wrong << " out of " << max << endl;
    }
    
    void printWorkingCopy(const std::string& word)
    {
    	cout << word << endl;
    }
    
    void updateWorkingCopy(const string& word, char guess, string& workingCopy, bool& found)
    {
    	found = false;
    
    	for (int i = 0; i < word.size(); ++i)
    		if (word[i] == guess)
    			found = workingCopy[i] = guess;
    }
    
    void updateGameState(const string& word, const string& workingCopy, bool& found, int maxWrongGuesses, bool& done, int& wrongGuesses)
    {
    	if (workingCopy == word) {
    		done = true;
    		std::cout << "you've won, the word was " << word << ".";
    		return;
    	}
    
    	if (found == false)	{
    		++wrongGuesses;
    		showHangman(wrongGuesses);
    
    		if (wrongGuesses == maxWrongGuesses)
    		{
    			done = true;
    			std::cout << "you've lost, the word was " << word << ".";
    		}
    	}
    }
    
    int main() {
    	string word = chooseWord();
    	string workingCopy = createWorkingCopy(word);
    	bool done = false;	// Game over?
    	int wrongGuesses = 0; // Number of wrong guesses
    	int maxWrongGuesses = 6; // Maximum number of wrong guesses (don't change)
    
    	// Draw the empty gallow
    	showHangman(0);
    
    	// Game loop (each iteration is a round of the game)
    	while (!done) {
    		printGameState(maxWrongGuesses, wrongGuesses);
    		printWorkingCopy(workingCopy);
    
    		char guess = '\0';
    
    		std::cout << "Your guess: ";
    		std::cin >> guess;
    
    		bool found = false;
    
    		updateWorkingCopy(word, guess, workingCopy, found);
    		updateGameState(word, workingCopy, found, maxWrongGuesses, done, wrongGuesses);
    	}
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.7.7)

  6. #6
    Join Date
    Oct 2020
    Posts
    4

    Re: Need help for a C++ hangman game

    Wow, it works, the autograder marked it complete. Thanks a lot!

    Btw, do I have to mark this thread as solved/closed or anything or just let it be?

  7. #7
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,289

    Re: Need help for a C++ hangman game

    Quote Originally Posted by Doomed View Post
    Wow, it works, the autograder marked it complete. Thanks a lot!

    Btw, do I have to mark this thread as solved/closed or anything or just let it be?
    But do you understand it? That's the important thing.

    I've marked it as complete.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.7.7)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)