import random words = ["apple", "banana", "orange", "grape", "watermelon", "pineapple", "strawberry", "kiwi", "mango", "pear"] def choose_word(words): return random.choice(words) def display_word(word, guesses): display = "" for letter in word: if letter in guesses: display += letter + " " else: display += "_ " return display def game(): word = choose_word(words) guesses = [] attempts = 6 print("Welcome to the Word Guessing Game!") while attempts > 0: print(display_word(word, guesses)) guess = input("Guess a letter: ").lower() if guess in guesses: print("You already guessed that letter!") elif guess in word: guesses.append(guess) if "_" not in display_word(word, guesses): print("Congratulations! You guessed the word: " + word) break else: attempts -= 1 print("Incorrect guess. You have {} attempts left.".format(attempts)) if attempts == 0: print("Sorry, you are out of attempts. The word was: " + word) game() [2024-10-08 19:48:53 | AI写代码神器 | 790点数解答]