DEV Community

Cover image for "Python Hangman: Guess the Word, Learn the Code"
Nincy
Nincy

Posted on

"Python Hangman: Guess the Word, Learn the Code"

CLI games are fantastic to solidify your understanding of programming concepts in general. One such activity I have done with Python (to learn the language) was to write a basic (Not so basic after all) Hangman game, even wanted to do it on paper several times XD – a text game in which the player has to guess the word by suggesting letters and is given only a certain number of attempts to do so.
In this article we look at the creation of the game, its design, how its mechanics are implemented, as well as our approach to handling input, and considerations I made for improvements in the future.

🧩GAME STRUCTURE🧩
The game was purposefully made an isolated, standalone game without dependencies. Here are the big details:

  • Target word as hardcoded: “universe”.
  • State: The state of the game is maintained using lists and sets.
  • Attempts limit: 8 Incorrect tries
  • Terminal I/O: Prompt about forword search, and updates based on back search. The structure is designed to be clean and the control flow to be clear, so it's not hard to follow the game's logic.

🎯CARE LOGIC 🎯
The main engine of the game is just a loop that keeps on going until the user has guessed the word or run out of turns. Here’s how the game handles the user input and updates its own state.

1- See Word State: the word is shown such as unguessed letter are displayed as (*e.g., u _ _ _ _ _ _ e *).

2- Input Validation: The user is asked to enter 1 alphabetic character. All other illegal inputs, multiple characters, numbers or punctuations are rejected and prompted with a clear message: ("Invalid input. Please enter a single alphabetic character.").

3- Tracking guesses:

  • A guessed_letters set prevents repeated inputs.
  • If the guess is correct. This is reflected in the word_display position.
  • Otherwise, the counter of remaining trials is decreased.

4- Victory defeat:

  • Winning is recognized if no underscores remain in the display.
  • When the player has no more attempts the game ends and the player sees the correct word: ("\nSorry, you've run out of attempts. The word was:", word_to_guess).

_

This concept also encourages positive user interaction and pacing and yet stays completely within terminal output.
_

🔨DESIGN CONSIDERATIONS 🔨
Having the sets such as, guessed_letters or correct_letters – especially for the above operations of lookups, makes it possible to have lookups performed effectively and keep the logic from being repeated. The list is updated in place, and the display logic can simply reflect a game state.

Although the game's word is hardcoded now, such this word can change when we decide not to have more copy-paste and we decide to "Ship" the game, as the technical team do the hard work here. But it is an opportunity for growth, as well.

LIMITATIONS
This game was a great way to practice:

  • Validation of the input and cycling of the user.
  • The manipulation of simple data structures for state handling.
  • That big picture of breaking logic into friendly, maintainable blocks.
  • How to keep user experience even between CLI based environments.

Simple though it may be, it is a good example of interactive programming and it shows how simple projects can light the way to broaden programming concepts.

👣 NEXT STEPS 👣
Some improvements I might suggest for future versions:

  • Use random. choice() to choose a word from a list or a file with a dictionary.
  • Add ASCII visuals of the hangman as attempts decrease.
  • Add some challenge levels by modifying the word length or the attempts.
  • Add support for whole word guessing and hints: (this would make the game not just an introduction, but a full-fledged fun interactive CLI application)

💡 FINAL THOUGHTS 💡
It’s a little one-trick pony of a game, but it does what it aims to do: provide a playable, interactive game using basic Python data structures. It also establishes the base to work with.
Whether a learning aid, interview showpiece or simply a steppingstone to bigger work, this sort of game demonstrates how straightforward code can still be memorable, enjoyable and illuminating.

CODE BLOCK

import string

word_to_guess = "universe"
max_attempts = 8
guessed_letters = set()
correct_letters = set()
word_display = ["_"] * len(word_to_guess)

print("Welcome to Hangman!")
print(f"You have {max_attempts} attempts to guess the word.")
print("The word has", len(word_to_guess), "letters.")

def display_word():
    return " ".join(word_display)

attempts_left = max_attempts
while attempts_left > 0:
    print("\nWord:", display_word())
    print(f"Attempts remaining: {attempts_left}")

    guess = input("Enter a single letter: ").lower()

    if len(guess) != 1 or guess not in string.ascii_lowercase:
        print("Invalid input. Please enter a single alphabetic character.")
        continue

    if guess in guessed_letters:
        print("You've already guessed that letter.")
        continue

    guessed_letters.add(guess)

    if guess in word_to_guess:
        print("Good guess!")
        for i, char in enumerate(word_to_guess):
            if char == guess:
                word_display[i] = guess
                correct_letters.add(guess)
        if "_" not in word_display:
            print("\nCongratulations! You guessed the word:", word_to_guess)
            break
    else:
        print("Wrong guess.")
        attempts_left -= 1

else:
    print("\nSorry, you've run out of attempts. The word was:", word_to_guess)

Enter fullscreen mode Exit fullscreen mode

Image credits

Top comments (0)