Last active
July 6, 2016 01:42
-
-
Save selik/d8e0a7622ceff0fe8984a7d19d44bfca to your computer and use it in GitHub Desktop.
Simple implementation of the "Hangman" word-guessing game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import string | |
drawings = ( | |
r""" | |
------| | |
| | |
| | |
| | |
| | |
-- | |
""", | |
r""" | |
------| | |
| 0 | |
| | |
| | |
| | |
-- | |
""", | |
r""" | |
------| | |
| 0 | |
| -+- | |
| | |
| | |
-- | |
""", | |
r""" | |
------| | |
| 0 | |
| /-+- | |
| | |
| | |
-- | |
""", | |
r""" | |
------| | |
| 0 | |
| /-+-\ | |
| | |
| | |
-- | |
""", | |
r""" | |
------| | |
| 0 | |
| /-+-\ | |
| | | |
| | |
-- | |
""", | |
r""" | |
------| | |
| 0 | |
| /-+-\ | |
| | | |
| | | |
-- | |
""", | |
r""" | |
------| | |
| 0 | |
| /-+-\ | |
| | | |
| | | | |
-- | |
""" | |
) | |
drawings = iter(drawings) | |
drawing = next(drawings) | |
print('Welcome to Hangman.') | |
print('Good luck!') | |
words = 'python ruby php java unix linux perl'.split() | |
target = list(random.choice(words)) | |
known = ['_'] * len(target) | |
used = [] | |
while known != target: | |
print() | |
print('-'.join(c if c not in used else ' ' for c in string.ascii_lowercase)) | |
print(drawing, '\n\t', ' '.join(known)) | |
guess = input('\nEnter your guess: ').lower() | |
while guess in used: | |
print("You've already guessed that letter") | |
guess = input('Please enter a new guess: ').lower() | |
used.append(guess) | |
if guess in target: | |
print('Yes, {!r} is in the word!'.format(guess)) | |
for i, letter in enumerate(target): | |
if guess == letter: | |
known[i] = letter | |
else: | |
print('Sorry, {!r} is not in the word.'.format(guess)) | |
try: | |
drawing = next(drawings) | |
except StopIteration: | |
print('\nYou have been hanged!') | |
break | |
else: | |
print('\nYou guessed the word correctly!') | |
print('The word was {!r}'.format(''.join(target))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment