# A Simple Hangman Game Implemented In 3 Lines Of Python

python hangman e1494845266809

Short Bytes: Today I’m sharing a clever implementation of Hangman in python by programmer Danver Braganza. Take a look at this 3-lines-long program and try to make it more compact.

You might have come across Python scripts teaching you how to code the classic game “Hangman”. For those who don’t know, it’s a word guessing game for two or more players. In the game, one player thinks of a word or a phrase and the other player tries to suggest letters or numbers within some fixed number of guesses.

When I came across a neat, small, working, fun implementation of Hangman on Hacker News, I decided to share it with fossBytes readers as it’s one of my favorite word games. Coder Danver Braganza decided to address the standard limit of 80 characters a line and write his hangman program in Python.

Also read: A Neural Network in 11 Lines of Python

“The restriction I set for myself was that each line must be just one Python statement or expression,” he writes. You can find the code below:

license, chosen_word, guesses, scaffold, man, guesses_left = 'https://opensource.org/licenses/MIT', ''.join(filter(str.isalpha, __import__('random').choice(open('/usr/share/dict/words').readlines()).upper())), set(), '|======\n|   |\n| {3} {0} {5}\n|  {2}{1}{4}\n|  {6} {7}\n|  {8} {9}\n|', list('OT-\\-//\\||'), 10
while not all(letter in guesses for letter in chosen_word) and guesses_left: _, guesses_left = map(guesses.add, filter(str.isalpha, raw_input('%s(%s guesses left)\n%s\n%s:' % (','.join(sorted(guesses)), guesses_left, scaffold.format(*(man[:10-guesses_left] + [' '] * guesses_left)), ' '.join(letter if letter in guesses else '_' for letter in chosen_word))).upper())), max((10 - len(guesses - set(chosen_word))), 0)
print 'You', ['lose!\n' + scaffold.format(*man), 'win!'][bool(guesses_left)], '\nWord was', chosen_word

This 3 lines of Python code is a pretty compact implementation of Hangman. You can copy the above code, paste into hangman.py and run it.

On his website, Danver also mentions some particular features of the game:

• A word is chosen randomly from the system dictionary. Of course, this dictionary includes proper names. The word list can be easily changed.
• Keeping track of the number of (wrong) guesses left. Successful guesses do not add to the hangman, and repeated missed guesses do not add to the hangman.
• Positional blanks hint at the hidden word, that are filled in with correct guesses.
• An ASCII Hangman built as you continue to guess wrongly.
• Multiple guesses are allowed, and non-alphabet character guesses are ignored.