Let's code Hangman in Python


Lately, I’ve been doing some Python development for two personal projects and I needed to reconcile with the language. Python’s syntax is pretty straight-forward, so it wasn’t a big deal for me coming back to the language. What I needed was to code some mini projects so that I can be comfortable with my personal projects.

The goal of this post is for a beginner programmer to see what the syntax and the logic looks like.

One mini challenge on the web is Hangman. Now Hangman itself is a very easy and fun game, and there’s a lot of freedom in how to go about implementing it. One can code up a GUI with Pygame, or if that’s not needed, you can always play in the command line interface, which is what we’re going to do.

We need a txt file for the words we use in the game. I just googled the top 10000 english words and pasted in a englishwords.txt file.

information
available
copyright
university
management
international
development
education
community
technology
following
...

Let’s select our word

We need to randomly select a word from our englishwords.txt file. In order to do that let’s write a function.

def random_word(from_file):
    """ Given a text file, returns a random line from file"""
    f = open(from_file, "r")
    lines = f.readlines()
    num_lines = sum(1 for line in open(from_file))
    random_line_num = random.randint(1, num_lines - 1)
    word = lines[random_line_num]
    f.close()
    return word

Our random_word function takes in a parameter, which is the filename, opens the file, reads how many lines the file has, creates a random number in that range and selects one of these words and returns it. For the randomness, you should import random

The game loop

The game loop refers to the period from the start of the game, until the game is finished in any state (win or loss)

While the player has not won or lost, the game has to continue.

The game logic

We will have a play() function, which will have our game loop with some variables defined. I will give the player 10 tries to find the word, will keep the guessed letters in a list (vs. a set, because the user might guess the same letter even though he/she shouldn’t, but we’ll count that as a wrong guess as well.)

I’ll also import time so that we can use time.sleep() for some ‘enhanced’ user experience.

def play():
    letter_guesses = []
    word = random_word("englishwords.txt").strip()
    lives_remaining = 10
    game_loop = True
    print("Let's play Hangman!")
    time.sleep(1)
    while game_loop:
        print("\nUsed letters:", set(letter_guesses))
        if set(word).issubset(set(letter_guesses)):
            print("\nYou win!")
            game_loop = False
            break
        for char in word:
            if char in letter_guesses:
                print(char, end=" ")
            else:
                print("_", end=" ")
        guess = input("\nGuess a letter: ")
        letter_guesses += guess
        if guess not in word:
            lives_remaining -= 1
            print("\nDarn it, {guess} is not in this word".format(guess=guess))
            print("You have {lives} tries left".format(lives=lives_remaining))
            if lives_remaining == 0:
                game_loop = False
                print("\nYou lost :(")
                print("The word was: {0}".format(word))
                break
        else:
            print("\nCorrect!")

Let’s take this apart.

When the game_loop is true, We will print the used letters.

After that we’ll check whether we won the game, to do that, we’ll see if the letters in our random word are all present in the letter_guesses by using set operations.

Then we’ll print the visual for our player. For each letter in our random word, if that letter is already guessed, we’ll print out that letter, and if not, we’ll just print a _ character.

We’ll then ask the user for a letter input. And we’ll add that guess to our letter_guesses.

If that guessed letter is not in our random word, we’ll decrement lives_remaining, show a print message. And check if the user has any guesses left. If not, we’ll set game_loop to false, print out a sad message and end our game. If the guess is correct, we’ll simply print out a correct message and go to the start of the loop.

play()

We need to call the play() function, so that we can play the game :)

As homework, when the user fails to guess the correct word, we can simply restart the game instead of exiting the program.

Let me know if you can think of additions to this very simple program.


Cihan Koseoglu

Learn/Think/Implement is a blog about web technologies, mostly on the front-end. Written or curated by