27.4 C
Gujarat
HomepythonHangman in Python

Hangman in Python

In this article, we will see how to create Game Hangman with Python, which will be a simple command-line game. It allows user input, and it releases the current hangman’s view with the word guessed at each turn.

hangman in python

if you wanna play online

https://repl.it/@PatelRohan/hangman-in-python#main.py

We will write all our codes in Python in a single Python file called hangman.py. Additionally, we will call another Python file words.py. Keeps a long list of words to use for the game.

Get Word

Let’s start first we need to define a function called. Get a word that gives a word to our game. for this function we can create a list of words. Or import a list of words to choose the program. Previously created a file with a list of several hundred words. So I’m going to import that list externally. And then we want to roughly select a word from this list. so let’s import the random library as well. Random.choice over the word in all capital letters by calling the upper(). We will convert all user input to uppercase. to simplify our comparative logic. So this word is printed in all uppercase. for the user to read for the actual interactive game.




def get_word():
    word = random.choice(word_list)

return word.upper()

Play

We are going to define a function called play. So we will create several variables that we update at each turn. We want to show the word first at each turn. We will underline the guessed letters and then show the letters as the correct guesses. To do this we will create a string called word completion Will be longer. Which will underline the beginning and underline the next. Next, we will create a variable called guess, which is falsely initialized and now we will create two lists. This is an attempt to have the letters that the user guesses and the words that the user guesses to be the last variable, which is the number of tries that correspond to the number of body parts to be drawn in the hangman. This is six before the user loses counting the head body with both hands and both feet.



def play(word):
    word_completion = "_" * len(word)
    guessed = False
    guessed_letters = []
    guessed_words = []

tries = 6

Display 

I have already created seven visual stages of Hangman. This includes the initial blank position and other positions. I store these in a list in a process called Display Hangman. The code for each phase corresponds to the number of attempts left by the user, which we will use to show the current phase of the hangman at each turn on the command line.


def display_hangman(tries):
    stages = [  # final state: head, torso, both arms, and both legs
                """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |     / \
                   -
                """,
                # head, torso, both arms, and one leg
                """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |     / 
                   -
                """,
                # head, torso, and both arms
                """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |      
                   -
                """,
                # head, torso, and one arm
                """
                   --------
                   |      |
                   |      O
                   |     \|
                   |      |
                   |     
                   -
                """,
                # head and torso
                """
                   --------
                   |      |
                   |      O
                   |      |
                   |      |
                   |     
                   -
                """,
                # head
                """
                   --------
                   |      |
                   |      O
                   |    
                   |      
                   |     
                   -
                """,
                # initial empty state
                """
                   --------
                   |      |
                   |      
                   |    
                   |      
                   |     
                   -
                """
    ]
    return stages[tries]

So go back to the play function after the variables start. For example we will print some initial release to help guide the user at the start of the game, underline all of Hangman’s starting position and word starting position, and we will print a new line. Our code will be incorporated into a little loop, and it will run until the end of the guessed word or user condition attempt.

We will write when not guessing, and since the attempts will be greater than zero, each iteration of the loop will correspond to the user’s turn, first asking the user to guess with input, please guess a letter or word, we will save the guess in a variable and make sure to send it to the uppercase in the circle each We will have three possible conditional branches based on the input.

Preventing guessing one letter / preventing guessing another letter means that the length of the guess is 1 and there are only letters from the alphabet, so calling a word alpha means that the length of the guest is equal.There are only the length and letters of the actual word, and then we have another statement that wants everything, and can not print the exact guess after each guest has been handled, print out a new line of hangman’s, print a new line each time, starting by guessing a letter.

whether the letter has already been guessed, is not in the word, so if the guess is inherent characters we will print what you have already guessed. Print the letter and the accompanying letter, if the guess is not in the word the guess will be printed not in the word here, we will reduce the number of attempts by 1 because the user has created a false guess, and we will write guest letters. The only possibility left is for the user to guess her. So we will create another volume and print the good job guess, this word will again refer to the two guest letters.

next, we have to update our variable word completion to reveal to the user all occurrences of guests for this will first convert word completion from a string to a list, so we’re able to index into it and we’ll store this in a new variable called words list. now we need to find all the indices where guests occur in a word so let’s use a list comprehension.

Here we’re calling enumerate onward to get both.The index I and letter at the index for each iteration or pending. I to this list if its corresponding letter equals guess. Now let’s use a simple for loop over indices to replace each underscore at index with guests. Then let’s update word completion with the new changes by calling an empty string, to join on word as a list to convert it back to a string. It’s also a possibility that guests now completes the word, Let’s include an if statement to check this we write if underscore not in word completion guest equals.

Now let’s go to the condition to guess a word, to guess a letter. If inside statement verification we need another condition module. This word is correct or incorrect if already guessed. So guess if the guest is in words. We will print what you have already guessed the word. Guessing is not an equivalent word, printing a guess is not in the word. And the number of attempts can be reduced one by one. We also make sure to pen the guest for guest words. In our other report the user guessed the word correctly. And will complete the word for the guests true and full word. When it ends or will be in the ring. After a while we will see if the user guesses the word correctly. Or we do this by checking that the efforts are over.

If guest is true and if so let’s print congrats you guess the word you win. Otherwise, we’ll print sorry we ran out of tries the word was insert word maybe next time finishing up.



def play(word):
    word_completion = "_" * len(word)
    guessed = False
    guessed_letters = []
    guessed_words = []
    tries = 6
    print("Let's play Hangman!")
    print(display_hangman(tries))
    print(word_completion)
    print("n")
    while not guessed and tries > 0:
        guess = input("Please guess a letter or word: ").upper()
        if len(guess) == 1 and guess.isalpha():
            if guess in guessed_letters:
                print("You already guessed the letter", guess)
            elif guess not in word:
                print(guess, "is not in the word.")
                tries -= 1
                guessed_letters.append(guess)
            else:
                print("Good job,", guess, "is in the word!")
                guessed_letters.append(guess)
                word_as_list = list(word_completion)
                indices = [i for i, letter in enumerate(word) if letter == guess]
                for index in indices:
                    word_as_list[index] = guess
                word_completion = "".join(word_as_list)
                if "_" not in word_completion:
                    guessed = True
        elif len(guess) == len(word) and guess.isalpha():
            if guess in guessed_words:
                print("You already guessed the word", guess)
            elif guess != word:
                print(guess, "is not the word.")
                tries -= 1
                guessed_words.append(guess)
            else:
                guessed = True
                word_completion = word
        else:
            print("Not a valid guess.")
        print(display_hangman(tries))
        print(word_completion)
        print("n")
    if guessed:
        print("Congrats, you guessed the word! You win!")
    else:
        print("Sorry, you ran out of tries. The word was " + word + ". Maybe next time!")

We just need a main function to put everything together. Let’s first get a word from get word. Then let’s pass this word to play this is all we need here to run the game once. But let’s add some code to give the user the option to play again. Let’s create a while loop asking the user for input prompting play again yes or no. We’ll call upper on the input and check if it’s equal to Y. Then inside we’ll call the same two functions. We did before therefore our program will continue as long as the user types yes to play again lastly.



def main():
    word = get_word()
    play(word)
    while input("Play Again? (Y/N) ").upper() == "Y":
        word = get_word()

play(word)

We’ll just add this code fragment here. That our python program Hangman.py will run by running our script on the command line. And you can also insert your own words into python file words.py


if __name__ == "__main__":
    main()

Hangman in python source code:

https://repl.it/@PatelRohan/hangman-in-python#main.py

Build HANGMAN with Python in 10 MINUTES

watch the video:https://youtu.be/m4nEnsavl6w

RELATED ARTICLES

8 COMMENTS

  1. My brother suggested I might like this blog. He was totally right.
    This post actually made my day. You can not imagine
    simply how much time I had spent for this information! Thanks!

  2. Oh my goodness! Awesome article dude! Thank you, However
    I am experiencing troubles with your RSS. I don’t know
    why I can’t join it. Is there anybody having identical RSS issues?
    Anyone that knows the answer will you kindly respond? Thanks!!

  3. I do not even know how I ended up here, but I thought this post was good. I do not know who you are but definitely you are going to a famous blogger if you aren’t already 😉 Cheers!

  4. Since it can be unhealthy. You will find NO Quick Fixes. Diet Appropriate, or Don???ê?èt Diet at all! Portion Control, it???ê?ès simple and everyone can do it. It???ê?ès a lifestyle alter, not a quick fix. Why lose it all, after which acquire it back? That???ê?ès just silly, and depressing.

  5. Hello just wanted to give you a quick heads up and let you know a few of the images aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same outcome.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

15,000FansLike
5,000FollowersFollow
535FollowersFollow
- Advertisment -spot_img

Subscribe to our newsletter

To be updated with all the latest news, offers and special announcements.

Most Popular