Hangman Game in Python - GeeksforGeeks

08 Jun, 2018
Hangman is a word game in which computer will randomly select a word from the dictionary and player has to guess it correctly in given number of turns. The word to be guessed is represented by row of stars. If the guessed letter is present is word, script will automatically be placed to correct places.
Rules to guess the word :
Input single letter in one turn.Don’t use repeated letters.Turns will be decremented after every guess.
Input single letter in one turn.
Don’t use repeated letters.
Turns will be decremented after every guess.
This is the text file used inside the code words.txt, which contains 50,000 English words.
Module needed :
import random
Below is the implementation :
# Python program to implement Hangman game  # Importing random moduleimport random  # Function to randomly select# a word from dictionarydef get_word():          # Path to the text file    with open('/Users/Admin/Desktop/words.txt', 'r') as f:                  # Reads each word after splitting        words1 = f.read().splitlines()          # Returns any random word        return random.choice(words1)  myword = get_word()  # Function prints row of# stars in place of wordsfor i in myword:          print("*", end = " ")      # Calculating length of wordl = len(myword)print("\nWord has %d letters" %l)  # Check if entered letter is correctdef check(myword, your_word, guess1):    status = ''    matches = 0          for letter in myword:        if letter in your_word:            status += letter        else:            status += '*'        if letter == guess1:            matches += 1                  if matches > 1:        print(matches, guess1)              elif matches == 1:        print(guess1)    return status  # Main Game functiondef game():    guess = 0    guessed = False    your_word = []    turns = len(myword) + 1    turns1 = turns          print("Total turns: ", turns)    while guess < turns1:        guess1 = input("Enter your guess: ")                  # Decrementing turn        # after every guess        turns -= 1                  # Print turns left        print("Turns left", turns)                  # If letter is already guessed        if guess1 in your_word:            print("You already guessed")        elif len(guess1) == 1:                          # Appending the letters            # on their place            your_word.append(guess1)            result = check(myword, your_word, guess1)                          if result == myword:                guessed = True                print("You won " + name)                print(myword)            else:                print(result)        else:            print("Invalid entry")        guess += 1    if guess == turns1:        print("Word is:")        print(myword)  # Driver Codegame()
Output :
* * * * * 
Word has 5 letters
Total turns:  11

Enter your guess: a
Turns left 10
**********

Enter your guess: i
Turns left 9
i
**i**i****

Enter your guess: s
Turns left 8
s
**i**i**ss

Enter your guess: r
Turns left 7
**i**i**ss

Enter your guess: h
Turns left 6
**i**i**ss

Enter your guess: e
Turns left 5
e
**i**i*ess

Enter your guess: o
Turns left 4
**i**i*ess

Enter your guess: u
Turns left 3
u
*ui**i*ess

Enter your guess: t
Turns left 2
t
*ui*ti*ess

Enter your guess: n
Turns left 1
n
*ui*tiness

Enter your guess: l
Turns left 0
l
*uiltiness

Word is:
guiltiness

Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?