1

我必须创建一个游戏,其中计算机选择一个随机单词,玩家必须猜测该单词。电脑会告诉玩家单词中有多少个字母。然后玩家有五次机会询问单词中是否有字母。计算机只能用"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") 

我不知道如何解决这个问题。

4

2 回答 2

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

于 2013-09-29T18:49:08.490 回答
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")
于 2013-09-29T19:57:18.877 回答