Hangman Game Using Python And C++

Introduction:





Hangman word means man hanging on a string. and rules of games say that man has few numbers of lives to guess the correct word.

We have given any random word from the file of words which can be any hard or easy. if we guess the word in given lives then we saved man's life but if we fail to do so that man will die.

In the next few minutes, you are going to know what really is the hangman game? how to code it in cpp? how to code it in python? 

What is hangman game: 

We are given a sum n number of lives to save man's life which is currently hanging on a string through the head of the man.

We will try to guess the letter of the word which is hidden for use if we guess wrong letter then given lives are decreased by one. if we fail to guess the whole word in the given number of total lives then our man going to die.

Hangman game in C++:

We are going to implement a hangman game with 7 maximum wrong guesses. which means given lives are 7.

After 7 guesses goes wrong game was finessed and we lost the game. else if we guess the correct word we won the game.

Every time we will be getting a new random number from the file named "words.txt".


words to guess


First of all import one header file <bits/stdc++.h>

#include <bits/stdc++.h>
using namespace std;

We will use this function random_word() to get the random word. see the implementation of code this will give us the equal probability of getting random word:

// this function returns random word by reading words_1.txt file.
string random_word()
{
    // open file words.txt in input file stream point.
    ifstream words;
    words.open("words.txt");
    // create set of word.
    set<string> words_set;
    string s;
    while (words >> s)
    {
        words_set.insert(s);
    }

    // convert set to vector.
    vector<string> words_array;
    for (auto word : words_set)
    {
        words_array.push_back(word);
    }

    // array size.
    int n = words_array.size();

    // set seed to time(0)
    srand(time(0));

    // random integer in range 0 to n-1.
    int random_int = rand() % n;
    // close words file.
    words.close();
    // return random_word[random_int].
    return words_array[random_int];
}


Our next function will be to print the status of the game if the letter guessed is  wrong see this statues printing code below:

// print_status(guesses_done) function print status of game.
void print_status(int guesses_done)
{
    if (guesses_done == 0)
    {
        cout << "+" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "+-------" << endl;
    }
    else if (guesses_done == 1)
    {
        cout << "+----+" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "+-------" << endl;
    }
    else if (guesses_done == 2)
    {
        cout << "+----+" << endl;
        cout << "|    |" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "+-------" << endl;
    }
    else if (guesses_done == 3)
    {
        cout << "+----+" << endl;
        cout << "|    |" << endl;
        cout << "|    o" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "+-------" << endl;
    }
    else if (guesses_done == 4)
    {
        cout << "+----+" << endl;
        cout << "|    |" << endl;
        cout << "|    o" << endl;
        cout << "|    |" << endl;
        cout << "|    |" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "+-------" << endl;
    }
    else if (guesses_done == 5)
    {
        cout << "+----+" << endl;
        cout << "|    |" << endl;
        cout << "|    o" << endl;
        cout << "|   \\|" << endl;
        cout << "|    |" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "+-------" << endl;
    }
    else if (guesses_done == 6)
    {
        cout << "+----+" << endl;
        cout << "|    |" << endl;
        cout << "|    o" << endl;
        cout << "|   \\|/" << endl;
        cout << "|    |" << endl;
        cout << "|" << endl;
        cout << "|" << endl;
        cout << "+-------" << endl;
    }
    else if (guesses_done == 7)
    {
        cout << "+----+" << endl;
        cout << "|    |" << endl;
        cout << "|    o" << endl;
        cout << "|   \\|/" << endl;
        cout << "|    |" << endl;
        cout << "|   /" << endl;
        cout << "|" << endl;
        cout << "+-------" << endl;
    }
    else if (guesses_done >= 8)
    {
        cout << "+----+" << endl;
        cout << "|    |" << endl;
        cout << "|    o" << endl;
        cout << "|   \\|/" << endl;
        cout << "|    |" << endl;
        cout << "|   / \\" << endl;
        cout << "|" << endl;
        cout << "+-------" << endl;
    }
}



We want our program to give feedback to enter letters again if the user inputs the wrong letter or non-letter input for that we create a get letter function to get always a letter from the user. this function recursively returns letters.

// get_letter() which return a letter entered by user.
char get_letter()
{
    // asking for input.
    cout << "Enter the alphabet:";
    // if length of L is 1
    string L;
    cin >> L;
    if (L.size() == 1)
    {
        // return L.
        return L[0];
    }
    else
    {
        // else ask to try again.
        cout << "please try again to input";
        // and recursively return call of get_letter() function.
        return get_letter();
    }
}

Now our main game() function goes here:

In starting of the main function create variables that are needed and call the functions which we have created above when they are needed.

While loop to check guess done is less than max guesses.

If the guess is correct then update guessed word and non-guessed word accordingly.

