Hangman Game in Python

Introduction

The Hangman game is a classic word-guessing game where players attempt to guess a hidden word by suggesting letters within a certain number of attempts. This Python implementation of Hangman provides a fun way to test your vocabulary and guessing skills. Players are given hints to help them guess the word, and they score points based on their guesses.

Prerequisites

Before running the Hangman game, ensure you have the following:

  1. Python 3.x: The game is written in Python, so you’ll need Python 3.x installed on your machine. You can download it from python.org.
  2. Basic Python Knowledge: Understanding basic Python concepts such as loops, conditionals, and functions will help you understand and modify the code.

Learning Objectives

By working through this project, you will learn:

  1. How to use Python for creating simple command-line games.
  2. How to work with lists, loops, and conditionals in Python.
  3. How to implement basic game logic and user interactions.
  4. How to use randomization and basic string manipulation in Python.

Installation Guide

  1. Install Python: If you haven’t already installed Python, download and install it from python.org.
  2. Set Up a Development Environment: You can use any text editor or IDE (Integrated Development Environment) of your choice.
  3. Download the Hangman Game Code: Copy the Hangman game code provided into a Python file. For example, you can name it hangman.py.

Project Steps

  1. Initialization: Set up the word list, hint list, and necessary global variables.
    • Define the hints and words.
    • Create lists for hints and corresponding words.
    • Initialize variables for keeping track of guessed letters and attempts.
  2. User Input: Prompt players to input their guesses (letters or whole words) in each turn.
    • Prompt for the player’s name.
    • Display the hint for the current word.
    • Ask the player to guess a letter or the entire word.
  3. Game Logic: Implement functions to update the game state, check for correct or incorrect guesses, and determine the game’s outcome.
    • Function dash to display the current state of the guessed word with dashes and correctly guessed letters.
    • Function game_on to check if the player wants to play another round.
    • Update the word display based on correct or incorrect guesses.
    • Keep track of the number of attempts left.
    • Determine if the player has won, lost, or needs to continue guessing.
  4. Gameplay Loop: Run the game in a loop until the player either wins, loses, or chooses to end the game.
    • Randomly select a word and its hint for each game.
    • Continuously prompt the player for guesses until the word is guessed or attempts run out.
    • After each game, ask if the player wants to play again.
    • End the game if the player chooses not to continue.

Code

				
					import random
import time

hints = ["Scary, floats", "Sand and water", "Shows happiness", "Makes things red, blue, etc.", "Stays on top of water", "Challenging to put together", "Lets you see outside",  "Speak very softly", "Captures pictures", "Colorful arc after rain", "What you learn and know",  "Beautiful flying insect", "Very grand or impressive", "Place you go to eat", "Makes lights work", "What you say to someone who wins", "A chance to do something", "Unusual event", "The words you know", "Being accountable for something",  
]

words = ["Ghost", "Beach", "Smile", "Color", "Float", "Puzzle", "Window", "Whisper", "Camera", "Rainbow", "Knowledge", "Butterfly", "Magnificent", "Restaurant", "Electricity", "Congratulations", "Opportunity", "Phenomenon", "Vocabulary", "Responsibility"
]

def dash(word):
    global ol
    for i in range(len(word)):
        print(ol[i], end=" ")
        time.sleep(0.2)
    print()

def game_on():
    ask=input("do you want to play again .enter yes or no.").lower()
    if ask=="yes":
        return 'yes'
    elif ask=="no":
        return "break"
    else:
        print("invalid text.")
        return "break"
print("----------WELCOME TO THE GAME OF HANGMAN---------- .\n")
name=input("Enter your name.\n")
print(f"Lets begin {name}!!!\n")
idx=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
while True:
    a=random.choice(idx)
    idx.remove(a)
    print(f"HINT: {hints[a]} \n")
    word=words[a].upper()
    ol=["_" for i in range(len(word))]
    dash(word)
    attempt=5
    guessed=[]
    if "_" not in ol: print(f"you won !! you guessed the word correctly. \nyour score is: {attempt*10} \n")
    while attempt> 0:
        if "_" in ol:
            ans=input("Enter an alphabet or word : \n").upper()
            if ans in guessed:
                print("you have already guessed the alphabet ! \n")
                continue
            elif ans==word:
                print(f"you guessed the word correctly. \nYour Score is : {attempt*10}\n")
                break
            else:
                guessed.append(ans)
                if ans not in word:
                    attempt=attempt-1
                    print(f"its wrong !. you have {attempt} chances left \n")

                if ans in word:
                    attempt=attempt-1
                    for i in range(len(word)):
                        if word[i]==ans:
                            ol[i]=ans
                    print(f"it's correct ! you have {attempt} chances left. \n ")

                dash(word)
    else:
        print("you lost")
        print(f"the word was: {word} \nYour score is 0. ")
    g=game_on()
    if g=="break":
        break

				
			

