import random # The standard module random is used for getting # a random element from the jumble word list. JUMBLE_FILE_NAME = 'jumble_words.txt' def read_jumble_words(filename = JUMBLE_FILE_NAME): """Read Jumber words file and return a list of the words..""" with open(filename, 'r') as file: return [line.rstrip() for line in file] def jumble_word(word): """Shuffles the letters of a given word and return a list of the letters""" return random.sample(word, len(word)) def get_word_from_user(prompt): """ Prompts the user to enter a word and returns it. Includes validation to ensure only a single word is entered. """ while True: user_input = input(prompt).strip().lower() if user_input.isalpha(): return user_input else: print("Invalid input. Please enter a word with only alphabets.") 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 Jumble game.""" # [1] Get a list of shuffled letters from the jumble word. jumbled_letters = jumble_word(word) # Show the shuffled lettes. print(f"Jumbled letters: {", ".join(jumbled_letters)}") # 2. Get user input, converted to lower cases. user_guess = input("Your guess: ").lower() # 3. Check the guess and provide the result. if user_guess == word: print("Congratulations! You guessed the correct word.") else: print(f"Sorry, incorrect guess. The correct answer is: {word}") def main(): # Play games as many times as the user like. # Read the jumble word file into the list words. words = read_jumble_words() # Print welcome message. print(f"Welcome to the Jumble Word Game!") print(f"Unscramble the following letters to form a valid word:") print("-" * 54) while True: # Get a random word. word = random.choice(words) # Play one jumble game. play_one_game(word) if not get_yes_no_answer('\nPlayer another game [y/n]: '): break; # print bye message. print("\nBye, see you later.") if __name__ == "__main__": main()