Hangman

Optional project · After Sorting and Sets

You should already know
Input, decisions, while loops, lists, reading a file, and the word counts and sorting through Sorting and Sets.
You'll build
A hangman game that picks its secret word from Shakespeare's most-used words.
You'll be able to
Loop over the letters of a string, keep track of guesses and decide when a game is won or lost.
You need
This page. Each example runs in its own code box; nothing to install.

We've counted Shakespeare's words and ranked them. Now let's play with them.

In hangman, one player thinks of a secret word and shows a blank for each letter. The other player guesses one letter at a time. A right guess fills in every blank where that letter belongs. A wrong guess uses up a chance, and the game ends when the word is complete or the chances run out.

Python will keep the secret; you'll do the guessing. This is an optional project, about 20–30 minutes. The other course projects don't depend on it.

Show the Word So Far

Start with the part the player sees: the word with its unguessed letters hidden.

We've used a for loop to visit every item in a list. It can visit every character in a string the same way, one letter at a time.

# Try it: Add 'h' to the guessed list and run again. Then change
# the secret to a word of your own.
# Each Run starts fresh.

secret = 'hamlet'
guessed = ['a', 'e']
display = ''

for letter in secret:
    if letter in guessed:
        display = display + letter + ' '
    else:
        display = display + '_ '

print(display)

display starts as an empty string. Each trip through the loop adds either the real letter or a blank, followed by a space so the blanks don't run together.

The secret never changes. What changes is the list of guesses, and the display follows from it. That's the whole trick of the game: we only need to remember the guesses.

Take a Guess

Put that display loop inside a while loop, so the word is shown again after every guess. Start with guessed = [] and chances = 6 above it, and keep going while chances > 0:.

Inside the loop, after showing the word:

  1. Ask for a letter, and use .lower() on the answer.
  2. If the letter is already in guessed, say so and take nothing away.
  3. If it's in secret, append it to guessed.
  4. Otherwise, append it to guessed and subtract one from chances.

Get that working before worrying about winning. For now, the game simply ends after six wrong guesses.

Know When It's Over

How do we know the player has won? Look at the display. If it has no blanks left, every letter has been found:

if '_' in display:
    # keep asking
else:
    print('You got it!')
    break

Losing is the other way out of the loop. When chances reaches zero, the while condition is no longer true and the loop ends. After the loop, check if chances == 0: and reveal the word.

One more rule is worth adding. Try answering ham in your game. Python says 'ham' in 'hamlet' is true, because in looks for a run of characters in a string, not only a single letter. Check len(guess) != 1 first and ask again without using up a chance.

Play the Finished Game

Here's a complete version to compare after you've tried those steps:

# Each Run starts fresh.

secret = 'hamlet'
guessed = []
chances = 6

print('The word has', len(secret), 'letters.')

while chances > 0:
    display = ''
    for letter in secret:
        if letter in guessed:
            display = display + letter + ' '
        else:
            display = display + '_ '
    print(display)

    if '_' in display:
        print('Guessed so far:', sorted(guessed))
        guess = input('Guess a letter: ').lower()
        if len(guess) != 1:
            print('One letter at a time.')
        elif guess in guessed:
            print('You already tried that one.')
        elif guess in secret:
            guessed.append(guess)
            print('Yes!')
        else:
            guessed.append(guess)
            chances = chances - 1
            print('No. Wrong guesses left:', chances)
    else:
        print('You got it!')
        break

if chances == 0:
    print('Out of guesses. The word was', secret)

sorted(guessed) shows the guesses in alphabetical order, which makes it easier to see what's left to try. It doesn't change the list itself.

Try these on fresh runs:

A game with one secret is only fun once. Let's fix that.

Let Shakespeare Choose

We already know how to count every word in shakespeare.txt. Those counts can supply the secrets.

Not every word makes a fair one. A short word such as the is over too quickly, a rare word is close to impossible, and some of our cleaned words still contain an apostrophe or a hyphen. So we'll keep a word only if it passes three tests:

Each test is an if inside the one before it, so a word must pass all three to be appended.

To choose one, we can reuse random.randint() from the guessing game. A list's positions run from 0 to one less than its length, so we ask for a random position in that range and look up the word there.

# Try it: Change 100 to 300 for more familiar words, or to 20 for a
# harder game. Counting the whole book takes a moment.
# Each Run starts fresh.

import random

text = open('shakespeare.txt').read()
counts = {}

for word in text.split():
    word = word.lower()
    word = word.strip('.,!?;:')
    if word != '':
        if word in counts:
            counts[word] = counts[word] + 1
        else:
            counts[word] = 1

words = []
for word in counts:
    if counts[word] >= 100:
        if len(word) >= 6:
            if word.isalpha():
                words.append(word)

secret = words[random.randint(0, len(words) - 1)]
guessed = []
chances = 6

print('Shakespeare uses this word', counts[secret], 'times.')
print('It has', len(secret), 'letters,', len(set(secret)), 'of them different.')

while chances > 0:
    display = ''
    for letter in secret:
        if letter in guessed:
            display = display + letter + ' '
        else:
            display = display + '_ '
    print(display)

    if '_' in display:
        print('Guessed so far:', sorted(guessed))
        guess = input('Guess a letter: ').lower()
        if len(guess) != 1:
            print('One letter at a time.')
        elif guess in guessed:
            print('You already tried that one.')
        elif guess in secret:
            guessed.append(guess)
            print('Yes!')
        else:
            guessed.append(guess)
            chances = chances - 1
            print('No. Wrong guesses left:', chances)
    else:
        print('You got it!')
        break

if chances == 0:
    print('Out of guesses. The word was', secret)

The game loop is the one you just played. Only the lines that choose secret are new.

len(set(secret)) is the set trick from Sorting and Sets, used on one word instead of a whole book. A set keeps one copy of each letter, so its length tells the player how many different letters there are to find.

You'll meet plenty of names. Hamlet, Othello and Cleopatra are spoken about so often, and named before so many of their own lines, that they count among Shakespeare's most-used words.

Make the Game Yours

Choose one bonus:

Copy the code from your working game into a plain-text file to keep your own version.

Which one value does the game need to remember in order to work out the display, the win and the list of letters already tried?