Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. import random
  2. import string
  3.  
  4. WORDLIST_FILENAME = "words.txt"
  5.  
  6. def loadWords():
  7.     """
  8.    Returns a list of valid words. Words are strings of lowercase letters.
  9.    
  10.    Depending on the size of the word list, this function may
  11.    take a while to finish.
  12.    """
  13.     print "Loading word list from file..."
  14.     # inFile: file
  15.     inFile = open(WORDLIST_FILENAME, 'r', 0)
  16.     # line: string
  17.     line = inFile.readline()
  18.     # wordlist: list of strings
  19.     wordlist = string.split(line)
  20.     print "  ", len(wordlist), "words loaded."
  21.     return wordlist
  22.  
  23. def chooseWord(wordlist):
  24.     """
  25.    wordlist (list): list of words (strings)
  26.  
  27.    Returns a word from wordlist at random
  28.    """
  29.     return random.choice(wordlist)
  30.  
  31. # end of helper code
  32. # -----------------------------------
  33.  
  34. # Load the list of words into the variable wordlist
  35. # so that it can be accessed from anywhere in the program
  36. wordlist = loadWords()
  37.  
  38. print 'Welcome to the game, Hangman!'
  39. secret = random.choice(wordlist)
  40. print 'I am thinking of a word that is ' + str(len(secret)) + ' letters long.'
  41. guesses = ''
  42. turns = 8
  43. avLetters = string.ascii_lowercase
  44.  
  45. while turns > 0:
  46.   missed = 0
  47.  
  48.   for letter in secret:
  49.     if letter in guesses:
  50.       print letter,
  51.     else:
  52.       print '_',
  53.       missed += 1
  54.  
  55.   print
  56.  
  57.   if missed == 0:
  58.     print 'Congratulations, you won!'
  59.     break
  60.  
  61.   print 'You have ' + str(turns) + ' guesses left.'
  62.   guess = raw_input('Please guess a letter: ')
  63.   guesses += guess
  64.  
  65.   if guess not in secret:
  66.     turns -= 1
  67.     if turns == 0:
  68.       print 'Sorry, you ran out of guesses. The word was ', secret
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement