Kids Coding
Project: Hangman
Guess letters. Keep the secret word in a list. Stop when it is complete or lives are gone.
KidsIntermediateProject: Hangman
Guess letters, not the whole word
Keep the secret as a string. Keep a list of _ the same length. When a guess matches a letter, replace that _.
Replay three guesses
secret = "fox"
shown = ["_", "_", "_"]
guesses = ["o", "z", "f"]
lives = 3
for guess in guesses:
print("Guess:", guess)
if guess in secret:
for i in range(len(secret)):
if secret[i] == guess:
shown[i] = guess
print("Yes:", "".join(shown))
else:
lives = lives - 1
print("No. Lives:", lives)
if "_" not in shown:
print("You won")
else:
print("The word was", secret)Remember which letters were already guessed. Without that, a player can pick the same wrong letter twice and lose two lives for one mistake, which feels unfair.
What you practiced
- Lists and indexes.
into test membership.- A loop over guesses.
Real life
A word on the blackboard with missing letters.
The class guesses one letter. Right letters fill in. Lives are the chalk marks.
Board word
secret = "cat"
shown = ["_", "_", "_"]
guess = "a"
for i in range(len(secret)):
if secret[i] == guess:
shown[i] = guess
print("Board:", " ".join(shown))Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Start shown as ["_", "_"] for hi. If the guess is h, set index 0 to h and print shown.
Show solution
shown = ["_", "_"]
guess = "h"
if guess == "h":
shown[0] = "h"
print(shown)