Code

				
					import random
import time

hints = ["Scary, floats", "Sand and water", "Shows happiness", "Makes things red, blue, etc.", "Stays on top of water", "Challenging to put together", "Lets you see outside",  "Speak very softly", "Captures pictures", "Colorful arc after rain", "What you learn and know",  "Beautiful flying insect", "Very grand or impressive", "Place you go to eat", "Makes lights work", "What you say to someone who wins", "A chance to do something", "Unusual event", "The words you know", "Being accountable for something",  
]

words = ["Ghost", "Beach", "Smile", "Color", "Float", "Puzzle", "Window", "Whisper", "Camera", "Rainbow", "Knowledge", "Butterfly", "Magnificent", "Restaurant", "Electricity", "Congratulations", "Opportunity", "Phenomenon", "Vocabulary", "Responsibility"
]

def dash(word):
    global ol
    for i in range(len(word)):
        print(ol[i], end=" ")
        time.sleep(0.2)
    print()

def game_on():
    ask=input("do you want to play again .enter yes or no.").lower()
    if ask=="yes":
        return 'yes'
    elif ask=="no":
        return "break"
    else:
        print("invalid text.")
        return "break"
print("----------WELCOME TO THE GAME OF HANGMAN---------- .\n")
name=input("Enter your name.\n")
print(f"Lets begin {name}!!!\n")
idx=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
while True:
    a=random.choice(idx)
    idx.remove(a)
    print(f"HINT: {hints[a]} \n")
    word=words[a].upper()
    ol=["_" for i in range(len(word))]
    dash(word)
    attempt=5
    guessed=[]
    if "_" not in ol: print(f"you won !! you guessed the word correctly. \nyour score is: {attempt*10} \n")
    while attempt> 0:
        if "_" in ol:
            ans=input("Enter an alphabet or word : \n").upper()
            if ans in guessed:
                print("you have already guessed the alphabet ! \n")
                continue
            elif ans==word:
                print(f"you guessed the word correctly. \nYour Score is : {attempt*10}\n")
                break
            else:
                guessed.append(ans)
                if ans not in word:
                    attempt=attempt-1
                    print(f"its wrong !. you have {attempt} chances left \n")

                if ans in word:
                    attempt=attempt-1
                    for i in range(len(word)):
                        if word[i]==ans:
                            ol[i]=ans
                    print(f"it's correct ! you have {attempt} chances left. \n ")

                dash(word)
    else:
        print("you lost")
        print(f"the word was: {word} \nYour score is 0. ")
    g=game_on()
    if g=="break":
        break

				
			

Flow Chart

Hangman Game in Python

Pseudo Code explaining this Python Project

				
					INITIALIZATION:
    Import random module
    Import time module

    Define hints list with corresponding hints
    Define words list with words to be guessed

DEFINE HELPER FUNCTIONS:
    Function dash(word):
        For each character in the word:
            Print an underscore with a delay

    Function game_on():
        Prompt player to enter 'yes' or 'no' to play again
        If player enters 'yes', return 'yes'
        Else, return 'break'

MAIN GAME LOOP:
    Print welcome message
    Prompt player to enter their name

    Initialize list of indices for words

    While there are indices left in the list:
        Randomly select an index from the list
        Remove selected index from the list
        Print the hint for the selected word

        Convert selected word to uppercase
        Initialize list of underscores for each letter in the word
        Call dash(word) to display initial state

        Initialize number of attempts to 5
        Initialize empty list for guessed letters

        Check if word is already guessed:
            If yes, print winning message and score

        While attempts are greater than 0:
            If word is not fully guessed:
                Prompt player to guess a letter or word
                If guess is already made:
                    Print message and continue
                If guess is correct word:
                    Print winning message and score
                    Break loop
                Else:
                    Add guess to guessed list
                    If guess is incorrect:
                        Decrement attempts
                        Print message
                    If guess is correct letter:
                        Update list of underscores with guessed letter
                        Print message
                    Call dash(word) to display current state

        If attempts are 0:
            Print losing message, correct word, and score 0

    Call game_on() to check if player wants to play again
    If player does not want to play again, break loop

				
			

Pseudo Code explaining this Python Project

				
					INITIALIZATION:
    Import random module
    Import time module

    Define hints list with corresponding hints
    Define words list with words to be guessed

