Advertisement
Guest User

Untitled

a guest
Dec 16th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. import random
  2.  
  3. def get_guess():
  4.  
  5.   # Set the dashes to the length of the secret word and set the amount of guesses
  6.   # the user has to 10
  7.   dashes = "-" * len(secret_word)
  8.   guesses_left = 10
  9.  
  10.   # This will loop as long as BOTH conditions are true:
  11.   # 1. The number of guesses of left is greater than -1
  12.   # 2. The dash string does NOT equal the secret word
  13.   while guesses_left > -1 and not dashes == secret_word:
  14.    
  15.     # Print the amount of dashes and guesses left
  16.     print(dashes)
  17.     print (str(guesses_left))
  18.    
  19.     # Ask the user for input
  20.     guess = input("Guess:")
  21.    
  22.     # Conditions that will print out a message according to
  23.     # invalid inputs
  24.     if len(guess) != 1:
  25.       print ("Your guess must have exactly one character!")
  26.      
  27.     # If the guess is in the secret word then we updtae dashes to replace the
  28.     # corresponding dash with the correct index the guess belongs to in the
  29.     # secret word
  30.     elif guess in secret_word:
  31.       print ("That letter is in the secret word!")
  32.       dashes = update_dashes(secret_word, dashes, guess)
  33.      
  34.     # If the guess is wrong then we display a message and subtract
  35.     # the amount of guesses the user has by 1
  36.     else:
  37.       print ("That letter is not in the secret word!")
  38.       guesses_left -= 1
  39.    
  40.   if guesses_left < 0:
  41.     print ("You lose. The word was: " + str(secret_word))
  42.  
  43.   # If the dash string equals the secret word in the end then the
  44.   # user wins
  45.   else:
  46.     print ("Congrats! You win. The word was: " + str(secret_word))
  47.    
  48. # This function updates the string of dashes by replacing the dashes
  49. # with words that match up with the hidden word if the user manages to guess
  50. # it correctly
  51. def update_dashes(secret, cur_dash, rec_guess):
  52.   result = ""
  53.  
  54.   for i in range(len(secret)):
  55.     if secret[i] == rec_guess:
  56.       result = result + rec_guess     # Adds guess to string if guess is correctly
  57.      
  58.     else:
  59.       # Add the dash at index i to result if it doesn't match the guess
  60.       result = result + cur_dash[i]
  61.      
  62.   return result
  63.    
  64. words = ["bob", "cool", "whatup"]
  65.  
  66. secret_word = random.choice(words)
  67. get_guess()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement