prev next 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Improving Our Game

We can already play our game. Now we need to fix it up so that it is fun.

  1. The player should win right away when there are no missing letters.
  2. The player should only lose a turn on a wrong guess.
  3. When the player loses, the game should tell the secret.

Here is one way to improve it.

#!/usr/bin/env python

print 'time to play hangman'
secret = 'crocodile'
guesses = 'aeiou'
turns = 5

while turns > 0:
  missed = 0
  for letter in secret:
    if letter in guesses:
      print letter,
    else:
      print '_',
      missed += 1

  print

  if missed == 0:
    print 'You win!'
    break

  guess = raw_input('guess a letter: ')
  guesses += guess

  if guess not in secret:
    turns -= 1
    print 'Nope.'
    print turns, 'more turns'
    if turns == 0:
      print 'The answer is', secret

The "missed" number counts how many blanks we are still missing. If if is zero, it means we won, and the "break" command breaks out of the "while" section early.

The "if guess not in secret" line checks if the guess was wrong. We only count down the "turns" if our guess was wrong.

When we guess wrong, we also print a bunch of stuff like "Nope" and how many more turns we have. When we are wrong for the last time we print the secret.