Hangman Game Program in Python

 

 

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

  1. Ensure Python is installed on your system.
  2. Copy the code into a file named hangman.py.
  3. Open a terminal or command prompt and navigate to the directory containing the file.
  4. Run the script using the command: python hangman.py.
  5. Follow the on-screen instructions to play the game.
© 2024 Learn Programming. All Rights Reserved.

 

One Reply to “Hangman Game Program in Python”

Leave a Reply to binance registration Cancel reply

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