from whrandom import randrange import sys from string import find,lower,strip dict = open("/usr/dict/words","r") words = dict.readlines() # words is a list of words we will pick from def pickword(words): while 1: idx = randrange(0,len(words)) # pick one of the words at random word = strip(words[idx]) # the word we picked if word == lower(word): return word def template(word,ltrs): """Show the letters we have correctly guessed on correct positions. Show other letters as '_' """ t = '' for c in word: if find(ltrs,c) < 0: c = '_' t = t + c return t def hangman(maxguesses): "Play one game of hangman." word = pickword(words) print 'I am thinking of a word with',len(word),'letters.' ltrs = '' wrong = '' while len(wrong) < maxguesses: t = template(word,ltrs) if t == word: print "You have guessed the word! The word is",word return guess = raw_input(t + " : " + wrong + " ") if len(guess) > 1: guess = guess[0] if find(ltrs,guess) >= 0 or find(wrong,guess) >= 0: print 'You have already guessed that!' elif find(word,guess) >= 0: print guess,' is correct!' ltrs = ltrs + guess else: print guess,'is not in the word.' wrong = wrong + guess print "Sorry, you took more than",maxguesses,"guesses." print "The word was",word while 1: hangman(15) ans = raw_input("Do you want to play again? ") if len(ans) > 0 and lower(ans[0]) != 'y': break