// game() function which starts game.
void game()
{
    // guesses allocated 7.
    int max_guesses = 7;
    // set guesses_done = 0 to count wrong guesses.
    int guesses_done = 0;

    // get hidden_word;
    string hidden_word = random_word();

    // length of hidden_word.
    int n_length = hidden_word.size();
    // guessed word which tracks guessed letter recode.
    string guessed_word = "";
    for (int i = 0; i < n_length; i++)
    {
        guessed_word += '*';
    }

    // notguessed word which tracks letter recode which are not guessed.
    string notguessing_word = hidden_word;

    // printing total number of guesses use has and length of hidden word.
    cout << "Guess the " << n_length << " letter word " << guessed_word << ", You have " << max_guesses << " guesses." << endl;

    // store guessed letter.
    set<char> guessed_letter;

    // print starting status.
    print_status(guesses_done);

    // run while loop for guesses_done < max_guesses
    while (guesses_done < max_guesses)
    {
        // use get_letter() function to get always letter.
        char guess = get_letter();
        // store copy of guess.
        char copy_guess = guess;
        // find index of letter form notguessed_word list.
        int index_l;
        // checking if letter is found in uppercase or lowercase.
        guess = tolower(guess);
        index_l = notguessing_word.find(guess);
        if (index_l == notguessing_word.npos)
        {
            guess = toupper(guess);
            index_l = notguessing_word.find(guess);
        }
        if (index_l == notguessing_word.npos)
        {
            guess = copy_guess;
        }
        // if guess letter found in notguessing_word.
        if (index_l != notguessing_word.npos)
        {
            for (int i = 0; i < n_length; i++)
            {
                if (notguessing_word[i] == guess)
                {
                    // set guessed_word index_l th element equal to  guess letter.
                    guessed_word[i] = guess;
                    // erase letter form notguessed_word by using '*' character.
                    notguessing_word[i] = '*';
                }
            }
            // print msg of correct guess.
            cout << "Correct guess " << guessed_word << endl;
        }
        else
        {
            // if it is from previously guessed letter.
            if (guessed_letter.find(guess) != guessed_letter.end())
            {
                cout << "letter had been tried before so, not counted as guess." << endl;
            }
            // else
            else
            {
                // print Incorrect msg.
                cout << "Incorrect letter." << endl;
                // count Incorrect guess
                guesses_done++;
                // print status
                print_status(guesses_done);
            }
        }

        // insert upper and lower of guess letter to guessed_letter
        guessed_letter.insert(tolower(guess));
        guessed_letter.insert(toupper(guess));
        // print total remaining guesses.
        cout << " You have " << max_guesses - guesses_done << " guesses." << endl;
        // check if word is complated or not
        // if '*' not in guessed_word then guessing is complated.
        if (guessed_word.find('*') == guessed_word.npos)
        {
            // print won msg.
            cout << "Yes!!! The correct word is " << guessed_word << "! you won the game." << endl;

            // ask to play again.
            string new_game;
            cout << "Do you want to start a new game?(Yes/No):";
            cin >> new_game;
            transform(new_game.begin(), new_game.end(), new_game.begin(), ::tolower);
            if (new_game == "yes")
            {
                cout << "Game is restarted....";
                // if input is yes call recursively game() to restart game.
                game();
                break;
            }
            else
            {
                break;
            }
        }
        // else if guesses_done become max_guesses.
        else if (guesses_done >= max_guesses)
        {
            // print status.
            print_status(guesses_done + 1);
            // print loss msg.
            cout << "No!!! The correct word is " << hidden_word << "! you loss the game." << endl;
            // ask to play again.
            string new_game;
            cout << "Do you want to start a new game?(Yes/No):";
            cin >> new_game;
            transform(new_game.begin(), new_game.end(), new_game.begin(), ::tolower);
            if (new_game == "yes")
            {
                cout << "Game is restarted....";
                // if input is yes call recursively game() to restart game.
                game();
                break;
            }
            else
            {
                break;
            }
        }
    }
}

Call game function from the main function.

// starting point.
int main()
{
    game();
    return 0;
}

Output of  C++ program hangman game:

The output of the program game

The output of the program game



Python program with a different example


import random

# get_letter() function which always return a letter (string of 1 length).
def get_letter():
    # asking for input.
    L = input("Enter the alphabet:")
    # if length of L is 1
    if(len(L) == 1):
        # return L.
        return L
    else:
        # else ask to try again.
        print("please try again to input")
        # and recursively return call of get_letter() function.
        return get_letter()


# return string of status of hangman.
def display_hangman(attempts):
    stages = ["""
                   --------
                   |      |
                   |      O
                   |     \\|/
                   |      |
                   |     / \\
                   -
                   """,
              """
                   --------
                   |      |
                   |      O
                   |     \\|/
                   |      |
                   |
                   -
                   """,
              """
                   --------
                   |      |
                   |      O
                   |     \\|
                   |      |
                   |
                   -
                   """,
              """
                   --------
                   |      |
                   |      O
                   |      |
                   |      |
                   |
                   -
                   """,
              """
                   --------
                   |      |
                   |      O
                   |
                   |
                   |
                   -
                   """,
              """
                   --------
                   |      |
                   |
                   |
                   |
                   |
                   -
                   """
              ]
    return (stages[attempts])

