Skip to content

Instantly share code, notes, and snippets.

@cicdw
Created October 17, 2017 19:17
Show Gist options
  • Save cicdw/4329130a70e720466b9313371e88fcb6 to your computer and use it in GitHub Desktop.
Save cicdw/4329130a70e720466b9313371e88fcb6 to your computer and use it in GitHub Desktop.
Hangman implemented w/ a recursive coroutine
def game(word, max_guesses=10):
'''Given a word and a guess limit, returns a
coroutine for playing hangman. Guess letters
by sending messages to the coroutine. Returns
True if you win, False otherwise.
Example
>>> g = game('jazz', 10)
>>> next(g) # prime the coroutine
>>> g.send('e') # guess 'e'
'''
game_status = '_' * len(word)
def play(game_status, num_left):
print(game_status)
guess = yield
revealed = ''.join([w if w == guess else g for g, w in zip(game_status, word)])
if revealed == word:
yield True
elif num_left == 0:
yield False
else:
yield from play(revealed, num_left - 1)
return play(game_status, max_guesses)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment