By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > Python > Hangman in Python
Python

Hangman in Python

Rohan750
Last updated: 2021/05/16 at 5:12 AM
Rohan750
Share
13 Min Read

Contents
Get WordPlayDisplay 
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

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Moving Car Animation using CSS and JavaScript
Next Article picture matching game using python
9 Comments 9 Comments
  • Rohan750 says:
    September 28, 2020 at 3:16 pm

    The problem is solved, now you see again

    Reply
  • Miriam says:
    November 17, 2021 at 12:47 am

    Everything is very open with a precise clarification of the
    challenges. It was really informative. Your site is extremely helpful.
    Thanks for sharing!

    Reply
  • Anja says:
    November 18, 2021 at 10:39 pm

    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!

    Reply
  • Blythe says:
    November 21, 2021 at 4:39 pm

    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!!

    Reply
  • ทางเข้าSUPERSLOT says:
    March 8, 2022 at 11:47 pm

    Fantastic blog post.Much thanks again. Will read on…

    Reply
  • Shakira Thursby says:
    May 2, 2022 at 7:48 am

    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!

    Reply
  • XMC.pl says:
    May 13, 2022 at 3:14 pm

    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.

    Reply
  • Selena Tunis says:
    May 22, 2022 at 11:38 am

    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.

    Reply
  • Pingback: How To Make Rock Paper Scissors Python Game 2022 - rocoderes

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

Rock Paper Scissors Python

How To Make Rock Paper Scissors Python Game 2022

November 26, 2022
python QR code generator

How To Make Python QR Code Generator

November 25, 2022
Countdown Calendar using Python Tkinter

How to Make Countdown Calendar using Python Tkinter

November 24, 2022
binary search algorithm in python

What is Binary Search Algorithm in python?

November 23, 2022
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?