Create a gist now

Instantly share code, notes, and snippets.

Hangman implemented in 3 lines of Python
license, chosen_word, guesses, scaffold, man, guesses_left = '', ''.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

First game...word I got was PHARMACOPOEIA! Can you squeeze a difficulty setting in here? ;)


Here's a one-liner (Python2/3):

list(v.update(num_bad_guesses=sum(1 for g in guesses if g not in chosen_word)) or \
     ((10 <= v['num_bad_guesses'] and prin('You lose!\n'+scaffold.format(*man))) or \
      (all(l in guesses for l in chosen_word) and prin('You win!'))) and \
     (prin('Word was ' + chosen_word) and next(iter([]))) or \
     prin(','.join(sorted(guesses)) + '({} guesses left)'.format(10-v['num_bad_guesses'])+'\n' +
          scaffold.format(*man[:v['num_bad_guesses']]+' '*10)) and \
                           inpt(' '.join(l if l in guesses else '_' for l in chosen_word)+': ').upper())) \
     for (license, chosen_word, guesses, scaffold, man, v, prin, inpt) in [(
             ''.join(filter(str.isalpha, __import__('random').choice(open('/usr/share/dict/words').readlines()).upper())),
             '|======\n|   |\n| {3} {0} {5}\n|  {2}{1}{4}\n|  {6} {7}\n|  {8} {9}\n|',
             (lambda x: __import__('sys').stdout.write(x + '\n') or True),
             getattr(__builtins__, 'raw_input', input))] \
     for _ in __import__('itertools').count()

It's too beautiful for my eyes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment