Question

Create a Hangman Game in C++ using Classes. The program doesn't need to have the hangman...

Create a Hangman Game in C++ using Classes. The program doesn't need to have the hangman drawing, it just needs the following:

- Ten 3-letter words
- Keep track of everytime the player misses a letter
- Simple and commented code

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>
#include <fstream>
#include <string>
#include <locale>
#include <vector>
#include <ctime>
#include <algorithm>
#include <sstream>

bool run;

int countLines(std::vector<std::string> words) {
    return words.size();
}
    
std::string getWord() {
    std::ifstream words_file;
    try {
        words_file.open("words.txt");
    }
    catch (...) {//words_file.fail()) {
        std::cout << "Error" << std::endl;
        run = false;
    }
        
    std::string line;

    std::vector<std::string> words;

    while (std::getline(words_file,line)) {
        words.push_back(line);
    }

    srand(time(NULL));

    int number_of_words = countLines(words);
    // std::cout << number_of_words << std::endl;

    std::string word = words.at(rand() % number_of_words);

    return word;
    
}

std::string runAI() {
    return (getWord());
}


void endGame() {
    std::cout << "Thank you for playing. Goodbye!" << std::endl;
    run = false;
}



std::string updateWord(std::string word, std::vector<int> characterLocations, char to_update) {
    char dummy;
    std::vector<char> word_vec (word.length(),dummy);

    for (int i = 0; i < word.length(); i++) {
        std::vector<int>::iterator found = std::find(characterLocations.begin(), characterLocations.end(), i);
        if(found != characterLocations.end()) { // if i is in the characterLocations vector
            word_vec[i] = to_update;
            characterLocations.erase(found);
        }
        else {
            word_vec[i] = word[i];
        }
    }
    

    std::string result(word_vec.begin(),word_vec.end()); // converts char vector to string

    return result;
}

bool has_only_alpha(std::string word) {
    char c;
    for (int i = 0; i < word.length(); i++) {
        c = word.at(i);

        if (! ( ( c >= 'a' && c <= 'z' ) ||
                    ( c >= 'A' && c <= 'Z') ) ) {
            return false;
        }
    }
    return true;
}

std::vector<int> findLocation(std::string sample, char findIt)
{
    std::vector<int> characterLocations;
    for(int i =0; i < sample.size(); i++)
        if(sample[i] == findIt)
            characterLocations.push_back(i);

    return characterLocations;
}

void toLower(std::string& word) {
    std::transform(word.begin(), word.end(), word.begin(), ::tolower);
}



int main() {
    std::cout << "Welcome to Hangman!" << std::endl;

    run = true;

    while (run) {

        std::string gameMode;

        std::cout << "Would you like to play against:\n 1) A friend\n 2) The computer?" << std::endl;
        std::cout << "Type 'quit' to end the game." << std::endl;

        std::cin >> gameMode;

        /* The commented code is used for creating a lower case string.

        std::locale loc;
        for (std::string::size_type i=0; i < str.length(); i++)
            std::cout << std::tolower(str[i],loc);
        */



        std::string hidden_word = "";
        std::string input;

        if (gameMode == "1") {
            bool isValidWord = false;

            std::cout << "=========PLAYER 1'S TURN=========" << std::endl;
            while (isValidWord == false) {

                std::cout << "Give me a word: ";
                std::cin >> input;
                isValidWord = has_only_alpha(input);
                if (isValidWord) {
                    for (int i = 0; i < 100; i++) { // clears the terminal
                        std::cout << "\n" << std::endl;
                    }
                    break;
                }
                std::cout << "Only letters are allowed in words." << std::endl;
            }

            for (int j = 0; j < input.length(); j++) {
                hidden_word += "_";
            }

            toLower(input);
   
            std::cout << "=========PLAYER 2'S TURN=========" << std::endl;

            bool game_over = false;

            int num_tries = input.length() + 1;

            std::cout << "The word that your friend gave was " << input.length() << " letters long." << std::endl;

            std::cout << "Updated Word: " << hidden_word << std::endl;

            while ((num_tries > 0) && (game_over == false)) {
                char letter;
                std::cout << "Number of tries left: " << num_tries << std::endl;
                std::cout << "Give me a letter you think is in the word: ";
                std::cin >> letter;
                
                
                std::stringstream stream;
                std::string str;

                stream << letter;
                stream >> str;

                toLower(str);
                            
                std::size_t found = input.find(letter);
                if (found != std::string::npos) {
                    std::cout << "That letter is in the word!" << std::endl;
                    std::vector<int> characterLocations = findLocation(input,letter);



                    hidden_word = updateWord(hidden_word, characterLocations, letter);
                    if (hidden_word == input) {
                        game_over = true;
                        break;
                    }
                    std::cout << "Updated Word: " << hidden_word << std::endl;



                }
                else {
                    std::cout << "That letter is not in the word." << std::endl;
                }

                num_tries--;
            }




            if (num_tries != 0) {
                std::cout << "Player 2 wins!" << std::endl;
            }
            else {
                std::cout << "Player 1 wins!" << std::endl;
            }
            std::cout << "The word you gave me was: " << input  << std::endl;
            run = false;
        }
        else if (gameMode == "2") {
           
            input = runAI();
            //std::cout << "word chosen by computer is: " << input << std::endl;
            for (int j = 0; j < input.length(); j++) {
                hidden_word += "_";
            }


            std::cout << "=========PLAYER 2'S TURN=========" << std::endl;

            bool game_over = false;

            int num_tries = input.length() + 1;
            while ((num_tries > 0) && (game_over == false)) {
                char letter;
                std::cout << "If you would like to guess the word, press 1." << std::endl;
                std::cout << "Number of tries left: " << num_tries << std::endl;
                std::cout << "Give me a letter you think is in the word: ";
                std::cin >> letter;
                
                if (letter == '1')
                {
                    std::string guess;
                    std::cout << "What is your guess?" << std::endl;
                    std::cin >> guess;
                    if (input == guess) {
                        std::cout << "You guessed the word right!" << std::endl;
                        num_tries = -1;
                    }

                }
                else {
                    std::size_t found = input.find(letter);
                    if (found != std::string::npos) {
                        std::cout << "That letter is in the word!" << std::endl;
                        std::vector<int> characterLocations = findLocation(input,letter);

                        for (int i = 0; i < characterLocations.size(); i++) {
                            std::cout << characterLocations[i] << std::endl;;
                        }

                        hidden_word = updateWord(hidden_word, characterLocations, letter);
                        if (hidden_word == input) {
                            game_over = true;
                            break;
                        }
                        std::cout << "Updated Word: " << hidden_word << std::endl;



                    }
                    else {
                        std::cout << "That letter is not in the word." << std::endl;
                    }

                    num_tries--;
                }
            }




            if (num_tries != 0) {
                std::cout << "You win!" << std::endl;
            }
            else {
                std::cout << "The computer wins!" << std::endl;
            }
            std::cout << "The word the computer gave was: " << input  << std::endl;
            run = false;
        }
        else if (gameMode == "quit") {
            run = false;
        }
        else {
            std::cout << "Please input only 1 or 2 or 'quit'." << std::endl;
        }

    }

    endGame();
    

    return 0;
}

words.txt

===============

put any number of three letter words here (Each word in new line)

Add a comment
Know the answer?
Add Answer to:
Create a Hangman Game in C++ using Classes. The program doesn't need to have the hangman...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Create a simple commented C++ HANGMAN game using CLASSES using the following specifications: - The game...

    Create a simple commented C++ HANGMAN game using CLASSES using the following specifications: - The game must keep track of the player misses - It must ONLY use 10 three letter words - It does NOT need a graphical implementation

  • Create the game hangman using c code: Program description In the game of hangman, one player...

    Create the game hangman using c code: Program description In the game of hangman, one player picks a word, and the other player has to try to guess what the word is by selecting one letter at a time. If they select a correct letter, all occurrences of the letter are shown. If no letter shows up, they use up one of their turns. The player is allowed to use no more than 10 incorrect turns to guess what the...

  • Create a Program in C++ We need commentaries in the program setter and getter we need...

    Create a Program in C++ We need commentaries in the program setter and getter we need the Output of the program and the code compiling and use a file. You will design a program that plays hangman. The rules are explained here. The program must at least include one class and client code. It does not require graphical representation but to keep track of the player misses. The host is the computer. The user has eight chances for error (otherwise,...

  • C++ Hangman (game) In this project, you are required to implement a program that can play...

    C++ Hangman (game) In this project, you are required to implement a program that can play the hangman game with the user. The hangman game is described in https://en.wikipedia.org/wiki/Hangman_(game) . Your program should support the following functionality: - Randomly select a word from a dictionary -- this dictionary should be stored in an ASCII text file (the format is up to you). The program then provides the information about the number of letters in this word for the user to...

  • For a C program hangman game: Create the function int play_game [play_game ( Game *g )]...

    For a C program hangman game: Create the function int play_game [play_game ( Game *g )] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) (Also the link to program files (hangman.h and library file) is below the existing code section. You can use that to check if the code works) What int play_game needs to do mostly involves calling other functions you've already...

  • Overview In this exercise you are going to recreate the classic game of hangman. Your program...

    Overview In this exercise you are going to recreate the classic game of hangman. Your program will randomly pick from a pool of words for the user who will guess letters in order to figure out the word. The user will have a limited number of wrong guesses to complete the puzzle or lose the round. Though if the user answers before running out of wrong answers, they win. Requirements Rules The program will use 10 to 15 words as...

  • hey dear i just need help with update my code i have the hangman program i...

    hey dear i just need help with update my code i have the hangman program i just want to draw the body of hang man when the player lose every attempt program is going to draw the body of hang man until the player lose all his/her all attempts and hangman be hanged and show in the display you can write the program in java language: this is the code bellow: import java.util.Random; import java.util.Scanner; public class Hangmann { //...

  • Create a modification to the Hangman game to provide enhancements for the user experience. Share the...

    Create a modification to the Hangman game to provide enhancements for the user experience. Share the code in text format in this thread. Could someone please assist me coming up with a modification in Python? 4. EXERCISE 4 The following code implements a very simple Hangman game: word = 'underutilise guesses = [] user_input = " while user_input == '0': user_input = input ("Enter a letter, or 0 to give up:') guesses.append(user_input) output = '' for letter in range(1, len...

  • javafx assisantance confused on where to start Problem Description: (Game: hangman) Write a JavaFX program that...

    javafx assisantance confused on where to start Problem Description: (Game: hangman) Write a JavaFX program that lets a user play the hangman game. The user guesses a word by entering one letter at a time, as shown in Figure followings. If the user misses seven times, a hanging man swings, as shown in Figures. Once a word is finished, the user can press the Enter key to continue to guess another word. Guess a word: ***** God Missed letters Guess...

  • I need to create a Tic Tac Toe program in C++. These are the requirements Write...

    I need to create a Tic Tac Toe program in C++. These are the requirements Write a program that allows the computer to play TicTacToe against a human player or allow two human players to play one another. Implement the following conditions: The player that wins the current game goes first in the next round, and their symbol is X. The other player will be O. Keep track of the number of games played, wins, and draws for each player....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT