我想创建一个单词猜谜游戏,程序从我的单词列表中随机选择一个单词,用户必须猜出单词。
所以我的程序遇到了很多问题:
这是我到目前为止所做的:
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!
答案 0 :(得分:0)
如何将猜测的信件留在空白处 下一轮的猜测?
只需存储包含猜测字母和下一轮空格的字符串。您每次都会从wordlist
重新计算它(每次都可以重新计算,但是您需要修改搜索功能以获取字母,请参阅答案2)
如果这个单词有两个相同的字母,我怎么才能在空白处显示它?
修改您的搜索循环,它应该在找到第一个匹配的字母后继续搜索。
letterIndex = randWord.index(guess)
将仅返回字符串中第一次出现的猜测。
如何显示每轮用户所遗漏的所有字母?
将它们存储在单独的字符串或列表中。所以你每次都可以打印出来。
答案 1 :(得分:0)
我没有重复使用上一轮中的newBlanks
字符串,而是建议使用join
和简单的列表理解重新构建它,使用包含所有猜测的字符串guessed
,例如{ {3}}。另请注意,检查正确/错误字母不会以这种方式运行,但会减少字段中每个字母的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)