Skip to content

Hangman Game

Abstract

Hangman is a classic word guessing game where players try to guess a hidden word by suggesting letters within a limited number of attempts. This Python implementation uses a text file containing a list of words and randomly selects one for the player to guess. The game provides feedback on correct and incorrect guesses and tracks the number of remaining attempts. This project is excellent for beginners to learn about file handling, string manipulation, and game logic in Python.

Prerequisites

  • Python 3.6 or above
  • A code editor or IDE
  • A text file with words (words.txt)

Before you Start

Before starting this project, you must have Python installed on your computer. If you don’t have Python installed, you can download it from here. You must have a code editor or IDE installed on your computer. If you don’t have any code editor or IDE installed, you can download Visual Studio Code from here.

Getting Started

Create a Project

  1. Create a folder named hangman-gamehangman-game.
  2. Open the folder in your favorite code editor or IDE.
  3. Create a file named hangman.pyhangman.py.
  4. Create a file named words.txtwords.txt and add some words (one word per line).
  5. Copy the given code and paste it in your hangman.pyhangman.py file.

Create Words File

Create a words.txtwords.txt file in the same directory and add words like:

words.txt
python
programming
computer
science
technology
development
software
coding
algorithm
function
words.txt
python
programming
computer
science
technology
development
software
coding
algorithm
function

Write the Code

  1. Copy and paste the following code in your hangman.pyhangman.py file.
⚙️ Hangman Game
Hangman Game
# Hangman game
# -----------------------------------
 
# Importing the random module
import random
import time
 
# Inputting the name of the user
name = input("What is your name? ")
print("Good Luck ! ", name)
 
time.sleep(1)
 
print("The game is about to start !")
print("Let's play Hangman")
 
time.sleep(1)
 
open_file = open("words.txt", "r")
words = open_file.readlines()
 
# Function will choose one random
# word from this list of words
word = random.choice(words)
word = word.lower().strip().replace("\n", "").replace("\r", "").replace(" ", "").replace("-", "")
print("Guess the characters")
 
guesses = ''
turns = len(word) * 2 
 
# Checks if the turns are more than zero
while turns > 0:
    failed = 0
 
    # for every character in secret_word
    for char in word:
 
        # see if the character is in the players guess
        if char in guesses:
            print(char, end="")
 
        else:
            print("_", end="")
 
            # and increase the failed counter with one
            failed += 1
 
    if failed == 0:
        print("\nYou Win")
 
        # this print the correct word
        print("The word is: ", word)
        break
 
    # if failed equals to zero
    # then you will get this message
    if turns == 1:
        print("\nYou have", turns, 'more guess')
    else:
        print("\nYou have", turns, 'more guesses')
 
    guess = input("guess a character: ")
 
    # every input character will be stored in guesses
    guesses += guess
 
    # check input with the character in word
    if guess not in word:
 
        turns -= 1
 
        # if the character doesn’t match the word
        # then “Wrong” will be given as output
        print("Wrong")
 
        # this will print the number of
        # turns left for the user
        if turns == 1:
            print("\nYou have", turns, 'more guess')
        else:
            print("\nYou have", turns, 'more guesses')
 
        if turns == 0:
            print("\nYou Loose")
            print("\nThe word is: ", word)
            break
 
Hangman Game
# Hangman game
# -----------------------------------
 
# Importing the random module
import random
import time
 
# Inputting the name of the user
name = input("What is your name? ")
print("Good Luck ! ", name)
 
time.sleep(1)
 
print("The game is about to start !")
print("Let's play Hangman")
 
time.sleep(1)
 
open_file = open("words.txt", "r")
words = open_file.readlines()
 
# Function will choose one random
# word from this list of words
word = random.choice(words)
word = word.lower().strip().replace("\n", "").replace("\r", "").replace(" ", "").replace("-", "")
print("Guess the characters")
 
guesses = ''
turns = len(word) * 2 
 
# Checks if the turns are more than zero
while turns > 0:
    failed = 0
 
    # for every character in secret_word
    for char in word:
 
        # see if the character is in the players guess
        if char in guesses:
            print(char, end="")
 
        else:
            print("_", end="")
 
            # and increase the failed counter with one
            failed += 1
 
    if failed == 0:
        print("\nYou Win")
 
        # this print the correct word
        print("The word is: ", word)
        break
 
    # if failed equals to zero
    # then you will get this message
    if turns == 1:
        print("\nYou have", turns, 'more guess')
    else:
        print("\nYou have", turns, 'more guesses')
 
    guess = input("guess a character: ")
 
    # every input character will be stored in guesses
    guesses += guess
 
    # check input with the character in word
    if guess not in word:
 
        turns -= 1
 
        # if the character doesn’t match the word
        # then “Wrong” will be given as output
        print("Wrong")
 
        # this will print the number of
        # turns left for the user
        if turns == 1:
            print("\nYou have", turns, 'more guess')
        else:
            print("\nYou have", turns, 'more guesses')
 
        if turns == 0:
            print("\nYou Loose")
            print("\nThe word is: ", word)
            break
 
  1. Save the file.
  2. Make sure you have the words.txtwords.txt file in the same directory.
  3. Open the terminal in your code editor or IDE and navigate to the folder hangman-gamehangman-game.
