How to make Hangman game in Python
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:
Result when player loses:
Above is how to create Hangman game in Python . Hope the article is useful to you.
You should read it
- How to create Hangman game using Svelte
- How to Create Power-Ups and Collections in Pygame
- How to add dialogue system in Python game using Arcade library
- How to use sprites in Arcade to develop games
- How to create scrolling backgrounds in Pygame
- How to Add Randomly Moving Objects Using Python's Arcade Library
- Build a color game using Tkinter in Python
- Easier game development with Pygame Zero
- How to Program a Game in Python with Pygame
- How to set up Python to program on WSL
- What is Python? Why choose Python?
- How to create a jumping mechanism in Godot
Maybe you are interested
How to optimize photo collages for social media and printing
How to print horizontally in Word Excel all versions
How to print multiple pages on one sheet of paper in Word 2010, 2013
What is Digital Footprint?
Excel 2016 - Lesson 12: Formatting pages and printing spreadsheets in Excel
How to print multiple Word files at once on your computer