1

我想创建一个猜词游戏,程序从我的单词列表中随机选择一个单词,用户必须猜测这个单词。

  • 用户一次只能猜一个字母。
  • 用户只能有 6 次失败的猜测。(使用 6 次失败尝试失败)。
  • 如果用户在使用 6 次失败尝试之前猜出完整的单词,则用户获胜。

所以我的程序面临很多问题:

  1. 当它进入下一轮猜测时,我如何让猜测的字母留在空白处?
  2. 如果这个词有两个相同的字母,我如何在我的空白处也显示它?
  3. 如何在每一轮中显示所有用户丢失的字母?

这是我到目前为止所做的:

import random

wordlist = ['giraffe','dolphin',\
            'pineapple','durian',\
            'blue','purple', \
            'heart','rectangle']

#Obtain random word
randWord = random.choice(wordlist)

#Determine length of random word and display number of blanks
blanks = '_ ' * len(randWord)
print ()
print ("Word: ",blanks)


#Set number of failed attempts
count = 6

#Obtain guess
while True:
    print ()
    guess = input ("Please make a guess: ")   
    if len(guess) != 1:
        print ("Please guess one letter at a time!")
    elif guess not in 'abcdefghijklmnopqrstuvwxyz':
       print ("Please only guess letters!")

#Check if guess is found in random word
    for letters in randWord:
        if guess == letters:
            letterIndex = randWord.index(guess)
            newBlanks = blanks[:letterIndex*2] + guess + blanks[letterIndex*2+1:]
            print ("Guess is correct!")
        else:
            count -=1
            print ("Guess is wrong! ", count, " more failed attempts allowed.")
    print() 
    print("Word: ",newBlanks) 

我希望获得的结果(对于 randWord 'purple'):

Word: _ _ _ _ _ _ 
Missed: 
Please make a guess: l
Guess is correct!


Word: _ _ _ _ l _ 
Missed:
Please make a guess: z
Guess is wrong! 5 more failed attempts allowed.


Word: _ _ _ _ l _ 
Missed: z
Please make a guess: o
Guess is wrong! 4 more failed attempts allowed.


Word: _ _ _ _ l _ 
Missed: z, o
Please make a guess: p
Guess is correct!


Word: p _ _ p l _ 
Missed: z, o
Please make a guess: e
Guess is correct!


Word: p _ _ p l e 
Missed: z, o
Please make a guess: r
Guess is correct!


Word: p _ r p l e 
Missed: z, o
Please make a guess: u
Guess is correct!


Word: p u r p l e 
YOU WON!
4

2 回答 2

0

当它进入下一轮猜测时,我如何让猜测的字母留在空白处?

只需存储包含猜测字母和空格的字符串以供下一轮使用。您每次都在重新计算它wordlist(也可以每次都重新计算,但是您需要修改您的字母搜索功能,请参见答案2)

如果这个词有两个相同的字母,我如何在我的空白处也显示它?

修改你的搜索循环,它应该在找到第一个匹配的字母后继续搜索。

letterIndex = randWord.index(guess)将仅返回字符串中第一次出现的猜测。

如何在每一轮中显示所有用户丢失的字母?

将它们存储在单独的字符串或列表中。因此,您可以每次都打印它。

于 2013-11-12T10:25:27.563 回答
0

我建议不要重用上一轮的字符串,而是使用一个简单的列表newBlanks推导重新构建它,使用一个包含所有猜测的字符串,比如这里。另请注意,您对正确/错误字母的检查不会以这种方式工作,但对于不是猜测字母的单词的每个字母都会减少。改为使用。此外,您可以使用for 循环的条件,并在循环的下一次迭代中使用 if不是单个字母。joinguessedcountif guess in randWord:countwhilecontinueguess

将它们放在一起,您的代码可能如下所示:

guessed = ""
while count >= 0:
    guess = input ("Please make a guess: ")   
    # ... check guess, continue if not a letter
    guessed += guess

    if guess in randWord:
        # ... print 'correct', else 'not correct', decrease count

    newBlanks = " ".join(c if c in guessed else "_" for c in randWord)
    print("Word: ",newBlanks) 
于 2013-11-12T10:36:34.283 回答