w3resource

Python Project: Hangman Game - Solutions and Explanations


Hangman Game:

Build a hangman game where players guess a word by suggesting letters. The game continues until the player correctly guesses the word or runs out of attempts.

Input values:
Player suggests a letter to guess the word.

Output value:
Feedback on whether the guessed letter is correct or incorrect. With revealed letters, display the current state of the word.

Example:

Input values:
Guess a letter: A
Output value:
Incorrect! Current state: _
Input values:
Guess a letter: E
Output value:
Correct! Current state: E 
Input values:
Guess a letter: S
Output value:
Incorrect! Current state: E 
Input values:
Guess a letter: R
Output value:
Correct! Current state: E R _ 

Here are two different solutions for a "Hangman" game in Python. The game allows players to guess a word by suggesting letters. The game continues until the player either correctly guesses the word or runs out of attempts.

Solution 1: Basic Approach using Functions and Loops

Code:

# Solution 1: Basic Approach Using Functions and Loops

import random  # Import the random module to select a random word

# List of words for the Hangman game
word_list = ['python', 'hangman', 'programming', 'developer', 'algorithm']

def choose_word(word_list):
    """Randomly select a word from the word list."""
    return random.choice(word_list)

def display_current_state(word, guessed_letters):
    """Display the current state of the guessed word with correct letters revealed."""
    current_state = ''.join([letter if letter in guessed_letters else '_' for letter in word])
    return current_state

def hangman():
    """Main function to play the Hangman game."""
    # Choose a random word for the player to guess
    word_to_guess = choose_word(word_list)
    guessed_letters = set()  # Set to store guessed letters
    attempts_left = 6  # Number of attempts allowed

    print("Welcome to Hangman!")
    print("Try to guess the word!")

    # Game loop
    while attempts_left > 0:
        # Display the current state of the word
        current_state = display_current_state(word_to_guess, guessed_letters)
        print(f"Current state: {current_state}")
        
        # Check if the player has guessed the entire word
        if '_' not in current_state:
            print("Congratulations! You've guessed the word!")
            break

        # Get the player's guess
        guess = input("Guess a letter: ").lower()

        # Validate the player's guess
        if len(guess) != 1 or not guess.isalpha():
            print("Invalid input. Please enter a single letter.")
            continue

        # Check if the letter was already guessed
        if guess in guessed_letters:
            print("You've already guessed that letter. Try again.")
            continue

        # Add the guessed letter to the set of guessed letters
        guessed_letters.add(guess)

        # Check if the guessed letter is in the word
        if guess in word_to_guess:
            print("Correct!")
        else:
            print("Incorrect!")
            attempts_left -= 1
            print(f"Attempts left: {attempts_left}")

    # If the player runs out of attempts
    if attempts_left == 0:
        print(f"Sorry, you've run out of attempts. The word was '{word_to_guess}'.")

# Start the Hangman game
hangman()

Output:

Welcome to Hangman!
Try to guess the word!
Current state: _________
Guess a letter: D
Incorrect!
Attempts left: 5
Current state: _________
Guess a letter: E
Incorrect!
Attempts left: 4
Current state: _________
Guess a letter: P
Incorrect!
Attempts left: 3
Current state: _________
Guess a letter: Q
Incorrect!
Attempts left: 2
Current state: _________
Guess a letter: S
Incorrect!
Attempts left: 1
Current state: _________
Guess a letter: A
Correct!
Current state: a________
Guess a letter: C
Incorrect!
Attempts left: 0
Sorry, you've run out of attempts. The word was 'algorithm'.

Explanation:

  • This solution uses basic functions and loops to implement the Hangman game.
  • The 'choose_word()' function selects a random word from the list.
  • The 'display_current_state()' function shows the current state of the word, revealing the correct guessed letters.
  • The main 'hangman()' function handles the game logic, including user input, validation, checking for guessed letters, and updating attempts.
  • This approach is simple and effective but lacks structure for future expansions or enhancements.

