A Simple Hangman Game Implemented In 3 Lines Of Python
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.
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.
You can read more about this Hangman implementation in 3 lines of python on Danver’s website.
If you can make this code more compact, share your suggestions in the comments below.
Get pure python hacker bundle at fossBytes store.