How to make Hangman game in Python

How to make Hangman game in Python Picture 1

How to play Hangman

Hangman is applied a lot in teaching, helping players practice their memorization ability. The owner of the game will give the word to guess with a specific number of letters, and the player has the task of finding it by giving each letter in turn that they think is in the answer.

If you guess the correct letter in the answer word, Hangman will fill it in the dash. Conversely, if the guess is wrong, the player will lose the opportunity, Hangman will draw a tile that makes up a part of the stickman (representing the score). The player has a total of 7 guesses. If they guess correctly, they win. If wrong, Hangman completes the stick figure.

How to build Hangman game

Import the random module and define a function, get_random_word_from_wordlist() , to select a random word in the file. This text file can contain common nouns or names of places, animals, movies, etc. that you like. Build a list using square brackets ( [] ).

 

Use the with command to open the file and change the mode to ' r ' read-only. It automatically closes the file at the end of the block even in case of an error. If you look at the file hangman_wordlist.txt , you will see that there is one word per line, so this file separates each word with a newline character.

Pass the escape character for the newline ( n ) to the split() function to contain each word in the list you originally defined. Use random.choice() to return a random word from the list.

import random def get_random_word_from_wordlist(): wordlist = [] with open("hangman_wordlist.txt", 'r') as file: wordlist = file.read().split("n") word = random.choice(wordlist) return word

Next, define a function, get_some_letters() that takes a randomly selected word as a parameter. This function will display an empty dashed string ( _ ) and some letters to the user.

Specifies an empty list of letters to contain all characters present in the word. Use the temp variable to store a numeric string of empty dashes equal to the length of the word. Use list() to convert the string to a character list and iterate over it. Use append() to add a character to the list if it doesn't already exist.

Use random.choice() to select the random character you want to display to the user with blank strokes. Iterate over the character of a word with enumerate to keep track of the index of each character.

When a randomly selected character is found, replace the blank with that character. Use join() to merge the character list into a complete string and return it.

def get_some_letters(word): letters = [] temp = '_' * len(word) for char in list(word): if char not in letters: letters.append(char) character = random.choice(letters) for num, char in enumerate(list(word)): if char == character: templist = list(temp) templist[num] = char temp = ''.join(templist) return temp

Define a function draw_hangman() that takes the number of chances as a parameter. This function provides a hanging person character. The number of chances decreases in proportion to the number of plays remaining. When the turn is over, the stickman character completes and the game ends.

 

def draw_hangman(chances): if chances == 6: print("________ ") print("| | ") print("| ") print("| ") print("| ") print("| ") elif chances == 5: print("________ ") print("| | ") print("| 0 ") print("| ") print("| ") print("| ") elif chances == 4: print("________ ") print("| | ") print("| 0 ") print("| / ") print("| ") print("| ") elif chances == 3: print("________ ") print("| | ") print("| 0 ") print("| /| ") print("| ") print("| ") elif chances == 2: print("________ ") print("| | ") print("| 0 ") print("| /| ") print("| ") print("| ") elif chances == 1: print("________ ") print("| | ") print("| 0 ") print("| /| ") print("| / ") print("| ") elif chances == 0: print("________ ") print("| | ") print("| 0 ") print("| /| ") print("| / ") print("| ")

Declare a function, start_hangman_game() that defines the main logic of the program. Get the random word by calling the function get_random_word_from_wordlist() and get the string shown to the user using the get_some_letters function .

Set the chance number to 7 and initialize a variable, found is false. You will set it to true if the guessed letter is in the word.

def start_hangman_game(): word = get_random_word_from_wordlist() temp = get_some_letters(word) chances = 7 found = False

Declare a loop that ends when the user guesses the word correctly or runs out of chances. Start the game by showing the sequence, the number of characters in the word, and the remaining chances. Ask the player to guess the word and get it using the input() function . Validate user input by checking the length of the character and see if it's alphabetic.

 while True: if chances == 0: print(f"Sorry! You Lost, the word was: {word}") print("Better luck next time") break print("=== Guess the word ===") print(temp, end='') print(f"t(word has {len(word)} letters)") print(f"Chances left: {chances}") character = input("Enter the character you think the word may have: ") if len(character) > 1 or not character.isalpha(): print("Please enter a single alphabet only") continue

If the input is valid, check if the character is in the word and replace it with the procedure seen earlier, then update the found value. If the character is not visible, the chance is reduced. If the character is present, reverting the found value to the original value is false.

 

If there are no more empty dashes, it will show the user to win with the number of guesses made. If not, show the hangman according to the number of chances left.

 else: for num, char in enumerate(list(word)): if char == character: templist = list(temp) templist[num] = char temp = ''.join(templist) found = True if found: found = False else: chances -= 1 if '_' not in temp: print(f"nYou Won! The word was: {word}") print(f"You got it in {7 - chances} guess") break else: draw_hangman(chances) print()

Define a function to play the game Hangman. If the user enters yes , call start_hangman_game() , otherwise exit the game with an appropriate message. In case the input is invalid, ask the user to re-enter the information again.

print("===== Welcome to the Hangman Game =====") while True: choice = input("Do you wanna play hangman? (yes/no): ") if 'yes' in choice.lower(): start_hangman_game() elif 'no' in choice.lower(): print('Quitting the game.') break else: print("Please enter a valid choice.") print("n")

Result:

Result when player wins:

How to make Hangman game in Python Picture 2

Result when player loses:

How to make Hangman game in Python Picture 3

Above is how to create Hangman game in Python . Hope the article is useful to you.

4 ★ | 2 Vote

May be interested

  • Bookmark 5 best Python programming learning websitesBookmark 5 best Python programming learning websites
    if you are a developer or you are studying and want to stick with this industry, learn python to add a highlight in your journey.
  • For in Python loopFor in Python loop
    in this article, we will learn more about for for loop in python as well as its variations, how to use for to repeat a string of elements in python such as list, string or other iterative objects.
  • Manage files and folders in PythonManage files and folders in Python
    python also provides a variety of methods to handle various directory-related operations. in this article, we will learn about managing files and directories in python, namely creating folders, renaming folders, listing folders and working with them.
  • Multiple choice quiz about Python - Part 3Multiple choice quiz about Python - Part 3
    today's topic quantrimang wants to challenge you is about file and exception handling in python. let's try the following 15 questions!
  • 5 choose the best Python IDE for you5 choose the best Python IDE for you
    in order to learn well python, it is essential that you find yourself an appropriate ide to develop. quantrimang would like to introduce some of the best environments to help improve your productivity.
  • What is Python? Why choose Python?What is Python?  Why choose Python?
    python is a powerful, high-level, object-oriented programming language, created by guido van rossum. python is easy to learn and emerging as one of the best introductory programming languages ​​for people who are first exposed to programming languages.
  • Module time in PythonModule time in Python
    python has a time module used to handle time-related tasks. tipsmake.com will work with you to find out the details and functions related to the time specified in this module. let's follow it!
  • Python data type: string, number, list, tuple, set and dictionaryPython data type: string, number, list, tuple, set and dictionary
    in this section, you'll learn how to use python as a computer, grasp python's data types and take the first step towards python programming.
  • How to install Python on Windows, macOS, LinuxHow to install Python on Windows, macOS, Linux
    to get started with python, you first need to install python on the computer you are using, be it windows, macos or linux. below is a guide to installing python on your computer, specific to each operating system.
  • How to set up Python to program on WSLHow to set up Python to program on WSL
    get started with cross-platform python programming by setting up python on the windows subsystem for linux. here's how to set up python for wsl programming.