Solution 2: Using a Class-Based approach for Organization and Reusability

Code:

# Solution 2: Using a Class-Based Approach for Organization and Reusability

import random  # Import the random module to select a random word

class HangmanGame:
    """Class to handle the Hangman game logic"""

    def __init__(self, word_list):
        """Initialize the game with a list of words and default values"""
        self.word_list = word_list
        self.word_to_guess = random.choice(word_list)
        self.guessed_letters = set()
        self.attempts_left = 6

    def display_current_state(self):
        """Display the current state of the guessed word with correct letters revealed"""
        return ''.join([letter if letter in self.guessed_letters else '_' for letter in self.word_to_guess])

    def make_guess(self, guess):
        """Process the player's guess and update game state"""
        # Add the guessed letter to the set of guessed letters
        self.guessed_letters.add(guess)

        # Check if the guessed letter is in the word
        if guess in self.word_to_guess:
            print("Correct!")
        else:
            print("Incorrect!")
            self.attempts_left -= 1
            print(f"Attempts left: {self.attempts_left}")

    def play(self):
        """Main function to play the Hangman game"""
        print("Welcome to Hangman!")
        print("Try to guess the word!")

        # Game loop
        while self.attempts_left > 0:
            # Display the current state of the word
            current_state = self.display_current_state()
            print(f"Current state: {current_state}")
            
            # Check if the player has guessed the entire word
            if '_' not in current_state:
                print("Congratulations! You've guessed the word!")
                break

            # Get the player's guess
            guess = input("Guess a letter: ").lower()

            # Validate the player's guess
            if len(guess) != 1 or not guess.isalpha():
                print("Invalid input. Please enter a single letter.")
                continue

            # Check if the letter was already guessed
            if guess in self.guessed_letters:
                print("You've already guessed that letter. Try again.")
                continue

            # Make the guess and update the game state
            self.make_guess(guess)

        # If the player runs out of attempts
        if self.attempts_left == 0:
            print(f"Sorry, you've run out of attempts. The word was '{self.word_to_guess}'.")

# List of words for the Hangman game
word_list = ['python', 'hangman', 'programming', 'developer', 'algorithm']

# Create an instance of the HangmanGame class
game = HangmanGame(word_list)

# Start the Hangman game
game.play()

Output:

Welcome to Hangman!
Try to guess the word!
Current state: ______
Guess a letter: p
Correct!
Current state: p_____
Guess a letter: y
Correct!
Current state: py____
Guess a letter: t
Correct!
Current state: pyt___
Guess a letter: h
Correct!
Current state: pyth__
Guess a letter: o
Correct!
Current state: pytho_
Guess a letter: n
Correct!
Current state: python
Congratulations! You've guessed the word!
Welcome to Hangman!
Try to guess the word!
Current state: _________
Guess a letter: v
Correct!
Current state: __v______
Guess a letter: d
Correct!
Current state: d_v______
Guess a letter: e
Correct!
Current state: deve___e_
Guess a letter: l
Correct!
Current state: devel__e_
Guess a letter: r
Correct!
Current state: devel__er
Guess a letter: o
Correct!
Current state: develo_er
Guess a letter: p
Correct!
Current state: developer
Congratulations! You've guessed the word!

Explanation:

  • This solution encapsulates all game logic within a 'HangmanGame' class, which is more organized and modular.
  • The '__init__' method initializes the game state (word to guess, guessed letters, attempts left).
  • The 'display_current_state()' method shows the current state of the word.
  • The 'make_guess()' method processes each guess and updates the game state.
  • The 'play()' method controls the game flow, taking user input and managing game progression.
  • This approach follows Object-Oriented Programming (OOP) principles, making the code easier to extend, maintain, and reuse.

Note:
Both solutions achieve the goal of implementing a basic Hangman game where players guess a word by suggesting letters, with Solution 1 using a straightforward function-based approach and Solution 2 utilizing a more organized, class-based design.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/projects/python/python-hangman-game-project.php