Skip to content

Instantly share code, notes, and snippets.

@selik
Last active July 6, 2016 01:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save selik/d8e0a7622ceff0fe8984a7d19d44bfca to your computer and use it in GitHub Desktop.
Save selik/d8e0a7622ceff0fe8984a7d19d44bfca to your computer and use it in GitHub Desktop.
Simple implementation of the "Hangman" word-guessing game
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