Loading

Hangman is a classic word-guessing game that people of all ages have enjoyed for many years. The game is played by guessing the letters of a word, with each incorrect guess resulting in a part of a stick figure being drawn. The game continues until the word is correctly guessed or the stick figure is completed.

This article will create a Hangman game in Python using an external word list stored in a text file. This approach allows us to easily add or remove words from the word list without modifying the code.

Implementation

We will start by importing the random module, which will be used to select a word from the word list.

import random

Next, we will define the play_hangman function, which will contain the logic for our game. The function will print a welcome message, open the external word list file, and select a random word from the list.

def play_hangman():
    print("Welcome to the Hangman game!")
    with open("words.txt", "r") as file:
        word_list = file.read().splitlines()
    random_word = random.choice(word_list)

Here’s an example of a words.txt file:

Calculator 
Banana 
Elephant 
Rainbow 
Butterflies

Each line in the file contains a single word. These words are used as the possible word choices in the Hangman game.

We will then print the length of the word and initialize a list of underscores, one for each letter in the word. This variable will represent the word with all its letters hidden. We will also initialize the number of tries to 6 and an empty list to keep track of used letters.

    print("The word has", len(random_word), "letters.")
    correct_word = ["_"] * len(random_word)
    print(*correct_word)
    tries = 6
    used_letters = []

We will then enter a loop where we repeatedly prompt the player to guess a letter. If the player has already used that letter, we will let them know and ask for another guess. If the letter is in the word, we will update the correct_word list with the correctly guessed letters and print it. Lastly, if the letter is not in the word, we will decrement the number of tries and let the player know.

 while "_" in correct_word and tries > 0:
        guess = input("Guess a letter: ").lower()
        if guess in used_letters:
            print("You already used that letter. Try again.")
        elif guess in random_word:
            used_letters.append(guess)
            for i in range(len(random_word)):
                if random_word[i] == guess:
                    correct_word[i] = guess
            print(*correct_word)
        else:
            tries -= 1
            print("Incorrect! You have", tries, "tries left.")

Finally, we will check if the player has won or lost. They won if they correctly guessed all the letters in the word. Otherwise, they have lost, and we will print the word.

    if "_" not in correct_word:
        print("You won!")
    else:
        print("You lost! The word was", random_word + ".")

We will then call the play_hangman function to start the game.

play_hangman()

In conclusion, we have seen how to create a Hangman game in Python using an external word list stored in a text file. The external text file provides a convenient way to manage the list of words used in the game, without having to modify the code each time a new word is added or removed. The implementation of the game uses basic programming concepts, such as reading from a file, selecting a random element, and looping until a condition is met. This project is a great example of how to write a simple yet entertaining game using Python, and can serve as a starting point for more complex projects.

Here is the entire program:

import random

def play_hangman():
    print("Hangman Game")
    with open("words.txt", "r") as file:
        word_list = file.read().splitlines()
    random_word = random.choice(word_list)
    print("The word has", len(random_word), "letters.")
    correct_word = ["_"] * len(random_word)
    print(*correct_word)
    tries = 6
    used_letters = []

    while "_" in correct_word and tries > 0:
        guess = input("Guess a letter: ").lower()
        if guess in used_letters:
            print("You already used that letter. Try again.")
        elif guess in random_word:
            used_letters.append(guess)
            for i in range(len(random_word)):
                if random_word[i] == guess:
                    correct_word[i] = guess
            print(*correct_word)
        else:
            tries -= 1
            print("Incorrect! You have", tries, "tries left.")

    if "_" not in correct_word:
        print("You won!")
    else:
        print("You lost! The word was", random_word + ".")

play_hangman()

Add Comment

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