# # Hangman version 2: h8.py (Fall 2025, CSCI 1470.1) # Two built-in modules may be needed. import sys import random def populate_words(infile_name = 'hangman_words.txt'): """ Read the file infile_name that contains one word per line. Strip away any trailing white spaces. Return a list of words. Write your code below. """ # The number of guesses is set to 13. Captial letters are used for constants. NUM_GUESSES = 13 def get_a_word(words): """ Return a random word from words, which is a list of words. """ return random.choice(words) def get_alphabet_from_user(prompt): """ Prompts the user to enter a single alphabetical character and returns it. Includes validation to ensure only a single letter is entered. Write your code below. """ def get_yes_no_answer(prompt): """ Prompt the user to enter a yes no answer. Return True if yes, False if no. """ while True: user_input = input(prompt).strip().lower() if user_input in ('y', 'yes'): return True elif user_input in ('n', 'no'): return False else: print("Invalid input. Please enter 'yes' or 'no'.") def play_one_game(word): """ Play one hangman game. The parameter word is the answer word. """ hidden_word = "-" * len(word) guess = 1 # guessed_chars is a set variable to keep track # of what characters have already been guessed. guessed_chars = set() while guess <= NUM_GUESSES and "-" in hidden_word: print(f"The hidden word: {hidden_word}") # Use a while loop to get a user input that is a character # which is not yet guessed before. while True: user_input = get_alphabet_from_user(f"Enter a character (guess #{guess}): ") # Include code to handle character already guessed and # the update of the set guessed_chars. if len(user_input) == 1: # Count the number of times the character occurs in the word num_occurrences = word.count(user_input) # Replace the appropriate position(s) in hidden_word with the actual character. position = -1 for occurrence in range(num_occurrences): position = word.find(user_input, position + 1) # Find the position of the next occurrence hidden_word = (hidden_word[:position] + user_input + hidden_word[position + 1:] ) # Rebuild the hidden word string guess += 1 if not "-" in hidden_word: print("Winner!", end=" ") else: print("Loser!", end=" ") print(f"The word was {word}.") def main(): # Populate the list words by calling populate_words() correctly. # If there are exceptions, exit the program. words = [] # Write your code here. # Print a welcome and introduction to the game. # Write your code below. # Play games as many times as the user like. while True: # Write your code here. # print bye message. print("\nBye, see you later.") if __name__ == "__main__": main()