# Hangman # One player chooses a category (e.g. Animals) and a secret word (e.g. rooster). # Second player guesses a letter A-Z, all instances are revealed. # If player guesses incorrectly 5 times, s/he loses. # If all letters are guessed, player wins. # Has some error-checking, and lots of comments. YOURS SHOULD TOO! # Hope you're having fun, folks. -- Mr. G. # Player 1 sets the category/word. category = input("Category: ").upper() secret = input("Secret word: ").upper() # Setup: 'reveal' shows all letters correctly guessed, and dashes otherwise, # while 'unguessed' starts with the original word, and replaces all correctly # guessed letters with dashes. alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" reveal = "-"*len(secret) unguessed = secret guesses = 5 # Clear the screen, start the game. for blankLine in range(50): print() print("The category is {}".format(category)) # Run the game until either the player has 0 guesses remaining, or there are no # unguessed letters in the revealed word. while guesses > 0 and "-" in reveal: print("{} Guesses remaining: {} {}".format(reveal, guesses, alphabet)) # Error-checking: make sure guess is a single unguessed letter. while True: letter = input("Guess a letter: ").upper() if len(letter) == 1 and letter.isalpha(): if not letter in alphabet: print("You've already guessed {}.".format(letter)) else: break else: print("Not a valid guess.") # Replace all instances in the revealed string with the guessed letter, if it # is a correct guess, and update the unguessed string with dashes. if letter in unguessed: while letter in unguessed: idx = unguessed.find(letter) reveal = reveal[:idx]+letter+reveal[idx+1:] unguessed = unguessed.replace(letter,"-",1) # Letter isn't in word. Deduct a guess. else: print("There is no {} in the secret word.".format(letter)) guesses -= 1 alphabet = alphabet.replace(letter, "-") # End the game. if "-" in reveal: print("You lose. \n") else: print("You win! \n") print("The secret word was {}.".format(secret))