Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # TODO: Add the possibility to play again at the end of a game
- import re # This is used later to find all indices of a certain letter
- import random
- words = [
- "cryptography",
- "librarian",
- "heartseeker",
- "treehouse",
- "energizer"
- ]
- secret = random.choice(words) # Pick a random word
- good_letters = []
- bad_letters = []
- guessed_word = []
- tries = 5
- def addLetter(listname, index):
- listname.pop(index)
- listname.insert(index, guess)
- def addSpace(listname, index):
- listname.pop(index)
- listname.insert(index, "-")
- for letter in secret: # Spaces equal to length of the word
- guessed_word.append("-")
- print(guessed_word) # Show the user how many letters long the word is
- while(True): # Start playing the game
- if(guessed_word == list(secret)):
- print("Congratulations! The word was: {}".format(secret))
- break
- elif(tries <= 0): # Break if the user runs out of tries
- print("I'm sorry, you ran out of tries! The word was: {}".format(secret))
- break
- guess = input("Please guess a single letter: ").lower()
- if(len(guess) < 2 and len(guess) > 0): # Single letters only
- if(guess not in good_letters and guess not in bad_letters): # Unique letters only
- if guess in secret:
- good_letters.append(guess)
- else:
- bad_letters.append(guess)
- tries -= 1
- # http://stackoverflow.com/questions/20039022/python-finding-more-than-one-index-in-a-list-of-letters
- # Link above for the explanation on how to find all indices
- indices = [x.start() for x in re.finditer(guess, secret)] # Find all indices of the guessed letter
- for index in indices:
- if guess in good_letters:
- addLetter(guessed_word, index) # If the guess is correct, add the letter
- else:
- addSpace(guessed_word, index) # If the guess is incorrect, add a space
- print("So far you have: {}".format(guessed_word))
- print("Good letters: {}".format(good_letters))
- print("Bad letters: {}".format(bad_letters))
- if(tries > 1):
- print("You have {} tries left".format(tries))
- else:
- print("You have one try left")
Advertisement
Add Comment
Please, Sign In to add comment