#!/usr/bin/python3 # -*- coding: utf-8 -*- """Play hangman.""" from __future__ import division, print_function import random, os, sys hangman = """ 1222222 1 3 1 3 1 444 1 4 4 1 4 1 5 1 65557 1 6 5 7 1 6 5 7 1 5 1 8 9 1 8 9 1 8 9 1"""[1:] def play(filename="/usr/share/dict/words"): with open(filename) as f: words = [w for w in (w.split()[-1].strip() for w in f) if all('a' <= c <= 'z' for c in w)] word = random.choice(words) missed = 0 guessed = set() print("\033[2J") # ANSI clear screen escape sequence while any(letter not in guessed for letter in word) and missed < 9: print("\033[H" + ''.join('\n' if c == '\n' else ' ' if c == ' ' or int(c) > missed else '#' for c in hangman)) print(' '.join(letter if letter in guessed else '_' for letter in word)) print("Guess a letter: ", end="") sys.stdout.flush() letter = sys.stdin.read(1).lower() if letter in guessed or letter not in word: missed += 1 guessed.add(letter) print() if any(letter not in guessed for letter in word): print("LOSER.") else: print("You win, so what.") print("It was", repr(word) + '.') if __name__ == "__main__": os.system("stty cbreak") try: if len(sys.argv) > 1: play(sys.argv[1]) else: play() finally: os.system("stty -cbreak")