Hangman Game in Python and store user records in a text file

Hangman Game On Python is about guessing letters (A-Z) to form the words. If the player guesses the right letter that is within the word, the letter appears at its correct position. The user has to guess the correct word until a man is hung, then the game is over.

Modules Used :

  • random : pre-installed

Python Requirement : 3.8 and above.

Source Code :

Hangman.py

def Hangman():

    import random

    f=open('wordlist.txt','r') #just create a file with the words           
                                to be used in the game
    f1=open('record.txt','a')

    words=f.read().splitlines() 
    #using splitlines() instead of f.readlines() to avoid end of 
     line character while viewing the written data 
    
    word = random.choice(words[:-1])
    comma=","

    allowed_errors = 3      
    User=input("Enter Your Name : ")
    guesses = []

    done = False 
 
    while not done:
        for letter in word:
            if letter.lower() in guesses:
                print(letter,end=" ")
            else:
                print("_",end=" ")
        print("")


        guess = input(f"Allowed Errors Left{allowed_errors},Next
                      Guess : ")
        guesses.append(guess.lower())

        if guess.lower() not in word.lower():
            allowed_errors -= 1

            if allowed_errors == 0:
                break

        done = True

        for letter in word:
            if letter.lower() not in guesses:
                done = False

    if done:
        print(f"You have found the word ! It was {word}!")
        f1.write(f"{User}{comma}Guessed the word ! It was
                 {word}!\n")
    else:
        print(f"Game Over ! The word was {word} ! \n")
        f1.write(f"{User}{comma}failed to Guess the word! It was
                 {word}! \n")

Hangman()

To View User’s Record :

Record.py

def Record():
    f=open('record.txt','r')
    record=f.read().splitlines()
    for i in record:
        print(i)
Record()

13 thoughts on “Hangman Game in Python and store user records in a text file

  1. I absolutesly love our website.. Excellent colors & theme.
    Did you make this webb site yourself? Please reply
    back as I’m attempting to create myy own personal website and would love to find
    out where you got this frm or just what the theme is
    named. Appreciate it!

    1. Yeah I customized it myself.Been years since I have written anything.Will continue with more projects soon.Thanks man for the feedback. Really helps me stay motivated to follow up with more projects.

  2. It’s appropriate time to mwke some plans
    for the future and it’s time to be happy.
    I have read this post and if I could I want to suggest you some interesting things or tips.

    Maybe you can write next articles referring to this article.
    I desire to read more things about it!

Leave a Reply

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