我必须创建一个游戏,其中计算机选择一个随机单词,玩家必须猜测该单词。计算机告诉玩家该单词中有多少个字母。然后玩家有五次机会询问一个字母是否在单词中。计算机只能以"yes"
或"no"
回复。然后,玩家必须猜出这个词。
我只有:
import random
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck" , "doom" , "mayonase" ,"flying" ,"magic" ,"mine" ,"bugle")
word = random.choice(WORDS)
print(len(word))
correct = word
guess = input("\nYour guess: ")
if guess != correct and guess != "" :
print("No.")
if guess == correct:
print("Yes!\n")
我不知道如何解决这个问题。
答案 0 :(得分:1)
我假设您想让用户询问计算机中是否有5个字母。如果是这样,这里是代码:
for i in range(5): #Let the player ask 5 times
letter = input("What letter do you want to ask about? ")[0]
#take only the 1st letter if they try to cheat
if letter in correct:
print("yes, letter is in word\n")
else:
print("no, letter is not in word")
关键是in
循环中的for
运算符。
答案 1 :(得分:0)
您正在寻找以下内容
import random
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck" , "doom" , "mayonase" ,"flying" ,"magic" ,"mine" ,"bugle")
word = random.choice(WORDS)
correct_answer = word
max_guesses = 5
print("Word length:", len(word))
print("Attempts Available:", max_guesses)
for guesses in range(max_guesses):
guess = input("\nEnter your guess, or a letter: ")
if guess == correct_answer:
print("Yay! '%s' is the correct answer.\n" % guess)
break
elif guess != "":
if guess[0] in correct_answer:
print("Yes, '%s' appears in the answer" % guess[0])
else:
print("No, '%s' does not appear in the answer" % guess[0])
else:
print("\nYou ran out of maximumum tries!\n")