command
C:\Users\Your Name\hangman-game> python hangman.py
What is your name? John
Good Luck !  John
The game is about to start !
Let's play Hangman
Guess the characters
________
You have 16 more guesses
guess a character: p
p_______
You have 16 more guesses
guess a character: r
pr______
You have 16 more guesses
guess a character: o
pro_____
You have 16 more guesses
guess a character: g
prog____
You have 16 more guesses
guess a character: r
progr___
You have 16 more guesses
guess a character: a
progra__
You have 16 more guesses
guess a character: m
program_
You have 16 more guesses
guess a character: m
programm
You have 15 more guesses
guess a character: i
programmi
You have 15 more guesses
guess a character: n
programming
You Win
The word is:  programming
command
C:\Users\Your Name\hangman-game> python hangman.py
What is your name? John
Good Luck !  John
The game is about to start !
Let's play Hangman
Guess the characters
________
You have 16 more guesses
guess a character: p
p_______
You have 16 more guesses
guess a character: r
pr______
You have 16 more guesses
guess a character: o
pro_____
You have 16 more guesses
guess a character: g
prog____
You have 16 more guesses
guess a character: r
progr___
You have 16 more guesses
guess a character: a
progra__
You have 16 more guesses
guess a character: m
program_
You have 16 more guesses
guess a character: m
programm
You have 15 more guesses
guess a character: i
programmi
You have 15 more guesses
guess a character: n
programming
You Win
The word is:  programming

Explanation

  1. Import the required modules.
hangman.py
import random
import time
hangman.py
import random
import time
  1. Get the player’s name and provide welcome messages.
hangman.py
name = input("What is your name? ")
print("Good Luck ! ", name)
 
time.sleep(1)
 
print("The game is about to start !")
print("Let's play Hangman")
 
time.sleep(1)
hangman.py
name = input("What is your name? ")
print("Good Luck ! ", name)
 
time.sleep(1)
 
print("The game is about to start !")
print("Let's play Hangman")
 
time.sleep(1)
  1. Read words from the file and select a random word.
hangman.py
open_file = open("words.txt", "r")
words = open_file.readlines()
word = random.choice(words)
word = word.lower().strip().replace("\n", "").replace("\r", "").replace(" ", "").replace("-", "")
hangman.py
open_file = open("words.txt", "r")
words = open_file.readlines()
word = random.choice(words)
word = word.lower().strip().replace("\n", "").replace("\r", "").replace(" ", "").replace("-", "")
  1. Initialize game variables.
hangman.py
print("Guess the characters")
guesses = ''
turns = len(word) * 2
hangman.py
print("Guess the characters")
guesses = ''
turns = len(word) * 2
  1. Main game loop - check guesses and display progress.
hangman.py
while turns > 0:
    failed = 0
    for char in word:
        if char in guesses:
            print(char, end="")
        else:
            print("_", end="")
            failed += 1
    
    if failed == 0:
        print("\nYou Win")
        print("The word is: ", word)
        break
hangman.py
while turns > 0:
    failed = 0
    for char in word:
        if char in guesses:
            print(char, end="")
        else:
            print("_", end="")
            failed += 1
    
    if failed == 0:
        print("\nYou Win")
        print("The word is: ", word)
        break
  1. Handle user input and game logic.
hangman.py
guess = input("guess a character: ")
guesses += guess
 
if guess not in word:
    turns -= 1
    print("Wrong")
    
    if turns == 0:
        print("\nYou Loose")
        print("\nThe word is: ", word)
        break
hangman.py
guess = input("guess a character: ")
guesses += guess
 
if guess not in word:
    turns -= 1
    print("Wrong")
    
    if turns == 0:
        print("\nYou Loose")
        print("\nThe word is: ", word)
        break

Features

  • Random word selection from a text file
  • Limited number of guesses based on word length
  • Real-time progress display with underscores
  • Win/lose conditions with appropriate messages
  • Input validation and feedback
  • Clean and intuitive user interface

How to Play

  1. Run the program and enter your name
  2. The game will display underscores representing each letter of the hidden word
  3. Guess letters one at a time
  4. Correct guesses reveal the letter’s position(s) in the word
  5. Incorrect guesses reduce your remaining attempts
  6. Win by guessing all letters before running out of attempts
  7. Lose if you exhaust all attempts without completing the word

Next Steps

You can enhance this project by:

  • Adding a graphical hangman drawing for wrong guesses
  • Implementing difficulty levels with different word categories
  • Adding a scoring system based on guesses used
  • Creating a GUI version using Tkinter
  • Adding hint functionality
  • Implementing multiplayer mode
  • Adding word definitions or categories

Conclusion

In this project, we learned how to create a Hangman game using Python. We covered file handling to read words from a text file, string manipulation for processing the selected word, and game logic for tracking guesses and determining win/lose conditions. This project demonstrates essential programming concepts like loops, conditionals, and user input handling. To find more projects like this, you can visit Python Central Hub.

Was this page helpful?

Let us know how we did