DEFINE HELPER FUNCTIONS:
    Function dash(word):
        For each character in the word:
            Print an underscore with a delay

    Function game_on():
        Prompt player to enter 'yes' or 'no' to play again
        If player enters 'yes', return 'yes'
        Else, return 'break'

MAIN GAME LOOP:
    Print welcome message
    Prompt player to enter their name

    Initialize list of indices for words

    While there are indices left in the list:
        Randomly select an index from the list
        Remove selected index from the list
        Print the hint for the selected word

        Convert selected word to uppercase
        Initialize list of underscores for each letter in the word
        Call dash(word) to display initial state

        Initialize number of attempts to 5
        Initialize empty list for guessed letters

        Check if word is already guessed:
            If yes, print winning message and score

        While attempts are greater than 0:
            If word is not fully guessed:
                Prompt player to guess a letter or word
                If guess is already made:
                    Print message and continue
                If guess is correct word:
                    Print winning message and score
                    Break loop
                Else:
                    Add guess to guessed list
                    If guess is incorrect:
                        Decrement attempts
                        Print message
                    If guess is correct letter:
                        Update list of underscores with guessed letter
                        Print message
                    Call dash(word) to display current state

        If attempts are 0:
            Print losing message, correct word, and score 0

    Call game_on() to check if player wants to play again
    If player does not want to play again, break loop

				
			

Code Explanation

  • Imports:
    • import random: Used to randomly select a word from the list.
    • import time: Used to add delays in the display of the word.
  • Hints and Words Lists:
    • hints: A list of hints corresponding to each word in the game.
    • words: A list of words that players will guess.
  • Helper Functions:
    • dash(word): Displays the current state of the guessed word, showing underscores for unguessed letters.
    • game_on(): Prompts the player to decide if they want to play another game and returns their choice.
  • Main Game Loop:
    • Welcome Message and Player Name:
      • Prints a welcome message and prompts the player to enter their name.
    • Word Selection and Initialization:
      • Randomly selects a word and its corresponding hint.
      • Initializes a list with underscores representing the unguessed letters of the word.
    • Gameplay:
      • Displays the hint and current state of the word.
      • Continuously prompts the player to guess a letter or the whole word until they either guess the word correctly or run out of attempts.
      • Keeps track of guessed letters to prevent repeated guesses.
      • Updates the state of the word and the number of attempts based on the player’s guesses.
    • End of Game:
      • Displays a message indicating whether the player won or lost, along with the correct word and score.
    • Play Again Prompt:
      • Asks the player if they want to play another round and continues or breaks the loop based on their response.

Challenges and Solutions

  • Challenge: Handling repeated guesses.

    • Solution: Maintain a list of guessed letters and words. Before processing a guess, check if it has already been guessed. If it has, inform the player and prompt for a new guess.

    Challenge: Ensuring valid inputs.

    • Solution: Validate each guess to ensure it is a single letter or the entire word. Handle invalid inputs by informing the player and prompting for a valid guess.

    Challenge: Providing real-time feedback.

    • Solution: Use functions to update the display of the word with correctly guessed letters and provide immediate feedback on correct or incorrect guesses.

Testing

  • Test with Various Inputs:
    • Ensure the game correctly processes single letter guesses, whole word guesses, and repeated guesses.
    • Verify that incorrect guesses decrease the number of attempts.
  • Verify Game Scenarios:
    • Check that the game correctly identifies win conditions when the word is fully guessed.
    • Ensure the game recognizes and handles loss conditions when the player runs out of attempts.
    • Test edge cases such as guessing the entire word correctly on the first try.
  • Test Play Again Functionality:
    • Verify that the game correctly prompts and handles the player’s decision to play another game or exit.

Additional Resources

FAQs

Q: Can the game handle repeated guesses?

A: Yes, the game maintains a list of guessed letters and words to ensure repeated guesses are not processed again. Players are informed if they attempt to guess a letter or word that has already been guessed.

Q: How are the guesses validated?

A: Each guess is checked to ensure it is either a single letter or the entire word. Invalid inputs are not processed, and the player is prompted to enter a valid guess.

Q: How is the word display updated?

A: The game uses a function to update the display of the word, showing underscores for unguessed letters and revealing correctly guessed letters in their respective positions.

Q: Can the game be played with more than one player?

A: The game is designed for single-player use. It does not support multiple players or turns in its current implementation.

Q: What happens when the player runs out of attempts?

A: When the player runs out of attempts, the game displays a message indicating they have lost, reveals the correct word, and sets the score to zero.

Q: Can the player play multiple games in a session?

A: Yes, after each game, the player is prompted to decide if they want to play again. If they choose to continue, a new word and hint are selected, and the game restarts.

Project by Anushka Khemaria, Team edSlash.