用Python3写一段猜字谜的代码每段字谜有三次机会回答回答错误就显示猜错了并显示还剩多少次机会当机会用完时就显示正确答案回答正确就显示猜对了!。每次结束一把游戏都询问玩家是否继续
import random
guesses = 3 play_again = True
while play_again: words = ['apple', 'banana', 'orange', 'grape', 'watermelon'] word = random.choice(words) print("Guess the word! It has", len(word), "letters.") guessed_word = '-' * len(word) print(guessed_word)
while guesses > 0:
guess = input("Guess a letter or the whole word: ")
if guess == word:
print("You guessed it! The word was", word)
break
elif guess in word:
for i in range(len(word)):
if word[i] == guess:
guessed_word = guessed_word[:i] + guess + guessed_word[i+1:]
if guessed_word == word:
print("You guessed it! The word was", word)
break
print(guessed_word)
else:
guesses -= 1
print("Wrong! You have", guesses, "guesses left.")
if guesses == 0:
print("The word was", word)
play_again_input = input("Play again? (y/n): ")
if play_again_input.lower() != 'y':
play_again = Fals
原文地址: https://www.cveoy.top/t/topic/hu2k 著作权归作者所有。请勿转载和采集!