随机单词猜谜游戏

问题描述 投票:1回答:2

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

  • 用户一次只能猜一个字母。
  • 用户只允许进行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!
python function python-3.x random words
2个回答
0
投票

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

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

如果这个单词有两个相同的字母,我怎么才能在空白处显示它?

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

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

如何显示每轮用户遗漏的所有信件?

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


0
投票

我没有重复使用前一轮的newBlanks字符串,而是建议用join和一个简单的列表理解重新构建它,使用字符串guessed持有所有猜测,如here。另请注意,检查正确/不正确的字母不会以这种方式起作用,但会减少count对于不是猜测字母的单词的每个字母。请改用if guess in randWord:。此外,如果count不是单个字母,您可以使用while作为continue循环的条件,guess使用循环的下一次迭代。

总而言之,您的代码可能如下所示:

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) 
© www.soinside.com 2019 - 2024. All rights reserved.