# game() function.
def game():
    # create empty dictionary.
    d = dict()
    d['Animals'] = ['dolphin', 'shark', 'coyote', 'hippopotamus', 'elephant', 'rhinoceros', 'squid', 'cardinal',
                    'wolverine', 'alpaca']
    d['Food'] = ['spaghetti', 'pizza', 'burrito', 'sushi', 'taco', 'cheeseburger', 'bratwurst', 'guacamole',
                 'cheesecake', 'cheesesteak']
    d['Brands'] = ['mcdonalds', 'chevrolet', 'mercedes', 'amazon', 'google', 'delta', 'microsoft', 'disney',
                   'boeing', 'comcast']
    # asking to Choose category.
    category = input('Choose a category: Animals, Food, Brands: ')
    # asking to choose a level
    level = input("Choose a category: first, second, three: ")
    length_by_level = 0
    # if level is first add 5 to length_by_level
    if(level == "first"):
        length_by_level += 5
    # else if level is second add 9 to length_by_level
    elif(level == "second"):
        length_by_level += 9
    # else add 20 to length_by_level
    else:
        length_by_level += 20

    # filter string by length.
    if category == 'Food':
        original_word = random.choice(
            list(filter(lambda x: x.__len__() <= length_by_level, d['Food'])))
    elif category == 'Animals':
        original_word = random.choice(
            list(filter(lambda x: len(x) <= length_by_level, d['Animals'])))
    elif category == 'Brands':
        original_word = random.choice(
            list(filter(lambda x: len(x) <= length_by_level, d['Brands'])))
    else:
        print("Invalid category choice")
        quit()

    # welcome_message
    print("The Hangman Game")
    # copy of hidden_word.
    hidden_word = original_word
    # length of hidden_word
    n_length = len(hidden_word)
    # guesses allocated 5.
    max_guesses = 5
    # guessed word which tracks guessed letter recode.
    guessed_word = list('-'*n_length)
    # notguessed word which tracks letter recode which are not guessed.
    notguessed_word = list(hidden_word)
    # printing total number of guesses use has and length of hidden word.
    print(
        f"Guess the {n_length} letter word {''.join(guessed_word)}, You have {max_guesses} guesses.")
    guesses_done = 0

    # printing hangman here list of string in display_hangman is in reverse order so i have printed it reversely by passing negative index to print appropriately.
    print(display_hangman(-guesses_done-1))

    # run while loop for guesses_done < max_guesses
    while guesses_done < max_guesses:
        # use get_letter() function to get always letter.
        guess = get_letter()

        # if guess is from notguessed_word letter. do this
        if(guess in notguessed_word):
            # find index of letter form notguessed_word list.
            index_l = notguessed_word.index(guess)
            # set guessed_word index_l th element equal to  guess letter.
            guessed_word[index_l] = guess
            # erase letter form notguessed_word by using '-' character.
            notguessed_word[index_l] = '-'
            # print msg of correct guess.
            print(f"Correct guess {''.join(guessed_word)}")

        else:
            # else print msg of Incorrect guess.
            print("Incorrect letter.")
            # count Incorrect guess
            guesses_done += 1
            print(display_hangman(-guesses_done-1))

        # print total remaining guesses.
        print(f" You have {max_guesses - guesses_done} guesses.")

        # check if word is complated or not
        # if '-' not in guessed_word then guessing is complated.
        if('-' not in guessed_word):
            # print won msg.
            print(
                f"Yes!!! The correct word is {hidden_word}! you won the game.")
            # ask to play again.
            new_game = input("Do you want to start a new game?(Yes/No):")
            new_game = new_game.lower()
            if(new_game == 'yes'):
                print("Game is restarted....")
                # if input is yes call recursively game() to restart game.
                game()
                break
            else:
                break

        # else if guesses_done become max_guesses.
        elif(guesses_done >= max_guesses):
            # printing last stage of hangman.
            print(display_hangman(-6))
            # print loss msg.
            print(
                f"No!!! The correct word is {''.join(hidden_word)}! you loss the game.")
            # ask to play again.
            new_game = input("Do you want to start a new game?(Yes/No):")
            new_game = new_game.lower()
            if(new_game == 'yes'):
                print("Game is restarted....")
                # if input is yes call recursively game() to restart game.
                game()
                break
            else:
                break
    # thanks to user.
    print("Thank you for playing Hangman!")


if __name__ == '__main__':
    game()


Output of  Python program hangman game:

Output of  Python program hangman game

Output of  Python program hangman game


Read also:



C++ code image:

Cpp code image hangman
Cpp code image hangman

Python code image:

Python code image hangman game






Post a Comment

0 Comments