Introduction
Hangman is a classic word-guessing game where players try to uncover a hidden word by guessing letters within a limited number of attempts. This program implements the Hangman game in Python, allowing users to interact with the game through the terminal.
Objective
The goal of this program is to create an interactive Hangman game in Python, enabling players to enjoy guessing words while keeping track of their attempts and progress.
Python Code
import random def choose_word(): words = ["python", "hangman", "programming", "developer", "challenge"] return random.choice(words) def display_word(word, guessed_letters): return " ".join([letter if letter in guessed_letters else "_" for letter in word]) def hangman(): word = choose_word() guessed_letters = set() attempts = 6 print("Welcome to Hangman!") while attempts > 0: print("\nWord: ", display_word(word, guessed_letters)) print(f"Attempts left: {attempts}") guess = input("Guess a letter: ").lower() if len(guess) != 1 or not guess.isalpha(): print("Invalid input. Please guess a single letter.") continue if guess in guessed_letters: print("You already guessed that letter. Try again.") continue guessed_letters.add(guess) if guess in word: print("Good guess!") if all(letter in guessed_letters for letter in word): print(f"\nCongratulations! You guessed the word: {word}") break else: attempts -= 1 print("Wrong guess.") if attempts == 0: print(f"\nGame Over! The word was: {word}") if __name__ == "__main__": hangman()
Program Explanation
This Python program creates a simple Hangman game. Here’s a breakdown of the program structure:
choose_word
: Randomly selects a word from a predefined list of words.display_word
: Displays the current state of the word, revealing correctly guessed letters and hiding others with underscores.hangman
: The main game logic, handling user input, checking guesses, and tracking attempts.
Steps to Run the Program
- Ensure Python is installed on your system.
- Copy the code into a file named
hangman.py
. - Open a terminal or command prompt and navigate to the directory containing the file.
- Run the script using the command:
python hangman.py
. - Follow the on-screen instructions to play the game.