#! /Usr/bin/env python Import random Import cPickle Class Hangman (object ): '''A simple hangman game that tries to improve your vocabulary A bit ''' Def _ init _ (self ): # The variables used, this is not necessary Self. dumpfile = ''# the dictionary file Self. dictionary ={}# the pickled dict Self. words = [] # list of words used Self. secret_word = ''# the 'key' Self. length = 0 # length of the 'key' Self. keys = [] # inputs that match the 'key' Self. used_keys = [] # keys that are already used Self. guess = ''# player's guess Self. mistakes = 0 # number of incorrect inputs Return self. load_dict () # Insert some random hints for the player Def insert_random (self, length ): Randint = random. randint #3 hints If length> = 7: hint = 3 Else: hint = 1 For x in xrange (hint ): A = randint (1, length-1) Self. keys [A-1] = self. secret_word [A-1] Def test_input (self ): # If the guessed letter matches If self. guess in self. secret_word: Indexes = [I for I, item in enumerate (self. secret_word) if item = self. guess] For index in indexes: Self. keys [index] = self. guess Self. used_keys.append (self. guess) Print "used letters", set (self. used_keys), '\ N' # If the guessed letter didn't match Else: Self. used_keys.append (self. guess) Self. mistakes + = 1 Print "used letters", set (self. used_keys), '\ N' # Load the pickled word dictionary and unpickle them Def load_dict (self ): Try: Self. dumpfile = open ("~ /Python/hangman/wordsdict. pkl "," r ") Handle t IOError: Print "Couldn't find the file 'wordsdict. pkl '" Quit () Self. dictionary = cPickle. load (self. dumpfile) Self. words = self. dictionary. keys () Self. dumpfile. close () Return self. prepare_word () # Randomly choose a word for the challenge Def prepare_word (self ): Self. secret_word = random. choice (self. words) # Don't count trailing spaces Self. length = len (self. secret_word.rstrip ()) Self. keys = ['_' for x in xrange (self. length)] Self. insert_random (self. length) Return self. ask () # Display the challenge Def ask (self ): Print ''. join (self. keys),": ", self. dictionary [self. secret_word] Print Return self. input_loop () # Take input from the player Def input_loop (self ): # Four self. mistakes are allowed Chances = len (set (self. secret_word) + 4 While chances! = 0 and self. mistakes <5: Try: Self. guess = raw_input ("> ") Failed t EOFError: Exit (1) Self. test_input () Print ''. join (self. keys) If '_' not in self. keys: Print 'Well done! ' Break Chances-= 1 If self. mistakes> 4: print 'the word was', ''. join (self. secret_word). upper () Return self. quit_message () Def quit_message (self ): Print "\ n" Print "Press 'C' to continue, or any other key to quit the game ." Print "You can always quit the game by pressing 'ctrl + d '" Try: Command = raw_input ('> ') If command = 'C': return self. _ init _ () # loopback Else: exit (0) Failed t EOFError: exit (1) If _ name _ = '_ main __': Game = Hangman () Game. _ init __() |