Moortiii

Python - Hangman

Apr 3rd, 2017
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.35 KB | None | 0 0
  1. # TODO: Add the possibility to play again at the end of a game
  2.  
  3. import re  # This is used later to find all indices of a certain letter
  4. import random
  5.  
  6. words = [
  7.     "cryptography",
  8.     "librarian",
  9.     "heartseeker",
  10.     "treehouse",
  11.     "energizer"
  12.     ]
  13.  
  14. secret = random.choice(words)  # Pick a random word
  15. good_letters = []
  16. bad_letters = []
  17. guessed_word = []
  18. tries = 5
  19.  
  20. def addLetter(listname, index):
  21.     listname.pop(index)
  22.     listname.insert(index, guess)
  23.  
  24. def addSpace(listname, index):
  25.     listname.pop(index)
  26.     listname.insert(index, "-")
  27.  
  28. for letter in secret:  # Spaces equal to length of the word
  29.     guessed_word.append("-")
  30.  
  31. print(guessed_word)  # Show the user how many letters long the word is
  32.  
  33. while(True):  # Start playing the game
  34.     if(guessed_word == list(secret)):
  35.         print("Congratulations! The word was: {}".format(secret))
  36.         break
  37.     elif(tries <= 0):  # Break if the user runs out of tries
  38.         print("I'm sorry, you ran out of tries! The word was: {}".format(secret))
  39.         break
  40.    
  41.     guess = input("Please guess a single letter: ").lower()
  42.    
  43.     if(len(guess) < 2 and len(guess) > 0):   #  Single letters only
  44.         if(guess not in good_letters and guess not in bad_letters):  #  Unique letters only
  45.             if guess in secret:
  46.                 good_letters.append(guess)
  47.             else:
  48.                 bad_letters.append(guess)
  49.                 tries -= 1
  50.            
  51.             #  http://stackoverflow.com/questions/20039022/python-finding-more-than-one-index-in-a-list-of-letters
  52.             #  Link above for the explanation on how to find all indices
  53.             indices = [x.start() for x in re.finditer(guess, secret)]  # Find all indices of the guessed letter
  54.             for index in indices:
  55.                 if guess in good_letters:
  56.                     addLetter(guessed_word, index)  # If the guess is correct, add the letter
  57.                 else:
  58.                     addSpace(guessed_word, index)   # If the guess is incorrect, add a space
  59.                    
  60.             print("So far you have: {}".format(guessed_word))
  61.            
  62.     print("Good letters: {}".format(good_letters))
  63.     print("Bad letters: {}".format(bad_letters))
  64.    
  65.     if(tries > 1):
  66.         print("You have {} tries left".format(tries))
  67.     else:
  68.         print("You have one try left")
Advertisement
Add Comment
Please, Sign In to add comment