Project: Hangman
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Project: Hangman
- The last project puts the whole course together: a game of hangman.
- You guess a word one letter at a time. Five wrong guesses and you lose.
- You use strings, lists,
in, functions, awhileloop andinput().
What you will build
a
_a_
z
_a_
t
_at
c
cat
You won!
Plan first
- Before you write the loop, write two small functions and test them:
mask(word, guessed)shows the word with_for letters not guessed yet.is_won(word, guessed)says whether every letter has been guessed.- Then the game loop only has to call them.
Step 1: build a string letter by letter
- Start with an empty string
"". - Loop over the word; add the letter, or
_, to the end each time. letter in guessedisTruewhen the list contains that letter.
Step 2: stop as soon as you know
- Loop over the letters. If one is not in
guessed,return Falsestraight away. - If the loop finishes, nothing was missing:
return True.
Step 3: the game loop
- Keep going while there are fewer than 5 wrong guesses and the word is not won.
- Inside: read a letter, remember it, count it if it is wrong, print the mask.
- After the loop, one
ifdecides between the winning and the losing message.
Play for real
- The computer picks a secret word from a list. Type one letter at a time.
import random
def mask(word, guessed):
result = ""
for letter in word:
result = result + (letter if letter in guessed else "_")
return result
word = random.choice(["python", "loop", "list", "print"])
guessed = []
wrong = 0
while wrong < 5 and mask(word, guessed) != word:
letter = input("Guess a letter: ")
guessed.append(letter)
if letter not in word:
wrong = wrong + 1
print(mask(word, guessed), " wrong:", wrong)
print("You won!" if mask(word, guessed) == word else "You lost! The word was " + word)
Now build it
- Three steps. Well done for reaching the end of the course!
Step 1: write mask(word, guessed) that returns the word with every letter that is not in the list guessed replaced by _. mask("python", ["p", "o"]) is "p___o_".
Click Run to see the output here.
Step 2: write is_won(word, guessed) that returns True when every letter of the word is in guessed, otherwise False.
Click Run to see the output here.
Step 3: the game. The word is cat. Read one letter per line with input() and add it to guessed. After each guess print the mask. Count the wrong guesses. Stop when the word is guessed (print You won!) or after 5 wrong guesses (print You lost! The word was cat). For the guesses a, z, t, c, the output is _a_, _a_, _at, cat, You won!.
Click Run to see the output here.