Advertisement
Guest User

Untitled

a guest
Aug 7th, 2021
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. #imports
  2. import secrets
  3.  
  4. #load words from a file into a list
  5. def load_words(filename):
  6.     with open(filename) as f:
  7.         dictionary = f.readlines()
  8.     dictionary = [x.strip() for x in dictionary]
  9.     return dictionary
  10.  
  11. #spit out something like c_t for cat and the guessed letters c,t
  12. def string_underscored(word, letters):
  13.     underscored=[]
  14.     for i in range(0,len(word)):
  15.         if word[i] in letters:
  16.             underscored.append(word[i])
  17.         else:
  18.             underscored.append('_')
  19.     string_underscored=''.join(str(x) for x in underscored)
  20.     return string_underscored
  21.  
  22. dictionary=list(load_words('dictionary.txt'))
  23.  
  24. #check if all letters of a word are in a string of letters
  25. def check_if_word_in_letters(word, letters):
  26.     if set(word) <= set(letters):        # <= means "is subset" in this context
  27.         return True
  28.     else:
  29.         return False
  30.  
  31. #replaying loop
  32. answer=''
  33. while answer!='n':
  34.     word_to_guess=secrets.choice(dictionary)
  35.     guessed_letters=''
  36.     underscore_word=string_underscored(word_to_guess, guessed_letters)
  37.     failed_tries=0
  38.     check=0
  39.  
  40.     #round loop
  41.     while not check and failed_tries<8:
  42.         print('\n'*50)
  43.         print (underscore_word)
  44.         print('Guessed letters:')
  45.         print('failed attempts: ')
  46.         print(failed_tries)
  47.         print(guessed_letters)
  48.         some_letter = input('Guess a letter: ')
  49.         guessed_letters+=some_letter
  50.         underscore_word=string_underscored(word_to_guess, guessed_letters)
  51.         check=check_if_word_in_letters(word_to_guess, guessed_letters)
  52.         if check:
  53.             print('Congratulations!')
  54.         if some_letter not in word_to_guess:
  55.             failed_tries+=1
  56.     print('The word was ' + ''.join(word_to_guess) + '!')
  57.     answer=input('Again? y/n')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement